# Question
Title: Tracking Multiple Touches using Hash codes in Cocos2d for iPhone
How do you implement a touch hash code and reference it later? I have read about a "hash" code, but I don't understand how to use it. I want to know when two of my Sprites are touched at the same time, like as if pressing a chord on two keys of a piano.

Here is an example of what I have for my ccTouchesBegan:

```
- (void) ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

  NSSet *allTouches = [event allTouches];
  int validTouchCount = 0;
  for (UITouch* touch in allTouches) {

    BOOL touchIsValid = FALSE;

    CGPoint location = [touch locationInView: [touch view]];
    CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

    if (CGRectContainsPoint(_fourButtonsRect, convertedLocation)) {
        NSLog(@"Touch is within four buttons");
        touchIsValid = TRUE;
    }

    _playerDidAction = 0;
    NSLog(@"before the loop");
    if (touchIsValid) {

        validTouchCount++;
        NSLog(@"Within ValidTouches loop");
        CGPoint validLocation = [touch locationInView: [touch view]];
        CGPoint convertedValidLocation = [[CCDirector sharedDirector] convertToGL:validLocation];

        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedValidLocation)) {
            _redButtonStatus = TRUE;
            [_redButtonSprite setTexture:_redButtonLit];
            if (validTouchCount == 1) {
                _playerDidAction = 1;
            }
        }
            else if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedValidLocation)) {
                _blueButtonStatus = TRUE;
                [_blueButtonSprite setTexture:_blueButtonLit];
                if (validTouchCount == 1) {
                    _playerDidAction = 2;
                }
            }
                else if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedValidLocation)) {
                    _greenButtonStatus = TRUE;
                    [_greenButtonSprite setTexture:_greenButtonLit];
                    if (validTouchCount == 1) {
                        _playerDidAction = 3;
                    }
                }
                    else if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedValidLocation)) {
                        _yellowButtonStatus = TRUE;
                        [_yellowButtonSprite setTexture:_yellowButtonLit];
                        if (validTouchCount == 1) {
                            _playerDidAction = 4;
                        }
                    }

        if (validTouchCount > 1) {

            if (_redButtonStatus && _blueButtonStatus) {
                _comboRB = TRUE;
                _playerDidAction = 5;
            }
                else if (_redButtonStatus && _greenButtonStatus) {
                    _comboRG = TRUE;
                    _playerDidAction = 6;
                }
                    else if (_redButtonStatus && _yellowButtonStatus) {
                        _comboRY = TRUE;
                        _playerDidAction = 7;
                    }
                        else if (_blueButtonStatus && _greenButtonStatus) {
                            _comboBG = TRUE;
                            _playerDidAction = 8;
                        }
                            else if (_blueButtonStatus && _yellowButtonStatus) {
                                _comboBY = TRUE;
                                _playerDidAction = 9;
                            }
                                else if (_greenButtonStatus && _yellowButtonStatus) {
                                    _comboGY = TRUE;
                                    _playerDidAction = 10;
                                }

        }
    }
  }
}

```

And here is the beginning of my ccTouchesEnded:

```
- (void)ccTouchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {

    for (UITouch *touch in touches) {

        CGPoint location = [touch locationInView: [touch view]];
        CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedLocation)) {
            _redButtonStatus = FALSE;
            [_redButtonSprite setTexture:_redButtonNormal];
        }
        if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedLocation)) {
            _blueButtonStatus = FALSE;
            [_blueButtonSprite setTexture:_blueButtonNormal];
        }
        if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedLocation)) {
            _greenButtonStatus = FALSE;
            [_greenButtonSprite setTexture:_greenButtonNormal];
        }
        if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedLocation)) {
            _yellowButtonStatus = FALSE;
            [_yellowButtonSprite setTexture:_yellowButtonNormal];
        }

    }
}

```

Could you give me an example of how I would code the capture of the hash code in the touchesBegan and then reference the hash code in the touchesEnded? I have been struggling and can't get the hash code to work - just not understanding how the hash code can be used to reference a touch later. I guess what I'm trying to make would be called a hash tracker?

I am sure there is a much less convoluted way to do it using the hash codes and less state variables. I haven't fleshed out the ccTouchesEnded method with the other state variable effects because I was hoping to find a simpler way (I know I still need to make the ccTouchesMoved and Canceled methods too).

Any advise would be very appreciated as I am stuck! B)

# Answer
Here is how I implemented this in case anyone else is trying to do this (I have limited it to 2-button combos but I could easily extend the logic to 3 & 4-button combos as well). I chose to handle each touch individually using the ccTouchBegan/Ended/Moved instead of using the ccTouchesBegan/Ended/Moved because I just couldn't get it to work with the hash code. Any alternative ideas would be welcome.

spuButton.h (a CCSprite Subclass)

```
#import <Foundation/Foundation.h>
#import "cocos2d.h"

typedef enum tagButtonState {
 kButtonStatePressed,
 kButtonStateNotPressed
} ButtonState;

typedef enum tagButtonStatus {
 kButtonStatusEnabled,
 kButtonStatusDisabled
} ButtonStatus;

@interface spuButton : CCSprite <CCTargetedTouchDelegate> {
@private
 ButtonState buttonState;
 CCTexture2D *buttonNormal;
 CCTexture2D *buttonLit;
 ButtonStatus buttonStatus;
}

@property(nonatomic, readonly) CGRect rect;

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture;

- (void)setNormalTexture:(CCTexture2D *)normalTexture;
- (void)setLitTexture:(CCTexture2D *)litTexture;
- (BOOL)isPressed;
- (BOOL)isNotPressed;
- (void)makeDisabled;
- (void)makeEnabled;
- (BOOL)isEnabled;
- (BOOL)isDisabled;
- (void)makeLit;
- (void)makeNormal;
- (void)dealloc;

@end

```

spuButton.m

```
#import "spuButton.h"
#import "cocos2d.h"

@implementation spuButton

- (CGRect)rect {
 CGSize s = [self.texture contentSize];
 return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture {
 return [[[self alloc] initWithTexture:normalTexture] autorelease];
}

- (void)setNormalTexture:(CCTexture2D *)normalTexture {
 buttonNormal = normalTexture;
}
- (void)setLitTexture:(CCTexture2D *)litTexture {
 buttonLit = litTexture;
}

- (BOOL)isPressed {
 if (buttonState== kButtonStateNotPressed) return NO;
 if (buttonState== kButtonStatePressed) return YES;
 return NO;
}

- (BOOL)isNotPressed {
 if (buttonState== kButtonStateNotPressed) return YES;
 if (buttonState== kButtonStatePressed) return NO;
 return YES;
}

- (void)makeDisabled {
 buttonStatus = kButtonStatusDisabled;
 buttonState= kButtonStateNotPressed;
 [self makeNormal];
}
- (void)makeEnabled {
 buttonStatus = kButtonStatusEnabled;
 buttonState= kButtonStateNotPressed;
 [self makeNormal];
}

- (BOOL)isEnabled {
 if (buttonStatus== kButtonStatusDisabled) return NO;
 if (buttonStatus== kButtonStatusEnabled) return YES;
 return NO;
}

- (BOOL)isDisabled {
 if (buttonStatus== kButtonStatusEnabled) return NO;
 if (buttonStatus== kButtonStatusDisabled) return YES;
 return YES;
}

- (void)makeLit {
 [self setTexture:buttonLit];
}

- (void)makeNormal {
 [self setTexture:buttonNormal];
}

- (id)initWithTexture:(CCTexture2D *)aTexture {
 if ((self = [super initWithTexture:aTexture]) ) {
  buttonState = kButtonStateNotPressed;
  buttonStatus = kButtonStatusEnabled;
 }
 return self;
}

- (void)onEnter {
 if (buttonStatus == kButtonStatusDisabled) return;
 [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
 [super onEnter];
}

- (void)onExit {
 if (buttonStatus == kButtonStatusDisabled) return;
 [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
 [super onExit];
}

- (BOOL)containsTouchLocation:(UITouch *)touch {
 return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
 if (buttonStatus == kButtonStatusDisabled) return NO;
 if (buttonState== kButtonStatePressed) return NO;
 if ( ![self containsTouchLocation:touch] ) return NO;

 buttonState= kButtonStatePressed;
 [self makeLit];

 return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
 // If it weren't for the TouchDispatcher, you would need to keep a reference
 // to the touch from touchBegan and check that the current touch is the same
 // as that one.
 // Actually, it would be even more complicated since in the Cocos dispatcher
 // you get NSSets instead of 1 UITouch, so you'd need to loop through the set
 // in each touchXXX method.

 if (buttonStatus == kButtonStatusDisabled) return;
 if ([self containsTouchLocation:touch]) return;

 buttonState= kButtonStateNotPressed;
 [self makeNormal];
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
 if (buttonStatus == kButtonStatusDisabled) return;

 buttonState= kButtonStateNotPressed;
 [self makeNormal];
}

- (void)dealloc {
 [buttonNormal release];
 [buttonLit release];
 [super dealloc];
}

@end

```

HelloWorldScene.m (Just my tick: method to keep my other functions from confusing the example)

```
-(void)tick:(ccTime)dt {
 if ([[_otherControlsArray objectAtIndex:0] wasPressed]) {
  [[_otherControlsArray objectAtIndex:0] setWasPressed:NO];
  [self removeChild:[_otherControlsArray objectAtIndex:0] cleanup:YES];
  [self addChild:[_otherControlsArray objectAtIndex:1]];
  NSLog(@"Play");

  _gameHasNotBeenPlayedYet = NO;
  Snarfle_s_PowerUPAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
  [delegate makeNotPaused];
  [self gameLogic];
 }

 if (_gameHasNotBeenPlayedYet) {
  return;
 }

 if (_buttonsPressedAndReleased > 0) {  //respond to button(s) released and reset
  NSLog(@"Buttons Pressed and Released-->%d",_buttonsPressedAndReleased);
  if ([self checkButtons:_buttonsPressedAndReleased]);
  _buttonsPressed = 0;
  _buttonsPressedAndReleased = 0;

  return;
 }
 if (_buttonsPressed <= 4) { // two buttons have not already been pressed
  for (spuButton *aButton in _fourButtonsArray) {
   if ([aButton isNotPressed]) continue; //this button is not pressed
   if (_buttonsPressed == 0) { //this button is pressed and no other buttons have been pressed
    _buttonsPressed = aButton.tag;
    continue;
   }
   //this button is pressed while another has been pressed
   //figure out which two buttons have been pressed
   if (_buttonsPressed == 1) {  //red plus another
    switch (aButton.tag) {
     case 2:   //blue
      _buttonsPressed = 5;
      [[_fourButtonsArray objectAtIndex:2] makeDisabled];
      [[_fourButtonsArray objectAtIndex:3] makeDisabled];
      break;
     case 3:  //green
      _buttonsPressed = 6;
      [[_fourButtonsArray objectAtIndex:1] makeDisabled];
      [[_fourButtonsArray objectAtIndex:3] makeDisabled];
      break;
     case 4:  //yellow
      _buttonsPressed = 7;
      [[_fourButtonsArray objectAtIndex:1] makeDisabled];
      [[_fourButtonsArray objectAtIndex:2] makeDisabled];
      break;
     default:
      _buttonsPressed = 1;
      break;
    }
   }
   if (_buttonsPressed == 2) {  //blue plus another
    switch (aButton.tag) {
     case 1:   //red
      _buttonsPressed = 5;
      [[_fourButtonsArray objectAtIndex:2] makeDisabled];
      [[_fourButtonsArray objectAtIndex:3] makeDisabled];
      break;
     case 3:  //green
      _buttonsPressed = 8;
      [[_fourButtonsArray objectAtIndex:0] makeDisabled];
      [[_fourButtonsArray objectAtIndex:3] makeDisabled];
      break;
     case 4:  //yellow
      _buttonsPressed = 9;
      [[_fourButtonsArray objectAtIndex:0] makeDisabled];
      [[_fourButtonsArray objectAtIndex:2] makeDisabled];
      break;
     default:
      _buttonsPressed = 2;
      break;
    }
   }
   if (_buttonsPressed == 3) {  //green plus another
    switch (aButton.tag) {
     case 1:   //red
      _buttonsPressed = 6;
      [[_fourButtonsArray objectAtIndex:1] makeDisabled];
      [[_fourButtonsArray objectAtIndex:3] makeDisabled];
      break;
     case 2:  //blue
      _buttonsPressed = 8;
      [[_fourButtonsArray objectAtIndex:0] makeDisabled];
      [[_fourButtonsArray objectAtIndex:3] makeDisabled];
      break;
     case 4:  //yellow
      _buttonsPressed = 10;
      [[_fourButtonsArray objectAtIndex:0] makeDisabled];
      [[_fourButtonsArray objectAtIndex:1] makeDisabled];
      break;
     default:
      _buttonsPressed = 3;
      break;
    }
   }
   if (_buttonsPressed == 4) {  //yellow plus another
    switch (aButton.tag) {
     case 1:   //red
      _buttonsPressed = 7;
      [[_fourButtonsArray objectAtIndex:1] makeDisabled];
      [[_fourButtonsArray objectAtIndex:2] makeDisabled];
      break;
     case 2:  //blue
      _buttonsPressed = 9;
      [[_fourButtonsArray objectAtIndex:0] makeDisabled];
      [[_fourButtonsArray objectAtIndex:2] makeDisabled];
      break;
     case 3:  //green
      _buttonsPressed = 10;
      [[_fourButtonsArray objectAtIndex:0] makeDisabled];
      [[_fourButtonsArray objectAtIndex:1] makeDisabled];
      break;
     default:
      _buttonsPressed = 4;
      break;
    }
   }
   if (_buttonsPressed > 4) break;  //more than one has been pressed and identified
  }
 }
 //now we know what buttons have been pressed now check to see if they have been released
 //if more than one has been pressed disable the other two
 //also if more than one has been pressed and one of them gets released disable the released one but keep it lit
 switch (_buttonsPressed) {
  case 1:  //red
   if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) _buttonsPressedAndReleased = 1;
   break;
  case 2:  //blue
   if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) _buttonsPressedAndReleased = 2;
   break;
  case 3:  //green
   if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) _buttonsPressedAndReleased = 3;
   break;
  case 4:  //yellow
   if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) _buttonsPressedAndReleased = 4;
   break;
  case 5:  //red & blue
   if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:1] isNotPressed])) _buttonsPressedAndReleased = 5;
   else {
    if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:0] makeDisabled];
     [[_fourButtonsArray objectAtIndex:0] makeLit];
    }
    if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:1] makeDisabled];
     [[_fourButtonsArray objectAtIndex:1] makeLit];
    }
   }
   break;
  case 6:  //red & green
   if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 6;
   else {
    if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:0] makeDisabled];
     [[_fourButtonsArray objectAtIndex:0] makeLit];
    }
    if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:2] makeDisabled];
     [[_fourButtonsArray objectAtIndex:2] makeLit];
    }
   }
   break;
  case 7:  //red & yellow
   if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 7;
   else {
    if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:0] makeDisabled];
     [[_fourButtonsArray objectAtIndex:0] makeLit];
    }
    if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:3] makeDisabled];
     [[_fourButtonsArray objectAtIndex:3] makeLit];
    }
   }
   break;
  case 8:  //blue & green
   if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 8;
   else {
    if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:1] makeDisabled];
     [[_fourButtonsArray objectAtIndex:1] makeLit];
    }
    if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:2] makeDisabled];
     [[_fourButtonsArray objectAtIndex:2] makeLit];
    }
   }
   break;
  case 9:  //blue & yellow
   if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 9;
   else {
    if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:1] makeDisabled];
     [[_fourButtonsArray objectAtIndex:1] makeLit];
    }
    if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:3] makeDisabled];
     [[_fourButtonsArray objectAtIndex:3] makeLit];
    }
   }
   break;
  case 10:  //green & yellow
   if (([[_fourButtonsArray objectAtIndex:2] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 10;
   else {
    if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:2] makeDisabled];
     [[_fourButtonsArray objectAtIndex:2] makeLit];
    }
    if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
     [[_fourButtonsArray objectAtIndex:3] makeDisabled];
     [[_fourButtonsArray objectAtIndex:3] makeLit];
    }
   }
   break;
  default:
   _buttonsPressedAndReleased = 0;
   break;
 }
}

```
> 0 votes

# Answer
To reduce the amount of `if` statements you have you need to make your solution *data-driven* instead of manually adding logic for each UI component that needs to interact.

You could do this by storing your buttons data (such as each buttons bounding box and state) in an array of structs or a NSArray (or NSMutableArray) of classes. Then when you receive a touch you just need to iterate over the list to see if any touches are inside the bounding box, if it is then update that objects texture.

To keep track of touches across their lifetime I use a single NSMutableDictionary with the touches pointer as its key and a custom class as its value. This allows me to store information per touch (such as if I've already handled it) and react to touches that are held and not moving.
> 3 votes

# Answer
i'm guessing that you are tiring of typing all those if statements.

maybe a simple addition to what you already seem to have going on is to add a setStatus method to your sprite class. also make the sprite object track what its state TRUE and state FALSE textures are. then you can just iterate thru the touches and check all your objects in a loop with a single setState call.

unless you have a zillion sprites it will probably be no slower than what you have going on now.

im not sure at all what you mean by hash codes in this instance?
> 0 votes

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


# Question
Title: Framework suitable for 3D RTS ala Homeworld?
I would like to make a game that amalgamates Homeworld and Freespace with inspirations from the novel Ender's game. This is probably not a new idea, but I haven't seen anything that did anything like it. It would be team based and allows players to control units in an RTS (Homeworld) or first person fashion (Freespace)

I was doing some research on frameworks to help get me started, and my findings are summarized below. I believe one of the hardest parts is going to be UI, which Homeworld did a decent job at, but could be improved slightly.

OGRE: just covers graphics, with plugs for collision detection

Irrilicht: Covers graphics / collision with plugins for Sound. looks dated, though mainly because of aged art assets

Unity: While looks fairly complete, the Free version is feature robbed, and Feels more like a "for artists" tool. I would like to be figuring out programming problems, not where buttons are on menus.

Torque: From what I hear is abandoned.

Are there other obvious choices that I missed?

# Answer
Unity is fairly easy to use, may take a small while, but it is worth it. Learning it can be fast thanks to UnityAnswers, a site stackoverflow-styled where you can ask pretty much anything about Unity and they usually answer pretty quickly. Unity supports a couple languages, like Javascript. Unity is pretty interesting, you make prefabs of your game objects and put them in your scenes. Performance is good, and I believe networking is fine as well.

It has great water surface assets, real-time lighting, tree creator, landscapes, skyboxes, a nice way to "expose" variables and quickly edit them without going directly into the code, nice HUD system, etc. Apparently, Unity Pro comes with a couple great performance tools that might come handy when drawing your game scenes too. There is also the Asset Store. You can buy graphic packs or other code projects, in case you need a boost somewhere in your game development.

Unity has a strong community, support and good documentation covering all the supported languages. Worth giving it a go. Learning may take a while thought.
> 3 votes

# Answer
The Homeworld Engine is available and open for use. Though I'm not 100% sure about the license for distribution. I would say that the Homeworld engine would be a great place to start for a Homeworld Style game. It it is free you are after look no further.
> 1 votes

---
Tags: rts
---


# Question
Title: problem with frustum AABB culling in DirectX
I am currently working on a project with a few friends, and I am trying to get frustum culling working. Every single tutorial or article I go to shows that my math is correct and that this should be working. I thought maybe posting here, somebody would catch something I could not. Thank you.

Here are the important code snippets

```
     /create the projection matrix
void CD3DCamera::SetLens(float fov, float aspect, float nearZ, float farZ)
{
 D3DXMatrixPerspectiveFovLH(&projMat, D3DXToRadian(fov), aspect, nearZ, farZ);
}

//build the view matrix after changes have been made to camera
void CD3DCamera::BuildView()
{
 //keep axes orthoganal
 D3DXVec3Normalize(&look, &look);

 //up
 D3DXVec3Cross(&up, &look, &right);
 D3DXVec3Normalize(&up, &up);

 //right
 D3DXVec3Cross(&right, &up, &look);
 D3DXVec3Normalize(&right, &right);

 //fill view matrix
 float x = -D3DXVec3Dot(&position, &right);
 float y = -D3DXVec3Dot(&position, &up);
 float z = -D3DXVec3Dot(&position, &look);

 viewMat(0,0) = right.x;
 viewMat(1,0) = right.y;
 viewMat(2,0) = right.z;
 viewMat(3,0) = x;

 viewMat(0,1) = up.x;
 viewMat(1,1) = up.y;
 viewMat(2,1) = up.z;
 viewMat(3,1) = y;

 viewMat(0,2) = look.x;
 viewMat(1,2) = look.y;
 viewMat(2,2) = look.z;
 viewMat(3,2) = z;

 viewMat(0,3) = 0.0f;
 viewMat(1,3) = 0.0f;
 viewMat(2,3) = 0.0f;
 viewMat(3,3) = 1.0f;
}

    void CD3DCamera::BuildFrustum()
{

 D3DXMATRIX VP;
 D3DXMatrixMultiply(&VP, &viewMat, &projMat);

 D3DXVECTOR4 col0(VP(0,0), VP(1,0), VP(2,0), VP(3,0));

 D3DXVECTOR4 col1(VP(0,1), VP(1,1), VP(2,1), VP(3,1));

 D3DXVECTOR4 col2(VP(0,2), VP(1,2), VP(2,2), VP(3,2));

 D3DXVECTOR4 col3(VP(0,3), VP(1,3), VP(2,3), VP(3,3));

 // Planes face inward
 frustum[0] = (D3DXPLANE)(col2);    // near
 frustum[1] = (D3DXPLANE)(col3 - col2);  // far
 frustum[2] = (D3DXPLANE)(col3 + col0);  // left
 frustum[3] = (D3DXPLANE)(col3 - col0);  // right
 frustum[4] = (D3DXPLANE)(col3 - col1);  // top
 frustum[5] = (D3DXPLANE)(col3 + col1);  // bottom

 // Normalize the frustum
 for( int i = 0; i < 6; ++i )
  D3DXPlaneNormalize( &frustum[i], &frustum[i] );

}

    bool FrustumCheck(D3DXVECTOR3 max, D3DXVECTOR3 min, const D3DXPLANE* frustum)
{
 // Test assumes frustum planes face inward.

 D3DXVECTOR3 P;
 D3DXVECTOR3 Q;
 bool ret = false;

 for(int i = 0; i < 6; ++i)
 {
  // For each coordinate axis x, y, z...
  for(int j = 0; j < 3; ++j)
  {
   // Make PQ point in the same direction as the plane normal on this axis.
   if( frustum[i][j] > 0.0f )
   {
    P[j] = min[j];
    Q[j] = max[j];
   }
   else
   {
    P[j] = max[j];
    Q[j] = min[j];
   }
  }

  if(D3DXPlaneDotCoord(&frustum[i], &Q) < 0.0f  )
   ret = false;
 }
 return true;
}

```

# Answer
> 2 votes
Thank you for looking at the code, everyone that did, I have fixed the problem. The problem was that our level editor's coordinate system was flipped on the x axis. So what we had to do was flip the x on the vectors of the min/max of the bounding boxes so that they were accurate. However, eventually we will go back and fix the level editor so that it has the correct coordinate system. lol

---
Tags: collision-detection, directx, rendering, frustum
---


# Question
Title: Recursive dungeon maps as represented by an elastic 2d array
I came up with a method for recursively generating simple dungeon maps by starting with one room and recursively connecting new adjacent rooms randomly to it.

Maps are represented as two dimensional arrays where each cell contains a value of 0-15. 0 represents no room while each direction is represented by north=1, east=2, south=4, west=8.

I wanted to start with a single non room (\[\[0\]\]) and then expand the 2d array as necessary to fit the generated map. The difficulty I face with this tree like recursion is that if the arrays have to be unshifted to add rows and columns to the left and top of the map, I have to adjust the current position of the function, what row and column it is at. This makes it so that separate branches are not aware of array index adjustments from other branches, only their child functions will know because they have the adjusted position passed to them as their row and column arguments.

Is there a way to do this? I tried storing row and column offset values outside of the recursion, but it did not work for some reason.

# Answer
> 5 votes
Is there a reason you must use a 2D array, or would some a hash table or other kind of map work? Then the x,y indices just continue into negative space, but it doesn't matter.

If you're concerned about memory or CPU speed, 1) Don't be, hash tables are very efficient at things like pairs of dense integers, 2) you can build the level in a hash table and then post-process it into an array once you know the final size.

# Answer
> 2 votes
I'm doing a similar thing, in Python. (Or at least the elastic part).

I have a dictionary of (x,y) tuples mapping to the cells. In pseudo code:

```
map = dictionary( (0,0) : cell at (0,0), (1,0) : cell at (1,0) ... (2, 2) : cell at (2,2)
getCell(x,y):
    return map[(x,y)]
    catch error if out of bounds:
         map[(x,y)] = new cell and return

```

A hash table would be very good for this kind of thing.

# Answer
> 1 votes
The minimum effort solution is to pick a maximum size (X and Y extent) that you want the dungeon to reach, put your starting point in the center of that, and don't allow growth outside of it. No need to do any shifting. Depends on a fixed extent being acceptable, of course.

# Answer
> -1 votes
You would want to use a graph instead of the 2D array.

Each room would be a node in the graph and knows which other rooms are adjacent to it:

```
Room {
    long x;
    long y;
    List adjacentRooms;
}

```

That way you don't have to define how large your map can become.

The x,y-Coordinates can be used as unique key in a hashmap for fast access to each room. Adding a new room would just add entries to the adjacentRooms lists of the rooms close-by.

The graph is also great for path finding algorithms, if you need them.

---
Tags: software-engineering, game-mechanics, level-design
---


# Question
Title: How to make footsteps sound sync with animation (FMOD/Wwise/similar)
How do you pros out there implement footstep sounds in so that they're synced with character animation?

I have an idea in mind: an FMOD event that has two footstep playback triggers, and a parameter that controls how fast each plays back in sequence, and the event is triggered as soon as the animation is on a frame (assuming the programmer handling animation will post an event or update a param for this) where you could reasonably assume the character's foot has hit the ground.

Is this overkill, or assuming too much accuracy out of an engine?

This is not a specific project, but I am working on integrating FMOD Designer support into an existing engine and am thinking of some general effects to implement while the audio spec is being figured out. Also, I mention FMOD since that's what we're using, but if anyone's done similar syncing tasks in Wwise, XACT or anything else (or heck, even if you hand-coded it) and could share their experiences that'd be great to hear as well.

# Answer
The way I typically do that is set up animation events that are hooked up to each frame that would require a footstep sound. So in the walk animation there will typically be two steps, so at those frames I tell whatever sound system I'm using to play a random step sound. (In your case, I think it's just a regular fmod event.)

Another way I've seen it done is by using your engine's physics engine. Attach colliders to your characters feet (parent them to the bones or something), and when they hit the ground play a step sound in the same way. I've personally never done it that way, though.

Either way, it's less "how do I do this in FMOD", and more "how do I do this with our animation or physics system".

One thing that sound guys will tell you is that "random sounds" isn't just picking from your sound randomly. The way you're supposed to do it is by shuffling all of your sounds from whatever bank you're currently picking from, and then go through that shuffled list in order. That way you don't run into the issue where your random number generator can get into a situation where it plays the same sound multiple times in a row.
> 12 votes

# Answer
Adding a "play sound" tag at specific keyframes in the walk animation is how I've always done it.
> 1 votes

---
Tags: audio, synchronization, fmod
---


# Question
Title: Visual Programming tool for creating game quests
I've found a question for visual script editing software tool for creating game behavior logic, but I am looking for something more flexible. I would like to configure the tool to make it produce code that I need. I use Lua for creating quests in my mmorpg game, but every time there is need of creating a new quest I feel like writing the same code all the time. I'd like to allow my co-workers to do this job in some easy way. The easiest way I can think of would be some sort of making graphs that would represent the quest, and fill all the nodes with different if statements and game texts or procedures like spawning mobs.

Is there any tool that I could use for this purpose?

# Answer
> 6 votes
Programming Role-Playing Games with DirectX walks through creating what the author calls a "Mad Lib Script System", complete with the editor and the module of the engine that is created over the course of the book. It would surely take some tweaking and doesn't generate LUA so it might be totally unrelated to what you need, but on the other hand, its functionality sounds a lot like what you describe: It takes a dictionary of different possible actions, and then scripts can be created which are just lists of the actions with the blanks filled in, like a Mad Lib. It's made to be extremely user friendly.

Here is a screenshot. I could not find the code online but it does come in full on the book's CD-ROM and of course is explained over the course of one of the chapters of the book (Chapter 10). (this is a Windows executable, but I ran it in Wine to take the screenshot, thus the Mac titlebar and old Windows 2000 look)

# Answer
> 4 votes
I would probably create your own editor. You can use C# or something similar to create a very simple windows application.

If you want to abstract away from having to script things using text, you can take a graphical approach (i.e. using buttons to add a goal). The only things that I would have as textual input are conditions, values, etc.

Firstly, I'd look over your LUA scripts, find the common elements and isolate them.

Then look at all the possible actions or goals that make up a quest and add a combo box with all those possible actions.

So for example, the quest is to kill 10 zombies, the workflow I would imagine is this:

1. Select "Kill" from Goals combo box
2. Another combo box appears with a list of enemies, select "Zombie"
3. Enter the condition in the condition textbox, so add "10".
4. Click "Add Goal"
5. The "Kill 10 Zombies" goal is added to the Quest listbox
6. If you want to change the sequence, just have some "Move up", "Move down" buttons

After you've finished "building" your quest like this, you can then just click the "Compose Script" button and it'll map all the actions you have listed to your LUA code, including the common stuff that you have in every script.

Hope that helps.

---
Tags: software-engineering, mmo, scripting
---


# Question
Title: Calculating camera frustum planes using existing matrix
I'm trying to get basic frustum culling against an AABB working, and I'm having a bit of trouble figuring out how to extract the frustum planes from my camera's transform matrix. All the example code I've found expects position, look, and up vectors, as you'd pass to gluLookAt. My camera matrix can be transformed by a parent and other bits of code, so those vectors never exist anywhere that I could use them.

I've looked at code for gluLookAt and tried to graft the inverse of that on top of the Lighthouse3D example for creating the Frustum planes. It's really close to correct, but I have objects flickering in and out of existence still, so something's not quite right. All of the related code is here, so I'm hoping this will be an easy find for somebody.

```
struct Frustum {
  enum {
    TOP,
    BOTTOM,
    LEFT,
    RIGHT,
    NEAR,
    FAR
  };

  Frustum(hsMatrix44 cam, float znear, float zfar, float angle, float aspect) {
    float nw, nh, fw, fh, tang;
    tang = (float)tan(angle * 0.5);
    nh = znear * tang;
    nw = nh * aspect;
    fh = zfar  * tang;
    fw = fh * angle;

    hsVector3 dir,nc,fc,X,Y,Z,P,U;
    hsVector3 ntl,ntr,nbl,nbr,ftl,ftr,fbl,fbr;

    Z.X = -cam(2,0);
    Z.Y = -cam(2,1);
    Z.Z = -cam(2,2);
    U.X = cam(1,0);
    U.Y = cam(1,1);
    U.Z = cam(1,2);
    X = U.crossP(Z);
    X = X * (1.f/X.magnitude());
    Y = Z.crossP(X);
    hsMatrix44 icam = cam.inverse();
    P.X = icam(0,3);
    P.Y = icam(1,3);
    P.Z = icam(2,3);
    nc = P - Z * znear;
    fc = P - Z * zfar;

    ntl = nc + Y * nh - X * nw;
    ntr = nc + Y * nh + X * nw;
    nbl = nc - Y * nh - X * nw;
    nbr = nc - Y * nh + X * nw;
    ftl = fc + Y * fh - X * fw;
    ftr = fc + Y * fh + X * fw;
    fbl = fc - Y * fh - X * fw;
    fbr = fc - Y * fh + X * fw;

    planes[TOP] = planeFromPoints(ntr, ntl, ftl);
    planes[BOTTOM] = planeFromPoints(nbl, nbr, fbr);
    planes[LEFT] = planeFromPoints(ntl, nbl, fbl);
    planes[RIGHT] = planeFromPoints(nbr, ntr, fbr);
    planes[NEAR] = planeFromPoints(ntl, ntr, nbr);
    planes[FAR] = planeFromPoints(ftr, ftl, fbl);
  }

  bool checkBox(const hsBounds3Ext& box) {
    for(int i = 0; i < 6; ++i) {
      float d0, d1;
      d0 = planes[i].W + planes[i].N.dotP(box.getMins());
      d1 = planes[i].W + planes[i].N.dotP(box.getMaxs());
      if((d0 < 0.f) && (d1 < 0.f))
        return false;
    }
    return true;
  }

  hsPlane3 planes[6];
};

hsPlane3 planeFromPoints(hsVector3 a, hsVector3 b, hsVector3 c) {
  hsPlane3 p;
  hsVector3 tmp0, tmp1;
  tmp0 = a - b;
  tmp1 = c - b;
  p.N = tmp1.crossP(tmp0);
  p.N = p.N * (1.f/p.N.magnitude());
  p.W = -(p.N.dotP(b));
  return p;
}

```

# Answer
I am using a function to extract the frustum from my Projection and modelview Matrix. This code was developed by a friend of mine using some Maple 5 or something like that. The code is a bit bulky (~10K) and the comments are in german, but it works fine ( i use it for octree-frustum culling in my OpenGL-Application).

The project is hosted on Sourceforge ( http://sourceforge.net/projects/sumkindaproject/ ).

The frustum-extraction and checking code is located in the folders inc/frustum.h and src/frustum.cpp

Please don't mind the nasty coding style in other files of this project, since it is more or less an experimental playground app - the Culling however works fine ;)
> 1 votes

---
Tags: camera, culling, frustum
---


title: RTS Engine or DotA-like game

text:
# Question
Title: RTS Engine or DotA-like game
Is there any good **documented** and **simple** Game engine for RTS games, especially for building DotA-like game?

I know I can use Crystal Space, Irrlicht or another Game Engine. But I need most similar game or engine to DotA gameplay.

# Answer
The Warcraft III and Starcraft II editors are probably, almost by definition, the best engines to make DotA-like games in. They are reasonably well documented, simpler than anything suggested thus far, and have a proven record of being able to make excellent RTS games.
> 12 votes

# Answer
Spring RTS engine looks very nice.
Stratagus is another option.

Both the above came from the search 'c++ RTS engine'.
> 9 votes

# Answer
Glest, especially MegaGlest and the Glest Advanced Engine (forums)

Its a classic RTS engine that is fairly straightforward to 'mod' and add 'factions' using 3D models and XML files to define the unit attributes. It can be used as a basis for 'total conversions' and the code-base is accessible enough to add specific features. It may be that you don't actually need to touch the code, however - its designed to be modded!

MegaGlest 3.4 has just reached beta - its an awesome engine that's approachable to modding.
> 7 votes

# Answer
The Neoaxis Engine might be an idea. When I was evaluating it, I recall that part of the demo involved an RTS. It's general purpose, and may be a little raw for what you want, though.
> 3 votes

---
Tags: c++, rts
---


# Question
Title: Where to start writing games, any tutorials or the like?
I'm actually an industrial systems developer with knowledge of .NET C# and VB.NET, C/C++, Delphi, and an intermediate knowledge of 80286 Intel assembly language.

I would be interested to learn how to develop games while taking as fully as possible advantage of my already acquired experience.

My first objective is to learn the differences between management and game software development so that I may make my mind up as to what is important to think about as a game developer.

Any hint as to where to start to learn is appreciated, such as game writing tutorials, the kind of "Hello World!" program, if I may say.

Besides, these following tutorials were found while "googling":

1. C++ Game Programming;
2. C and C++ Programming Games and Entertainment Tutorials;
3. C++ Game Programming Resource Center;
4. Creating a game in C++.

Are they any good?

The answer that will have guided me the most will be accepted. Thanks for your help! =)

# Answer
With your .NET experience, I'd suggest getting read up on XNA. It's a .NET framework for creating games on Windows, Xbox 360, and Windows Phone 7.

The "Hello World" of the games world is probably a very simple game like Pong or Breakout. There are plenty of tutorial on XNA:

http://create.msdn.com/en-US/education/catalog/tutorial/2d\_chapter\_1

http://www.riemers.net/

And check out the http://www.gamedev.net forums as they currently have an XNA 4.0 workshop going on.

That's just a taster of what you can do and getting a basic sense of game architecture. I'd recommend getting Game Coding Complete (any edition) by Mike McShaffry. It offers a good overview of all aspects of game development without bombarding you with irrelevant facts.

EDIT:

With regards to the tutorials that you have found, personally, I don't like the look of http://www.cppgameprogramming.com Simply because it looks like a C++ wrapped around C. If you're using C++, I'm of the opinion that you should be using the object-oriented features in C++.

I haven't used SDL, but have heard a lot of good things about it so I would read up on it and use Jari Komppa's link to it.

The last link is also in C, so I don't think it's completely relevant.

Just to clarify, I'm not against the use of C for game development at all. I just think a game that is designed using an OOP approach is easier to understand (and therefore implement in code), especially when you're starting out with game dev.

Hope that helps.

Ray
> 10 votes

---
Tags: c#
---


title: Game engine for "racing" game

text:
# Question
Title: Game engine for "racing" game
I've been planning for a long time to mix data from OpenStreetMap, some digital elevation model (heightmap), satellite imagery for textures, and cook a racing/cruising game where I could drive around familiar parts of the city.

OpenStreetMap contains very nice and detailed maps of all the locations I've checked, so I imagine it won't be so hard to download data for a specified region, like Boone County, Nebraska and stuff them into the game. I could generate buildings in 3d somewhat, as they have defined contour in OpenStreetMap. Roads would be the easiest thing to do as they are the core part of OSM.

What I'm worried about is the game/"simulator" part. I don't know where particularly to start. I suppose I would have to generate a lot of this world during the loading / on the fly. I don't even know if there is anything racing/vehicular-like out there available to use, except for the XNA Racing Game. I'm employed as C# developer, so I'm skilled in that language, but I'd be willing to venture into Python or something similar, if it would increase productivity in this hobby project.

Can you recommend me some engines worth looking into?

# Answer
> 6 votes
Personally I don't think there's that much special about racing games that makes them that specific to choose engines for.

I would think that things like cost, language, platforms, art pipeline, etc. are more relevant to the topic at hand. Since there are at least a dozen "what engine should I use for game type X" questions out there I'm not going to rehash the same answers over and over.

A lot of the problems with making a game can be solved by not picking a design that requires advanced features. Don't try to make a racing game with Forza-style ultra realistic physics. Don't try to make a game where there are streaming levels or procedurally generated levels. Solve the "make the game fun" part first, then add the complicated features. Pretty much any engine with some kind of middleware can be used to some success to make a car work. Visibility problems and solutions (occlusion culling, mainly) are going to be similar in pretty much all engines.

All that being said, if you're completely floundering about, the Unity guys put together a sample project with a pair of cars that would get you up and running pretty quickly, and the Unity engine itself is easy to use. See http://blogs.unity3d.com/2010/04/24/car-tutorial/

---
Tags: racing
---


title: Make Pong on android using OpenGL-ES

text:
# Question
Title: Make Pong on android using OpenGL-ES
I am trying to make a simple pong game using opengl-es. I have checked out some of the tutorials/samples, but most of them are pre-dated to 2009.

I am familiar with game programming, and consider pong to be the hello-world!

Right now, I intend to make it using their supplied SDK (2.3), but eventually I want to make it in NDK, so I can port my other work to android.

Would anyone have a good reference for a starting point ?

Thanks

# Answer
> 2 votes
If you are already familiar with game programming, I would suggest you to get started with studying some source code. Here you can find an Pong for Android with source-code: http://code.google.com/p/android-pong/

If you would prefer something like an tutorial, here you go: http://mikeyhogarth.wordpress.com/2010/10/09/how-to-develop-pong-for-android/

And further I would also recommend you the Android Reference to get started: http://developer.android.com/reference/packages.html

If you try it and get lost somewhere, you can come back here with more precise questions...

# Answer
> 0 votes
There is not a single feature your game requires that would necessitate the need for the Android SDK 2.3 (Ginger bread). For instance, the improvements to the phone camera(s) in the 2.3 sdk will do nothing to improve your game of Pong whatsoever.

Do your game with Android SDK 1.6. Test it out with a 2.3 emulator, and you'll see that it works just fine on anything 1.6 and above. If you're doing this game to learn OpenGL (which frankly, your simple 2D game doesn't really need either), then you can use OpenGL ES 1.1 within Android 1.6, or if you'd prefer to learn OpenGL ES 2.0 instead, then target Android 2.1.

My point is: either do 1.6 or 2.1, they will both work as intended on phones and emulators of higher versions, but do not do it on 2.3, there is not only no reason to do so, and the syntax isn't even different, but that needless move would only ensure that your program couldn't run on anything, but the Nexus S (the only phone that runs Ginger bread right now).

---
Tags: android, opengl-es
---


# Question
Title: jquery ondrag map load only what has not been viewed
When a person mouse down, moves the mouse, and mouses up the system gets the different in the mouse down coord and the mouse up coords and loads in the new map items. However, the problem is it loads them every time so I want a way to track what has been loaded without too much work on checking or storing checks.

* Most promising. Came up with while typing this. Section the screen into 250x250 sectors and check if that sector has been loaded.
* Keep track of each corner of the screen and see if there is an area of those that have not loaded.
* Keep a record of the corners of the screen. When mouse up coords are greater then load the different. Problem is if they are at coord 10,000 then it will load from -10k to 10k positive and that is a lot of items to load.
* Check every item on the page to see if it is loaded. If I do this I might as well reload the whole page.

If anyone has some suggestions; feel free to pass them on.

# Answer
> 2 votes
You might just want to look at a Javascript based "slippy map" library like Polymaps or OpenLayers. These already do the kind of tile-based sectioning that you (correctly) surmise would work.

# Answer
> 0 votes
Unless I misunderstand your question, I would expect what you describe to be desired behavior. It seems to me, like you are streaming the mapping data as the user pans around the map. As soon as it's off the screen, I would unload those resources and then load up resources for the newly visible sections.

If you don't unload resources as the user pans around, eventually, the user will have the entire map loaded into memory, and this would defeat the purpos of streaming data to the user in the first place.

If the actual streaming of the map is what's got you stumped, I think your first approach is best. Put the map into sections (usually called Tiles) as the user pans around, determine which tiles should be loaded and unloaded, then render all of the loaded tiles.

---
Tags: javascript, maps
---


# Question
Title: Different camera movement methods in a 2d- side-scrolling game that makes it fun
Possible reference to this question, but I want specific answers pertaining to Side-scrollers.

IMO, side-scrollers can be classified as

1. Player doesn't move, the background graphics move to fake player movement.
2. Player moves also background moves, but background movement is dependent on the (x,y) movement of the player \> I find this more appealing
3. Player can't move, the background moves at a fast speed. Depending upon the obstacles coming along with the background the player has to perform actions like jumping, ducking, charging, etc...

I would like to know what all *other things* can be added to the gameplay so that the above mentioned 3 side-scroller categories can be made more addicting.Please mention the category of the side-scroller in your reply.

**Edit** Modified the question title to reflect what I actually want

# Answer
I've written pretty extensively about implementing "dead zones" in the camera for a side scroller (or top-down game). The dead zone is the area in the center (or sometimes off-center) of the screen where moving your character does not cause the camera to move. This can reduce motion sickness and almost always makes the game feel a little less amateurish than if you completely lock the camera onto the X-axis position of the player. One of the subtle things that can make a side scroller more playable is the value you choose for your left-side or right-side camera buffers!

For example, I made a short video demonstrating the (very narrow) dead zone in Super Mario Bros 3: http://www.youtube.com/watch?v=89TRXUm8jMI

If you want to learn the basics of implementing a dead zone, check out the article I wrote that I linked above. For an in-depth explanation of what different kinds of dead zones can make the player feel, check out Steve Swink's book Game Feel.
> 8 votes

# Answer
(If you talk about shoot'em'up)

I'll be old fashioned, I'll be not innovative but you can't do a shoot'em'up without a very well done and rewarding power up system and without epic end level bosses.
> -3 votes

---
Tags: side-scroller, game-design
---


# Question
Title: Going fullscreen without stretching in an XNA game
I've got a 2D game that I'm working on that is in a single aspect ratio. When I switch it to fullscreen mode on my widescreen monitor it stretches. I tried using two viewports to give a black background to where the game shouldn't stretch to, but that left the game in the same size as before. I couldn't get it to fill the viewport that was supposed to hold the whole game.

How can I get it to go fullscreen without stretching and without me needing to modify every position and draw statement in the game?

# Answer
> 2 votes
From: http://forums.create.msdn.com/forums/p/58545/358858.aspx (emphasis mine)

> There is a very simple answer to your question: **your monitor is a widescreen monitor, if you set a non-widescreen resolution to it, it will have to stretch the output to give you an image**. Some graphics adapters and some screens provide a '4:3 in wide' mode which destretches for you.
>
> However if you want your game to always look right and not be stretched you have todo the following:
>
> * Render to a rendertarget instead of to the screen directly
> * Get the texture from the render target
> * Clear the screen to black
> * Start a spritebatch and render your texture at the correct aspectratio on screen scale it by using an overload that uses the targetRectangle, this way you have automatic black borders either above or on the sides.
>
> This should be be realy easy to implement :)

# Answer
> 2 votes
You can just set your ProjectionMatrix like so:

```
ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4,
                                                        (float)Game.Window.ClientBounds.Width / (float)Game.Window.ClientBounds.Height,
                                                        1.0f,
                                                        3000.0f );

```

This will set your aspect ratio correctly, in whatever screen you're using.

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


# Question
Title: How do you handle scripting in multithreaded environment
In my experience, two approaches are preferred when people want to handle scripting in multithreaded environment.

1. Synchronize every accesses to scripting module with one coarse-grained lock.
2. No Synchronization - Scripting module should be used by just one logic thread.

Of course, both solutions are not scalable in multi-core perspective.

Question - Is there any other (multi-core) scalable solution?

# Answer
Treat scripts like the GPU treats shaders- no global variables, limited inputs and outputs, that is, enforce thread safety via language rules.
> 10 votes

# Answer
It's impossible to say what sort of synchronisation you need when you've not mentioned the kind of resources you will have your scripts accessing.

Personally, having looked at what happens in a couple of game engines and thought about the various implications of scripting with regards to concurrency, I'd be inclined to have all game logic and scripting running sequentially and have other features use your extra cores.
> 1 votes

---
Tags: scripting, multithreading
---


# Question
Title: What's the best server architecture for real-time games?
I'm developing a Real-Time game which should hold thousands of players in real-time (FPS like. max 1s lag). What would be the best infrastructure for this?

My idea was using 2 server clusters - one for the Server End (all the computing side) and one for the Database end, where a load balancer is "responsible" for each of the clusters. One main server will receive the requests from the users and send back the IP address of the relevant server that the user can work this.

The database cluster will use database replication for consistency between the databases.

There should be a geographical load balancer as well - so it will assign the regional load balancer to each user for best response.

I'm using .NET + MSSQL for the game.

Thanks!

# Answer
> 6 votes
There is no best architecture without knowing a lot more about your requirements, eg. the sort of interactions between characters, how much data is going to be persistent, and so on.

If you can cope with 1 second of latency, you can probably host 1000 players on a single server without problems - but that actually conflicts with the idea of an FPS as they typically require much lower latency, eg. less than 100ms. But a system that can deal with high latency can afford to do everything via message passing which makes consistency pretty trivial. Providing your logic is quite simple, that is - complex logic gets even worse when you turn it into a message-based system rather than a locked-object system - but it all depends on your application's needs.

Similarly, if you're not persisting much data, you don't need the database machine at all, but without knowing that, it's hard to say. If you're persisting small amounts of data, and perhaps only doing it at the end of a tournament or something, again you don't need a separate database, certainly not a cluster of them. On the other hand if you're not persisting much but reading a lot, that's where the replicated databases can help you - but it also indicates that a relational database may not be the best match for your problem in the first place. Often an in-memory cache is a better solution. Similarly, if there are no transaction-style interactions between characters, then consistency becomes less important. (And if there are only a few such transactions, you can make them a special case.)

In fact, be wary of adopting an RDBMS just because it is the done thing in large systems. Although I personally do approve of using them in online games, it's best to look at your requirements and figure out your persistence strategy from that, rather than taking your preferred database and then trying to tweak it with caches and replication to get it to fit your app. You may find that all you need is offline reporting capability, in which case it's probably best to have a background process logging from your game persistence mechanism into a remote RDBMS somewhere else.

# Answer
> 4 votes
Disclaimer: my game programming experience is based around client-side single player games, but I have a background in web applications (specifically on the Microsoft stack), so that is where I'm coming from with this answer, I feel that much would apply, but without actual testing a real game server its difficult to say how it will apply, but here goes. Know this: I haven't deployed a game server, only webapps.

I would suggest a two (server) tier approach. A database tier and an "application" tier; with the third (presentation) tier being your game client.

Relational databases, are great at querying data, and decent at writing data. The key is to serialize your database writes into manageable size chunks that your cluster can handle. The more advanced editions (Data center/Enterprise) of SQL Server support clustering and replication. I would start by building a small cluster and running some queries against it to see how it works.

In the application tier, if you're doing "zoning" or something similar, you can probably get away without setting up any clusters, and simply setup a server per zone. If your zones become to big, you could setup a cluster for each zone.

You will want to build a serialization process for sending data from application tier --\> database tier. The key is to have multiple levels of serialization going on. Something *like* this:

* Level 1: Save to DB every X seconds, includes critical data:
    + Player Health
    + Player Items/Pickups
* Level 2: Save to DB every 2X seconds, includes medium data:
    + Player locations
    + NPC locations
* Level 3: Everything else, as infrequently as possible

This will keep your writes consistent and predictable, depending on the nature of your game, you could have infrequent database writes. The key is to realize that if your application server crashed, you'd have to come back online from the state in your database, so serializing player inventory every 90 minutes might make players upset.

For reading data, you'll want to load as much as possible into memory in the application tier as possible, then insure that all of your code uses this memory pool, in the background you can synchronize the memory pool with the database. As Joe points out, there will be times when you need "real-time" transactions. By serializing most of your writes, you should still have sufficient IO on your database to do real-time transactions when necessary, presuming sufficient hardware on the database server/cluster.

---
Tags: server, client-server, .net
---


# Question
Title: Is there any game-oriented virtual machine out there?
I'm investigating about virtual machines and their use in Games.

I'm looking for something cross-platform (at least win/mac/linux, mobile and consoles are a nice to have but not mandatory) and it would be nice if it could be binded to the usual things that you need for a game, like a graphics and sound lib. If it had any sort of automatic garbage collection, it would be nice, too. And since I want to use it for games, it should be fast and not very memory-consuming.

So far I've found:

I'm leaving the Java Virtual Machine and .net VM out of this list since I feel they are a bit too big for my purposes - but I'm far from an expert on these things. If you think I should include them, please put your reasons below.

Am I missing any important one?

PS: I think this should be a community wiki, but I don't seem to be able to mark it as one.

EDIT: My final objective is creating a scripting language for game development. I've no problem with interpreters (have implemented a couple in the past) but this time I'd like to translate the Abstract Syntax Tree of my language to a VM, for efficiency mostly.

# Answer
> 2 votes
If you are looking for something to embed, Lua or Python are probably your best bet. Python is an easier language to work in than Lua, but Lua is the better choice for ease of embedding (we just did both and use them for different tasks). Also if you are concerned about speed, LuaJIT makes it so much of a non-issue your head will spin. Look at something like Luabind or SWIG to help expose C/C++ to the script environment.

# Answer
> 9 votes
"Game oriented virtual machines" have been around just about as long as there has been games. Zork, and other Infocom games, ran on Z-Machine. Whenever the company got the Z-Machine ported onto a new platform (say, c-64), they could easily release their whole portfolio on said platform.

Later on, companies like Sierra or LucasArts came up with their own (AGI, SCI, SCUMM).

Those were, however, extremely limited scope VMs for games (interactive fiction in case of infocom and graphic adventure in case of Sierra or LucasArts).

So what's needed for a game anyway? Steve Wozniak was quoted to say that when he was designing the apple, (or possibly apple II?) he pondered what features a game needs - and the computer was never primarily a game platform. So looking for a VM that aims JUST games seems kind of funny, unless you're targeting some extremely specific game genre.

As such, the most distributed VMs out there today that are used for games are, I guess, java vm and flash vm.

# Answer
> 3 votes
If you can get a copy, Game Scripting Mastery is a great book for exactly what you want. It goes through the design and implementation of a scripting language for a game, covering everything you need to know.

It goes from the general reasons to use a scripting language, to writing the **virtual machine and bytecode**, and writing a parser and lexer.

Of course, it covers a lot more than you want for this question, but I think it would fit perfectly with your current project, if you can afford a copy. ;-)

EDIT: This isn't exactly what you're wanting, since you're looking for an out-of-the-box solution. However, if you're interested in rolling your own, it is a great resource. And not skimpy (1250 pages).

# Answer
> 1 votes
I would put the Java VM back on your list. It has been used by enterprise programmers for over a decade, has many good libraries that do exactly what you are looking for, and is running between 85 ~ 90 % the speed of compiled native code (sometimes faster, sometimes slower, but usually close). On top of that, Java's reflection API will let you map 'script' classes into java code very easily, and you could emulate a script such as Groovy if you wanted to.

Yes, it is big, but you only need to use as much of it as you require. The Java VM (JVM) has a notion of a maximum heap size. This maximum memory imprint is set by using the `-Xmx(Size)M` parameter. An example of this would be:

```
java game.jar -Xmx512M

```

This would set the maximum memory heap size of the JVM to 512 MB. This link may prove to be helpful. For what it's worth, Minecraft Server usually operates fine with a heap size of 1024 MB, as detailed at the bottom of the download page.

---
Tags: cross-platform, virtual-machines
---


title: Navmesh string pulling vs funneling

text:
# Question
Title: Navmesh string pulling vs funneling
I'm creating a path-finder for navmesh. I'm wondering which method should I use after the A\* has been completed, funneling or string pulling? What are the advantages/disadvantages of using them on a triangle-based navmesh?

# Answer
> 1 votes
If you're stopping condition for the funneling algorithm is the invalidity of the cone I think you'll get pretty much the same end result than with string pulling.

But using another stopping condition you can produce more various behaviors by setting a particular aperture threshold and/or by tweaking how the local target/velocity is chosen in the final cone.

---
Tags: path-finding
---


# Question
Title: How do I price a game that sells internationally online?
If I have a downloadable game or in-game item that I need to sell for a fixed amount in all countries, how do I work out how to set the price? My local currency is UK pounds. Would I come up with a round number figure in £ and let customers in other countries deal with the currency fluctuations? Should I try to display the figure in the local currency if possible? Would it be better to price the game in dollars or euros and deal with the currency fluctuations myself? How are other games handling this?

# Answer
> 6 votes
Plimus, at least, gives you lots of different options;

* Fixed price in one currency, or set values of each currency
* Various rounding options on currency conversions

As an example, 12.34 turns into..

* 12.30
* 12.35
* 12.50
* 12.95
* and so on, depending on the options you choose

As to what price point to choose for your game, and whether you want to anchor to one currency or define unique price for each, depends on the market you're entering. The iDevice market, for instance, is a completely different beast from Steam. In any case I'd look at what the other games in your target market are doing, and start from there.

It does seem, for instance, that Europeans always get higher prices than the folks in the US. Maybe we're just stupid enough to pay higher prices.

# Answer
> 4 votes
I would suggest just finding a round figure in your own currency and let the customers deal with the fluctuation.

It looks smoother and most people have a rough estimate of how much their own currency is worth in comparison to the big world currencies. (Euro,USD,GBP)

Because a customer usually just does a fast conversion in their heads they will still buy the game even though their currency is weak in comparison to GBP.

Some payment services like PayPal previews what the cost in the local currency will be before you pay.

# Answer
> 0 votes
It really depends on whether you have access to a merchant account in multiple currencies (they usually only work in your home currency) in which to receive the international payments. I would say specify the price in GBP / USD / EUR and then you will have most things covered.

As a rule of thumb however, most stuff denominated out of the States in USD is usually cheaper than we pay here in the UK. If you accept payments via Paypal then you can keep all the currencies in your Paypal account and hedge as appropriate.

Good luck.

---
Tags: online, sales
---


# Question
Title: How can I render text above a mesh in DirectX 9?
I want to render some text over a mesh in my DirectX app. It will have a similar application to health bars for units in games, just as text rather than a bar. I'm looking for the simplest way to do this.

It's a Win32 app, I'm using DirectX 9 and I need it to be in 3D (i.e. when the unit is moving around the Z-axis, the text above moves with it).

Any ideas?

# Answer
> 7 votes
ID3DXFont can be used to render 2D text, and D3DXCreateText can be used to generate a 3D text mesh you could render as well. In general I would think the 2D approach is preferable, unless you want the text to do something odd like spin in 3D space.

To find the appropriate place to start rendering the text (for the 2D case), you'll want to use the character's position in world space (perhaps plus some offset vector that provides a position just above the character's head). Then multiply that point by the combined view and projection matrix via something like D3DXVec3Project. This will yield a screen space position you can render the text to. Note that you may need to offset the screen space position by, for example, -(width of text / 2) or use the `DT_CENTER` flag if you want the text centered.

# Answer
> 3 votes
You can use D3DXCreateText to create a text "mesh", which you can then render however you like.

---
Tags: 3d, rendering, directx9, text
---


# Question
Title: MVC (Model-View-Controller) Game Engine Architecture - Yes or No?
I am reading one great book, **Game Coding Complete**, and that book strongly recommends using **MVC (Model-View-Controller)** approach, with three key layers:

1. *Game Application Layer*
2. *Game Logic*
3. *Game View*

To me, this approach looks like an overkill for a mobile computer game.

What is your opinion, please? Is it worth of implementing this architecture, even if it adds extra communication needed between modules? Can this design consume so much CPU power, that at the end, the result would be significantly slower, than if it weren't implemented?

# Answer
I somewhat support using an MVC structure even for a simple mobile game. If nothing else, it helps with an issue that plagues developers who haven't gotten bitten by it enough times: separating the display code from the game logic.

I'll also say, though, to keep in mind that MVC, like all design patterns, exists *to make your life easier*. That means that if, at any given time, staying within some set of rules about what you should and shouldn't do when using MVC is making your life harder, *ignore it*. One of two things will happen: 1) you'll get bitten later, and then will understand why doing it differently in the first place would actually have made your life easier in the long run, or 2) no consequences whatsoever.

Computer programming, by its nature, gets a lot of rule-followers who value adherence to elegant principle over actually accomplishing anything, and they love to propound their value system; don't let them make you one of them. The most important thing that can happen to your game is *shipping it*.
> 32 votes

# Answer
Compile-time designs do not consume CPU power, unless you have an incredibly abysmal compiler. An object orientated language or approach is no different in performance characteristics than a procedural one. You will not invoke any additional overhead for using MVC. Modularity exists at compile-time, not run-time, once the code is inlined and optimized, it won't make any difference at all.

Many modern games actually run the models and the views on separate threads and gain great performance benefits on most platforms.

Ultimately, MVC is a good design that gets you increased maintenance and less bugs etc for *free*. There's no reason *not* to use it. It's like asking why you should use a `for` loop instead of hand-written `goto`s. Unless you have a superior design in mind, it's sure as hell better than nothing.

Edit: Compile-time designs do not consume CPU power. Run-time designs like inheritance obviously do.
> 5 votes

# Answer
There is almost always a tradeoff between the clarity of the code and the technical requirements (speed, memory, etc.) of the program. Object-oriented languages have an overhead compared to procedural languages, but they have been shown to have many advantages over procedural languages, especially in long-term maintenance of code (bugs, etc.) and often development speed as well.

So with that in mind, I propose that **MVC is worth implementing for your sake as the game programmer**. Your code will better follow object-oriented principles, especially encapsulation, and you will likely have a much easier time maintaining it (fixing bugs or adding new features).

On the other hand, make sure to actually finish a game and not spend so much time working on the "engine" that it never gets done.

For more info, please read the question "Why are MVC & TDD not employed more in game architecture?" and my really long answer.
> 4 votes

---
Tags: architecture
---


title: What heuristics are used in NavMeshes?

text:
# Question
Title: What heuristics are used in NavMeshes?
What heuristics do programmers use in A\* pathfinding for NavMeshes?

NavMesh = Navigation Mesh, its a type of pathfinding that uses meshes instead of waypoints.

# Answer
> 9 votes
Take your pick:

http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html

There's a load of heuristics described in that link, either for speed or accuracy. There's always a trade-off, so I would assume that developers would use the most accurate heuristic that would cause minimal impact to their game's performance.

# Answer
> 1 votes
A very, very rough (but very speedy) heuristic to use is: (Manhattan distance)

```
vec1 = start vector
vec2 = end vector

heuristic = abs(vec2.x - vec1.x) + abs(vec2.y - vec1.y))

```

This avoids any square rooting, which could be costly (Pythagorean distance).

---
Tags: path-finding
---


title: Available AI middleware

text:
# Question
Title: Available AI middleware
A useful list of AI middleware. Please provide URL, free/open-source or licenced, and brief description of abilites.

Format:

```
*Package* (License)
Link

Pros

Cons

```

# Answer
**Recast/Detour** (ZLib license)

Googlecode link

Recast is a library to generate navigation meshes from polygon soups. Detour is a pathfinding and spatial reasoning toolkit that works on navigation meshes.
> 13 votes

# Answer
**OpenSteer** (MIT License):

> OpenSteer is a C++ library to help construct steering behaviors for autonomous characters in games and animation. In addition to the library, OpenSteer provides an OpenGL-based application called OpenSteerDemo which displays predefined demonstrations of steering behaviors. The user can quickly prototype, visualize, annotate and debug new steering behaviors by writing a plug-in for OpenSteerDemo.

I've seen it used to great effect in simple games.
> 8 votes

# Answer
There also MicroPather - an open source path finding library from the same guy who made TinyXML.

http://www.grinninglizard.com/MicroPather/index.htm
> 2 votes

# Answer
Havok AI (Commercial - not cheap)

http://www.havok.com/index.php?page=havok-ai

Havok is pretty good at physics, and has been offering behaviour, animation and other kinds of middleware for a while now.

Physics and AI is not easy to get to cooperate, especially animations, so save yourself some time and use Havok.

Highly recommended. :)

If you can afford it.

Pros: Industry strength quality, proven technology. Makes AI and Physics cooperate.

Cons: Steep Price.
> 1 votes

# Answer
**SharpSteer**. (MIT license?)

https://github.com/boki/sharpsteer

SharpSteer is a C# port of OpenSteer. Like OpenSteer, the aim of SharpSteer is to help construct steering behaviors for autonomous characters in games and animation, with a current implementation focus toward Microsoft's XNA.
> 0 votes

# Answer
AI.implant (Licensed)

http://www.presagis.com/products\_services/products/ms/simulation/aiimplant/#

No idea if it's any good, I just remember getting some brochures from them at GDC a few years back, and it appears they're still around.
> 0 votes

# Answer
xAItment (commercial)

http://www.xaitment.com/

Fairly new middleware suite providing everything from pathfinding to behavior / decision making systems. Haven't tried it myself, so I can't say if it's any good.
> 0 votes

# Answer
Kynapse (commercial) is from what I understand the number 1 market share for pathfinding libraries. It's the oldest of the commercial AI middlewares around.

http://usa.autodesk.com/adsk/servlet/pc/index?siteID=123112&id=11390544

My experience with previous versions were that they were bulky with a terrible API and not very nicely implemented. We had tons of problems with it.

Now in their new version it seems they've changed data formats and some other radical changes, so maybe they've fixed the problems now.

It's also a commercial product and fairly expensive.
> 0 votes

# Answer
NavPower (commercial)

http://www.babelflux.com/

My experience with it has been positive, although I haven't shipped any title with it yet. Most others I've talked to about it have had a similarly positive experience with it. API is easy to understand.

Fairly simplistic API, which can be a limitation.
> 0 votes

# Answer
**Golaem** (Commerical)

http://www.golaem.com

I'll add to the list of commercial products Golaem (Full disclosure: I work for them).

Golaem Path is a real time 3D navigation library (path finding & reactive navigation / steering behaviors). It is not marketed for game development but could be used for a game.
> 0 votes

---
Tags: ai
---


title: Games for Facebook, iPhone, Web

text:
# Question
Title: Games for Facebook, iPhone, Web
if I want to build a game for web, facebook, and iphone, do I need to build 3 completely different versions? I know there is a new company that is "build once, launch anywhere," but I'm asking about current best/practice and methodology in doing this.

# Answer
This really depends what type of game that you are making.

If your game is a simple text based game, then you can build the same interface in HTML and use different CSS to make it look good based on where the game is being accessed from.

More realistically, your game is highly interactive, and it would be best to build the web/facebook version in Flash/Silverlight or another browser plugin. Then port it to iPhone in Objective-C. (Or, if you're more proficient in Objective-C start there and port to web/facebook.)

The main issue that you'll probably run into is that on iPhone the input scheme will be different which could impact gameplay.

The bottom line, is that you will need to, at a minimum, build a different Rendering and Input scheme for each platform you wish to deploy to. Facebook, is really just a normal web deployment, inside the facebook site, so the design would be the same for facebook or any other web game.

**edit**

A few things I'd like to point out, based on your comments. First, HTML5 is probably NOT a good place to start, it has poor browser support (thought getting better), I'd stick with HTML4 and/or XHTML 1.1 and CSS2, these will work in almost all modern browsers; however, if you require any animation, I'd recommend using Flash or Sliverlight to build the game, and use their associated ability to call web services to save state to a server. Second, HTML is just the presentation, if you don't go the plugin route, you would likely need PHP or ASP.NET on the server to manage your game state and persist it to a database.
> 1 votes

# Answer
There are platforms that could enable you to minimize the amount of porting work you'd need to do -- Unity, for example, which somebody apparently managed to integrate into Facebook with at least some success. It's certainly technically possible to build a product that more-or-less seemlessly compiled and deployed to multiple distinct platforms like that, but there are problems that are nontechnical in nature that you'd have to overcome -- such as how to design a game that functions well in the wildly different contexts of all those platforms (some of which have very different input styles).
> 2 votes

---
Tags: game-design, iphone, cross-platform
---


# Question
Title: Per-Frame Function Calls versus Event Driven Messaging in Game Design
The **traditional game design**, as I know it, uses **polymorphism and virtual functions** to update game objects states. In other words, the same set of virtual functions are called in regular(ex: per-frame) intervals on every object in the game.

Recently, I discovered, that there is another - **event driven messaging system** available to update states of game objects. Here, the objects usually are not updated on per-frame basis. Instead, a highly efficient **event messaging system** is built, and game objects get updated only after receiving valid event message.

**Event Driven Game Architecture** is well described in: *Game Coding Complete*by Mike McShaffry .

Could I kindly ask for help with the following questions:

* What are the advantages and disadvantages of the both approaches?
* Where is one better over the other?
* Is Event driven game design universal and better in all areas? Is it therefore recommended for usage even in mombile platforms?
* Which one is more efficient and which is more difficult to develop?

*To clarify, my question is not about removing polymorphism completely from a game design. I simply wish to understand the difference and benefit from using event driven messaging vs regular(per-frame) calls to virtual functions to update game state.*

---

**Example:** This question caused a bit of controversy here, so let me offer you example: According to MVC, the game engine is divided into three main parts:

1. Application Layer (Hardware and OS communication)
2. Game Logic
3. Game View

In a racing game, the Game View is responsible for rendering the screen as quickly as possible, at least 30fps. Game View listens for player's input too. Now this happens:

* Player presses fuel pedal to 80%
* GameView constructs a message "Car 2 Fuel Pedal Pressed to 80%" and sends it to Game Logic.
* Game Logic gets the message, evaluates, calculates new car's position and behavior and creates the following messages for GameView: "Draw Car 2 Fuel Pedal Pressed 80%", "Car 2 Sound Acceleration", "Car 2 Coordinates X, Y" ...
* GameView receives the messages and processes them accordingly

# Answer
> 8 votes
I'm a full believer in necessity being the mother of invention. I do not like to code anything unless its need is clear and well-defined. I think that if you start your project by setting up an event messaging system, you're doing it wrong. I believe that only once you've created and tested your infrastructure and have all the pieces to your project as well-defined, working modules should you focus on how you're going to connect these modules to each other. Trying to design an event messaging system before you understand the shape and needs of each module is out of order.

*What are the advantages and disadvantages of both approaches?*

I think some people would argue that there are good messaging systems out there ready to be installed and used. Perhaps this is true. Certainly the performance of a custom-build solution specifically tailored to your needs would be greater than a general-purpose message bus. The big question is - how much time are you going to spend building a messaging system rather than using something that has already been built. Obviously, if you could find some sort of event system with exactly the feature set you need, then it's a pretty easy decision. This is why I make sure that I understand exactly what I need before I make that decision.

*Where is one better over the other?*

We could talk about memory and resources here. If you're developing for any hardware with limited resources, it's certainly an issue to use a event system that will cut into that significantly. Really, though, I think the issue comes down to what you need, which as I mentioned already is something that you don't know until you see what all the pieces look like. If you have enough experience building these systems that you know in advance exactly what all the pieces are going to look like, then you can answer this question in advance as well. I'm guessing you don't have this experience, since you wouldn't be asking this question if you did.

*Is Event driven game design universal and better in all areas? Is it therefore recommended for usage even in mobile platforms?*

Universal and better in all areas? A pretty blanket statement like that is easily rejected. Anything that adds overhead needs to be carrying its share of the workload. If you're not using events enough to warrant the overhead of the design, then it's the wrong design.

*Which one is more efficient and which is more difficult to develop?*

Efficiency depends on how its implemented. I think that a well-developed traditional design will out-perform an event-based system any day of the week. This is because communication between pieces can be micro-managed and made super efficient. Of course, this also makes it more difficult to design from the standpoint of experience and time required to complete it and make it more efficient. On the other hand, if you lack this experience or don't have the time to develop the application well, then using an event based design that suits your needs will be more efficient. If you have custom event needs that doesn't easily fit into an event-based structure, this could make the event-based structure very difficult to design - especially to keep the design efficient.

# Answer
> 7 votes
I think you're comparing apples and oranges here. Polymorphism isn't replaced by messaging at all. You would probably want events/messaging to connect loosely coupled components. Eg. to send a message from an entity when a collision occurs, to update the player score or maybe to trigger a sound-effect. So that these individual classes don't know the other classes and just send out and/or handle messages.

But your game is most likely going to have an update loop somewhere and since you *have* that update loop, it can easily be used to update all game entities that need to be updated every frame as well. This doesn't prevent you from using messaging though...

If you have some sort of structure where you add/remove game-entities, you can just as well include them in your update loop instead of dispatching an *update* message to them every frame. So why not call *update* on your game entities directly while you're using messaging to connect different sub-systems of your game? I also like the Signal/Slot concept (see qt example) for event-like systems.

Bottom line: There's no better approach, nor are they exclusive.

# Answer
> 4 votes
This started as a comment to bummzack's answer, but got long.

Unless you actually make it asynchronous (dispatch events on a new thread), your objects are still getting the memo synchronously. Assuming your event dispatcher uses a basic hash table with a linked list in a cell, the order will be the order in which objects were aded to that cell.

Further, unless you decide to use function pointers for some reason, you still are using virtual function calls since each object getting a message must implement IEventListener (or whatever you call it). Events are a high level abstraction that you build using polymorphism.

Use events where you find yourself having to call a laundry list of methods for various in-game happenings in order to synchronize different systems in the game or where various objects and systems' reaction so said happenings are not able to be clearly defined or you want to add more reactions to said happenings in the future.

They are a great tool, but like bummzack said, don't assume that polymorphism and events solve the same problem.

# Answer
> 2 votes
I would say that choosing one or the other is pretty wrong. Some objects need calling every frame- some don't. If you have an object you want to render, you *need* to make a render call to it every frame. Events can't make this change. The same is true for any time-based physics objects- you *must* call them every frame.

However, I don't make calls every frame to my object management objects, or my user input objects, or anything like that. Mass virtual calls to every object on frame is a terrible idea.

The design used for any particular object should be based on the needs of those objects, and *not* based on some ideology for the system as a whole.

Edited to be more clear on my first sentence.

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


# Question
Title: Is Test Driven Development viable in game development?
As being Scrum certified, I tend to prone for Agile methodologies while developping a system, and even use some canvas from the Scrum framework to manage my day-to-day work.

Besides, I am wondering whether TDD is an option in game development, if it is viable?

If I believe this GD question, TDD is not much of a use in game development.
Why are MVC & TDD not employed more in game architecture?

I come from industrial programming where big projects with big budgets need to work flawlessly, as it could result to catastrophic scenarios if the code wasn't throroughly tested inside and out.

Plus, following Scrum rules encourages meeting the due dates of your work while every single action in Scrum is time-boxed! So, I agree when in the question linked above they say to stop trying to build a system, and start writing the game. It is quite what Scrum says, try not to build the perfect system, first: make it work by the Sprint end. Then, refactor the code while working in the second Sprint if needed!

I understand that if not all departments responsible for the game development use Scrum, Scrum becomes useless. But let's consider for a moment that all the departments do use Scrum... I think that TDD would be good to write bug-free code, though you do not want to write the "perfect" system/game.

So my question is the following:

**Is TDD viable in game development anyhow?**

# Answer
It's certainly viable, although a lot of game programmers haven't really gotten on board with the idea yet, or have a good understanding of how to test complicated systems. I admit myself that I rarely use it, except for non-gameplay-related systems that are easy to test.

Expect to use a lot of mock objects. Because of how tied together a lot of systems are, it's hard to test individual components of that.

Plus a lot of things can't be thoroughly tested. How do you test-drive, say, a particle system? How do you test that your animation system is working correctly? A lot of things are visual in nature, and aren't obvious (at least to me) as to how to do proper testing.

There are, however, a lot of things that aren't necessarily unit tests in the traditional sense of the word, but that exists as "tests" for specific features. Things like test levels for AI navigation are pretty common, but aren't necessarily the easiest things to automate.

There are certain aspects of games that can (and probably should) have unit tests written for them. Any kind of generic "file reading" system should be tested. Maybe have some tests for initialization of hardware things (3d surfaces, etc). Maybe have some mock servers and test your client/server interaction code. Things like that.
> 12 votes

# Answer
I don't think TDD, as such, is appropriate as a foundation for game development. Automated unit testing as part of methodology, sure, but too many of the key concerns of game development are subjective and not machine-testable for testing to be the *driver* of development. How are you going to write a scripted test for whether a game mechanic is fun? That a level is visually appealing? Even that a level takes a typical player around 15 minutes to complete? TDD fits situations where the maturity of a project can be quantitatively measured in terms of its compliance to a specification, and that just isn't game development.
> 13 votes

# Answer
It's a bit difficult to work out exactly what you're asking since the title is purely about TDD but you seem to be making Scrum an integral part of the question too - and as I understand it, one does not require the other.

> If I believe this GD question, TDD is not much of a use in game development.

That is correct. I don't think I've ever heard of it used in practice in the games industry. (But then I never heard of it used outside the games industry either - just by individuals.)

> I come from industrial programming where big projects with big budgets need to work flawlessly, as it could result to catastrophic scenarios if the code wasn't throroughly tested inside and out.

Games don't need to work flawlessly. So there is much less emphasis on code correctness. TDD doesn't guarantee code correctness, but some people feel it reduces the incorrectness. I'm yet to see proof of this.

> Plus, following Scrum rules encourages meeting the due dates of your work while every single action in Scrum is time-boxed!

I've never seen a methodology that didn't encourage meeting due dates, or having actions that weren't time-boxed. The problem is that no matter what methodology you use, estimating software complexity is quite hard. It's not impossible, but estimating it accurately is not much to do with the process. If my task is to add a new GUI panel, or to fix a bug with the animation, or add a new statistic to characters, then the use of Scrum is not going to speed that up at all, and the use of TDD is going to slow down the task (at the possible benefit of reducing further maintenance tasks later). They're certainly not going to make it easier to estimate the task duration.

> I think that TDD would be good to write bug-free code, though you do not want to write the "perfect" system/game.

If TDD is proven to write better code than other methods, then yes.

Is there proof of this? The fact that industry might use it is not proof. Industry is well known for producing poor code that is delivered late. The absence of examples of major TDD projects that have failed or run late may just be because it's a new approach and few people have actually finished such a project yet. (And the ones that are running late... may still be running.)

> Is TDD viable in game development anyhow?

Viable? Of course. Beneficial? That's yet to be proven.
> 8 votes

# Answer
No, Test Driven Development is not suited for Game Development. Sure you can write tests for some parts you do want to test, but the Game Development process is completely different from Test Driven Development which requires having exact specifications before progress is started.

Games rarely have exact specifications when started. And if they do, they always change and evolve during the development process.

**Game design is an art, you can't have specific tests to know when art is good or complete.**
> 5 votes

# Answer
sorry for my poor english and sorry for my biased point of view: i am not a game designer but a coder.

I think there are some misunderstanding in this discussion. i'll talk about TDD in more general form, the so called BDD. Behavior driven development is not a way to test project (the tests are something like side effects). **BDD is a way to design**, a way to do refactor and software design during all the production (see some mottos as KISS, "keep quality in", "test early, test often") and not in a alone phase. BDD is the opposite of some classical software process like waterfall process or some other iterative methodology to make software.

Another point is that automatic tests are for that features that could be tested automatically by a computational machine. there is no test for fun in games, and there is no test for usability of a graphical user interface. fun or usability are materials for other jobs and not for software development like interaction designer, world and level d. in the same way that artistic parts(modelling, texturing, etc) are for artist that use computers as tool for creativity - obviously those jobs could be performed by the same person that write code, but this is not the point. physics could be tested, optimization algorithms could be tested, singual object behaviours could be tested (with mocks, stubs and dummy as mentioned before)

the last think is that, imho, is that not only game design but whole writing code is an art.
> 5 votes

# Answer
Here's a case study from someone who thinks TDD and gamedev mix pretty well:

http://powertwenty.com/kpd/downloads/TestDrivenDevelopmentInPython.pdf

Admittedly, this is a small project in Pygame, but it gives the idea of which parts can be tested with a graphical game and which can't. I was surprised at how much could be done with TDD in this scenario.
> 5 votes

---
Tags: architecture, software-engineering, methodology, testing, test-driven-development
---


# Question
Title: Moving a sprite in XNA/C#, using vectors
I'm currently looking into XNA game development with the C# language.

I have two classes: the main game handler and a "sprite" class. Following is some basic pseudo-code which I hope adequately describes the issue.

**Game.cs**

```
class game {
  sprite the_sprite;
  void update(time) {
    var mouse = mouse.state
    if(mouse.clicked) { this.the_sprite.moveTo(mouse.x, mouse.y) }
    this.the_sprite.update(time)
    base.update(time)
  }
}

```

**Sprite.cs**

```
class sprite {
  vector2 location;
  vector2 move_to;
  void moveTo(x, y) { this.move_to = new vector2(x, y) }
  void update(time) {
    if(this.location.x > this.move_to.x /* (or less than) */) {
      // adjust location.x
    }
    if(this.location.y > this.move_to.y /* (or greater than) */) {
      // adjust location.y
    }
  }
}

```

Basically: when the user clicks somewhere in the game window, the x and y coordinates of the mouse are taken, and the game object will move towards that location over a period of time.

Well... the code works, but it's ugly, and objects don't move directly towards the object (instead, it's diagonal movement, followed by single-axis movement). I'm guessing there are some mathematical functions I can use, but I honestly haven't a clue where to get started. Any suggestions?

# Answer
If I understand your problem properly, you should just have a direction Vector2 representing the direction you want to move in inside your sprite class. Like this:

```
public Vector2 Direction { get; set; }

```

This is the normalized vector(which means it has a length of 1) showing where you want to go.

Then, add a Speed float property, which says how fast the sprite should go.

```
public float Speed { get; set; }

```

You also need to add a UpdateSprite function, so why not put it inside your Sprite class?

```
public Update(GameTime gameTime)
{
   Position += Direction * Speed * gameTime.ElapsedGameTime.TotalSeconds;
}

```

This will update the sprite's position to make it move(you multiply by the delta seconds so that the sprite moves properly on slow computers too).

Finally, you just set your direction property like this:

```
sprite.Direction = location - sprite.Position;
sprite.Direction.Normalize();

```
> 12 votes

# Answer
Google normalization... i am also a little lost at this, but i am pretty sure this will help solve your problem. Someone else can elaborate or disprove my answer i am sure

Edit: I could answer this better, apologies

I personally always look to this blog post to help with these types of problems: http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/

It starts from scratch and is relevant to game development.
> 2 votes

---
Tags: xna, c#, vector, movement
---