# Question
Title: Sparse Voxel Octrees which parts on GPU or CPU?
I'm currently doing research into building my own voxel engine and found a lot of articles mentioning SVOs as the best mechanism. I just wanted to know that I understood the algorithm correctly, before I implement it.

I read my data into an octree on the CPU, maintained through standard node-\>children constructs. With that I can do collision detection, frustum culling, etc.

For rendering the octree is then written to a texture and processed by vertex and pixel shader to display the actual voxel directly on the GPU. Although I guess I could walk the octree on the CPU, and instead of building the texture, draw the individual voxels through instancing although probably a bit slower.

Is that correct or did I misunderstand?

# Answer
Cyril Crassin just published his thesis on Gigavoxels: http://maverick.inria.fr/Publications/2011/Cra11/

I'm sure it's going to answer lots of your questions.

Sorry for not being able to help you myself, I thought pointing you to this reference would be useful though.
> 2 votes

# Answer
More recent work by Laine (Nvidia) and source code here: http://research.nvidia.com/publication/efficient-sparse-voxel-octrees-analysis-extensions-and-implementation
> 0 votes

---
Tags: architecture, algorithm, voxels, gpu, octree
---


# Question
Title: How do I implement group formations in a 3D RTS?
I managed to get pathfinding work for a single unit, and I managed to avoid agent-agent collision, but now I need to be able to send a group of agents to some location.

This is my set-up so far:

* Waypoint pathfinding
* The minimum distance between two nodes is a little bigger than the biggest bounding sphere radius allowed for an agent.
* Agents avoid collisions with other agents by doing some steering behaviour I based on clearpath

So now I need to send my agents somewhere in group. I have read some posts saying that some way to do it is to create a group leader and give the other units offsets to his position.

But then the problem is, what if the group formation cannot be achieved? e.g. you want to form a rectangle, but at the target position there is a structure nearby which prevents you from creating a rectangle setup.

# Answer
There is actually a pretty nice article about this over at Gamasutra. And covers topics like formations and resolving collisions:

And another article from them on the same topic, which is a bit shorter but has more pseudo code examples:

Finally, a nifty thing to think about when implementing your system is the idea of a "Flow Field" Supreme Commander 2 used this; And it's based on Washington State University's Crowd Flows research.
> 14 votes

# Answer
I think you can have a invisible "flock entity" that is the boss of the formation, and make so the other creatures position himself relative to this entity. If this entity can rotate, then the relative position will rotate too.

...oopos.. you are already doing that.

What about this:

Why you cant calculate new positions for the entities colliding? I don't need to be fancy, maybe just dram a line from the desired original point, and the leader, and move the desired position to the middle of this line. Test again for collision.
> 2 votes

---
Tags: path-finding, rts
---


title: DirectX Flicker

text:
# Question
Title: DirectX Flicker
I'm using DirectX 9 via SlimDX (C#). My screen flickers a lot during rendering. I dug a little deeper and see that the surface is being cleared early. Here's an example: http://pastebin.com/HXyAUwLp.

I'm using Windows XP on a low-end card. I've seen it act correctly on this computer, but I obviously have something wrong with my drawing routines or something and have reached the end of my resources.

The draw method starts at line 135 in that paste. To make the action more apparent, make sure the code in one or more of the preprocessor directives executes.

This shows that the buffer is being cleared before Present. I think things are supposed to work such that one scene to be visible until after Present, after which, the next scene is present. The user should never see the `Clear`ed surface.

Let me know if you need more information.

# Answer
The answer doesn't have to do with `DoubleBuffered`, but rather with the default behaviour of `System.Windows.Forms.Form`s, which paint their own background when they need to paint. The answer is to add an override in the form:

```
protected override void OnPaintBackground(PaintEventArgs e)
{ }

```

Which fixes the problem.
> 4 votes

# Answer
Something to do with the .net controls not having doublebuffering enabled by default and the default redraw functionality.. There should be some ways to go around that.

Using slimdx's RenderForm instead of .net's Form works as you yourself noticed in above commentary.
> 1 votes

---
Tags: c#, directx, directx9, slimdx
---


# Question
Title: As3 Character movement in diffrent directions with labels?
I hope you can help me with the following problem:

I made a character in Illustrator. The player sees the character from above. When you press the left arrow key `character.gotoAndStop('left');` the character moves to the left. (Same goes for the right direction with label 'right' When you release the left or right arrow key (upKey) the character goes back to the label 'up'.

I'm trying to accomplish the following: When the character is facing down ('down'). the left key should go to the ("facingdownleft") label and on release back to the label ('down'). (Same for the right direction)

```
stage.addEventListener(KeyboardEvent.KEY_DOWN, downKey);
function downKey(event:KeyboardEvent)
{
 if(event.keyCode==39){
 isRight=true;
 character.gotoAndStop('right');}
 if(event.keyCode==37){
 isLeft=true;
 character.gotoAndStop('left');}
 if(event.keyCode==38){
 isUp=true;
 character.gotoAndStop('up');
 }
 if(event.keyCode==40){
 isDown=true;
 facingdown=true;
 character.gotoAndPlay('down');}
}

if( facingdown == true && isLeft == true)
{
 character.gotoAndPlay('downleft');
}

stage.addEventListener(KeyboardEvent.KEY_UP, upKey);
function upKey(event:KeyboardEvent){
 if(event.keyCode==39){
 isRight=false;
 character.gotoAndPlay('up')}
 if(event.keyCode==37){
 isLeft=false
 character.gotoAndPlay('up')}
 if(event.keyCode==38){
 isUp=false;}
 if(event.keyCode==40){
 isDown=false}
 }

```

I made a boolean for facingdown and an if statement for downleft:

```
  if( facingdown == true && isLeft == true)
    {
     character.gotoAndPlay('downleft');
    }

```

But before I make numerous amounts of if statements again, I would like to know if I'm on the right track and if you can help me accomplish this? Thank you so much in advance and feel free to ask questions.

# Answer
You could try something like the following code:

```
stage.addEventListener(KeyboardEvent.KEY_DOWN, downKey);
function downKey(event:KeyboardEvent)
{
    if( event.keyCode == Keyboard.UP )
    {
        isUp=true;
        character.gotoAndStop('up'); // up (animated?)
    }
    else if( event.keyCode == Keyboard.DOWN )
    {
        isUp=false;
        character.gotoAndStop('down'); // down (animated?)
    }

    else if( event.keyCode == Keyboard.LEFT )
    {
        if( isUp )
            character.gotoAndStop('left'); // (up)left
        else
            character.gotoAndStop('downleft'); // downleft
    }
    else if( event.keyCode == Keyboard.RIGHT )
    {
        if( isUp )
            character.gotoAndStop('right'); // (up)right
        else
            character.gotoAndStop('downright'); // downright
    }
}

stage.addEventListener(KeyboardEvent.KEY_UP, upKey);
function upKey(event:KeyboardEvent)
{
    if( event.keyCode == Keyboard.RIGHT || event.keyCode == Keyboard.LEFT )
    {
        if( isUp )
            character.gotoAndStop('up'); // up (still?)
        else
            character.gotoAndStop('down'); // down (still?)
    }
}

```

I tried to do something as close as possible to your original code.

But it's yet a very simple solution that doesn't handle multi-key pressed at the same time etc... And obviously you should consider different keyframes for immobile and animated "up" and "down". I supposed that your bools were globals so I reduced it to one because it doesn't seems useful in this portion of code, but indeed you can re-introduce the other bools if needed elsewhere.
> 2 votes

---
Tags: flash, actionscript-3, movement, character
---


title: Gamepad API For Multiple Pad Types

text:
# Question
Title: Gamepad API For Multiple Pad Types
I'm a C++ newbie working on adding gamepad support to Moai as a learning exercise and because I'd like to be able to use a gamepad with it. I'm starting by implementing the Xbox 360 gamepad via XInput and that's going pretty well. Eventually I'd also like to support the PS3 gamepad.

This has got me thinking: the 360 and PS3 pads are mostly similar. They have the same number of buttons in more or less the same places that do more or less the same things (e.g., the right trigger on the 360 pad is an analog trigger, so is the R2 trigger on the PS3 pad). From the standpoint of creating an API to support both pads the main difference is the labeling applied to each button.

The PS3 square button is in the same place as the 360 X button, triangle matches Y, circle matches B, and X matches A. Some comparison images:

When creating the API to work with gamepads I see a couple ways to approach it:

1. Use the 360 naming conventions exclusively.
2. Use the PS3 naming conventions exclusively.
3. Come up with something in between.

I'd like to go with option #3 and could devise my own solution easy enough but don't want to reinvent the wheel unnecessarily.

Is there some standard naming convention used for a gamepad API that supports both 360 and PS3 (and possibly other, similar) gamepads? Is this even really an issue -- should I just create an API, document it and call it good?

# Answer
> 0 votes
What I ended up doing was rolling my own API and documenting it well. In naming buttons I tried to make them both descriptive and controller agnostic.

For example, on the PS3 pad there is a button called R1 that is on the right shoulder. This corresponds with the 360 pad's Right Bumper button. In my API this button is referred to as "Right Shoulder". Where the PS3 has R2, the 360 has Right Trigger and I have Right Trigger as these buttons are analog triggers in both cases. For the face buttons I started where the X/Square buttons (360/PS3) are and counted moving clockwise ending up with Face 1, Face 2, Face 3, Face 4.

---
Tags: c++, gamepad, xbox-controller
---


# Question
Title: Can someone explain this Pulsate code to me
```
// Pulsate the size of the selected menu entry.
double time = gametime.TotalGameTime.TotalSeconds;
float pulsate = (float)Math.Sin(time * 6) + 1;
scale = new Scale(1 + pulsate * 0.05f,1 + pulsate * 0.05f);

```

I grabbed it from the XNA GameState sample and just curious.

# Answer
Looks like it's using a sine wave to change the scale of an object. Sine ranges from -1 to +1, so adding one to the `pulsate` variable puts the range at `0` to `2`. Then adding 1 to `(pulstae * 0.05f)` Puts the range at 1 to 1.10.

As the name implies, this would likely give the appearance of pulsating.

Multiplying the time by 6 compresses the sine wave on the x-axis. Making the pulsing happen faster. If you were to multiply it by a smaller number (or not multiply it by anything) you could slow the pulsing.
> 5 votes

---
Tags: xna, mathematics, xna-4.0
---


# Question
Title: Export information to a custom file type from Air
So I have an engine (air application) that basically (for now) is loading some windows on the screen/stage, and you can drag them around. And later on, I'll be able to add other objects onto the stage.

How would I export any kind of information (like co-ordinates or sizes of windows) out of my application to an external custom file. And then I would use that file to reload a previous project if I were to re-load the engine.

I'm working in AS3/Air and in FlashDevelop.

Thanks for the help and time. If anymore information is needed please let me know.

Cheers.

# Answer
since you're creating the windows and have the drag / sizing information do you not already have the x,y, width, height information?

for saving files, AIR will allow you to do this without user prompting (what it sounds like your after) through the flash.filesystem. The AS3 should be something like the following (not tested)

```
import flash.filesystem.*;
import flash.events.Event;

private function saveFile():void{
    var file:File = File.desktopDirectory; // change to suit your needs
    file= file.resolvePath("example.txt");
    var fileStream:FileStream = new FileStream();
    fileStream.openAsync(file, FileMode.WRITE);
    fileStream.writeUTFBytes("Saved content!!!"); // change this for the data you want
    fileStream.addEventListener(Event.CLOSE, fileClosed);
    fileStream.close();
}

function fileClosed(event:Event):void {
   trace("closed file event!");
}

```

Hope that helps ;-)
> 1 votes

---
Tags: actionscript-3, file, flashdevelop
---


# Question
Title: How do I manage the visibility of enemy spawn locations in a long scrolling shooter?
How do I handle the situation of an enemy spawn place being visible on a screen in a scrolling shooter? The tutorials I have seen are about setting all the enemies on a whole map only. But it is not appropriate if the map is huge.

# Answer
If I am interpreting your question correctly, you do not want your enemies to have already spawned because your “world” is so large. As such, you want them to spawn only when the player is approaching the spawn point.

If your scroller moves at a constant pace, then you could spawn your enemies after a specific time interval. If your scroller does not move at a constant pace, or if it is multi-directional, then you need something to trigger spawning. Checking the distance between the player and the spawn point would work, assuming you don’t have thousands of spawn points. Or if they cross over a “trigger” object in your world, that could be used to spawn your enemies.

There are many approaches you could take. Depending on the number of enemies and the size of your world, you could easily have your enemies already spawned, but inactive. Generally, just having them in existence is not nearly as CPU intensive as updating them within your game loop, but there are exceptions.

So, you can have them already spawned, but they don’t come to life until certain conditions are met, such as the distance between the player and the enemy, or if the player touches or shoots the enemy, etc.

Since you tagged your question with Cocos2d, take a look at this tutorial:

http://www.packtpub.com/article/cocos2d-iphone-surfing-through-scenes

It will pretty much guide you through the entire process of creating a game from start to finish. The game is simple, but you will learn the basics and some handy techniques.

Also look here for many helpful tutorials.

http://www.raywenderlich.com/tutorials

I hope this helps.
> 2 votes

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


# Question
Title: How to expose game data in the game without a singelton?
I'm quite new to cocos2d and games programming, and am currently I am writing a game that is currently in Prototype stage. Everything is going okay, but I've realized a potentially big problem and I am not sure how to solve it.

I am using a singelton to store a bunch of arrays for everything, a global list of planets, a global list of troops, a global list of products, etc. And only now I'm realizing that all of this will be in memory and this is the wrong way to do it.

I am not storing files or anything on the disk just yet, with exception to a save/load state, which is a capture of everything.

My game makes use of a map which allows you to select a planet, then it will give you a breakdown of that planets troops and resources,

Lets use this scenario:

My game has 20 planets. On which you can have 20 troops.

Straight away that's an array of 400!

This does not add the NPC, which is another 10.

So, 20x10 = 200

So, now we have 600 all in arrays inside a Singelton.

This is obviously very bad, and very wrong. Especially as the game scales in the amount of data.

But I need to expose pretty much everything, especially on the map page, and I am not sure how else to do it.

I've been told that I can use a controller for the map page which has the information I need for each planet, and other controllers for other items I require global display for.

I've also thought about storing each planet's data in a save file, using `initWithCoder` however there could be a boatload of files on the user's device?

I really don't want to use a database, mainly because I would need to translate NSObjects and non-NSObjects like CGRects and CGPoints and Colors into/from SQL.

I am open to other ideas on how to store and read game data to prevent using a singelton to store everything, everywhere.

Thanks for your time.

# Answer
> 3 votes
You seem to be worried about how to store your data when you should be concerned with the design of both your data, and how you expose it. Storing data in files or using a database is not a solution to design.

Instead of a singleton, pass the data by reference into functions. It may make sense to use a hierarchy of data types, such as a planet type that contains the troops, and a universe that contains the planets.

# Answer
> 1 votes
According to the description of your game i think you should use core data which is not so hard once to start developing your game with core data to manage all of your data.

For thinks like CGRect or CGpoint you can create some functions in the class of NSManagedObjects that will fetch and store these values at run time so that you dont have to do it every time you need them, something like this

```
- (void)setRect:(CGRect)rect
{
    self.x = [NSNumber numberWithFloat:rect.origin.x];
    // And so on.....
}

- (CGRect)getRect
{
    CGRect rect;
    rect.origin.x = [self.x floatValue];
    // And so on......
    return rect;
}

```

# Answer
> 0 votes
An approach that I used was to create property lists that defined the initial state of each planet, and loaded them into dictionaries as I needed them. Assuming the player could be at one planet at a time, you would only have one dictionary to contend with at any given time, which could be accessed via your singleton, if you wanted to use a singleton, or just have the dictionary as part of your games main controller. If the status of the planet is changed and needs to be stored, then you just save the dictionary back to a plist, outside your bundle of course, and reload it if the player returns to that planet.

I don’t know how much data you are referring to, but this approach could certainly work and is very easy to implement.

---
Tags: cocos2d, design-patterns, memory-efficiency
---


# Question
Title: Create an infinite scroll using CCParallaxNode in Cocos2D-X
I'm trying to create an infinite scroll using two images in a CCParallaxNode, making one move to the end of the scroll when it gets off the screen. I have tried several implementations but none has worked. The method setPosition is not available for the sprites once they have been added to the parallaxnode, and the array where the offset positions are stored is not documented so I don't know how to handle it.

Given that you cannot add the same child twice because the program crashes, I have tried to add a new sprite at the end whenever the old one dissappeared from screen. But the getPosition methods for either the sprites or the scroll doesn't seem to give accurate positions to calculate when a sprite is outside the screen. I ended up implementing a loop that added N sprites in a row and then "breaking" the program.

I was using a scaled image for the sprite with 512 width, scaled times 5. Screen size 1024x768

**EDIT FOR CODE SNIPPET**

init

```
voidNode = CCParallaxNode::node();
parta = CCSprite::spriteWithFile("backg.png");
parta->setScaleX( 5 );
parta->setAnchorPoint(ccp(0,0));
parta->setPosition(ccp(0,0));
voidNode->addChild(parta, -1, ccp(0.4f,0.5f), ccp(0,0));

maxscroll = parta->getContentSize().width*5;

CCMoveBy* moveRight = CCMoveBy::actionWithDuration(0.1f,ccp(-600, 0));
CCRepeatForever* repeat =
        CCRepeatForever::actionWithAction((CCSequence *)CCSequence::actions(moveRight,0));
voidNode->runAction(repeat);

```

update

```
// I tried with voidNode->getPos() and voidNode->m_tLastPosition.x too
int newPos = parta->getPosition().x;
if (maxscroll - abs(newPos) - initPos) < level->getContentSize().width*5){

// 1st: parta->setPosition wont work, even when goten as child
// 2nd: I dont now how to access the m_pParallaxArray to alter the offset positions

// 3rd implementation
parta = CCSprite::spriteWithFile("backg.png");
parta->setScaleX( 5 );
parta->setAnchorPoint(ccp(0,0));
voidNode->addChild(parta, -1, ccp(0.4f,0.5f), ccp(maxscroll,0));
maxscroll += parta->getContentSize().width*5;
}

```

# Answer
> 4 votes
You could use something that someone has already created.

http://ak.net84.net/iphone/creating-a-repeating-backgroundinfinite-parallax-effect-in-cocos2d/

It looks like the developer who wrote that ran into some troubles using the out of the box object as well and as such he decided to write a custom solution and subsequently share it with the world!

Good programmers write good code. Great programmers steal great code. (Granted I haven't tested so maybe it's not that great. Who knows!)

# Answer
> 0 votes
Check out this tutorial. It demonstrates what you are asking about.

http://www.raywenderlich.com/3611/how-to-make-a-space-shooter-iphone-game

Actually, I just noticed that you listed Cocos2D-X, which I am unfamiliar with. I don't know if the referenced tutorial will help, but I will leave the reference in case it does.

---
Tags: c++, android, iphone, cocos2d, cocos2d-x
---


# Question
Title: What is the first game I should Develop?
What is the first game every developer should develop?

# Answer
> 5 votes
The Guess the Number game.

# Answer
> 3 votes
One that they finish............

---
Tags: javascript
---


# Question
Title: How do I randomly create and store enemy data for my iPhone game?
In my game you need to protect something from enemies. There can be many on the screen at once. But I don't know how to create the enemies randomly, and how I can save the data to each enemy? Can give good tips or good links to tutorials?

# Answer
In short:

* To generate random numbers use rand()
* To keep track of enemies make arrays/lists of them

Expanded:

You can use the rand() function to generate random numbers. You could use these random numbers to set the position/health points or any other attribute or your enemies.

As for saving the enemies data (I'm assuming you just mean store the variables, correct me if I'm wrong) you need to store the data in an array or list. This can be done in many different ways.

If your enemy is a C-Struct then you can store your enemies in a plain C-Array. If your enemy is implemented as an Objective-C class, then you can store your enemies in a NSArray class (such as NSMutableArray).
> 1 votes

# Answer
Simple thing that you can do is iterate for few times for each enemy generation with the 'rand' function such that the generated values are at a specific distance(MINIMUM\_ENEMY\_DISTANCE\_FROM\_PLAYER) from the player.

something like this...

```
    #define SCREEN_WIDTH 480      //just assuming Landscape mode
    #define SCREEN_HEIGHT 320
   for(i from 1..100) // 100 is some random number-for number of iterations
   {
       enemyPositionX = arc4random()% SCREEN_WIDTH ;
       enemyPositionY = arc4random()% SCREEN_HEIGHT ;
       if(distanceToPlayer(enemyPositionX,enemyPositionY) > MINIMUM_ENEMY_DISTANCE_FROM_PLAYER)
       {
          break;
       }
   }
   //Now use enemyPositionX , enemyPositionY as spawn points for your enemies.

```

Other option can be... If the enemies generated are moving enemies,you can have some predefined spawnpoints and generate from that positions.You can have a check of this kind of game something like 'Robokill'.
> 0 votes

# Answer
I got a tutorial in my blog about how i made bomb rush that is basically protecting the base from some enemies, it's as3 oriented but the enemies generation concept is the same.

Here is a link to it BliipStudio

Hope it helps you.
> -1 votes

# Answer
If you look through the tutorials at this link, you will find ideas for creating enemies, storing their data, etc.

http://www.raywenderlich.com/tutorials
> -1 votes

---
Tags: iphone, objective-c
---


# Question
Title: Shoot a bullet towards cursor - top down 2d
I am making a 2D topdown shooter game, in which the player's movement is controlled with WASD and gun with the mouse. I'm having a hard time figuring out how to update the position of the bullet as it moves towards the cursor.

I have the player's X and Y coords, and the cursor's X and Y coords. I need to be able to update the bullet's X and Y coords each frame based on its trajectory.

# Answer
The bullet's position changes based on it's trajectory. The trajectory you have is likely in a 2D vector? The simple update is:

```
UpdateBullet(Bullet bullet, float deltaTime) {
    bullet.x = bullet.x + (bullet.trajectory.x * bullet.speed * deltaTime);
    bullet.y = bullet.y + (bullet.trajectory.y * bullet.speed * deltaTime);
}

```

If instead you're asking about how to find the trajectory its self (which I'm guessing could be the case, but that's not clear in the body of your question). The trajectory is equal to the cursor position minus the player position.

```
Vector2f trajectory = new Vector2f(cursorPosition.x - playerPosition.x,
                                   cursorPosition.y - playerPosition.y);

```

And typically you'll want to normalize the trajectory so you can have consistent firing speeds.
> 4 votes

---
Tags: javascript, html5
---


# Question
Title: Do I create a first login tutorial for new users?
I'm finishing my first browser game. I really don't know if I have to develop a "first login" tutorial or not. Do you think it's important? I hate the image-based tutorials, with just few screenshot and the buttons "next" and "prev". I wanted to guide the user in the first step, using the real website but with forced choices.

Is it a good idea?

Is there some piece of code (i.e. jquery plugin) to help me in this phase?

# Answer
As usual with these types of things it's completely up to you. You may need a tutorial, it depends on the complexity of the game. I suggest some play testing, to see how easy it is for people to figure out how to play. However, if you do make a tutorial, I would suggest making it optional.

Simply give the user the choice to proceed through the tutorial, or just get into the game.
> 1 votes

# Answer
Since we already have a question that discusses the issues of whether you should have an in-game tutorial at all, that only leaves the question of it being "forced".

It depends: is it fun? If it's not fun, then it shouldn't be forced. Though I would also point out that if it's not fun, then fix *that*.

There are plenty of games that have a "tutorial" without ever really *being* a tutorial, without being obvious that you're being taught the controls and so forth. I would suggest aiming for something like that.
> 1 votes

---
Tags: browser-based-games, tutorials
---


# Question
Title: 2D RPG - Character sprite size bigger than tile size
Ok so I'm trying to make a nice little RPG game in Java & Slick2D engine, the tiles are 16x16, so the collision array is also 16x16, how ever my character sprite is 16x20

What would be the best method of moving the character in relation to a 16x16 grid, also checking for collision?

# Answer
> 6 votes
What you should do is keep characters separate from tiles, but in terms of placement, just have a position at like feet/bottom of the sprite and align that with the bottom edge of the tile. And for collision checking, you could use a rectangle intersection check based on maybe the bottom quarter of the player or the size of the tile even. Experiment

---
Tags: java, sprites, rpg, character
---


# Question
Title: What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8?
I know this is a potential dupe of this question, but the last answer there was 18 months ago and a lot has happened since.

There seems to be some uncertainty about XNA in Windows 8. Specifically, Windows 8 by default uses the Metro interface, which is not supported by XNA. Also the Windows 8 store will not stock non-metro apps, so it will not stock XNA apps.

Should we stick with XNA or does Microsoft want us to move to a different framework for managed game development in Windows 8?

Edit: As pointed out in one of the comments, Windows 8 will be able to run XNA games in a backward compatibility mode. But that smells of deprecation.

# Answer
EDIT: It's official, Microsoft has killed off XNA. I'm saddened by this but it was not unexpected, it's what I was predicting would happen, but hoping I was wrong. Everything below this point is my original post from early 2012.

Something else to consider is that Microsoft is likely to release a new console in mid to late 2013. Will they continue with trying to have something like XNA work on their console? If they want individuals to make games on the new Xbox, they're going to need something, and it would be wasteful to scrap XNA and start anew with something else. Additionally, Windows 8 will run on tablets with ARM processors, and we all know how big the market is for apps for phones and tablets, that's a big opportunity for Microsoft to have an API for creating apps on those devices, but will that be XNA, or only .NET?

I see a couple of potential paths:

1. XNA hasn't been extremely successful with the current Xbox, mostly due to how few XNA games are showing up, and how poorly setup the store is for XNA games on Xbox Live. So Microsoft may decide to pull the plug entirely, leaving us with XNA 4.0, which is compatible with DX10, and will be a decent platform for people to make simple PC games with for the next few years before it disappears.
2. Microsoft may see the huge possibilities with homemade apps, things like Apple's App Store are huge money makers, and if Microsoft can make it easier to make games and get them onto Xbox Live and Windows 8 tablets, then they have a chance to make it big in the console apps market. If Microsoft goes down this path I see the new XNA supporting DX11.1 with its next version, and continuing support for XNA for at least 5 more years.

Some things to consider:

* Currently with XNA you must pay $100 if you want to develop your game for the Xbox 360, that's $100 just to try it out and see if you could make any money, and even then MS gets a chunk of the profits from your game. If Microsoft takes out the $100 fee and just takes the chunk of the profits, they may actually end up seeing a lot more games and make more money off of the deal.
* XNA games have performance problems on the Xbox 360. Microsoft did not want XNA games posing a security risk when they ran on other people's Xboxes, so they basically run XNA games in a sandbox with limited access to the CPU, GPU, and memory. In addition to the limited access, games programmed on the full Xbox SDK are not written in C# and do not need things like garbage collection, but XNA runs on Microsoft's own C#, so Microsoft had to write a wrapper to get XNA to run on the Xbox, and that wrapper slows things down quite a bit. Things like floating point performance can be up to 10x slower than Xbox games that are written through the full SDK. These performance problems mean that Xbox games developed through XNA cannot really use the full potential of the Xbox, which just hurts the quality of the games that Microsoft can get from the community. Microsoft would do well to consider this if they continue with XNA so that their next console allows XNA developers to use the system to its full potential.
* As far as I know, XNA will not support Windows 8's metro style, so developers will not be able to write games to take advantage of it. XNA also will not run on ARM processors, so you could not use XNA to write apps for Windows 8 tablets that will be coming out soon. Is this a sign that XNA might not be supported in the future?
* Microsoft uses XNA for games right now, but with a little work it could be used to make some interesting applications as well. If Microsoft pushed XNA to communities other than game developers then it might get used more often and have more reason for Microsoft to continue supporting it.
* The XNA forums have dried up a bit, it takes more time for people to get answers, and I rarely see any member of the XNA team on the forums anymore except Shawn Hargreaves, so they may just be in a support role at this time.
* I created and support an open-source game engine for XNA, over the last 2 years the downloads of the engine have dropped to about half of what they started at, even though the engine is much better than it used to be. This signals to me that a lot fewer people are using XNA than used to. Here's a graph of the number of hits I have on my site, you can see interest in XNA peaked around late 2007 to mid 2008.

Here is a long discussion that includes some members of the XNA team. Of course, they're not willing to comment on much because Microsoft doesn't talk about things much before they're announced:

http://xboxforums.create.msdn.com/forums/t/91616.aspx

Also quotes like this are interesting:

> Create immersive games using the power of DirectX The new Windows 8 graphics stack is better integrated, making Direct2D, Direct3D, and DirectCompute components easier to use together and requiring fewer duplicated resources than before. Capabilities previously available only in XNA, such as DirectXMath, XAudio2, and XInput, are now available. For the ultimate experience in gaming and video, use DirectX 11.1 to bring stereoscopic 3D to your apps.

http://download.microsoft.com/download/1/E/4/1E455D53-C382-4A39-BA73-55413F183333/Windows\_Developer\_Preview-Windows8\_guide.pdf

I currently support an open-source game engine for XNA, so I would prefer to see it supported in the future, however, even if XNA 4.0 is the last XNA, it's still a decent platform for creating Windows games quickly and easily, and also a great API for those who want to learn how to make video games.

My honest opinion is that XNA 4.0 will be the last one, but I truly hope I'm wrong about that.
> 61 votes

# Answer
MonoGame ( an OpenSource, OpenGL implementation of XNA ) v2.5 was released today with support for custom shaders across iOS, Android, MacOS and Linux. Our team has started work on adding PlayStation Suite SDK support and also Window8 Metro ( based on SharpDX I believe ).

We already have a 3D branch, imaginatively named develop3d, which is where all of our efforts will be focused on in the coming months, now that v2.5 is out. Have a look at our YouTube channel for where we are currently at with 3D - http://www.youtube.com/user/MonoGameTeam?feature=watch.

We have developers from a couple of game studios helping out, so we think the develop3d branch should be more optimised than our v2.5 branch currently is and it almost a total re-write. The Reach demo took 15 minutes to port from Windows to MacOS X, when I started from scratch last week-end. The develop3d branch is not perfect yet and neither is the whole of MonoGame, but we think we are on the way to ironing out the issues we do have and if more people help out, even better.

There are already 28 iOS games ( 27 2D and 1 3D ) on the Apple App Store, 5 on the Android market place and 1 on both MacOS and Linux stores. If anyone here has played Bastion in their Google Chrome browser, that uses a modified version of MonoGame and we hope to support NaCL games in future, thanks to SuperGiant sending us information about how they got MonoGame to work with NaCL.

We have about 4-5 active developers working on MonoGame and if you fancy chatting with us, please jump over to monogame.codeplex.com, or on irc.gnome.org on the #MonoGame channel. Grab the latest code from Github

So I suppose my point is, please consider MonoGame if you plan to write cross-platform games using XNA.

Dominique.
> 47 votes

# Answer
From what I understand about the situation it can go either of two ways. The API is either being deprecated or they are ramping up to create a XNA version based off DirectX 11.

Here is an article about each perspective:
> 16 votes

# Answer
1. > What is the future of XNA on Windows 8?

XNA will only run on the Win8 desktop and there is almost no chance that Microsoft is working on a XNA compatible API running under Win8 Metro UI/DirectX11.1.

If you really want to continue developing on a XNA like API on Windows 8 Metro, while still being able to use the content pipeline (one of the reasons why XNA is low-budget game developer friendly), you should follow the ANX Framework project. This project has some good chance to be ready before Windows 8 RTM (at least with SpriteBatch support). Although It will probably require to slightly change shaders (for example semantics), ANX is providing a way to import an existing XNA project, so that could greatly help. They are also working on other backends (like OpenGL for graphics), so they could also be able to target other .NET platforms (like Mono on Android/iPhone).

MonoGame could be another option, but it is currently only for 2D, with a single OpenGL/ES backend, so It will not be able to run on Windows 8 Metro (OpenGL is not a "certified" API under Win8 Metro, and most likely not part of Microsoft plans).
2. > How will managed games \[other than using XNA API\] be developed in Windows 8 (Metro)?

There are several options:

* You could use directly SharpDX, a low level DirectX API (ANX is using it). For example, a minimal framework for a 2D game is typically feasible with a low level API like this (and could be done with Direct2D). I know at least two small companies that are using it to develop Win8 Metro games.
    * You could start using DeltaEngine that will be hopefully compatible with Win8 Metro in the coming months (will require probably a license)
    * You could try to develop with Unity3D, although they have not announced any Windows 8 Metro support yet (requires a license). But they worked recently on a Direct3D11 renderer, so that shouldn't be so hard for them to provide Win8 support (but as lots of Win32 API are not authorized from Win8 Metro, It's probably not the only thing they need to port).
> 11 votes

# Answer
With WinRT release it's becoming more and more obvious that Microsoft way have taken a big turn. Managed hype is going down, Native hype is stronger than ever. Apparently someone influential in company (some claims it's core Windows team) is not satisfied with .NET performance at all. The main trend I see in latest articles is something like

> WinRT is the next .NET, and C++/CX is the next C#.

They say:

> Hey it's just as easy to write in C++ as in C#! Why do you need XNA if you can write in C++ and DirectX?

That's the feeling I get all last time. Given that you can expect slowdown of all managed related projects, the only difference is slowdown amount.

The Microsoft have my respect for almost never dropping support for products, they are just not developed anymore. So at least we can use XNA 4.0 for quite some time even if it's the last supported version.
> 5 votes

# Answer
It's not looking good for us indie XNA developers who want to port our XNA games into Metro. Microsoft has shown no interest and expects us to go back to C++/DirectX programming or adopt third party C# frameworks, most of which do not support any XNA Content Pipeline.

All pretty sad, I really cannot understand MS sometimes.
> 2 votes

---
Tags: xna, windows
---


# Question
Title: How to do reflective collisions with particles hitting background tiles?
In my 2d pixel old-school platformer, I'm looking for methods for bouncing particles off of background tiles. Particles aren't affected by gravity and collisions are "reflective". By that I mean a particle hitting the side of a square tile at 45 degrees should bounce off at 45 degrees as well.

We can assume that tiles will always be perfectly square. No slopes or anything.

What are efficient methods and algorithms to do this? I'd be implementing this on a Sega Genesis.

# Answer
When testing a particle to see if it's hit a block, you'll usually know if it hits a side or top or bottom.

If you express the velocity of the particle as a delta\_x and delta\_y, you can invert an individual axis when hitting a wall.

For instance, if you hit a vertical surface, invert the x-axis, and the y-axis if it was a horizontal surface.
> 1 votes

# Answer
In a perfectly reflective collision, the angle of reflection is equal to the angle of incidence reflected over the surface normal.

I'm not sure if I'm understanding your question in its entirety, but assuming you have access to the surface normal at the point of contact and the particles' movement vectors, it should be as simple as reflecting one vector over the other according to this formula:

> Vr = Vi - 2(N dot Vi) * N

Where N is the normal vector, Vr is the reflected vector and Vi is the incident vector. Hope that helps!
> 0 votes

---
Tags: 2d, collision-detection, platformer, pixel
---


# Question
Title: Is storing data via property lists in an iPhone application's documents directory secure?
Is storing game state in plists in an iPhone application’s documents directory a secure method? Meaning, does anything other than the application have access to that directory?

# Answer
AFAIK legally not, no one can access that directory, other than application itself. But if the device is jail-broken you can easily access and even change everyfile anywhere on iPhone. So if it's some critical data, you don't want any one to access it's contents, I suggest using some encryption before saving it.
> 1 votes

# Answer
An *attack* coming from another application on the same device is unlikely, I wouldn't worry about root. Since you want to avoid the *user* from tampering with the savegames, I would try to do everything as secure as possible, since any user (jailbroken or not) can use tools like iExplorer to retrieve files from the device and inspect them on their home machine.

As example, I'm attaching a capture of this application exploring a non-jailbroken ipod to retrieve a database from the game Spice Bandits, from which you can easily read the contents:

```
[~/Desktop]$ sqlite3 greystripedb.sql
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .schema
CREATE TABLE adTags('slotName' TEXT PRIMARY KEY, 'url' TEXT);
CREATE TABLE ads('slotName' TEXT, 'id' TEXT, 'dlTime' INTEGER, 'type' INTEGER, 'content' TEXT, 'trackers' TEXT, 'clickText' TEXT, 'clickthrough' TEXT, 'expiration' INTEGER, PRIMARY KEY ('slotName', 'dlTime'));
CREATE TABLE demographicAnswers('key' TEXT PRIMARY KEY, 'value' TEXT, 'skipCount' INTEGER default '0');
CREATE TABLE settings ('id' TEXT PRIMARY KEY, 'data' BLOB);
sqlite>

```

And of course, you can change the database and reupload it.

Maybe the best would be for you to avoid storing savegames on the machine (online services for iDevices and Android are spawning nowadays like hotcakes) and instead save the games on a server, or use tools like SQLCipher which encrypt sqlite databases to avoid quick and easy tampering of data.
> 2 votes

# Answer
I agree with @Gajet. Yes, an application is sandboxed, ie the app is limited to its files, preferences, etc and has limited network and hardware access. The link I have included even notes that developers should defend against attacks.
> 1 votes

---
Tags: iphone, data
---


# Question
Title: Light mask map and camera for static lights in XNA Platformer
Using the example for some basic light maps found here : http://blog.josack.com/2011/07/xna-2d-dynamic-lighting.html, I've managed to create a lightmap texture using individual lightmaps and display it over a 2D tiled world as in the Platformer example.

I'm using the very basic 2D camera example as found here : http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/, and the problem is that the lightmap texture scrolls with the player sprite. This looks pretty good and would be excellent for lighting the player sprite as it moves. But, I also want to be able to place static lights (or some initial position for the lights) that do not move with the player or camera.

When I turn off the camera or give it a static position, it works as a series of static lights so I believe it's probably caused by the camera transformation matrix following the player around. I'm using RenderTarget2Ds, one for the main game screen after all the backgrounds and tiles are rendered, and one for the "lightmap" which consists of a black background and a bunch of lighting textures which are merged with it using additive blending.

For now, I'm doing all of this in PlatformerGame.cs where the camera transformation and position is set and the level.Draw() call is made. I can't figure out how to separate the drawing of the lightmap and the camera following the player. I was thinking it would be better to render the shadows and lighting directly in the drawing of the level itself, but I'm not sure how to do that either because this technique requires RenderTarget2Ds and calling SpriteBatch.Begin()/End().

# Answer
> 1 votes
Most likely you are trying to draw the light map as a full screen quad. Try changing your lightmap to having a world position, like a normal sprite, and rendering it using SpriteBatch.Draw();

You may also find that you don't need the second render target. Create your lightmaps as if their just other objects in the scene. Then give them some transparency and turn alpha blending on. If you make sure to render them at the end, they blend with the scene you have already drawn and either make it lighter or darker.

If you play around with different blending modes you should find one that multiplies you're world pixel colours by the lightmap to give you the lighting effect you want.

---
Tags: xna, 2d, camera, lighting
---


title: Navigation using Marmalade

text:
# Question
Title: Navigation using Marmalade
How do I achieve navigation to different views in Marmalade? Like what using `startActivity(intent)` in Android does.
I know that there's only a single view in Marmalade, but still couldn't figure out how to make a similar example.

# Answer
> 1 votes
I've come to know that there's nothing similar like `Activities` in `Marmalade`. Because Marmalade works on Game loop, in which a particular rendering has to be done frequently in the loop, so as to make it look persistent on the screen. Something like what we do in the custom View's `onDraw(Canvas canvas)` method, although we use `invalidate()` method to do that instead of the loop.
The `CIwMaterial` looks similar like a fullScreen View which can be used in lace of the `Activity`, though there's nothing like the same in it. `IwGxSetMaterial()` is the global function to render the newer material on the screen.
This answer is not perfect, but atleast will help those who want to code in `C++` using `marmalade` for the first time and previously doing it using the `Android SDK`.
**PS:** Kindly correct me wherever I am wrong.

---
Tags: c++, android, marmalade
---


title: Accuracy vs distance formula

text:
# Question
Title: Accuracy vs distance formula
Consider a shooter and a target. My question is if there is any realistic approximation of calculating with which probability the shooter hits the target.

Neglecting the weapon and shooter skill, I guess the first order approximation should be that the probability to hit would be proportional to 1/r^2, where r is the distance to the target.

The motivation to this relation comes from using the idea that the area of a sphere centered at the shooter decays as r^2. So, the probability to hit a target should be, in worse case scenario, decaying as 1/r^2.

I've tried Googling some relation for any weapon, but I didn't find any...

Does anyone knows more information about this topic? Is this approximation valid?

**EDIT:**

More on the question: I'm considering a tactics game. In particular, I would like to model the shooting between two units (so, not a FPS game, the player does not aim, it issue orders). To do that, I'm considering that the unit has some experience, the weapon has some accuracy, and the environment (foggy, vegetation, etc) effects the overall accuracy. Before working some difficult model, the simplest model to test is considering all factors constant, and accuracy only depending on distance.

The question is how does this accuracy should depend on the distance. My first guess would be a 1/r^2 decay. But, has well mentioned on comments, this looks like a very rapid decay.

# Answer
Your approximation basically dictates shots are landing on a part of the surface of a sphere, determined by angle; the target area within that surface is a constant; the probability distribution is constant within the surface and zero elsewhere.

Gajet has already given a number of good reasons why some of these assumptions fall flat, but holds on to the same inaccuracy model: a bounded error in angle. The result still falls off with r^-2, but with a small constant.

Say the shooter has a maximum spread of 5°. He has a chance of firing between a 0° and 1° error, but the area of the ring between 4° and 5° is much larger than the area of the ring/circle between 0° and 1°. Larger errors have a larger probability of occuring. Increase the error any further, and the probability suddenly drops to zero, because we're out of the five degree limit. That doesn't seem very realistic.

A more accurate representation would be to have a guassian distribution of angular error, i.e.: `A(ϕ) = sqrt(a/π) exp(-a ϕ²)`. The variable a can be used to include the shooter's skill etc. Note this solution is one-dimensional. If your target is very tall compared to its width, you might omit the vertical error altogether and just assume the shot landed at the correct elevation. Alternatively, you can run the calculation twice and multiply the result, assuming the target is roughly rectangular.

To get from the probability function to the actual probability of hitting a target, we integrate the function A and end up with an expensive error function - which is actually called the error function: `p(ϕ) = erf(ϕ sqrt(a))`. The angle ϕ equates to the angle between the targeted point and the target's edge. In terms of target size s and distance r: `p(r) = erf(arctan(s/2r) sqrt(a))`. This function is plotted below for a target of size 1 and accuracy values of `a=2` and `a=10`.

Note that unlike a falloff of r^-2, the probabilty neatly stays below one, no matter how close the target is. In fact, even a target at exactly zero distance can be missed, due to the extremely small probability the error is more than 90°.

Like I said before, the error function is quite expensive, but its argument `ϕ sqrt(a)`, doesn't vary all that much for any sensible shooter scenario. We can do a lot better by evaluating part of the Taylor series instead and capping the result. First, we map `x = arctan(s/2r) sqrt(a)`, then evaluate: `2 x - (2/3) x^3 + (1/5) x^5 ...`. Omit or add as many terms as deemed necessary, but keep in mind an even number of terms will cause unwanted behavior for low distances. Plotted below is the real error function, compared to the first three non-zero terms of its Taylor series.

As a final note, this is purely mathematics. Throw in a couple of sine functions, random coefficients and logarithms and your game might be equally fun.
> 5 votes

# Answer
The probability certainly is a function of 1/r^2 but does not fall off as fast as 1/r^2 itself. Let't do a simple math, and for the ease of calculation I shall first go with a 2D shooting which will result in 1D error in shooting. The target always has a same width, for example we know that target has a width of one meter. And we also know that while shooting the gun can miss the target with at most 5 degrees. here is a figure showing the situation:

Now look at these three states. assume that they have `h1`, `h2` and `h3` distance from the corner. Based on these values and the angle, we can calculate how much the distance is at those state. It's calculated as simple as `h*tan(10/2)*2` (as shown in figure 2).

We know that `h/l = cos(theta/2)` and `r/l = sin(theta/2)` =\> `r/h = sin(theta/2)/cos(theta/2) = tan(theta/2)` =\> `r = h*tan(theta/2)` =\> `edge length = h*tan(theta/2)*2`

At other hand we know the target itself is 1 meter wide, so as long as that value is less than one meter we will always hit. after that part it has a probability of `"target surface"/"hit area"` which is equal to `1 / (h*tan(10/2)*2)`. Note that we can always assume all of target surface is inside cone of fire. it's doesn't really affect game-play that much but ease calculations very much!

now back to our 3D problem with a 2D target. Since it's a cone we are talking about the bullet will always pass through a circle of certain diameter when passing the target. again we need to compute it's radius, then the area of that circle. As I've explained before we can use `r=h*tan(10/2)*2` and hence the surface area is `pi*r^2 = h^2*tan^2(10/2)*4 * pi`. And in the end we know probability is `"target area"/"circle area" = 1 / h^2*tan^2(10/2)*4 * pi`. as I said it's a function of h^2 but since `tan^2(5)` is very small, it takes a long time before that probability falls very low.
> 5 votes

# Answer
For this, you need a defined concept of "inaccuracy". What is inaccuracy? How does it work? If you code an AI which shoots and it computes the exact path every time, then obviously the inaccuracy is 0 over any distance.

Any shooting AI defines the perfect path first, and then adds aiming inaccuracy. This inaccuracy is entirely defined by you, and that definition is necessary before any probability can be computed.
> 1 votes

---
Tags: game-design
---


title: Calculate vertex coordinates

text:
# Question
Title: Calculate vertex coordinates
Newbie here!

I need to know the effective coordinates of a triangle after applying transformations (rotations & translations) to the current (MODELVIEW) matrix.

That is, given a vertex P, I want to calculate, for instance, the new coordinates of P after a rotation of 90º on the x-axis.

How can I do that? Is it also possible to use only OpenGL matrix operations to do this?

Thanks in advance for any tips.

**Edit:** The easy one is translation. I implemented it as

```
#define T(x, v) (x+v)

```

where I apply T to every coordinate of every vertex.

But what about rotation over a specific axis. Can you please give me some hint?

# Answer
> 2 votes
Modern OpenGL (3.0 and up) doesn't contain any built-in matrix operations so you have to do everything yourself.

Check out a library like GLM http://glm.g-truc.net/

Or search for a good tutorial on "3d matrix math"

---
Tags: opengl, matrix
---


# Question
Title: Best physics engine for OpenGL ES (different implementations)?
Can you recommend a good physics engine which is easily portable between WebGL and other OpenGL ES implementations like in Android and iPhone?

I don't want a game engine. Only the physics part.

# Answer
> 2 votes
For handheld devices the best option is to use a C/C++ physics API as processing power is quite limited.

Bullet physics is a very good 3D physics engine. It works on Android, iOS, PS3, Windows, Mac... it's portable. You can use it in 2D mode as well. It has been ported to javascript (compiled using emscripten).

Box 2D works very well for 2D physics. It's used in many games. Angry birds being the prime example. For javascript the most up to date version is box2dWeb.

There are other option. But these are the most popular and work well on mobile devices.

# Answer
> 2 votes
This probably has an answer somewhere, but if you want a good 2D portable physics engine Box2D is sort of the standard: http://box2d.org/

I have got it to work on Android (using the NDK as it is a C library) and it works fine on IOS. For webGL, everything runs in JavaScript, so you would need a port of Box2D, like: http://box2d-js.sourceforge.net/

For 3D, there is probably a huge list somewhere, bullet being fairly popular: http://bulletphysics.org/wordpress/

---
Tags: physics, webgl
---


# Question
Title: How to fight against memory editing cheat software?
What is the best way to protect run-time memory from such software?

We just published an online game (written on AS3, Flash, published on a social network), and pretty much all of the players got `max_int` money just using a simple memory editor ("ArtMoney").

# Answer
> 18 votes
Simple ways to protect your game:

* Duplicate your data: store some information twice and compare the copies. If they are different, something is going wrong. You don't have to do it per variable, you can also make CRC's on some big areas of memory (ex: on a struct that contains all player information).
* Encrypt your data before its written to memory (and unencrypt after reading). A simple xor could be effective. This will make finding the addresses of some interesting variables a LOT harder.
* Never declare sensitive data "static" (with a fixed memory address) but rather use pointers. If someone find the address of interesting variable, the address will change next time process is run, making it harder to create a trainer (but not impossible).

In some professional games (like GTA IV), the game is split in two parts:

* One main process for rendering, input and processing game logic, which is unprotected (like most games).
* Another process that keep sensitive data (ex: player health, money, weapons, ...). This process has several protections against cheating (memory regions are readonly, data is encryted and so on). It's not possible to modify these values directly by writing in them, but only by using a set of functions that the process provide. These functions are only available after you have been authenticated using a set of keys/challenges. I guess other sensitive stuff like load/save savegames is also done here.

I guess this has some costs. Every modification of game data require some interprocess communication and some other checks (instead of a single read/write to memory).

However, all protections can be defeated: someone could disassemble your game to figure out exactly where and how data is stored. Or even better, modify the .exe himself to directly remove the protections. Anyway, I think using what I described above will stop most cheaters.

---

EDIT:

If it's a Flash game, you can regularly send some game events to a server (eg: "+50 points at frame 41, lose one life at frame 1231"). Then analyze these events and some statistics (eg: total seconds the game was played, number of player actions (mouse moves, key presses)) and compare to the submitted score to see if it appears to be possible...

# Answer
> 15 votes
You can't stop memory editing cheats, so design your game so that such cheats won't matter. For an online game, sensitive data like money on your own server, and don't rely on the client to have the correct amount. That way it won't matter if players change the amount of money displayed on the client, because when the player purchases stuff the game checks the amount stored on the server.

# Answer
> 3 votes
There are a lot of complex ways to go about blocking your process from being modified externally. Most of these dip into the realm of anti-reverse engineering solutions at their core. Such as anti-debugging, breakpoint detection, etc.

If this is a concern for you focus your efforts on automated solutions and not on the person performing the operation by hand. Tools have to find ways to identify what your information is in order for it to change it. By making runtime changes in how you organize and store your data you can make these tasks more difficult.

Few things you can do:

* Mask string constants and use Encrypt/Decrypt functions to change masked strings to output strings. This quickly deters someone from walking through a string table. Localization can often times add this feature without any intentional effort to obfuscate strings.
* Checksums. On all sorts of data to validate their integrity. This requires at least a two step process of the person changing the value and the checksum associated with it. Just don't store them in the same area so they are easily identified.
* Encrypting data in memory (as previously mentioned) is a good way to avoid a person easily modifying your contents. They will first have to identify how the data is encrypted and then any relative pattern or key associated with it.
* Hook the Windows API functions that are commonly used by trainers. Such as ReadProcessMemory and WriteProcessMemory. A simple hook can let you know when a trainer is using these on your process, and you can determine if you want them to occur or not. It's not the only way to modify the memory contents but it's the most common.

Once you begin going outside of simple things you really are moving into Anti-RE territory. Which also applies to anti-cheating, but becomes much more in depth. These techniques take time to implement carefully and may be overkill for your intended purposes.

* Launch a child process and have the child process attach to the parent process as a debugger. This will stop additional debuggers from attaching to your process.
* Keep sensitive data that doesn't need to be used frequently (not stuff used every frame) in guard pages. These are created through VirtualProtect() and will make the process throw an exception when the memory is accessed.

There's a lot more options you can explore, but I won't go into length here. Just lookup Anti-RE.

# Answer
> 1 votes
You run the software far away from the user like for example onlive does it.

Google "Cloud gaming" if you wan't more information about the technique.

# Answer
> 1 votes
Also, you could use simple sanity checks. A player doesn't just randomly pick up a billion gold.

# Answer
> 0 votes
One very effective technique used by some roguelikes (DoomRL, Brogue) is to *mask the actual variables.* What this means is that instead of showing health as "2/10," show it as "20%."

Remember, most memory editors work well with specific value searching/filtering. If you don't know the specific value, you can still track it down (eg. search for changed/decreased values after the player health drops), albeit it takes much longer to do it that way.

I also suggest an anti-cheat backlash. For example, if you have a game where the player takes non-positive damage and their health didn't drop, you can easily and accurately check this and know that the player cheats. Do something interesting, like spawning some uber enemies around him :)

---
Tags: security, online, anti-cheat
---


# Question
Title: Making a 2d puzzle game like Unblock Me for iOS and need advice.
I have a simple game on the Apple App Store written entirely in Objective-C and Cocoa Touch.

I would like my next game to be like the Unblock Me game or Auqeduct where you have to drag pieces around the game board arranging them to create something or free something to exit the board.

My question is how are games like this started. Do they work on a grid? How does collision work? When one piece hits the other piece they stop. Is this all done using Core Animation for moving the pieces and using functions like "CARectIntersectsRect()" to test for collision?

I love puzzle games that involve falling blocks and color matching and puzzles like mentioned above. Is there a resource I could read more about on the principles of these games that is language independent or explains how to make them?

# Answer
Rather than coding it all from scratch I'd personally want to use a framework like Cocos2D or Kobold2D that has built-in physics support. It can be an interesting exercise/learning tool to code up physics on your own, but I tend to assume that someone smart has already put in a ton of time making it great and hence I'd rather just get on with my project.
> 0 votes

---
Tags: ios, puzzle
---


title: How do I measure time in XNA?

text:
# Question
Title: How do I measure time in XNA?
Is there any simple way to calculate time that is spent in each method that's called from the Update and Draw methods? I want to do this to find bottlenecks in my engine. Is that a good way?

# Answer
If you want to do it in code as then I suggest you check out System.Diagnostics.Stopwatch class. Its designed for measuring very, very small amounts of time.

I personally use the Visual Studio Profiler. One of my favorite features is it will list all the methods along with the % of processing time they occupy. Very useful for finding bottlenecks.
> 3 votes

# Answer
well Gametime.ElapsedGameTime is how long it takes from frame to frame (however, think its rendering and updating). But, as a comment said, use profiling and good judgement as to whats taking so long. Check any loops because those are generally the reason. Maybe if you could describe any issues you're having, we could help you narrow your search down.
> -1 votes

---
Tags: xna-4.0
---


title: Pathfinding for units of variable size

text:
# Question
Title: Pathfinding for units of variable size
I'm using a grid map for a top-down RTS, and I am using the a\* algorithm for pathfinding. Specifically, I've found one implementation which is heavily optimized, and I've been using it for a while, but now I've realized I only checked it with infantry and not with vehicles, which take more map space, and so I can't rely on the algorithm - what would be "hugging a cliff" for infantry would be passing through it for a vehicle.

So, I'm trying to decide what to do. I see three options. a. The obvious thing is write my own A\* implementation, but this is both very time consuming and I presume I won't reach near the optimized speed of the algorithm I found. (rewriting the algorithm is out of the question - I just don't have the time to try to read it and understand it).

b. corrections - read the path generated by the algorithm, and either correct it at every step or when receiving the path recalculate it for width.

c. Hold variable sized maps, that are different representations of the free space on the map, on account of size.

Option C sounds to me the simplest, but is likely to be too memory heavy, even if there're only three-four size categories. Between options a & b, I'm not sure what is likely to take more calculation time - a non-optimised A\*, or running over & correcting a path.

# Answer
A\* is not a hard algo to understand and it is one you should get intimately familiar with if you plan on using it in games.

What you really need from your description is an annotated pathfinder. (clearance based) There is a great description of one here.

Clearance Based Path Finding

This article describes a hierarchical annotated a\* path finder however once you can write your own A\* from scratch adding features you need for each project is very simple.

Heavy use of a profiler will help you optimize your path finding in short order. It really is a simple piece of code once you get the hang of it.

Edit: I am sorry I forgot to add. If you already have a fast a\* the modification to add the clearance based checks is pretty simple. Obviously your base object that anything that is going to use the path finder is derived from needs a "clearance" variable of some kind.

Inside the actually path finder just find the spot where it is checking against if things are walkable or not and that is where you add in the clearance checks. Also when you first generate your map you need to add a var to the node or however your graphing your map to pre-calculate the clearance values.(that will make it faster) Really that is basically all there is to it.
> 3 votes

# Answer
Without stepping in and altering the algorithm itself, you could just stick with option B.

Calculating corrections won't be optimized anyway, and most probably you'll have to define ad hoc routines for each type/size of unit you're going to use.

Another thing to take into account is a possible collision detection implementation: The very idea of 'hugging' a wall with a vehicle can be (sort of) easily solved that way, even more if you won't care for vertical movement collisions since you'll be just working with a 2D world at that point. Even more easy and fast if you also don't care for a high level of precision with collisions (i.e: every unit is a circle with a defined radius).

Edit:

If you need a generic explanation on collision detection just search for any tutorial (or this website), there's plenty online.

If you mean in this specific case instead, once you obtain the path from your algorithm, just make the unit follow the path, and have the collision detection do its job once the unit actually tries to pass through any surface that you defined as a surface to check.

I.E: If you define your tank unit as a circle (A is the center, R is the radius) for the collision detection, once it's following a path that would be correct for infantry, the collision detection will prevent the tank from passing through (partially or completely) the wall by checking if the point A is closer than distance R to the wall. The way you handle the result of the collision depends entirely on what you want to do. The easiest way is to make the component of the movement that is perpendicular to the wall null, so it will 'slide' along, basically 'hugging' the wall.

I suggested this approach mainly because working with 2D bound shape is easy and fast.
> 0 votes

# Answer
I don't understand how you can be resistant to ditching your "heavily optimized" code in favor of finding multiple paths each time or the increased complexity of holding multiple maps (both clearly the other direction from optimized). I doubt your current code is so optimized that you would be better off going with those options instead of writing your own implementation.

I suggest you **go with option A (in an option B sort of way)**. I think your presumption is correct that you won't reach the same optimization, however you're ruining that optimization anyway with options B (multiple paths) and C (considerably more work than re-writing your path-finding). I do believe you could reach a better optimization with option A than B or C.

Combine options A and B. Rewrite your algorithm to include checks for size when picking a new node. You'll maintain most of your optimizations, learn something along the way and get the end result you desire.
> 0 votes

---
Tags: c#, path-finding
---


title: In-Game Tutorial Decisions

text:
# Question
Title: In-Game Tutorial Decisions
I'm working on a game with confusing mechanics such as energy storage and the coolant temperature. What is the best way to get a new player learned quickly? What are the pros and cons of different in-game tutorial methods? I was thinking of a tutorial with annotated screenshots, but that makes it sound like a science textbook ("**Active towers** are towers that consume energy and may generate heat."). Other ways include:

* in-game tutorials, which is somewhat difficult to program
* tips that will show in-game and after game over
* a reduced difficulty without the energy and coolant things

# Answer
> 34 votes
> I'm working on a game with confusing mechanics such as energy storage and the coolant temperature. What is the best way to get a new player learned quickly?

Don't make confusing mechanics. That may sound flippant, but strongly consider this. Just as you don't write overly confusing code, you should not write mechanics that are innately confusing.

The first step in getting players to learn quickly is to not confuse them in the first place. Find out what it is about your mechanics that they are finding confusing and fix *that*. Then, once you have a quality set of mechanics, you can start working on how to introduce players to your game.

> in-game tutorials, which is somewhat difficult to program

Then you need to make a judgment call: do you want your game to be easy to write, or do you want it to be *good*?

Yes, making a real in-game tutorial is a pain. But that pain is the difference between forgettable games and the ones people actually want to play.

> tips that will show in-game and after game over

I've never found this to be a useful strategy for teaching anything useful. It's like the teacher giving you a test on the first day, then every day after this they putting up a question from the test and explaining what the answer is. It might work to teach you something, but it still makes you feel stupid.

Asking someone to do something that you have not really prepared them to do can be read as rude by players. It's always better to introduce information up-front.

> a reduced difficulty without the energy and coolant things

This is just me personally, but I don't like difficulty levels. The pacing of the game, the change from level to level, area to area, challenge to challenge, is the most important part of the game. That pacing changes when you just arbitrarily decide that skill level X will have fewer monsters or less mechanics or whatever. This makes the increase in challenge of the game over time less deliberate.

And worst of all, since you're clearly designing the game to play best at the normal difficulty level, the people playing at reduced difficulty are going to have a sub-optimal gaming experience. You can't just yank out mechanics and expect everything to play fine for them. Either the game is going to be too easy, too hard, or too inconsistent in its difficulty.

# Answer
> 11 votes
I recommend that you play the original Portal with the developer commentary turned on - a large chunk of the commentary is devoted to how they introduced the player to the portal gun, a game mechanic that you could definitely consider "fairly confusing" (in certain respects thats kind of the point!)

Rather than explaining game mechanics through tutorials and text / voiceover, Portal introduces game mechanics through a series of easily achievable challenges that demonstrate the mechanics. For example:

* The first portal experienced by the player is positioned in such a way that the player is forced to observe themselves walking through the first portal. This perfectly explains the relationship between the two portals without a single word, as well as teaching the user that they are able to walk through portals.
* The player then goes through a series of puzzles of increasing complexity where portals are placed for them rather than giving the player the portal gun immediately. Each of these puzzles has a specific goal, building on everything that the player has already seen in order to teach the player a new mechanic (for example what surfaces portals can and can't be placed on, or how portals can be used to reach otherwise inaccessible positions).

The key is to teach the player **one thing at a time** in a way that is engaging and fun by demonstrating the game mechanic to the player, rather than telling them about it (if the player figures out a mechanic for themslves rather than being told about it then not only is it more fun and involved for the player but they are more likely to understand what is going on).

Keep each step nice and simple - if you find that players struggle with certain mechanics then go back and split it down into even more simpler steps. To solve the first "puzzle" in Portal the player only has to walk through the portal!

Don't think of your tutorial as being something that the player must do to learn how to play the game - *your tutorial is part of your game* (and usually the first thing they do - first impressions count!) Also listen to the Portal developer commentary - it really is very interesting.

# Answer
> 10 votes
Nowadays, games tends to use the In-Game tutorial, sometimes with tips during gameplay. IMHO, if you just have a "text and screenshot" tutorial, most players will just go straight to the game, trying to figure it ourselves (I plead guilty, even tough I will come back to the tutorial if I can't figure it out).

Another thing you could do is to design your game to make sure that the player get the needed skills to be able to advance. For example, make a place where there is no or few risk of failure, but are obliged to use a new skill, then, make them use the same skill, somewhere where they failure mean that they can't go further.

Think Portal, where the first time you see an energy ball is in a safe room, then, you must manipulate a ball above water and get in the path of the ball, at the same time. The first room teach the player how the balls go into the receptors, the second one that water is toxic and balls kill you if you touch them.

For another example, see here for an explanation of how the first level of Super Mario Bros. teaches you everything you need to play the game.

# Answer
> 4 votes
### Ingame tutorials disguised as levels

Introduce gameplay mechanics and concepts one at a time, each new level introducing another mechanic and building on knowledge that the player has learnt in the previous level.

# Answer
> 3 votes
The game Ashen Empires (which used to be known as "Dransik" back when it was in "beta") currently has a tutorial section (I believe others like RuneScape also have a similar setup) where new players are in a "new player" area that they can't get out of until they get a very small number of experience points in certain essential skills.

Ashen Empires (free to play; pay for expansions)
http://www.ashenempires.com/

Once the player has completed the super-easy quests to gain the needed skill points (e.g., kill three giant spiders and bash the hell out of a few over-sized sewer rats), they will be permitted by the guards to pass through the gates.

And on a slight digression, for those players who try to "level up" in the "new player" area, after getting to a certain level they no longer get points for killing the super-easy stuff, so there's no real motivation to remain in the "new player" area after a while.

So, this is one approach that could work for you -- you could require new players to all demonstrate that they can use those specialized features you created relating to energy storage and understand how coolant temperature factors in (e.g., one simple quest could require the player to get extremely close to the overheating temperature without actually overheating -- if they don't get within that specific range, then they have to re-do the quest). But, do consider making this "new player" area easy for experienced players to just blow through really quickly so they won't get annoyed when creating new characters.

# Answer
> 3 votes
Create an introduction video where you demonstrate and explain the ingame behavior.

This has a few nice points:

* Easy to create
* Can't have bugs. half the tutorials in commercial games I player broke in some way.
* You can upload it on youtube so even people who don't have the game can view it as promotional material
* You can speed up boring or repetitive parts(wait for building to finish)
* You can perhaps explain basics of strategy afterwards by commenting actual play. In my experience learning the rules of a game isn't necessarily the hardest part. You need also to learn which options are useful at which time.

# Answer
> 3 votes
For me, you really cannot decide until you have other people play test your game. If they find that they are getting the concepts, then you are probably alright. However, if they are having trouble playing you game, then you have a some options:

* Elongating the learning curve
* Simplifying game mechanics
* Having different difficulty levels

Remember that the goal is not to make the programmer's life easier, its to produce a quality game for the end user.

# Answer
> 1 votes
Speaking from the POV of a gamer, and not a dev, I find that most things that can be described as tutorials are annoying at best. I don't mind a somewhat complex user interface as long as mundane tasks are not made complex by neccessity, and as long as it does not present an eyesore. That said, I hate the general concept that a person would need reflexes, timing and dexterity to play a game well. In the process of attempting to complete a task, the intricacy, IMO, should be in interacting with the NPC player actors via dialogue and AI response, with far less emphasis on an arbitrary combination of keypresses being needed to perform lesser tasks.

For that matter, I'm a believer that aside from a standard template or two to default to, the user should be the one defining the mapping of commands. So I posit something possibly out-of-box: design a process by which the user becomes familiar with basic movements, letting them remap keys as they see fit, making sure to give them a reserved escape sequence if they set up a mapping that doesn't work for them. This way you can combine the general process of tutorial with key mapping.

SUMMARY: combine tutorial, key mapping, and to some degree, training/try-out for various classes/stats/skills/feats. focus on doing this in a manner that is consistent with plot, but is not overly restrictive. Of tutorial sequences:

* if cinematic, (or other non-interactive) make bypassable, always.
* if cinematic, (or other non-interactive) make replayable.
* not required at all. (let the user be as independent as they want to)
* not needing incessant confirmation of clunky dialogue. (you are supposed to be making the game easier to understand and play, not more like a powerpoint presentation)
* not overly restricted to location. (if the user is having problems, they probably can't run back to town across a vast desert without getting killed, in order to figure out how to run back to town...)
* do not neccessarily have to be completed sequentially, unless there's a natural prerequisite, like basic archery before bowhunting big game. (in essence, let the user revisit what tutorials they desire to where and when possible, at least to the extent that plot and setting allow)
* actually reward them for what they accomplish in tutorial as incentive (payment, free stay at inn, some ammo, a free weapon, a mercenary, a treasure map, or at the very least some actual useful gossip on occasion)
* consider that some *more advanced* tutorials can be made as games-in-game (as long as they generally aren't pointless or completely unrelated to anything in the realm of play) with some inherent cost, or have less concrete rewards, such as target practice on a range where betting is placed, an obstacle course which reveals entry to a bonus dungeon, or actively attempting to recruit an NPC/merc by completing a very dangerous side-quest/gaiden, but having that NPC be fairly badass)

I cannot emphasize enough that lack of solid interface and consistency with the main game is what makes most tutorials seem less than useful/usable to me.

---
Tags: game-design, game-mechanics
---


# Question
Title: Scripting: Loading all scripts at runtime vs loading scripts when needed
I'm using Boo as a scripting language in my C#/.NET game via the in memory compiler with it and I really love it, however I'm having trouble deciding when I should load my scripts.

**This is my first time using a scripting language with a game and my first time implementing one into anything.**

Currently I load scripts as needed - this works well. However I end up with a lot of assemblies loaded(one per file currently, as I'm just loading each when it is needed) and realized as my game expands this could turn into a large number of assemblies - is this bad? I guess I could get around this by managing appdomains and loading/unloading after scripts haven't been used for a long time. I currently don't use any appdomains for my scripts at all so I end up with a lot of appdomains due to them getting recompiled while working on them.

Loading all scripts at the same time would be a big overhead when loading as my loading times are quite fast right now, rather big memory usage due to them all being loaded at the same time, and if I want to dynamically recompile scripts when they're changed while the game is running I have to recompile all of them. Currently I can just recompile them one file at a time. The benefits of this is that I obviously have a lot less assemblies loaded.

I guess my real question is having a lot of small assemblies loaded in C# a bad thing compared to one large assembly, and compiling scripts during gameplay vs a big loading screen?

# Answer
Your question basically consist of two smaller ones:

* If it's better to load all scripts while loading the game?
Loading all scripts when the game is loading has advantage of easing game-time coding. I mean you know all the scripts are loaded and you can call whatever you want whenever you want. But it also result in larger memory consumption and an increase in game load time. Exactly Opposite to that when you load scripts on the run, you'll save some memory and decrease load time, but instead you need to make sure each script is loaded before calling it, and if loading an script takes noticeable time (maybe more than 0.1s) then you need to somehow predict script usage and load it before you need it in a separated thread. I guess gameplay time loading is just an optimization you shouldn't think about before you get an actual problem with performance.
* If it's better to split your scripts between several files or put them all into one large file?
It is better to split scripts whether you are loading them separately during gameplay time or loading them all at once while loading the game. You've pointed out the main problem yourself, if you combine all scripts into one file you'll need to recompile everything even with smallest changes. Also note that if you create a large file, later changing it will also be hard for game designer, even if you are the game designer. Reading ,editing and maintaining a file with 200 lines of code, is a lot harder than working with 10 files each 30 lines of code.
> 2 votes

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


title: Height Map vs 3D Model Mesh

text:
# Question
Title: Height Map vs 3D Model Mesh
I'm currently working on a 3D PC game (written in C++ and DirectX 9.0) and I'm trying to find the best way to store level data in the memory.

The game's action takes place under the ground, so there's always a ceiling above the player. The ground is rather bumpy and there are things like stalagmites present at all times. Levels are small-ish in size and mostly look like corridors. Here are the options that I've managed to find so far:

Two height maps stored on the hard drive as either a bitmap or binary/text file. One height map for the ceiling (top), one for the ground.

OR

A single 3D mesh in some 3D model format (say, .fbx, .x, .obj whatever).

How should I approach level data storage? What would my best option be, performance-wise speaking? I'm also having some trouble when it comes to texturing a level loaded via a height map; using a 3D model makes texturing a breeze.

Thanks!

# Answer
> 4 votes
Performance-wise, both options should be equivalent since everything will be converted to a model sooner or later.

Heightmaps:
+Easy to store and edit
+Easy to calculate texture coordinates if they're not precalculated
-Poor texturing on steep surfaces
-Needs companion models for better detail
-Does not allow overlapping terrain (no overhangs).

Models:
+More control over horizontal displacement
+Overlapping terrain is possible
+Maximum control over textures
-Collision is a bit more complicated
-Could use up a bit more memory on disk

In my experience, it's best to use a somewhat flat heightmap for the base terrain and the use models for things like the stalagmites, and you can even use repeating models for such objects (to save memory).

Of course, you could use a vector field, but that's basically a model with easier texturing.

# Answer
> 1 votes
It might help if you told us what genre the game is, what the camera sees, etc. I assume you're talking about an FPS but I'm not sure.

Anyway, here's a link to a talk about the terrain in Halo Wars that I found interesting and may give you ideas: http://www.gdcvault.com/play/1277/HALO-WARS-The-Terrain-of . It deals with some of the issues and possible solutions you mentioned.

# Answer
> 0 votes
You don't necessarily have to choose one over the other, both can be effective, and there's no reason you can't combine the two.

If you use heightmaps, I would personally choose a bitmap format though. Directx should be able to do all the bitmap loading for you and turn it into a resource you can use. If you use a plain text file, you'll have to parse it yourself. This of course gives you some more freedom in interpreting the file, and might be a good starting point to allow easier experimentation.

One thing to consider though is that a heightmap will leave you with a fixed resolution, so the stalagmites you mention might be hard to represent well, unless you increase the pixel density of the entire map.

Generally, I'd say a heightmap is an effective means to store your terrain, but adding detail like stalagmites would be a lot more flexible with models.

---
Tags: c++, 3d, directx, level-design, heightmap
---


# Question
Title: calculate new vertex position given a transform matrix?
How can I get the new position of my vertex given a 4x4 transform matrix or simply 9 floats (positionX, positionY, positionZ, rotationH, rotationP, rotationR, scaleX, scaleY, scaleZ)? Usually I can assign the matrix to my final mesh (or "node", or "object", or "geom"), but right now I need to do it manually.

# Answer
> 5 votes
In order to apply a general 4x4 transformation matrix to a vertex represented as a 3 dimensional vector, you need to:

1. Expand the vector into the 4th dimension by adding a 1 as the w component:

`(x, y, z) => (x, y, z, 1)`
2. Multiply the transformation matrix by the 4 dimensional vector above. The result will be another 4 dimensional vector:

`( 4x4 matrix ) * (x, y, z, 1) => (tx, ty, tz, w)`

The general formula for multiplying a 4x4 matrix by a 4x1 vector is (if I didn't mess up):

```
[ m11 m12 m13 m14 ][ x ]   [ m11 * x + m12 * y + m13 * z + m14 * w ]
[ m21 m22 m23 m24 ][ y ]   [ m21 * x + m22 * y + m23 * z + m24 * w ]
[ m31 m32 m33 m34 ][ z ] = [ m31 * x + m32 * y + m33 * z + m34 * w ]
[ m41 m42 m43 m44 ][ w ]   [ m41 * x + m42 * y + m43 * z + m44 * w ]

```

Or if you consider the usual configuration of a transformation matrix:

```
[ m11 m12 m13 px ][ x ]   [ m11 * x + m12 * y + m13 * z + px ]
[ m21 m22 m23 py ][ y ]   [ m21 * x + m22 * y + m23 * z + py ]
[ m31 m32 m33 pz ][ z ] = [ m31 * x + m32 * y + m33 * z + pz ]
[ 0   0   0   1  ][ 1 ]   [ 1 ]

```
3. Convert it back into the 3rd dimension by homogenizing the vector, i.e. dividing everything by the fourth component `w`:

`(tx, ty, tz, w) => (tx/w, ty/w, tz/w)`

The thing is that if your transformation matrix only does a simple translation / rotation / scale, the value of `w` will be 1 and you can just drop the fourth component since that will be the same as dividing by 1.

But it's good to remember that dropping w component does not work for every case, e.g. with projection matrices you must remember to do this third step.

# Answer
> 1 votes
Matrix-vector multiplication:

```
[ rxx rxy rxz px ] [ vx ]   [ vx' ]
[ ryx ryy ryz py ] [ vy ]   [ vy' ]
[ ryx ryy ryz pz ] [ vz ] = [ vz' ]
[   0   0   0  1 ] [  1 ]   [  1  ]

```

See the page on wikipedia for more

---
Tags: 3d, matrix, vertex
---


title: Rotation going wrong

text:
# Question
Title: Rotation going wrong
I'm calculating matrices by hand. Translations are fine:

```
 void Translate (float x, float y, float z, float[4][4] m) {
     Identity (m);
     m[3][0] = x;
     m[3][1] = y;
     m[3][2] = z;
 }

```

If I multiply a vector with this matrix, I get the correct transformation. My problem now is Rotations. I copied the definition from the OpenGL reference on glRotation, but I can't get it right. Can you spot my mistake?

```
void Rotate (float angle, float x, float y, float z, float[4][4] m) {
    float c = cos (angle);
    float s = sin (angle);
    m[0][0] = x*x*(1-c)+c;
    m[0][1] = y*x*(1-c)+z*s;
    m[0][2] = x*z*(1-c)-y*s;
    m[0][3] = 0;
    m[1][0] = x*y*(1-c)-z*s;
    m[1][1] = y*y*(1-c)+c;
    m[1][2] = y*z*(1-c)+x*s;
    m[1][3] = 0;
    m[2][0] = x*z*(1-c)+y*s;
    m[2][1] = y*z*(1-c)-x*s;
    m[2][2] = z*z*(1-c)+c;
    m[2][3] = 0;
    m[3][0] = 0;
    m[3][1] = 0;
    m[3][2] = 0;
    m[3][3] = 1;
}

```

I don't know what else is relevant, so, if you're kind enough to lend me a hand on this and if I just don't present enough info, just say it.

Thank you for taking the time to read this question.

**EDIT** The trouble I'm having is the following: If I do `Rotate (180,0,0,0)`, the vertexes are inverted as intended but the resulting triangle (in this case) is smaller.

Screenshot:

# Answer
> 2 votes
The coefficient computations are correct. I can think of two things:

* you do not appear to ensure `(x,y,z)` is a unit vector; if the caller does not take care of this, you should divide each component by `sqrt(x²+y²+z²)`.
* the OpenGL convention is to have angles in degrees, and you are using `cos()` and `sin()` directly.

If none of these are your actual problem, you should describe what is going wrong exactly, maybe with a little example.

---
Tags: opengl, matrix
---