# Question
Title: How can I make OpenGL textures scale without becoming blurry?
I'm using OpenGL through LWJGL.

I have a 16x16 textured quad rendering at 16x16. When I change it's scale amount, the quad grows, then becomes blurrier as it gets larger.

*How can I make it scale without becoming blurry, like in Minecraft.*

Here is the code inside my RenderableEntity object:

```
public void render(){
    Color.white.bind();
    this.spriteSheet.bind();
    GL11.glBegin(GL11.GL_QUADS);
        GL11.glTexCoord2f(0,0);
        GL11.glVertex2f(this.x, this.y);
        GL11.glTexCoord2f(1,0);
        GL11.glVertex2f(getDrawingWidth(), this.y);
        GL11.glTexCoord2f(1,1);
        GL11.glVertex2f(getDrawingWidth(), getDrawingHeight());
        GL11.glTexCoord2f(0,1);
        GL11.glVertex2f(this.x, getDrawingHeight());
     GL11.glEnd();

}

```

And here is code from my initGL method in my game class

```
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glClearColor(0.46f,0.46f,0.90f,1.0f);
GL11.glViewport(0,0,width,height);
GL11.glOrtho(0,width,height,0,1,-1);

```

And here is the code that does the actual drawing

```
public void start(){
    initGL(800,600);
    init();

    while(true){
        GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);

        for(int i=0;i<entities.size();i++){
            ((RenderableEntity)entities.get(i)).render();
        }

        Display.update();
        Display.sync(100);

        if(Display.isCloseRequested()){
            Display.destroy();
            System.exit(0);
        }
    }
}

```

# Answer
You need to change the texture magnification type, like so:

```
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

```

Read about glTexParameter.
> 16 votes

# Answer
You can't. The nature of any kind of digital data is that once information has been removed it can never be put back, and likewise you can't fill in information that was never there in the first place - the best you can do is a rough approximation, which gives you blurriness.

Using GL\_NEAREST won't blur but it will become pixellated instead.

The solution is to use a larger texture with mipmaps. That way you get good quality no matter what size the geometry being textured is.
> 8 votes

# Answer
I've experienced this issue first hand - making a block-based game with low res (8px * 8px) textures. No matter how far close or how far the camera was, the textures were being cross "blended" by OpenGL's default settings - they appeared blurry.

You need to enable "nearest" magnification to disable bilinear filtering. That is, when the camera is zoomed in close to the texture; each pixel is defined as the colour of the texel that is closest - no blending.

You do this with these two lines:

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

```
> 2 votes

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


title: AS3 Replay all the child timelines?

text:
# Question
Title: AS3 Replay all the child timelines?
Flash CS5 AS3 Is there a way to reset all the timelines while/if the Frame 1 en Scene 1 is called?

I happen to have lots symbols with timelines, if I gotoAndPlay Scene 1 frame 1, most symbols won't restart.

I use

```
MovieClip(root).gotoAndPlay("one");

```

# Answer
If you have only one level of children, it's easy. You just loop through them and call `gotoAndPlay` like this:

```
for (var i:int = 0; i< MovieClip(root).numChildren; i++)
{
    MovieClip(root).getChildAt(i).gotoAndPlay("one");
}

```

But if you have multiple levels of children, you should do a recursion through all children and run the code above for all of them.
> 1 votes

---
Tags: flash, actionscript-3
---


# Question
Title: Collision detection between a sprite and rectangle in canvas
I'm building a Javascript + canvas game which is essentially a platformer. I have the player all set up and he's running, jumping and falling, but I'm having trouble with the collision detection between the player and blocks (the blocks will essentially be the platforms that the player moves on).

The blocks are stored in an array like this:

```
var blockList = [[50, 400, 100, 100]];

```

And drawn to the canvas using this:

```
this.draw = function() {
    c.fillRect(blockList[0][0], blockList[0][1], 100, 100);
}

```

I'm checking for collisions using something along these lines in the player object:

```
this.update = function() {
    // Check for collitions with blocks
    for(var i = 0; i < blockList.length; i++) {
        if((player.xpos + 34) > blockList[i][0] && player.ypos > blockList[i][1]) {
            player.xpos = blockList[i][0] - 28;
            return false;
        }
    }

    // Other code to move the player based on keyboard input etc
}

```

The idea is if the player will collide with a block in the next game update (the game uses a main loop running at 60Htz), the function will return false and exit, thus meaning the player won't move.

Unfortunately, that only works when the player hits the left side of the block, and I can't work out how to make it so the player stops if it hits any side of the block. I have the properties `player.xpos` and `player.ypos` to help here.

# Answer
> 1 votes
Using the same logic you've applied, for detecting collisions on the right side of a block:

```
if(player.xpos < blockList[i][0] + blockList[i][2] && player.xpos + player.width > (blockList[i][0] + blockList[i][2]) && player.ypos > blockList[i][1] && player.ypos + player.height < blockList[i][1] + blockList[i][3]){
    //Your stuff
}

```

Note that I've used `player.width` and `player.height` instead of hard-coded values. It'll help you later.

So what we're checking for here is if the player's right side is ahead of the block and if it's left side is less than the block's right side, while also being in the same y-positions. I'd recommend changing your current code to check for all 4 possibilities like my code up there did, because that's what will ensure that `//Your code` is executed only and only if it is colliding. Without checking for the `y` co-ordinates, the player wouldn't be able to jump over, or go under blocks. And without the 2 `x` co-ordinate checks, the code to be executed for a collision on the right, would be executed even if the player was on the left of the block.

---
Tags: collision-detection, javascript, html-canvas
---


# Question
Title: Should collision sounds and UI responses be deferred or processed immediately?
When checking for collisions between entities, should you play a collision sound immediately on discovering a collision or queue every collision and process the sounds later?

Similarly for user user input: When the user presses *keypad left*, should you insert the event in a queue for later processing or immediately update the world?

# Answer
> 2 votes
**1)** I guess it depends on the capability of your sound-engine and the number of objects/collisions you might have at any given time. If you have lots of collisions, the amount of concurrently playing sounds might exceed the limitations of your sound-engine.

It would be a good idea to have notifications for collisions. Whenever your collision-solver detects a collision, it notifies the entities and maybe also your "sound-manager". There you can decide if this new collision should play a sound or (if it's concurrent with another collision of the same type) you don't need to play a sound at all. You should also make sure that a collision fires a notification just once.

**2)** It's definitely a good idea to queue user-input. Depending on how your input works, you might get multiple user-inputs during one update and you don't want to miss any of these. But this heavily depends on the input library you use (some do input buffering already or allow you to poll on updates etc.).

Generally it's a good idea to have an intermediate layer that handles/normalizes input. Just imagine you want to allow key-remapping or different control-schemes. You don't want to check `if(keyPressed == W_KEY || keyPressed == LEFT_KEY)`. Rather your input-layer would know about the currently active key-mapping, do the check and return (or broadcast) normalized commands, like `left` etc.

# Answer
> 1 votes
1. I wouldn't do either. I'd change the state of the object (this sounds fancy - in code I do something like i\_collided\_with\_something = true) and then I'd implement a seperate method in the class which is responsible for playing sounds (which does nothing else than if(i\_collided\_with\_something) playcollisionssound();). This seperates the actual state-logic from playing the sounds (you can change the sound without fiddling around in the collision-management code).
2. Since I consider the position of the player to be a state, I'd change it immediately. There's no real advantage to be gained from saving all that stuff in a list and doing it all at once later.

---
Tags: architecture, events
---


# Question
Title: Suggestions to start a cross-platform project
I have a big project in my head, it should be cross-platform (Win, Max and Linux), online (Client - Server) and with 3D graphics. I would like some suggestions to start with the right things.

Currently I'm a PHP/MySQL coder, I used to code in C and Pascal on DOS ages (Borland Times ;)), my C knowlegde need a refresh but it's ok.

I guess C++ it's the right language. What platform and what i should use to code? I can choose from all three platforms. My idea was to use Visual Studio 2010 C++, but i'm not sure if it support Native code.

What kind of libraries should i use? I guessed OpenSSL for the login, OpenGL for graphics part. For the Audio or the GUI? Any other suggestions are well accepted.

I know it's a "BIG DEAL" but I have no rush and it'll be a free-time project, only for my pleasure.

Thank you in advance.

# Answer
> 2 votes
My game setup (a multiplayer persistent game) can run on Windows and Linux (the client doesn't but it is more of a configuration thing than a code thing).

I use MySQL and TinyXML on the server side. I had to do some tweaking with: sockets, criticalsections, timers, threads and text (ie. 4bytes widechars and different syntax of wsprintf). It compiles on MSVC (C++) on my Windows development machine, on Ubuntu with gcc for the 'live' server.

The client also uses TinyXML, sockets, criticalsections, threads and timers and also Irrlicht for the rendering (Irrlicht is the 3D engine and is cross platform: Win,Linux & MacOS).

C++ is probably the way to go if you want to tie together a big project, I'd advice OpenGL too as it is widespread, cross platform and quite good.

Just out of curiosity, what will the game be about?

ps. oh, old Borland 4.52, I remember that one :-)

---
Tags: cross-platform
---


title: Rotate 3D Model from a custom position

text:
# Question
Title: Rotate 3D Model from a custom position
I have a 3D Model like above in which i want to rotate it from a given location(pointed in red) but I can only rotate it from the middle. How can I rotate it from a custom point.

**Edit:**

I successfully able to rotate the model from the below position by getting the radius of the model and applying it to the world matrix

```
        Vector3 point = new Vector3(-radius, 0, 0);
        world = Matrix.CreateTranslation(-radius, 0, 0);

```

But now I cannot change the position of the object and it always centered in middle of the screen. I think that's because i applied the above code. How can I place it anywhere I want?

# Answer
Finally i was able to do that,

```
    Matrix rotation = Matrix.Identity;

```

Inside the constructor get the radius and make it minus. because originally it was set to Matrix.Identity

```
    rotation = Matrix.CreateTranslation(-radius, 0, 0);

```
> 2 votes

# Answer
You have to bring the point you want to rotate to the (0,0,0) position and then apply the rotation.
> 1 votes

# Answer
You have to translate your custom point to the (0,0,0) and then rotate it from there. If your box is 2 x 5 x 2 and you wanted to rotate it over de the X axis, if were using OpenGL you could do something like this

```
glTranslatef(-1.0f,-2.5f,-1.0f);
glRotatef(rot, 1.0, 0.0, 0.0);

```
> 1 votes

---
Tags: xna, xna-4.0, models
---


# Question
Title: Refactoring an immediate drawing function into VBO, access violation error
I have a MD2 model loader, I am trying to substitute its immediate drawing function with a Vertex Buffer Object one....

I am getting a really annoying access violation reading error and I can't figure out why, but mostly I'd like an opinion as to whether this looks correct (never used VBOs before).

This is the original function (that compiles ok) which calculates the keyframe and draws at the same time:

```
glBegin(GL_TRIANGLES);
    for(int i = 0; i < numTriangles; i++) {
        MD2Triangle* triangle = triangles + i;
        for(int j = 0; j < 3; j++) {
            MD2Vertex* v1 = frame1->vertices + triangle->vertices[j];
            MD2Vertex* v2 = frame2->vertices + triangle->vertices[j];
            Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac;
            Vec3f normal = v1->normal * (1 - frac) + v2->normal * frac;
            if (normal[0] == 0 && normal[1] == 0 && normal[2] == 0) {
                normal = Vec3f(0, 0, 1);
            }
            glNormal3f(normal[0], normal[1], normal[2]);

            MD2TexCoord* texCoord = texCoords + triangle->texCoords[j];
            glTexCoord2f(texCoord->texCoordX, texCoord->texCoordY);
            glVertex3f(pos[0], pos[1], pos[2]);
        }
    }
glEnd();

```

What I'd like to do is to calculate all positions before hand, store them in a Vertex array and then draw them. This is what I am trying to replace it with (in the exact same part of the program)

```
int vCount = 0;
    for(int i = 0; i < numTriangles; i++) {
        MD2Triangle* triangle = triangles + i;
        for(int j = 0; j < 3; j++) {
            MD2Vertex* v1 = frame1->vertices + triangle->vertices[j];
            MD2Vertex* v2 = frame2->vertices + triangle->vertices[j];
            Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac;
            Vec3f normal = v1->normal * (1 - frac) + v2->normal * frac;
            if (normal[0] == 0 && normal[1] == 0 && normal[2] == 0) {
                normal = Vec3f(0, 0, 1);
            }

            indices[vCount] = normal[0];
            vCount++;
            indices[vCount] = normal[1];
            vCount++;
            indices[vCount] = normal[2];
            vCount++;

            MD2TexCoord* texCoord = texCoords + triangle->texCoords[j];
            indices[vCount] = texCoord->texCoordX;
            vCount++;
            indices[vCount] = texCoord->texCoordY;
            vCount++;

            indices[vCount] = pos[0];
            vCount++;
            indices[vCount] = pos[1];
            vCount++;
            indices[vCount] = pos[2];
            vCount++;
        }

    }

         totalVertices = vCount;

        glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_VERTEX_ARRAY);

    glNormalPointer(GL_FLOAT, 0, indices);
    glTexCoordPointer(2, GL_FLOAT, sizeof(float)*3, indices);
    glVertexPointer(3, GL_FLOAT, sizeof(float)*5, indices);

    glDrawElements(GL_TRIANGLES, totalVertices, GL_UNSIGNED_BYTE, indices);

    glDisableClientState(GL_VERTEX_ARRAY);  // disable vertex arrays
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);

```

First of all, does it look right?

Second, I get access violation error "Unhandled exception at 0x01455626 in Graphics\_template\_1.exe: 0xC0000005: Access violation reading location 0xed5243c0" pointing at line 7

```
Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac;

```

where the two Vs seems to have no value in the debugger.... Till this point the function behaves in exactly the same way as the one above, I don't understand why this happens?

Thanks for any help you may be able to provide!

EDIT ----------------------------------------------------------------------------------

Thank you Zacharmarz for your guidance, I eventually got the code working with vertexArrays (since the regular array was causing the exception due to unknown size of vertices).... after all this work I was expecting an improvement in performance but my frame rate is almost half what it was when rendering twice with immediate mode.... Maybe I'm doing something extra here? I managed to implement a std::vector collection like recommended:

```
    for(int i = 0; i < numTriangles; i++) {
        MD2Triangle* triangle = triangles + i;
        for(int j = 0; j < 3; j++) {
            MD2Vertex* v1 = frame1->vertices + triangle->vertices[j];
            MD2Vertex* v2 = frame2->vertices + triangle->vertices[j];
            Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac;
            Vec3f normal = v1->normal * (1 - frac) + v2->normal * frac;
            if (normal[0] == 0 && normal[1] == 0 && normal[2] == 0) {
                normal = Vec3f(0, 0, 1);
            }

            normals.push_back(normal[0]);
            normals.push_back(normal[1]);
            normals.push_back(normal[2]);

            MD2TexCoord* texCoord = texCoords + triangle->texCoords[j];
            textCoords.push_back(texCoord->texCoordX);
            textCoords.push_back(texCoord->texCoordY);

            vertices.push_back(pos[0]);
            vertices.push_back(pos[1]);
            vertices.push_back(pos[2]);
        }

    }

    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_VERTEX_ARRAY);

    glNormalPointer(GL_FLOAT, 0, &normals[0]);
    glTexCoordPointer(2, GL_FLOAT, 0, &textCoords[0]);
    glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);

    glDrawArrays(GL_TRIANGLES, 0, vertices.size()/3);

    glDisableClientState(GL_VERTEX_ARRAY);  // disable vertex arrays
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);

    vertices.clear();
    textCoords.clear();
    normals.clear();

```

Is there something extra that I am doing here? Cos this is really meant to be more efficient that glBegin()/End(), right?

Thanks for your time and help!

# Answer
> 3 votes
First of all: You misunderstood glDrawElements. This function takes as its last parameter **indices** to array of vertices/normals/texture\_coordinates (**not array with vertices / normals.....**) - this can be used for indexed geometry.

Second of all: You misunderstood glNormalPointer / glVertexPointer / glTexCoordPointer. Its 3rd parameter is stride, which means stride in the whole array of vertices / normals / tex\_coordinates. So its always 8\*sizeof(float). And also its lasta parameter is pointer to first elements (vertex coordinate, texture coordinate, normal coordinate). So it should be for normals really indices, for textures &(indices\[3\]) (I think also indices + 3 should work) and for vertices &(indices\[5\]).

And for your first problem - you should use glDrawArrays, if you don't want to use indexed geometry. And you should use it in this way: glDrawArrays(GL\_TRIANGLES, 0, totalVertices/8) - here "totalVertices/8" is your real count of vertices - each vertex has 8 parts - 3 normal coordinates + 2 texture coordinates + 3 vertex coordinates.

But I really don't understand how your Unhandled exception... can occur, when you use the same mechanism in first case and there it's working properly.

BTW: And this is not VBO. These are called vertex arrays \- geometry data is transfered from CPU side to GPU side each time you call glDrawArrays. If you want to use VBOs (geometry is stored in GPU memory), you can try this tutorial. But what I have understood, you are doing some animation or interpolation (?) - you are using frame1 and frame2 and frac variable. So you can use vertex arrays of VBOs with some "streamed" flag - this means the data will be changed every frame (specified once and used once). –

---
Tags: c++, opengl, vertex-arrays
---


# Question
Title: What are some great papers/publications relating to game programming?
What are some of your favorite papers and publications that closely relate to game programming? I'm particularly looking for examples that are well-written and illustrated, and/or have had a profound influence on the industry. (Here's one example: in this GDC talk, Bungie's David Aldridge mentions that a paper called "The TRIBES Engine Networking Model" was the starting point for Halo's network code.)

# Answer
Game programming gems 1-8. A compilation of technical papers and various methods used in game programming. Tried to give one answer since it's so open ended
> 5 votes

---
Tags: software-engineering
---


# Question
Title: What is some game development literature purely in javascript?
I'm mainly interested in the videogames development in pure javascript, since nowadays there's so many books about htm5 and javascript I couldn't find any book about game development with javascript only.

# Answer
> 4 votes
This question looks like to this one :

https://stackoverflow.com/questions/1506803/good-resources-for-javascript-2d-game-programming

The answer seems to point to useful ressources about Javascript video game programming.

# Answer
> 0 votes
http://www.amazon.com/Unity-Game-Development-Essentials-Goldstone/dp/184719818X

The book doesn't only focus on javascript since unity supports c# and boo. If you don't want to go the HTML 5 route then an engine like unity would probably be the thing to do. There are others like unity but I'm biased

---
Tags: javascript
---


# Question
Title: Where can I read about techniques used in NES-era games?
I enjoy reading about techniques used in NES-era games. Is there a blog or site that is pretty much dedicated to this topic?

For example, here is an article talking about Pac-Man, and another about the movement in The Legend of Zelda.

# Answer
> 3 votes
> I'm looking for general coding techniques. Preferably language agnostic, but that doesn't really matter. If you take a look at the links I posted about you will see what I mean.

The NES specifically is very old, so you're not going to find too too much on that. This past year at the Game Developers Conference had a number of classic game Postmortems, which sounds more like what you're looking for. You can find many of them freely in the GDC Vault.

http://www.gdcvault.com/free/gdc-11

If you want something more, the GameBoy survived for a really long time (I worked on and shipped a commercial game in 2001 that still sold \> 200,000 copies), specifically the GameBoy Color had graphics hardware on par with the original NES (better actually). For the most part, a lot of old game consoles and old computers were similar in capability. The only thing that set apart a Nintendo from a Commodore 64 was support for a larger number of on screen sprites, and registers for controlling the horizontal and vertical scrolling of the character map (background). Everything until 3D accelerated consoles came along (N64, PS1) was based around more and more advanced forms of hardware sprites and scrollable character maps. Character map hardware was originally designed for displaying text characters, but since you could change the character glyphs, many developers started referring to them tiles and tile hardware.

I do have one suggested link about a NES game, Grand Theiftendo, a homebrew game by a friend of mine:

http://retrocityrampage.com/blog/2011/05/see-rcr-precursor-grand-theftendo-in-action/

If you like what you see, you should check out Retro City Rampage, a dramatically improved commercial version of the game he's been working on.

Above is how many classic game developers had to work... literally, by hard-wiring and creating custom hardware to interface with devices like the NES. If you were an official Nintendo Developer, they would send you an officially pre-modified box that you could test on instead (since not everyone has the technical know-how to wire in and flash flash-memory). And programming wise, nearly everything was done in Assembly (6502 or z80, depending on the device). C compilers took a long time before they became practical for embedded devices.

In the last decade though, things have been more streamlined. Flash carts became available; These were devices you could plug in to a cart programmer (writer), and upload a game binary right to the cart. Then you could plug the cart right in, power on the device, and test. This process can be rather slow though, so on GameBoy Color at least, many developers got familiar with using emulators to test games. Compile, run on emulator. Even if an emulator wasn't 100% accurate, they were often good-enough to initially test. You could flash a cart after you were sure something was working, then sit back and try it as it should be experienced (on device).

Emulators were only ever good for simulating really old hardware, GameBoy and NES era being ideal candidates. Today though, now that everything is 3D accelerated and pushes polygons, it's far more practical to write cross-platform code. Most devices support OpenGL ES, which is an API that is sooooo close to OpenGL, in fact, you can treat GL ES as a subset of regular OpenGL. I.e. You can write games that run on both by writing them against the OpenGL ES spec.

That's my brief on classic-\>modern gamedev techniques. Hopefully that gives you some insight where to dig for more. Alot of information is out there, you just have to know what you're looking for.

# Answer
> 0 votes
Its worth checking Farat's page especially for NES and Gameboy architecture pages.

---
Tags: blog
---


# Question
Title: What should I do to get my Blender models into my iOS game?
I am working on a 3D OpenGL|ES game for iPad. All the models are created in Blender. How should I go about getting my models into my game?

I have the following requirements of my models:

1. One texture map
2. Material
3. Skeletal animation data
4. Attachables / Socket Points

# Answer
> 2 votes
You need a file format readable on iOS, which technically is anything, but if you need a place to start the PowerVR SDK has tools for making and reading POD files.

http://www.imgtec.com/powervr/insider/powervr-sdk.asp

Be sure to grab the correct SDK depending on the OpenGL ES version you are targeting (OpenGL ES 1.1 if you don't know yet).

From Blender 2.5+ you can export to Collada (DAE) files, then import them in to this to make PODs:

http://www.imgtec.com/powervr/insider/powervr-collada2pod.asp

# Answer
> -3 votes
Use this script in blender http://www.innerloop.biz/code/objc.py.zip

Then look at this sample project http://innerloop.biz/code/ExportTest.zip

---
Tags: 3d, opengl-es, ios, blender
---


# Question
Title: iPhone Open GL ES using FBX - How do I import animations from FBX into iPhone?
I've been researching this extensively.

We have a game that's 90% complete, using custom game logic in iPhone 4.0. We've been asked to import a 3D model and have it animate when various events happen in the game.

I've put together an OpenGL view (based on Eagl and several examples), and used Blender to import the model, as well as Jeff LeMarche's script to export the .h file. After much trial, it worked, and I was able to show a rotating model (unskinned).

However, the 3d artist hadn't UV unwrapped the model, so provided me a new model, this one as a Maya file, along with animation in a FBX format, a .obj file, and .tga texture unwrapped.

My question is : how can I use FBX inside OpenGL ES inside iPhone to run through animations? And what's the pipeline to get this Maya file into Blender to be able to create a .h file. I've tried the obj2opengl however the model is missing normals (did it have it in the first place?) and the skin isn't applying at all (possibly a code issue, something I think I can fix).

I'm trying to use Jeff LeMarche's animation tutorial but can't figure out how to get the model files into a proper .h file for use.

Any advice?

# Answer
I am not sure if Maya has Collada format export by default. I guess it does. Only in the case it does not, you might then just install a plugin: http://sourceforge.net/projects/colladamaya/ .Then, use a Blender build that supports collada import in at least in bones, weights, animation. I think latest blender beta builds do support it. You might try one or several of the latest here: http://www.graphicall.org/builds/

So, if all that works, means you can export as collada file from Maya, import that file into Blender, and from blender, export as just blend file (ie, for using in that engine mentioned) , or export as directx \*.x file (perhaps the import might also work as well, and I think there are x exporters for Maya) , or, reported to work, export from Blender as FBX file,lastly, but with some tech problems of the md2 file format, you could use md2. You could as well just "bake" all frames inside an "Action" in blender, there's a button for that, so to be able to export an OBJ per frame, or, less memory/performance waste, one per x frames, then, in your code, use interpolation, linear or spline, between keyframes, if you can. You might need to do a conversion from these OBJ files to your .h files in a way that your code interpolates (blends motion between two keyframes), as so many objs might be too much memory for the iphone.
> 2 votes

# Answer
First you need to think what you want/need to implement.

You either implement a skeletal animation system or a keyframe animation system.

If you only need one animation and it's not very long go for the keyframe animation, the skeletal stuff takes a while and if you never done it's going to take a while...

My last project with keyframe animation I did the following:

1. Imported the FBX into blender, there's a script to import, it's buggy as hell
2. Exported all the keyframes as .obj files, make sure you select these options on the blender export: Keep Vert Order, Normals, HQ, Triangulate.
3. Converted the .obj files with a script of mine (based initially in obj2opengl), so that all the keyframes are exported to a binary file with all the vertex data interleaved.
4. When the animation is needed load the bin files into memory
5. Running the animation is done by interpolating between two keyframes and storing the result in a VBO

For reference I'm using a model with 4096 Vertices and 16 keyframes, runs well even on a iPhone 3G.
> 2 votes

# Answer
Import the file with blender and then convert it to something you can use. The 3D iPhone engine oolong can import blender files for example.
> 0 votes

---
Tags: iphone, opengl-es
---


# Question
Title: Advice for programming a lobby for a network multiplayer game?
I'm working on learning network programming. I'm working on a simple card game. The basic idea is:

```
Players enter the lobby
Players see tables
Players sit at an empty seat

```

Once they sit, they do not need any information from the lobby, they see the card table and the data about the other players and so forth.

I've programmed the server portion for the game itself. The clients connect to my server object and the server then receives and sends messages; quite simple.

The tricky concepts for me are:

```
What's a good way to run many tables at the same time?
What's a good way to keep the lobby consistently updated for each person in the lobby (eg: MSG_TABLE_FILLED, 22)

```

Ideally I'd like to have 1 server exe for all of this and to have to deal with multithreading as little as possible.

I'm going to use the enet library.

I was thinking that each time a game session starts, I push a new Game and I map the client IPs to that table, then I just route messages from those clients to that Game.

Since enet supports channels I was thinking of using 2 channels per table, one for the game messages and one for in game chat.

Would something like this work?

Does anyone have any advice / design ideas for a game with a lobby and many tables? Is there a usual way this is done that I'm overlooking?

Any conceptual ideas or even c/c++ code examples would be very helpful.

Thanks

# Answer
First, don't use the IP address. IP addresses can change and UDP is stateless. Instead, assign each client a session and have them pass the session ID back to you in each message. The `enet` library already does this. The `event` structure will tell you the ID of the client.

You'll need to keep a structure for each peer. That should include whether the peer is in a game or not, and if so which game they are in. Also store in the game structure a table of which peers are in that game.

When a message is sent to the lobby, iterate over the table of peers (or a table just of peers in the lobby) and send the message to each peer. When a game message is received, look up which game that peer is in, and send the message to the handler function for that game object.

I'm not sure what else to tell you at such a high level.
> 5 votes

---
Tags: c++, c, networking
---


title: 3d Model Scaling With Camera

text:
# Question
Title: 3d Model Scaling With Camera
I have a very simple 3D maze program that uses a first person camera to navigate the maze. I'm trying to scale the blocks that make up the maze walls and floor so the corridors seem more roomy to the camera. Every time I scale the model, the camera seems to scale with it, and the corridors always stay the same width.

I've tried apply the scale to the model in the content pipe (setting the scale property of the model in the properties window in VS). I've also tried to apply the scale using Matrix.CreateScale(float) using the Scale-Rotate-Transform order with the same result. If I leave the camera speed the same, the camera moves slower, so I know it's traversing a larger distance, but the world doesn't look larger; the camera just seems slower.

I'm not sure what part of the code to include since I don't know if it is an issue with my model, camera, or something else. Any hints at what I'm doing wrong?

Camera:

```
Projection = Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, _device.Viewport.AspectRatio, 1.0f, 1000.0f );

Matrix camRotMatrix = Matrix.CreateRotationX( _cameraPitch ) * Matrix.CreateRotationY( _cameraYaw );
Vector3 transCamRef = Vector3.Transform( _cameraForward, camRotMatrix );
_cameraTarget = transCamRef + CameraPosition;
Vector3 camRotUpVector = Vector3.Transform( _cameraUpVector, camRotMatrix );
View = Matrix.CreateLookAt( CameraPosition, _cameraTarget, camRotUpVector );

```

Model:

```
World = Matrix.CreateTranslation( Position );

```

# Answer
How do you set the height of the camera above the floor? Is this height getting scaled along with the model, perhaps? To make the space appear larger, the camera should be placed down closer to the floor.

If you have fog or a similar depth-based effect in your game, pulling in the distance on that can also be a good way to give a sense of scale.
> 2 votes

---
Tags: xna, c#, models, first-person-shooter
---


# Question
Title: How can I make a car follow the terrain in a 2D (side-view) game?
I'd like to create a game where a car drives over a 2D terrain. Which algorithm to use so the car will follow the mountain incline?

# Answer
> 3 votes
The game you linked to in your comment most likely uses a physics-engine like Box2D (flash port) for the car physics. So the basic steps are: Create a car body with connected wheels (use joints) and use either a procedural approach or a level editor to create the terrain.

The car following the terrain will be handled by the physics-engine if you set things up correctly.

---
Tags: 2d, algorithm, physics
---


# Question
Title: How to create multiple balloon bodies in Box2D?
In Box2D, how would I go about making a body that's being lifted by multiple "balloons"? These balloons would have to be able to be destroyed (for example, by a bow and arrow).

# Answer
I would model the balloon as a circle shape physics-body and use `ApplyForce` to apply an upward force to the body. If the applied force is `negative(gravity * mass)`, then the balloon should be standing still in the air. Applying a stronger force will cause the balloon to move upwards.

You can then connect another body to the balloon using joints (eg. a distance-joint). If the applied force on the balloon is strong enough, it should also lift the attached body. You might have to experiment with the force to apply and also with the mass of the bodies you want to attach to the balloons (the mass should be rather low to keep things realistic).

Destroying the balloon would simply mean to destroy the balloons physics body and maybe also the joint.
> 6 votes

---
Tags: android, box2d
---


# Question
Title: What functional language is most suited to create games with?
I have had my eye on functional programming languages for a while, but am hesitating to actually get into them. But I think it's about time I at least starting glancing that direction to make sure I'm ready for anything.

I've seen talk of Haskell, F#, Scala, and so on. But I have no clue the differences between the languages and their communities, nor do I particularly care; except in the context of game development.

So, from a game development standpoint, **which functional programming language has the most features suited for game programming?** For example, are there any functional game development libraries/engines/frameworks or graphics engines for functional languages? Is there a language that handles certain data structures which are commonly used in game development better?

Bottom line: **what functional programming language is best for functional game programming, and why?**

*I believe/hope this question will declare a clear best language therefore I haven't marked it CW despite its subjective tendency.*

# Answer
> 12 votes
F# being part of Microsofts .net family has access to XNA, which is a fantastic base for building games. A bit of googling turns up some tutorials, videos and articles. The great XNA docs should help as well.

There has been some movement in games for Haskell as well, see here. You'll probably be using openGL bindings.

Since Scala plays in Java land, it integrates with all the available Java engines/bindings, see this SO post.

I think it comes down to preference, while I've only played with Haskell, I'd imagine each functional language has it's own idiosyncrasies. It may be worth whipping up a small test game in each and seeing which one feels better to you.

Like I said I only have minimal Haskell experience, so I can't comment on the best, but these resources should get you started hopefully.

# Answer
> 8 votes
I would say Lisp.

It has been used in games as a scripting language, at Naughty Dog at least (or it was I think), and is a very mature language.

The advantage of Lisp is in deserialization, which is a major part of what we call asset management. Deserializing lisp is trivial, the code and the data are one. This makes it easier to have a file format for assets and behaviors. It's not like you a one in json/xml/yaml/bin and one F# file for AI. You can save everything as s-expressions which is going to simplify the asset pipeline a lot.

# Answer
> 8 votes
After gaining some practical experience with it, I would vote for Clojure - already written one little game in it, and planning to do more.

Reasons:

* **Productivity** \- Clojure is a dynamic language. It has great features for interactive REPL-style development, for example you can use the REPL to query or alter state inside a running game application instance. Code in Clojure is also often ridiculously concise. I'd guess I am 3-5 times more productive in Clojure than in Java or C#.
* **Impure** \- while I appreciate the beauty and elegance of pure functional languages like Haskell, game programming is a messy pursuit where pragmatism wins. I want to be able to put side effects in my functions when I need them, and Clojure allows this. Having said that, idiomatic Clojure style is to be purely functional *most of the time*.
* **Metaprogramming** \- Clojure's Lisp heritage as a homoiconic language makes it great for metaprogramming / code generation. It's easy to "extend the language" to make your own DSLs or eliminate biolerplate. You could easily use Clojure as it's own game scripting language, and the dynamic code compilation means that your scripts will run just as fast as your core game engine.
* **Access to Java libraries**. You can use all the sound / graphics / AI / networking libraries from Java, which is a huge advantage vs. most other functional languages (where you'll have to either write these from scratch or develop a lot of tricky interfacing code). This can be a life-saver.
* **Cross-platform** \- this comes for free from running on the JVM, but it's a nice bonus.
* **Performance** \- for a dynamic functional language, Clojure is about as fast as you can get. It is always JIT compiled, never interpreted. with intelligent optimization you can match the speed of pure, low-level Java code in Clojure. For example, you can use Java primitive arrays, or provide type hints to ensure that the compiler produces statically typed function calls in performance-critical code.
* **Concurrency** \- Clojure has a great model for managing concurrent state, supported by an impressive software transactional memory system. Worth seeing this video for more insights on how this works.

The only time I *wouldn't* consider Clojure would be if I was writing a state-of-the-art graphically intensive game where you need cutting edge performance (where I still think you need C/C++).

---
Tags: functional
---


title: What makes in-game tutorials effective?

text:
# Question
Title: What makes in-game tutorials effective?
Has there been any research into how to maximize in-game tutorials effectiveness? Any blogs, articles or research papers would be appreciated.

# Answer
> 7 votes
The comments say it all, but ... no, there probably hasn't been much research on it. But, one thing is for sure: **in-game, interactive tutorials work better than "read this" tutorials.**

This is easy to see in Flash games; you can see the evolution of static screenshots/images linked from the main menu ("Tutorial" button) into in-game tutorials (or tutorial-like levels).

The benefit, obviously, would be seeing things happen and how actions play out, while the game progresses, instead of reading a bunch of instructions before you even have a good idea about how the game will go.

# Answer
> 2 votes
This might be really subjective, but could be used as a reference. From my personal experience, tutorials with lots of text immediately turn off some players (tldr) and then they get frustrated when they can't do something that was explained because they didnt read.

Also do not give all the instructions at the start. Players will not see the relevance of some gameplay aspect and will be confused or forget when they actually need it.

The best tutorials are the one that you do not notice. Integrate into your gameplay/story. Make the tutorials feel like they actually matter in some way (advancing story etc...). Kinda like "learn as you play" kind of experience.

Good luck! :D

---
Tags: tutorials
---


# Question
Title: Where can I find a good tutorial to replicate Game Maker's surfaces and blend modes in XNA?
I know Game Maker's surfaces exist in XNA (It's more the othe way around, XNA's surfaces exist in Game Maker), same thing for blend modes, since (I think) they both use DirectX.

This is the question: "Where can I find a good tutorial to replicate Game Maker's surfaces and blend modes in XNA?"

I'm using XNA 4.0 and Game Maker 8.1 Pro.

**Background**

I'm slowly moving from Game Maker to... Something else.

I've learned some good C++ but DirectX is hardcore and OpenGL needs some pretty good understanding of the language to be able to use it correctly.

XNA and C# together seemed like a good middle but the documentation is hard to understand for a newb like me.

In the end, I chose to focus on XNA.

# Answer
Here's a custom BlendState that should do the same as Game Maker's `bm_subtract` does, based on the post found here. Here's a complete example with combining two RenderTarget2Ds, so you also see how they work in practice.

```
private GraphicsDeviceManager graphics;

private SpriteBatch spriteBatch;

private RenderTarget2D sprites;

private RenderTarget2D shadows;

private readonly BlendState blendStateSutractive = new BlendState
{
    ColorSourceBlend = Blend.Zero,
    ColorDestinationBlend = Blend.InverseSourceColor,
    ColorBlendFunction = BlendFunction.Subtract,
    AlphaSourceBlend = Blend.Zero,                    // Not sure if these are needed.
    AlphaDestinationBlend = Blend.InverseSourceColor, // Not sure if these are needed.
    AlphaBlendFunction = BlendFunction.Subtract       // Not sure if these are needed.
};

public Game1()
{
    this.graphics = new GraphicsDeviceManager(this);
    this.graphics.PreferredBackBufferWidth = 1280;
    this.graphics.PreferredBackBufferHeight = 720;
}

protected override void LoadContent()
{
    this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
    this.sprites = new RenderTarget2D(this.GraphicsDevice, this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight);
    this.shadows = new RenderTarget2D(this.GraphicsDevice, this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight);
}

protected override void Draw(GameTime gameTime)
{
    // We make it so future drawing is done to the sprites RenderTarget2D.
    this.GraphicsDevice.SetRenderTarget(this.sprites);
    // Then we clear it to one color.
    this.GraphicsDevice.Clear(Color.Black);
    this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

    // Here you draw your main sprites/textures/whatever.

    this.spriteBatch.End();

    // We make it so future drawing is done to the shadows RenderTarget2D.
    this.GraphicsDevice.SetRenderTarget(this.shadows);
    // Then we clear it to one color, don't know if this should be black or white.
    this.GraphicsDevice.Clear(Color.Black);
    this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

    // And here you draw whatever you need drawn subtractively.

    this.spriteBatch.End();

    // We then reset to the main RenderTarget2D.
    this.GraphicsDevice.SetRenderTarget(null);
    // No need to clear, as the other two RenderTarget2Ds will cover it completely.

    this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
    this.spriteBatch.Draw(this.sprites, Vector2.Zero, Color.White);
    this.spriteBatch.End();

    this.spriteBatch.Begin(SpriteSortMode.Deferred, this.blendStateSubtractive);
    this.spriteBatch.Draw(this.shadows, Vector2.Zero, Color.White);
    this.spriteBatch.End();
}

```

If you have any questions, fire away in the comments section below this answer. And remember to mark whatever answer your satisfied with correct, so future visitors know which answer to look at.
> 3 votes

# Answer
You can use the RenderTarget2D class to draw parts of your game to a bitmap, which you can then apply operations to to get the desired result

check these pages: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.rendertarget2d\_members%28v=XNAGameStudio.40%29.aspx

You might start here to learn the concepts: http://www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale
> 0 votes

---
Tags: c#, xna, blending, game-maker
---


# Question
Title: How do I build a matrix to translate one set of points to another?
I've got 3 points in space that define a triangle. I've also got a vertex buffer made up of three vertices, that also represent a triangle that I will refer to as a "model".

How can I can I find the matrix M that will transform vertex in my buffer to those 3 points in space ?

For example, let's say my three points A, B, C are at locations:

```
A.x = 10, A.y = 16, A.z = 8
B.x = 12, B.y = 11, B.z = 1
C.x = 19, C.y = 12, C.z = 3

```

given these coordinates how can I build a matrix that will translate and rotate my model such that both triangles have the exact same world space ? That is, I want the first vertex in my triangle model to have the same coordinates as A, the second to have the same coordinates as B, and same goes for C.

nb: I'm using instanced rendering so I can't just give each vertex the same position as my 3 points. I have a set of three points defining a triangle, and only three vertices in my vertex buffer.

# Answer
Do the transformations algebraically with a matrix of unknowns, set the result equal to the desired result. This gives you a system of linear equations, solve it, now you have a plug in formula for making such a matrix.

For translating from the points A, B and C to F, G, and H you'll get: quickmath.com

Result image, in case the link breaks:
> 6 votes

---
Tags: c++, mathematics, matrix
---


# Question
Title: Which toolkit to use for 3D MMO game development?
Lately i've been thinking about which path to follow for developing an 3D Online game. I have googled a lot but i couldnt find a good article that covers both game development and online server & client development in same context. This question has been in mind for about 2 weeks now. So.. yesterday i started developing a game from scratch by using Irrlicht.Net Wrapper to use Socket library of .NET which im already familiar. But i found out .Net wrapper of Irrlicht is not totally finished yet and still have lacks from the original. So i lost all my motives :/.

So i thought why not to ask the experts before i run into another dead end...

What Game Engine and Networking Library is best way to go for 3D MMO Development?

Here is some of my early conclusions: Please let me know the ones im wrong.

C++:

* Best Performance for 3D Graphics.
* Most Game Engines has native C++ Libraries.
* Lacks a Solid Socket Library
* .NETC++ Lacks Intellisense Support.

C#:

* Intellisense Support
* NET Socket Library
* Lacks 3D Graphics Performance
* Lacks a native solid 3D Game Engine

# Answer
> 5 votes
The quickest/cheapest way to get up and running would be to use the Unity engine for the client, and something like Photon as your socket server backend.

If you're looking for something with more off-the-shelf support, there's things like Hero Engine.

If you're asking which language to use, I'm assuming you're not experienced enough to pull off starting from scratch.

---
Tags: networking, mmo, ogre, irrlicht
---


title: Trying to simulate a cannon ball

text:
# Question
Title: Trying to simulate a cannon ball
I'm writing a game, and I need to simulate a the path of a cannon ball. I imagine I would have the initial velocity vector, and a vector for gravity. Is there a good tutorial on how to do this? (maybe I need to read some high school text books?)

# Answer
> 2 votes
What I would do is learn how to use Cocos2d. You can use a function thats kind of like a timer, it is called 60 times a second by default but you can change this.

What you would do with this is update the x/y position of your sprite (the cannonball image) by a minuscule amount inside this time function, called ccTime.

If your actually looking for the math for the trajectory, here is an amazing tutorial on that

Here is a question on a forum very similar to yours

# Answer
> 2 votes
You show read the basics of the **trajectory** from where you can extract any equation you need.

If you google '**cannon ball trajectory**' there is hundreds of tutorials of how to compute the position of an object following a cannon ball trajectory at any given time. **Here** there's an example

---
Tags: iphone, physics
---


title: Objective-c Cocos2d moving a sprite

text:
# Question
Title: Objective-c Cocos2d moving a sprite
I hope someone knows how to do the following with cocos2d:

I want a sprite to move but not in a single line by using

```
[cocosGuy runAction: [CCMoveTo actionWithDuration:1 position:location]];

```

What I want is the sprite to do some kind of movements that I preestablish. For example in some point i want the sprirte to move for instance up and then down but in a curve. Do I have to do this with flash like this documents says?

http://www.cocos2d-iphone.org/wiki/doku.php/prog\_guide:animation

Does animation in this page means moving sprites or what?

thanks

# Answer
> 2 votes
The document you linked to describes approaches to animating sprites. This (usually) doesn't involve the movement of the sprite, but rather an image-sequence that is played in place. Eg. a walk-cycle animation (which will give the impression of a walking character if the sprite is *additionally* moved).

You're on the right track with your approach. Instead of running a single action, you should run a sequence of actions instead. This could be a movement upwards, followed by a CCBezierTo or CCBezierBy action, which allows movement along a Bezier curve.

Using the CCSequence allows for some pretty complex animations. You can even add special actions like `CCCallFunc` or similar to execute code at certain points in your sequence.

---
Tags: animation, sprites, cocos2d-iphone, cocos2d, objective-c
---


# Question
Title: Organising levels / rooms in a MUD-style text based world
I'm thinking of writing a small text-based adventure game, but I'm not particularly sure how I should design the world from a technical standpoint.

My first thought is to do it in XML, designed something like the following. Apologies for the huge pile of XML, but I felt it important to fully explain what I'm doing.

```
<level>
    <start>
        <!-- start in kitchen with empty inventory -->
        <room>Kitchen</room>
        <inventory></inventory>
    </start>
    <rooms>
        <room>
            <name>Kitchen</name>
            <description>A small kitchen that looks like it hasn't been used in a while. It has a table in the middle, and there are some cupboards. There is a door to the north, which leads to the garden.</description>
            <!-- IDs of the objects the room contains -->
            <objects>
                <object>Cupboards</object>
                <object>Knife</object>
                <object>Batteries</object>
            </objects>
            </room>
        <room>
            <name>Garden</name>
            <description>The garden is wild and full of prickly bushes. To the north there is a path, which leads into the trees. To the south there is a house.</description>
            <objects>
            </objects>
        </room>
        <room>
            <name>Woods</name>
            <description>The woods are quite dark, with little light bleeding in from the garden. It is eerily quiet.</description>
            <objects>
                <object>Trees01</object>
            </objects>
        </room>
    </rooms>
    <doors>
        <!--
            a door isn't necessarily a door.
            each door has a type, i.e. "There is a <type> leading to..."
            from and to are references the rooms that this door joins.
            direction specifies the direction (N,S,E,W,Up,Down) from <from> to <to>
        -->
        <door>
            <type>door</type>
            <direction>N</direction>
            <from>Kitchen</from>
            <to>Garden</to>
        </door>
        <door>
            <type>path</type>
            <direction>N</direction>
            <from>Garden</type>
            <to>Woods</type>
        </door>
    </doors>
    <variables>
        <!-- variables set by actions -->
        <variable name="cupboard_open">0</variable>
    </variables>
    <objects>
        <!-- definitions for objects -->
        <object>
            <name>Trees01</name>
            <displayName>Trees</displayName>
            <actions>
                <!-- any actions not defined will show the default failure message -->
                <action>
                    <command>EXAMINE</command>
                    <message>The trees are tall and thick. There aren't any low branches, so it'd be difficult to climb them.</message>
                </action>
            </actions>
        </object>
        <object>
            <name>Cupboards</name>
            <displayName>Cupboards</displayName>
            <actions>
                <action>
                    <!-- requirements make the command only work when they are met -->
                    <requirements>
                        <!-- equivilent of "if(cupboard_open == 1)" -->
                        <require operation="equal" value="1">cupboard_open</require>
                    </requirements>
                    <command>EXAMINE</command>
                    <!-- fail message is the message displayed when the requirements aren't met -->
                    <failMessage>The cupboard is closed.</failMessage>
                    <message>The cupboard contains some batteires.</message>
                </action>
                <action>
                    <requirements>
                        <require operation="equal" value="0">cupboard_open</require>
                    </requirements>
                    <command>OPEN</command>
                    <failMessage>The cupboard is already open.</failMessage>
                    <message>You open the cupboard. It contains some batteries.</message>
                    <!-- assigns is a list of operations performed on variables when the action succeeds -->
                    <assigns>
                        <assign operation="set" value="1">cupboard_open</assign>
                    </assigns>
                </action>
                <action>
                    <requirements>
                        <require operation="equal" value="1">cupboard_open</require>
                    </requirements>
                    <command>CLOSE</command>
                    <failMessage>The cupboard is already closed.</failMessage>
                    <message>You closed the cupboard./message>
                    <assigns>
                        <assign operation="set" value="0">cupboard_open</assign>
                    </assigns>
                </action>
            </actions>
        </object>
        <object>
            <name>Batteries</name>
            <displayName>Batteries</displayName>
            <!-- by setting inventory to non-zero, we can put it in our bag -->
            <inventory>1</inventory>
            <actions>
                <action>
                    <requirements>
                        <require operation="equal" value="1">cupboard_open</require>
                    </requirements>
                    <command>GET</command>
                    <!-- failMessage isn't required here, it'll just show the usual "You can't see any <blank>." message -->
                    <message>You picked up the batteries.</message>
                </action>
            </actions>
        </object>
    </objects>
</level>

```

Obviously there'd need to be more to it than this. Interaction with people and enemies as well as death and completion are necessary additions. Since the XML is quite difficult to work with, I'd probably create some sort of world editor.

I'd like to know if this method has any downfalls, and if there's a "better" or more standard way of doing it.

# Answer
If you're not completely wedded to C#, then the "more standard" way of doing this is to use one of the many text adventure creation tools which already exist to help people make exactly this kind of game. These tools give you an already-functioning parser, handling for death, save/restore/undo, character interaction, and other similar standard bits of text adventure functionality. Right now, the most popular authoring systems are Inform, and TADS (though there are a half dozen others available as well)

Inform can compile down into most of the Z Machine virtual machine instruction sets used by Infocom games, or into the more recent glulx virtual machine instruction sets. TADS, on the other hand, compiles down into its own virtual machine code.

Either type of binary can be run by most modern interactive fiction interpreters (in the old days, you often needed separate interpreters for TADS games from ZMachine games from glulx games. But thankfully, those days are basically over now.) Interpreters are available for just about any platform you'd want; Mac/PC/Linux/BSD/iOS/Android/Kindle/browser/etc. So you've already got cross-platform well and truly taken care of.

For most platforms, the currently-recommended interpreter is Gargoyle, but there are plenty of others, so do feel free to experiment.

Coding in Inform (especially the latest version) takes a little bit to get used to, since it's marketing itself more toward authors than toward engineers, and so its syntax looks weird and almost conversational. In Inform 7's syntax, your example would look like this:

```
"My Game" by Polynomial

Kitchen is a room. "A small kitchen that looks like it hasn't been used in a
while. It has a table in the middle, and there are some cupboards. There is a
door to the north, which leads to the garden."

In the Kitchen is a knife and some cupboards.  The cupboards are fixed in
place and closed and openable.  In the cupboards are some batteries.

Garden is north of Kitchen. "The garden is wild and full of prickly bushes.
To the north there is a path, which leads into the trees. To the south there
is a house."

Woods is north of Garden.  "The woods are quite dark, with little light bleeding
in from the garden. It is eerily quiet."

Trees are scenery in the Woods.  "The trees are tall and thick. There aren't any
low branches, so it'd be difficult to climb them."

```

Whereas TADS looks more like a traditional programming language, and the same game in TADS looks like this:

```
#charset "us-ascii"
#include <adv3.h>
gameMain: GameMainDef
    initialPlayerChar = me
;
versionInfo: GameID
    name = 'My Game'
    byline = 'by Polynomial'
;
startroom: Room                  /* we could call this anything we liked */
    roomName = 'Kitchen'         /* the displayed "name" of the room */
    desc = "A small kitchen that looks like it hasn't been used
            in a while. It has a table in the middle, and there
            are some cupboards. There is a door to the north,
            which leads to the garden."
    north = garden         /* where 'north' will take us */
;

+me: Actor
;

cupboards: OpenableContainer
    vocabWords = 'cupboard/cupboards'
    name = 'cupboards'
    isPlural = true
    location = startroom
;
battery: Thing
    name = 'battery'
    location = cupboards
;
knife: Thing
    name = 'knife'
    location = startroom
;
garden: Room
    roomName = 'Garden'
    desc = "The garden is wild and full of prickly bushes. To the
            north there is a path, which leads into the trees. To
            the south there is a house."
    north = woods
    south = startroom
;
woods: Room
    roomName = 'Woods'
    desc = "The woods are quite dark, with little light bleeding
            in from the garden. It is eerily quiet."
    south = garden
;
trees: Decoration
    desc = "The trees are tall and thick. There aren't any low
            branches, so it'd be difficult to climb them."
    location = woods
;

```

Both systems are freely available, very frequently used, and have copious amounts of tutorial documentation (available from the links I gave above), so it's worth checking out both of them and picking the one you prefer.

Note that the two systems do have subtly different standard behaviours (although both may be modified). Here's a screenshot of the game being played, as compiled from the Inform source:

And here's one from the game being played (inside a terminal – typography can be a lot nicer than this), as compiled from the Tads source:

Interesting points to note: TADS gives you a 'score' display in the top right by default (but you can turn it off), while Inform doesn't (but you can turn it on). Inform will by default tell you open/closed states of items in the room description, Tads won't. Tads tends to automatically take actions for you in order to carry out player commands (unless you tell it not to), where Inform tends not to (unless you tell it to).

Either one can be used to make any sort of game (as they're both highly configurable), but Inform is more structured toward producing modern-style interactive fiction (often with minimal puzzles and more narrative in style), where TADS is more structured toward producing old-style text adventures (often strongly focused on puzzles and rigorously defining the mechanics of the game's world model).
> 13 votes

---
Tags: c#, xml, text-based, adventure-games
---


# Question
Title: Game Physics With RK4 Implementation For A 2D Platformer
I been reading about RK4 for physics implementation in a game, so I read in some pages and all people recommend me this page:

http://gafferongames.com/game-physics/fix-your-timestep/

This page shows clearly how this one works, but I can't figure out how to implement in my game, maybe I don't understand that good but I find some things that are not really clearly to me.

In my game, the player decides when change direction in the X-Axis but I can't figure out how with this RK4 implementation change the direction of the object, in the example the point goes side to side but I don't understand how I can control when he goes right or left.

So if anyone can give a little bit of clarity in this implementation and my problem which I do not understand I will be really grateful.

Thanks beforehand

# Answer
> 1 votes
To be frank: RK4 almost certainly isn't your biggest need right now. What's more, unless you're after *very* accurate game physics, I recommend against using Runge-Kutta entirely - it's simply more complication, and for most platformers standard Euler integration should be more than enough. In fact, most platformers don't really need that sort of physics at all - if you're looking to try and control character position, I would suggest 'faking it' by giving the character a constant velocity while the keys are down, with simple acceleration to speed (increase the velocity by a constant amount each tick until maximum speed is reached) and the inverse (deceleration to 0) when the key is released. What's the core problem that you're trying to solve?

---
Tags: c++, physics, rk4
---


# Question
Title: Is it possible to make an MMO game with Flash and ActionScript?
Is it possible to make an MMO game in Flash CS5 with ActionScript 3.0?

I'm not asking *how*, but I'd also like to see some examples if it's already been done.

# Answer
It depends what you mean by "MMO" it would be quite possible to build an MMO client in Flash.

The real question becomes what does your server side software look like? How real-time is this game going to be? Are you talking an MMO like World of Warcraft or something similar to a text-based-turn-based game like Kings of Chaos?

IMHO, you could make a very fun turn-based game in Flash. With the proper server software, you could probably make a real-time game as well, the problem you'll have is loading a big seamless world that many MMOs feature now.

I think you may be trying to shoehorn your existing skills onto game development (I say go for it). I'd recommend starting out with some fun, casual Flash based games. Once you have that under your belt, move on to something bigger.
> 5 votes

# Answer
SmartFox Server is a technology used for building online games. It's got a good track record for small-to-medium scale MMOs. It allows you to write server-side ActionScript 3.0, so that you can code all your game logic, client and server, in that language; Flash CS5 is a given.

That said, I would quote the usual, "don't go for MMOs to start", because that's not sensible. Build a simple single-player game, then a simple multiplayer game, at least, before you even attempt something like this at home.
> 2 votes

# Answer
Club Penguin is an example of a MMO in Flash (wikipedia), as is DOFUS which bearcdp already mentioned (wikipedia). Adventure Quest Worlds is yet another one (wikipedia).

You'll notice similar qualities in each of these games (as far as I know, from my limited experience in them): there are no "twitch" actions, combat is usually slow real-time or turn-based, and they're 2D or 2.5D. These are all artifacts of the Flash technology - it would be difficult to make a really real-time MMO or a 3D game with Flash (though this may be changing; I know recently Flash has been making headway in the 3D graphics space).

If Flash/Actionscript is what you know best and the above games are the kind of quality you would want to aim for, then by all means, clearly Flash is a capable technology for multiplayer games. There's certainly nothing wrong with innovation; if you were to utilize Adobe's latest 3D technologies to make a 3D MMO in Flash, you would apparently be the first and it could mean extra publicity, along with the perks of having a game that works in the browser. But if you are just surveying technologies, then weigh your other options against this; if you specifically want a browser MMO, also consider HTML5/WebGL/WebSocket and Java (we have a good number of questions about these two technologies on the site).
> 1 votes

# Answer
Yes, but it depends on how you define “MMO”, and Flash has limitations — it won't be able to do everything you can do with native code, especially when it comes to networking.

Here's an example: Realm of the Mad God is real-time combat MMO written in ActionScript 3 on the client and C++ on the server. Watch this youtube video to see lots of people playing together — the green dots on the minimap are other players. (The retro graphics are intentional, as it was written for the TIGSource Assemblee competition.) (Disclaimer: I'm loosely involved with the team that wrote the game.)
> 1 votes

---
Tags: actionscript-3, mmo, flash-cs5
---


title: SFML - Moving a sprite on mouseclick

text:
# Question
Title: SFML - Moving a sprite on mouseclick
I want to be able to move a sprite from a current location to another based upon where the user clicks in the window. This is the code that I have:

```
#include <SFML/Graphics.hpp>

int main()
{
    // Create the main window
    sf::RenderWindow App(sf::VideoMode(800, 600), "SFML window");

    // Load a sprite to display
    sf::Texture Image;
    if (!Image.LoadFromFile("cb.bmp"))
        return EXIT_FAILURE;
    sf::Sprite Sprite(Image);

    // Define the spead of the sprite
    float spriteSpeed = 200.f;

    // Start the game loop
    while (App.IsOpened())
    {
        if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Escape))
            App.Close();

        if (sf::Mouse::IsButtonPressed(sf::Mouse::Right)) {
            Sprite.SetPosition(sf::Mouse::GetPosition(App).x, sf::Mouse::GetPosition(App).y);
        }

        // Clear screen
        App.Clear();

        // Draw the sprite
        App.Draw(Sprite);

        // Update the window
        App.Display();
    }

    return EXIT_SUCCESS;
}

```

But instead of just setting the position I want to use Sprite.Move() and gradually move the sprite from one position to another. The question is how? Later I plan on adding a node system into each map so I can use Dijkstra's algorithm, but I'll still need this for moving between nodes.

# Answer
> 3 votes
The easiest way I see is to store velocity, when user clicks on screen. This velocity will define, which direction sprite should move and by what speed (so for example direction * spriteSpeed).

Direction can be obtained by simple vector math: `(TargetPosition - CurrentPosition).normalize()`

And then you will update sprites position each frame. So just add to while loop: `CurrentPosition += Velocity * ElapsedTimeSinceLastFrame`. ElapsedTimeSinceLastFrame is just for sure - if you don't use time and run this application on faster machine (while loop will be executed faster), your sprite will move of course faster.

And finally - you should control, if sprite is at the end of its journey. So control, if `(Velocity * ElapsedTime).length()` is not more than `(TargetPos - CurrentPos).length()`. If it is, move sprite to target position and set velocity to zero (or set some flag not to update sprite position till next mouse click).

---
Tags: c++, sprites, input, mouse, sfml
---


# Question
Title: XNA C# How to draw fonts in different color
I'm doing a simple chat system with XNA C#. It is a chatbox that contains 5 lines of chat typed by the users. Something like a MMORPG chatting system.

```
[User1name] says: Hi
[User2name] says: Hello
[User1name] says: What are you doing?
[User2name] says: I'm fine
[System] The time is now 1:03AM.

```

When the user pressed 'ENTER', the text he entered will be added inside an ArrayList

```
chatList.Add(s);

```

For displaying the text he entered, I used

```
for (int i = 0; i < chatList.Count(); i++)
{
spriteBatch.DrawString(font, chatList[i], new Vector2(40, arr1[i]), Color.Yellow);
}

```

> ```
> *arr1[i] contains 5 y-axis points to print my 5 line of chats in the chatbox
>
> ```

**Question1: What if I have another type of message which will be added into ChatList (something like a system message). I need the System Message to be printed out in red color.**

And if the user keeps on chatting, the chat box will be updated according: (MAX 5 LINES) The newest chat will be shown below, and the oldest one will be deleted if they reached the max 5 lines.

```
[User2name] says: Hello
[User1name] says: What are you doing?
[User2name] says: I'm fine
[System] The time is now 1:03AM.
[User1name] says: Ok, great to hear that!

```

I'm having trouble to print each line color according to their msg type. For normal msg, it should be yellow. For system msg, it should be red.

**Question2: And for the next problem, I need the chat texts to be white color, while the names of the user is yellow (like warcraft3 chat system). How do I do that?**

I have a hard time thinking of a solution for these to work. Advise needed.

# Answer
You can use a class 'ChatMessage' that contains a property 'MessageType'. It can check what type it is and draw itself in the right color. Something like this (unoptimized):

```
public class ChatMessage
{
    public Dictionary<string, Color> TypeColors
    {
        get;
        protected set;
    }

    private string MessageType;
    private string Text;
    private string UserName;
    private SpriteFont Font;

    public ChatMessage(string userName, string text, string type, SpriteFont font)// Gets all the data necessary
    {
        MessageType = type;
        Text = text;
        UserName = userName;
        Font = font;

        InitTypeColors();
    }

    protected void InitTypeColors()// Set these to what ever you want and add more
    {
        TypeColors = new Dictionary<string, Color>();
        TypeColors["normal"] = Color.Yellow;
        TypeColors["message"] = Color.White;
        TypeColors["system"] = Color.Red;
    }

    public void Draw (SpriteBatch batch, Vector2 position)
    {
        batch.DrawString(Font, UserName, position, TypeColors[MessageType]);// Draws the user name in one color
        batch.DrawString(Font, Text, new Vector2(position.X + Font.MeasureString(UserName).X + 15, position.Y), TypeColors["message"]);// then the message, 15 pixels to the right, in the color associated with that type
    }
}

```

Then in your game use a `List<ChatMessage>` for your chatList. In your Game Draw method replace this:

```
spriteBatch.DrawString(font, chatList[i], new Vector2(40, arr1[i]), Color.Yellow);

```

with this :

```
chatList[i].Draw(spriteBatch, new Vector2(40, arr1[i]));

```

That should work, but you may want to optimize the code a bit.
> -1 votes

# Answer
For a flexible system, you'll want to make new classes to represent a line of text that can contain multiple sections of text with a given colour.

```
public class TextSection
{
    String text;
    Color color;
    Font font;
    public void Draw(SpriteBatch spriteBatch, Vector2 location)
    {
        spriteBatch.DrawString(font, text, location, color);
    }
    public Vector2 GetMeasurements()
    {
        return font.MeasureString(text);
    }
}

public class TextLine
{
    List<TextSection> sections;
    public void Draw(SpriteBatch spriteBatch)
    {
        int x = 0;
        int y = 0;    // Determine this however you want, pass it in maybe?

        foreach(var textSection in sections)
        {
            textSection.Draw(spriteBatch, new Vector2(x, y));
            Vector2 textSize = textSection.GetMeasurements();
            x += textSize.X;
        }
    }
}

```

Note, the above may not compile, take it with a grain of salt. The concept is there though. Each section of text on a line will be drawn it its own colour, and each section is pushed over by the size of the previous section(s).

Edit: As a general tip, break problems up into small chunks that make sense to you. If the big picture doesn't make sense right away, start working on some of the small helper methods and classes that you know will be used, and work up from there. The pieces usually fall into place.
> 9 votes

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


# Question
Title: How can I disable/dim the screen when I click the pause button?
I am working in an android game using cocos2d. I want to dim the background screen when I click the pause button.

How can I do this ?

# Answer
I achieved this effect by using a specified pixel from a texture I was already using in this way:

```
  CCSprite *layer = [CCSprite spriteWithTexture:TEX_INTERFACE.textureAtlas.texture rect:CGRectMake(87, 143, 1, 1)];
  CGSize size = [[CCDirector sharedDirector] winSize];
  layer.scaleX = size.width;
  layer.scaleY = size.height;
  layer.position = ccp(size.width/2, size.height/2);
  layer.opacity = 0;
  [game addChild:layer z:100 tag:TAG_PAUSE_OVERLAY];
  id action = [CCEaseOut actionWithAction:[CCActionTween actionWithDuration:0.1 key:@"opacity" from:0 to:220] rate:2];
  [layer runAction:action];

```

Mind: this is Cocos2D for Objective-C, not for Android but translating it is straightforward
> 1 votes

# Answer
I would need a bit of code to give a more detailed answer, but you probably want to use glClearColor when you "click the pause button".
> -1 votes

---
Tags: opengl, android, cocos2d
---


# Question
Title: Smooth Camera Rotation around 90 degrees
I'm developing a third person 3D platformer in XNA. My problem is when I try to rotate the camera around the player.
I would like to rotate (and animate) the camera 90 degrees around the player. So the camera should rotate until it has reached 90 degrees from the starting position.
I cannot figure out how to keep track of the rotation, and when the rotation has made the full 90 degrees.

Currently my cameras update:

```
public void Update(Vector3 playerPosition) {
    if (rotateCamera) {
        position = Vector3.Transform(position - playerPosition, Matrix.CreateRotationY(0.1f)) + playerPosition;
    }
    this.viewMatrix = Matrix.CreateLookAt(position, playerPosition, Vector3.Up);
}

```

The initial position of the camera is set in the constructor.
The "rotateCamera" bool is set on keypress.

Thanks for the help in advance.

Cheers.

# Answer
You can have a variable in your class that store the rotation angle that your camera have already done. In your code it seems you rotate around Y by 0.1 each frame. So you set the initial value of the variable to 0 and increment it by 0.1 each time you rotate. You check the value before rotating, if it's under 90 you continue, else you stop to rotate. The value 0.1 is in radians, wether you convert it back in degrees and compared with 90, or you can keep it in radians and compared with rad(90).
> 3 votes

---
Tags: 3d, xna-4.0, camera
---


# Question
Title: How to make and render a simple game just with 3d max?
I want to make a simple EXE file, where there is one object in the scene and the user can rotate that object by using arrow keys (or mouse). Is there any way in which I don't have to use a game engine and do it only using 3dsmax script? Cause there is a special renderer I want to use, which is V-Ray a kind of renderer which provides 3D images for 3D glasses. I am not good at making games and engines so I want to know if I can do it only with 3dsmax scripts?

# Answer
> 3 votes
There is no way to do this. MaxScript is only an exposure of internal Max functionalities. If there is a something you cannot do with Max or with its sdk, you can't do it.

Also Maxscript is not compiled so you can't generate exe's. The SDK does but does not do what you want :(

# Answer
> 0 votes
You might want to have a look at Blender (www.blender.org), which has a complete game engine included. You should be able to produce something very close to what you want.

Also, V-Ray is a raytracer, no? I don't think it's suitable for a real-time application like you have in mind.

Last alternative could be QuicktimeVR, though I don't know if that works with 3D glasses.

---
Tags: scripting, 3dsmax
---


# Question
Title: How to evaluate a user against optimal performance?
I have trouble coming up with a system of assigning a rating to player's performance. Well, technically there is is a trivial rating system, but I don't like it because it would mean assigning negative scores, which I think most players will be discouraged by.

The problem is that I only know the ideal number of actions to get the desired result. The worst case is infinite number of actions, so there is no obvious scale. The trivial way I referred to above is to take **score = (#optimal-moves - #players-moves)**, with ideal score being zero. However, psychologically people like big numbers. No one wants to win by getting a mark of 0. I wonder if there is a system that someone else has come up with before to solve this problem?

Essentially I wish to score the players based on:

1. How close they've come to the ideal solution.
2. Different challenges will have different optimal number of actions, so the scoring system needs to take that into account, e.g. Challenge 1 -\> max 10 points, Challenge 2 -\> max 20 points.
3. I don't mind giving the players negative scores if they've performed exceptionally badly, I just don't want all scores to be \<=0

# Answer
> 4 votes
Take the reciprocal of a growing value to get a value that shrinks instead, and vice versa. Multiply that up to get the large numbers you want.

score = 10 / (#players-moves - #optimal-moves + 1)

A perfect win scores 10. 1 excess move scores 5, 2 excess moves scores 3.33, etc.

To get progression that *seems* more linear you can multiply moves difference by some small factor. For example, using `10 / [(#players - #optimal) * 0.1) + 1]`, perfect win scores 10, 1 excess move scored 9.1, 2 excess moves 8.3, etc.

# Answer
> 2 votes
Benchmarking might also help you.

Benchmarking people mind you, it helps if your know your mean, have various people play the game see what kind of score they get when playing the game, also chart their progress. (first time they play, second time, etc)

For example for me one of the lower benchmarks is the wife which I have to force to play, so I probably won't get a worse kind of player (unless minor), then I chart her progression and make sure there's some candy along the way even for the worse players.

A real gammers chart is very different, say your max score was 10, a bad player will start at 2 and progress up to say 6, there are a lot of steps and a continuos reason to progress, but if a gammers chart starts at 9, getting him up to 9.5 might not be so rewarding, so in this case I wouldn't use a linear scoring for example....

---
Tags: game-design, algorithm, game-mechanics, leaderboards
---


# Question
Title: How can player actions be "judged morally" in a measurable way?
While measuring the player "skills" and "effort" is usually easy, adding some "less objective" statistics can give the player supplementary goals, especially in a MUD/RPG context.

What I mean is that apart from counting how many orcs were killed, and gems collected, it would be interesting to have something along the line of the traditional Good/Evil, Lawful/Chaotic ranking of paper-based RPG, to add "dimension" to the game.

But computers cannot differentiate good/evil effectively (nor can humans in many cases), and if you have a set of "laws" which are precise enough that you can tell exactly when the player breaks them, then it generally makes more sense to actually prevent them from doing that action in the first place.

One example could be the creation/destruction axis (if players are at all allowed to create/build things), possibly in the form of the general effect of the player actions on "ecology".

So what else is there left that can be effectively measured and would provide a sense of "moral" for the player? The more axis I have to measure, the more goals the player can have, and therefore the longer the game can last. This also gives the players more ways of "differentiating" themselves among hordes of other players of the same "class" and similar "kit".

# Answer
I think this needs to be progressive - you can't instantly judge an action. Take these two examples:

* I could place a steel barrel in the middle of a road; which is technically creation - however it may land up killing the passengers in a car.
* I could go and kill an entire Orc camp; which is technically destruction - however it would bring an end to the raping and pillaging they have been doing.

Your actions should be both immediate and outcome-based. You would see an immediate increase in "good" because of the barrel you have placed; however at such a point it causes a disaster you would see a larger change toward "evil".

This means that you would need to be able to store 'interaction attributes' with everything in the game world. "The player has interacted with this barrel", "the barrel has resulted in evil", "the player is evil." **\- or -** "The Orc has interacted with this village", "the Orc is evil", "the player has killed the Orc", "the player is good."

At the end of the day you need a set of basic outcomes that ultimately determine the good/evil of an action: create vs. destroy, heal vs. damage, assist vs. hinder etc.

When correctly designed this would be entirely emergent behaviour; for example if, during the second play, the player went and killed the Orcs before they had committed any evil it would count as evil - you can't kill someone on the premise that they will do evil: some other condition might arise that would prevent them from performing said evil.

Remember that "good" and "evil" are relational to your upbringing/faction/religion - therefore as an Orc partaking in their raids would be counted as "good" - however you could spin this as "Orcs tend toward evil, as such your standing is higher as an evil entity."
> 10 votes

---
Tags: ranking
---


# Question
Title: XNA Skinned Animated Mesh Rendering Exported from Maya
I am working on translating an old RTS game engine I wrote from DirectX9 to XNA. My old models didn't have animation & are an old format, so I'm trying with an FBX file. I temporarily "borrowed" a model from League of Legends just to test if my rendering is working correctly.

I imported the mesh/bones/skin/animation into Maya 2012 using an "unnamed" 3rd-party import tool. (obviously I'll have to get legit models later, but I just want to test if my programming is correct). Everything looks correct in maya and it renders the animations flawlessly.

I exported everything into a single FBX file (with only a single animation). I then tried to load this model using the example at the following site: http://create.msdn.com/en-US/education/catalog/sample/skinned\_model

With my exported FBX, the animation looks correct for most of the frames, however at random times it screws up for a split second. Basically, the body/arms/head will look right, but the leg/foot will shoot out to a random point in space for a second & then go back to the normal position. The original FBX from the sample looks correct in my program.

It seems odd that my model was imported into maya wrong, since it displays fine in Maya. So, I'm thinking either I'm exporting it wrong, or the sample code is bad & the model from the sample caters to the samples bad code.

I'm new to 3D programming & maya, so chances are I'm doing something wrong in the export. I'm using mostly the defaults, but I've tried all 3 interpolation modes (quaternion, euler, resample).

# Answer
I suggest you use kw X-Port for 3DS Max, as it's specifically made for use with XNA.
> 2 votes

---
Tags: xna, maya
---


title: Merging adjacent cubes into large ones

text:
# Question
Title: Merging adjacent cubes into large ones
I am currently working on a basic minecraft like game. I have a list of coordinates using which i render instances of a cube model. To optimize my rendering, i need to merge similar adjacent cubes into a single largest possible cube so that the total number of polygons that needs to be rendered is reduced

Any suggestions?

# Answer
> 2 votes
Assuming you already know which cubes are adjacent, you can:

1. Throw all 12 (if they have shared vertices) or 16 (if not) vertices into a collection
2. Find the extents and center of the collection
3. Remove the original cubes from your index list
4. Calculate the maximum dimension from the extents you already found
5. Add 8 new vertices to define the new cube centered at the center you already calculated
6. Add the indices connecting those vertices to your index lists

If you're looking for coplanar faces that can be removed to create rectangular prisms (to remove hidden faces), just zip through your index list and find pairs of triangles that use the same vertices, though probably in opposite order (clockwise vs counter clockwise), and remove both triangles assuming they face each other.

@BjornWesen's comment is correct in that this can be overkill unless your mesh is pretty complex.

However, removing unnecessary faces potentially saves a lot of time in the pixel shader. Any time you draw multiple primitives in back-to-front order (typically a function of your camera location relative to the mesh), each primitive must be rendered, then overwritten or discarded (based on depth comparison) by any closer primitives when their turn comes. Obviously this takes unnecessary time which could be used for other things.

In short, if you feel that any performance issues you're seeing may be due to overdraw, I think this is a good place to start looking. (The profiler is your friend! Don't assume you know where your bottleneck is unless it's written in 40 foot (12.2 meter) flaming letters in your mind.

---
Tags: architecture, minecraft-modding, voxels
---


title: Collision with half of a semi-circle

text:
# Question
Title: Collision with half of a semi-circle
I am trying to port a game I made using Flash/AS3, to the Windows Phone using C#/XNA 4.0. You can see it here: http://goo.gl/gzFiE

In the flash version I used a pixel-perfect collision between meteors (it's a rectangle, and usually rotated) that spawn outside the screen, and move towards the center, and a shield in the center of the screen(which is half of a semi-circle, also rotated by the player), which made the meteor bounce back in the opposite direction it came from, when they collided.

My goal now is to make the meteors bounce in different angles, depending on the position it collides with the shield (much like Pong, hitting the borders causes a change in the ball's angle).

So, these are the 3 options I thought of:

1. Pixel-perfect collision (Microsoft has a sample) , but then I wouldn't know how to change the meteor angle after the collision
2. 3 BoundingCircle's to represent the half semi-circle shield, but then I would have to somehow move them as I rotate the shield.
3. Farseer Physics. I could make a shape composed of 3 lines, and use that as the collision object for the shield.

Is there any other way besides those? Which would be the best way to do it(it's aimed towards mobile devices, so pixel-perfect is probably not a good choice)? Most of the time there's always a easier/better way than what we think of...

# Answer
Your approach is way to complicated. You don't need pixel perfect collision detection or a physics-engine. Actually you just need the **radius** of your shield, the **direction normal** of your shield (a vector pointing from the world center to the middle of your arc) and the delta of the incoming vector to your world center.

Let's declare some stuff:

* `Rs` is the radius of your shield
* `thickness` thickness of the shield
* `Re` is the radius of the earth
* `Vs` is the normal of your shield (eg. where the shield is pointing at, viewing from the center of "earth")
* `Vm` is the vector from the earth center to the meteor.

You'll need just some dot-products to solve your problem. In pseudo code:

```
// get distance from meteor to earth and normalize Vm
distance = normalize(Vm)

if(distance < Re){
    // meteor hit the earth :(
    return;
}

// check if meteor is in the range of the shield
if(distance < Rs + thickness && distance > Rs - thickness){
    // the dot product will give an indication whether the shield
    // faces the meteor or not
    facing = dotProduct(Vs, Vm)

    // angle will be the angle of impact (usually in radians)
    angle = acos(facing)

    // facing will be greater than zero when the shield faces the meteor
    if(facing > 0 && angle < PI / 4){
        // deflect the meteor here
        deflectMeteor()
    }
}

```

**Update**:

To actually perform the deflection of the meteor, you can simply "reflect" the meteor normal with the shield normal (using the variables used above, make sure `Vm` is normalized):

```
newDirection = (2 * facing * Vm) - Vs;

```
> 1 votes

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


title: Almost working 2D Collisions

text:
# Question
Title: Almost working 2D Collisions
I'm terribly sorry I'm asking this question YET AGAIN, but I can almost guarantee that this will be the last time I'll have to ask.

I'm currently on the verge of FINALLY getting these collisions to work for my game, made with libGDX in Java. My collisions use the same method as (and are basically copied and modified code from) the XNA Platformer example (here) where the direction of the collision is based on the rectangle where two objects are overlapping.

The collisions themselves almost work perfectly, but for some reason, holding down/up and left and colliding with the floor/ceiling while doing so doesn't seem to work well. I'm not at all sure why.

Instead of vaguely giving my problem and snippets of code, I've decided to instead provide a binary and the source of the game I have so far so you can see for yourself what my problem is. Link. (Note: make sure you unzip everything into a folder somewhere or it will not work)

You'll find the collision code in the method workingCollisions() in Link.java. Please excuse the messy code and terrible graphics as this whole thing is in pre-pre-alpha.

If anyone is kind enough and helps me out here, you are the best person ever. I'm completely desperate; I've been trying this on and off for months and I just can't get it to work. I cannot thank you enough.

# Answer
I'm not going to go through your code, but one thought is that, if you're "holding down" navigation buttons and moving relatively quickly, your bounding box may skip from one side of the object you're colliding with to the other in a single step.

One way to avoid this is to calculate a ray from the original position to the new one, and check that for intersections with the other objects in your scene. Since you're checking the path the object takes instead of just it's new position, it'll catch anything that should have triggered a collision.
> 1 votes

---
Tags: 2d, java, collision-detection, libgdx
---


title: Static "LoD" hack opinions

text:
# Question
Title: Static "LoD" hack opinions
I've been playing with implementing dynamic level of detail for rendering a very large mesh in XNA.

It occurred to me that (duh) the whole point of this is to generate small triangles close to the camera, and larger ones far away. Given that, rather than constantly modifying or swapping index buffers based on a feature's rendered size or distance from the camera, it would be a lot easier (and potentially quite a bit faster), to render a single "fan" or flat wedge/frustum-shaped planar mesh that is tessellated into small triangles close to the near or small end of the frustum and larger ones at the far end, sort of like this (overhead view)

(Pardon the gap in the middle - I drew one side and mirrored it) The triangle sizes are chosen so that all are approximately the same size when projected.

Then, that mesh would be transformed to track the camera so that the Z axis (center vertical in this image) is always aligned with the view direction projected into the XZ plane. The vertex shader would then read terrain heights from a height texture and adjust the Y coordinate of the mesh to match a height field that defines the terrain.

This eliminates the need for culling (since the mesh is generated to match the viewport dimensions) and the need to modify the index and/or vertex buffers when drawing the terrain.

Obviously this doesn't address terrain with overhangs, etc, but that could be handled to a certain extent by including a second mesh that defines a sort of "ceiling" via a different texture.

The other LoD schemes I've seen aren't particularly difficult to implement and, in some cases, are a lot more flexible, but this seemed like a decent quick-and-dirty way to handle height map-based terrain without getting into geometry manipulation.

Has anyone tried this? Opinions?

# Answer
> 2 votes
One issue you'll run into is that the mesh is camera-relative, so you'll get a "swimming" effect as you move and pan the camera around, as the topology of the mesh sweeps over the underlying heightfield data. This can be a distracting visual artifact. However if you can minimize that, it could be a good approach. It's reminiscent of what CryEngine 2 did for water, as described in this article.

---
Tags: terrain, level-of-detail
---


# Question
Title: How does this snippet of code create a ray direction vector?
In the Minecraft source code, this code is used to create a direction vector for a ray from pitch and yaw:'

```
float f1 = MathHelper.cos(-rotationYaw * 0.01745329F - 3.141593F);
float f3 = MathHelper.sin(-rotationYaw * 0.01745329F - 3.141593F);
float f5 = -MathHelper.cos(-rotationPitch * 0.01745329F);
float f7 = MathHelper.sin(-rotationPitch * 0.01745329F);
return Vec3D.createVector(f3 * f5, f7, f1 * f5);

```

I was wondering how it worked, and what is the constant `0.01745329F`?

# Answer
> 4 votes
It works by using spherical coordinates. In particular see the section about converting to Cartesian coordinates. The Wikipedia article uses a slightly different convention for the definitions of the angles than your code, resulting in some sin / cos factors being swapped, but it's the same idea.

# Answer
> 1 votes
0.01745329F is the conversion rate between degrees and radians. Degrees are easier to understand but most mathematical functions need radians so this is a common conversion to perform. The -pi part just rotates the value further.

I'll let someone else address the trigonometry part. :)

---
Tags: opengl, minecraft-modding, lwjgl, raycasting
---