# Question
Title: Adjust Keyboard input to match look direction?
A concept I am working on uses W,A,S,D for movement and sometimes the camera will be oriented so that the game is side scrolling, where D is forward (moving right), but other times the camera might be behind the player looking forward (Kinda like 3rd person) and In this case, W would need to be forward.

Currently I only have it set up where D is always forward but it gets highly confusing when the camera angle changes at a certain parts.

Is there a simple enough way to figure out how to determine which key would be appropriate for forward? I kinda think of it like making the keys act analogue or something like that, but can't think of a good way. Maybe something like the closer the cameras forward direction is to the players forward direction, interpolate key inputs to match axis?

Also, my camera is following on a spline path so when the direction its looking at the player changes, its not immediately 3rd person. It eases into that, so to make this more complicated, I would think that sometimes a combination of two keys would be forward (D to D&W to W)

Sorry if this is common but I couldn't figure out what to search for.

Edit: I didnt include the detail that its not purely left/right for the side scrolling part, the character can go in all 4 directions (+X,-X,+Y,-Y) but is limited by a small path. Space would be my jump. See pic below:

# Answer
> 2 votes
I would make the transition snappy and clear cut. The user needs to know when to use which keys. While I agree it's more natural for `D` to be forward on a side scroller and `W` to be forward in 3rd person follow, transitioning between is not so common, and less intuitive.

If when in side scrolling mode there is no use for `W` then I would allow the user to continue to use it for forward, in addition to `D`. Otherwise, you'll need to make it clear that `W` is not moving them forward when in side scrolling mode.

The transition between doesn't need to detect camera angle or anything so complex. Surely you have a trigger that makes the camera switch modes from 3rd person to side scroll. Apply the keyboard input changes at the same time the transition is initiated. And always make sure the transition happens at a time when the user doesn't need to be moving forward.

If you want to make the change automatically, you can set the change to happen when the camera forward direction and the player forward direction are perpendicular or close to. You can test that by finding the angle between the two.

EDIT based on your update.

I would not switch the controls at all in this case. If the camera is free flowing between states, it will be difficult and frustrating for the user to keep straight which button to use for going forward.

**If the transition is not clearly defined by a state machine and you have to derive it based on the camera angle, then the player will also have to derive it.** If the transition is not immediately clear and only happens when the user is at a door or some other stopping point, it will be confusing to the player. When it's close to the transition point, the user will have to guess which button to use. Guessing wrong means frustration. Additionally, since they could be holding `W` to move forward, and the camera freely switches to side scroll follow, then they're suddenly moving up and not forward.

# Answer
> 1 votes
In both views, map the keys according to the view vector and movement of the camera. In 2D view the world may be "flat", but still thinking in terms of looking at it from a Z depth in 3D space. For me it's easier to compare it to a traditional 2D fighter where you can only walk left or right, but 3D fighters allow sidestepping and circle-strafing. Think of how the joysticks are mapped according to these views.

It is indeed harder to map WASD keys when the "clear" path to walk along is at an angle offset from what the camera sees, it's why analog joysticks are much preferred for the granularity.

*Initially, WASD keys should be moving the player along the camera's local coordinates at the moment when the key(s) were pressed.* This is the most intuitive way to map the keys when you cannot know for certain where the camera is in relation to the player. That blue vector that points up can just as well be the "away" vector (imagine it going down the camera's local Z axis). Contrast this to "tank" controls where W and S move the player along the vector to what the *character* sees.

Since your camera moves along a spline, its local coordinates change, because the tangent might change. If the player is currently moving and the camera changes direction, do not update the controls to its new local coordinates until the keys are released. This way, the player can keep running along a straight path without frantically switching controls as the camera moves.

I pretty much learned this making a Marble Blast-type game, such a game would have more slippery movement and require twitch reactions. If I wanted to U-turn on a dime, I would initially press Down to move towards the camera, but as it quickly swivels around, I would be again going away from the camera, but still holding Down and moving in the other direction. Upon releasing Down, the controls "shift" to match the camera's new orientation.

---
Tags: input
---


# Question
Title: Vector2's static methods and the garbage collector
I discovered that Vector2's static methods return a different Vector2 from the parameters you give them and I'm under the impression that creating new objects and dereferencing old ones on this kind of scale (100's of method calls per update) is bad for the GC.

Is this the case with C# or does XNA pool these Vector2's for use on later method calls?

I ask because I want my entities collision shapes to share the same position Vector2 as the entity itself to eliminate the need to call `updateBounds()` after practically every position change. However since the methods return a different Vector2 the entities position and its respective bounds' position become differing objects.

Also is it worth making my own Vector2 class and have its methods non static so I can use `someVector.add(otherVector)` instead of XNA's way?

# Answer
`Vector2`s in XNA are not objects, they are structs, which are not reference types. This is why you get a copy back from the methods. They will have entirely different allocation behavior than objects (stack rather than heap). If you manipulate them in certain ways, they can be "Boxed" into objects, which will use the heap. But if you use them properly, then they are no more of a memory waste than declaring `int i` in a for loop.

@Byte56 is exactly correct. You are optimizing for a problem that is not really a problem.
> 4 votes

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


# Question
Title: Can I make a Cue in XACT to play two sounds?
I have my gun shot and reload sounds with their own cues, can I create a cue that points to both of them so they are played one after the other when playing the cue?

I would have tried the documentation but: Where is the XACT documentation?

**UPDATE:**

The documentation now found says:

> A cue allows a game programmer to play sounds. It is composed of one or more sounds, and is referenced through a sound bank.

and:

> ...XACT enables audio designers ... to create transitions between cues

So my hunch was correct! But still cannot find how to do it. Why why doesnt the tool come with a comprehensive manual? whats the point in creating it if you dont tell people how to use it!!??

# Answer
Looks like to play them one after other you would call

GetCue ("sound1") GetCue ("sound2")

as describe here

But you will need to set up, AudioEngine, SoundBank and WaveBank first.

**UPDATE**

Bit of pseudo code.

```
Play Sound
Keep Reference to Cue
Every Update
  check if is playing
  when false play next one

```

Hope this helps

**UPDATE2**

From this image I am going to say that yes it is possible to have multiple sounds in a single cue but not to play at the same time they are played based on a probability.
> 1 votes

# Answer
Not that I know of, unless you can do that from within the XACT editor GUI, which should be obvious considering how basic it is? (I'll check it out later tonight)

I would create a reference/instance or whatnot to a soundeffect and play that, using the audio engine setup, and check each update if the effect has stopped playing - if so, it's reached the end so start playing the second one. Simple but kludgy ^^
> 1 votes

# Answer
I don't think you can do it in XACT (not sure though) but a possible workaround would be to use audacity or some other tool to merge the sounds into a single file which might make sense if they will always be played together.
> 1 votes

# Answer
You can do something functionally equivalent in XACT if your willing to make one more sound.

Put both TRACKS into one SOUND, and have your cue play that sound. They both play at the same time now, so we have to delay one. In the tree on the right side of the sound bank editor, click on "Play Wave" and look at the properties on the lower left side of the screen. The "Time Stamp" allows you to delay the playing of a track, so you can delay the reload track to play after shoot track.

I know this is an old question, but I needed to do something similar with my game's soundtrack, and thought I should post the answer online since it's not clear at all.
> 1 votes

---
Tags: xna
---


title: XNA HLSL 2D outline shader

text:
# Question
Title: XNA HLSL 2D outline shader
I have gotten into quite a bit of trouble getting my rendering correct in my tile based 2D game.

> This kind of shader is surprisingly annoying to write, I've heard (we used it in one of our 3D games and kept running into unsightly edge cases). One thing you might want to consider is encoding the outline directly into the sprite texture with a specific color like (0, 255, 255, 0), and just have the shader transform that color when the sprite is selected. Then the shader is a trivial color change, and you have a high level of artist control over the outline and any details you want. https://gamedev.stackexchange.com/a/3822/25297 by "Joe Wreschnig"

I'm trying to do as Joe Wreschnig suggests.

It works fine for the color part, for example if the HighlightState of an object is set to None, then I render the outline transparent so you can not see it.

If the HighlightState is Friendly then i render it as LighGreen, Enemy is Red and so on, the color switching is done with a parameter in the shader as I wanted to draw the objects in one batch (because I have to sort the sprites on Y position to render from TOP to BOTTOM to make sure that a tall object on a tile below another one is rendered on top of the one above).

However, this is where the trouble occurs. I need to change an Effect Parameter depending on the HighlightState of the object that is to be drawn. If I render with any SpriteSortMode other than SpriteSortMode.Immediate, every object will get the outline color of the last rendered object (since it is batched). Sadly, SpriteSortMode.Immediate is not a choice since there can be quite many objects on the screen at one time.

To avoid the issue with the same color upon rendering all the objects as one batch, I thought, why not split the object list into many, one for each HighlightState? This worked terrific, except for one small issue. The Y sorting. If I render them as separate batches, there is no way to tell that one object in one batch should be placed behind another in a different batch or vice versa, which makes me wonder if it feasible to render the outline using a shader or if I have to resort to two sprites per sprite, one slightly enlarged white sprite(color tinted) rendered behind the first one to fake a highlight..

How would I solve this issue in the best manner? If you need code, I will post it but the problem is not really the code I guess, more like the logic itself.

**EDIT (SOLUTION):**

Based on Nathan's(THANK YOU) answer I managed to implement a shader that can handle different color outlines depending on the state of the object, meaning if it is friendly, an enemy etc.

If you run into this problem yourself, trying to set parameters for each sprite drawn in a single batch and you notice that you only get the last set parameters for ALL the sprites in the batch, it probably be solved.

I for example, wanted to set the outline color individually for each sprite and it worked great using the SpriteBatch.Draw's Color parameter (which sets the vertex color in the VertexDeclaration I assume), I could then use that color in my pixel shader to set the correct outline color.

# Answer
> 2 votes
Instead of having the highlight color be an effect parameter, you probably want to have it be a vertex parameter. The vertices of each individual sprite can then store the highlight color for that sprite, and you can batch them all together and draw them in the correct Y-order.

It looks like the XNA SpriteBatch system already supports vertex color (there's another question about that), so assuming you're not using that for anything else, you can just use vertex color for highlight color and write your pixel shader accordingly.

---
Tags: xna, c#, fragment-shader
---


# Question
Title: Making A Sprite Rotate To A Specific Angle XNA 4.0
I have a game that the character spins when you press either of the triggers on the xbox remote. Here's the code.

```
if (gamepadState.IsButtonDown(Buttons.RightTrigger))
        RotationAngle += spinSpeed;

if (gamepadState.IsButtonDown(Buttons.LeftTrigger))
        RotationAngle -= spinSpeed;

```

what i want to happen is when neither of the triggers are being pressed he rotates back to a rotation angle of 0. I know How to make him go back to 0 when neither triggers are pulled but its too abrupt. How can i make the sprite actually rotate back to an angle of 0?

# Answer
Try something like this:

```
private bool isTurning;

public override void Update(GameTime gameTime)
{
    isTurning = false;
    if (gamepadState.IsButtonDown(Buttons.RightTrigger))
    {
        RotationAngle += spinSpeed;
        isTurning = true;
    }

    if (gamepadState.IsButtonDown(Buttons.LeftTrigger))
    {
        RotationAngle -= spinSpeed;
        isTurning = true;
    }

    if (!isTurning && RotationAngle != 0)
    {
        if (RotationAngle > 0)
        {
            RotationAngle -= spinSpeed;
            if (RotationAngle < 0)
                RotationAngle = 0;
        }
        else if (RotationAngle < 0)
        {
            RotationAngle += spinSpeed;
            if (RotationAngle > 0)
                RotationAngle = 0;
        }
    }
}

```
> 2 votes

---
Tags: xna-4.0, rotation
---


title: Simple iOS glDrawElements - BAD_ACCESS

text:
# Question
Title: Simple iOS glDrawElements - BAD_ACCESS
You can copy paste this into the default OpenGl template created in Xcode.

Why am I not seeing anything :-)

It is strange as the glDrawArrays(GL\_TRIANGLES, 0, 3); is working fine, but with

glDrawElements(GL\_TRIANGLE\_STRIP, sizeof(indices)/sizeof(GLubyte), GL\_UNSIGNED\_BYTE, indices);

Is giving BAD\_ACCESS?

### Copy paste this into Xcode default OpenGl template: ViewController

```
#import "ViewController.h"

#define BUFFER_OFFSET(i) ((char *)NULL + (i))

// Uniform index.
enum
{
    UNIFORM_MODELVIEWPROJECTION_MATRIX,
    UNIFORM_NORMAL_MATRIX,
    NUM_UNIFORMS
};
GLint uniforms[NUM_UNIFORMS];

// Attribute index.
enum
{
    ATTRIB_VERTEX,
    ATTRIB_NORMAL,
    NUM_ATTRIBUTES
};

@interface ViewController () {

    GLKMatrix4 _modelViewProjectionMatrix;
    GLKMatrix3 _normalMatrix;
    float _rotation;

    GLuint _vertexArray;
    GLuint _vertexBuffer;

    NSArray* arrayOfVertex;
}
@property (strong, nonatomic) EAGLContext *context;
@property (strong, nonatomic) GLKBaseEffect *effect;

- (void)setupGL;
- (void)tearDownGL;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

    GLKView *view = (GLKView *)self.view;
    view.context = self.context;
    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;

    [self setupGL];
}

- (void)dealloc
{
    [self tearDownGL];

    if ([EAGLContext currentContext] == self.context) {
        [EAGLContext setCurrentContext:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

    if ([self isViewLoaded] && ([[self view] window] == nil)) {
        self.view = nil;

        [self tearDownGL];

        if ([EAGLContext currentContext] == self.context) {
            [EAGLContext setCurrentContext:nil];
        }
        self.context = nil;
    }

    // Dispose of any resources that can be recreated.
}

GLuint vertexBufferID;
GLuint indexBufferID;

static const GLfloat vertices[9] = {
    -0.5, -0.5,  0.5,
    0.5, -0.5,  0.5,
    -0.5,  0.5,  0.5
};

static const GLubyte indices[3] = {
    0, 1, 2
};

- (void)setupGL
{
    [EAGLContext setCurrentContext:self.context];

    // [self loadShaders];

    self.effect = [[GLKBaseEffect alloc] init];
    self.effect.light0.enabled = GL_TRUE;
    self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f);

    glEnable(GL_DEPTH_TEST);

    // glGenVertexArraysOES(1, &_vertexArray);
    // glBindVertexArrayOES(_vertexArray);

    glGenBuffers(1, &vertexBufferID);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
    glBufferData(GL_ARRAY_BUFFER,
                 sizeof(vertices),
                 vertices,
                 GL_STATIC_DRAW);

    glGenBuffers(1, &indexBufferID);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                 sizeof(indices),
                 indices,
                 GL_STATIC_DRAW);

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, // Specifies the index of the generic vertex attribute to be modified.
                          3, // Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4.
                          GL_FLOAT, //
                          GL_FALSE, //
                          0, //
                          BUFFER_OFFSET(0)); //

    // glBindVertexArrayOES(0);
}

- (void)tearDownGL
{
    [EAGLContext setCurrentContext:self.context];

    glDeleteBuffers(1, &_vertexBuffer);
    glDeleteVertexArraysOES(1, &_vertexArray);

    self.effect = nil;
}

#pragma mark - GLKView and GLKViewController delegate methods

- (void)update
{
    float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
    GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f);

    self.effect.transform.projectionMatrix = projectionMatrix;

    GLKMatrix4 baseModelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -4.0f);
    baseModelViewMatrix = GLKMatrix4Rotate(baseModelViewMatrix, _rotation, 0.0f, 1.0f, 0.0f);

    // Compute the model view matrix for the object rendered with GLKit
    GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -1.5f);
    modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f);
    modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix);

    self.effect.transform.modelviewMatrix = modelViewMatrix;

    // Compute the model view matrix for the object rendered with ES2
    modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, 1.5f);
    modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f);
    modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix);

    _normalMatrix = GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3(modelViewMatrix), NULL);

    _modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix);

    _rotation += self.timeSinceLastUpdate * 0.5f;
}

int i;
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // glBindVertexArrayOES(_vertexArray);

    // Render the object with GLKit
    [self.effect prepareToDraw];

    //glDrawArrays(GL_TRIANGLES, 0, 3);

    // Render the object again with ES2

    // glDrawArrays(GL_TRIANGLES, 0, 3);
    glDrawElements(GL_TRIANGLE_STRIP, sizeof(indices)/sizeof(GLubyte), GL_UNSIGNED_BYTE, indices);
}

@end

```

# Answer
This is *always* caused by having a vertex array enabled for which you have either supplied no data or not enough data (e.g the buffer for which the glVertexAttribPointer call is made may not be big enough). During the draw itself you get a buffer overrun and it crashes, so check that part of your draw setup; you'll find something.
> 2 votes

# Answer
you have

```
//glGenVertexArraysOES(1, &_vertexArray);
//glBindVertexArrayOES(_vertexArray);

```

commented out in setupGL

but in your drawInRect function you call

```
glBindVertexArrayOES(_vertexArray);

```

but the value in \_vertexArray was never set (because you commented it out) and is surely garbage ...

maybe try getting the sample code to work before you edit it perhaps.

EDIT:

here

```
glDrawElements(GL_TRIANGLE_STRIP, sizeof(indices)/sizeof(GLubyte), GL_UNSIGNED_BYTE, indices);

```

you are doing sizeof(array). This will not work, this will return size of a pointer, probably 4 (bytes).
> 0 votes

# Answer
I finally found the solution, in case you are interested - "Specifies a pointer to the location where the indices are stored." That is what the documentation says, but ohh boy that is wrong - it has to be a fake pointer for the glDrawElements to do pointer arithmetic on - to be able to offset the indices. Well, that was 10 hours well spend :-)
> 0 votes

---
Tags: ios, opengl-es
---


# Question
Title: Canvas animation drops to 30fps every 3-4 seconds
Ok! I solved the problem.

## Chapter One - Multiple Canvases

I started to make pong utilizing requestAnimationFrame and I noticed that the ball was stuttering and slowing down every 3-4 seconds. So I implemented a crude FPS function to write the current fps to the screen and realized that the slow down was accompanied by an fps drop to 30fps. I thought it had something to do with my collision detection function, but it was not the case.

MarkR noticed that I had two canvases drawing and updating the player/ball separately, he suggested that I combine the two canvases into one. This produced better performance and now I could only see the slow-down/stuttering every 15~ seconds. The problem was, the stuttering was still happening.

## Chapter Two - Vsync, Chrome Developer Tools

In comes Dreta! Dreta said that the fps was dropping to 30fps because canvas is trying to Vsync. I had no idea what he was talking about, so I asked Mr. Google and found a really good explanation of how Vsync/double-buffering/triple-buffering works. It's a medium read, but it it definitely worth checking out if you want to learn more about how your graphics card/monitor works.

He also told me that I can look at the fps of the game in Chrome by using the Developer Tool(which can be accessed by right-clicking -\> inspect element -\> Timeline tab and clicking on the black circle at the bottom-- the circle will turn red when recording). You can also look at the memory usage and I noticed that it was periodically shooting up to 4mbs of memory used. Dreta suggested it was a memory leak--

## Chapter Three - Memory Leaks

To locate a memory leak, use the following process: Found at microsoft site (http://msdn.microsoft.com/en-us/library/ms859415.aspx)

- Find the memory leak – Detect the presence of a memory leak in the system, given a particular reproducible sequence. You should be able to identify a specific process, but demonstrating an overall increase in committed system memory can qualify a memory leak as well.
- Isolate the memory leak – Determine the exact location in the source code where the un–freed allocation occurs. This can be a lengthy and tedious process, requiring specific tools, trial–and–error, and teamwork with the original author of the code.
- Fix the memory leak – After the first two steps are completed, this is easy. Fixing the memory leak usually involves adding some code to free the memory in the questionable code path.

Dreta suggested that I use heap profiling to find memory leaks. I personally have not read up on it yet, but here's a link to chrome's explanation of heap profiling developers.google.com/chrome-developer-tools/docs/heap-profiling.

He said:

> Each time you update the player, you're creating a function. You probably want to change the Player class from:

```
this.update = function() {
$("#c").mousemove(function(event) {
  tempY = event.pageY;
});
this.y = tempY;
}

```

which creates a function every 16ms I update the player

> to:

```
var that = this;

$("#c").mousemove(function(event) {
  that.y = event.pageY;
});

```

This helped optimize the game further.

## Chapter Four - I'm stupid, yeah... Chrome Tabs + Memory

I remembered that there was an issue with chrome with multiple tabs open, and I decided to quit out of and restart chrome anew. Behold! Constant 60fps and 1-2.5 mb memory usage(where it was 2-4mb memory usage before).

Moral of the story... close down all tabs and restart chrome before determining the problem, and use heap profiling to locate memory leaks.

Thank you everyone for your help! I really do appreciate it.

Here's the code on github. Please let me know if you find more stupid mistakes or you have general tips on working with canvas/programming.

Feel free to email me yangsunwoo@gmail.com

# Answer
> 6 votes
An FPS counter doesn't do much for you if you're using requestAnimationFrame. If you go over the 60 FPS budget, the browser might drop you straight to 30 FPS because it's trying to vsynch. You can check your frame budget in Chrome in the Timeline tab of the Developer Tools. There's plenty of tutorials for that, so i won't go into detail.

I can see that most of the time, you're well in budget. The issue is that you're leaking memory. Quite heavily, i might add. Just take a few heap snapshots. I'm sure the hiccups are because of that.

My guess is that this is the issue:

```
  this.update = function() {
    $("#c").mousemove(function(event) {
      tempY = event.pageY;
    });
    this.y = tempY;
  }

```

Each time you update the player, you're creating a function. You probably want to change the Player class to something like this:

```
function Player(y) {
  this.x = 20;
  this.y = y;
  this.width = 20;
  this.height = 60;

  var that = this;

  $("#c").mousemove(function(event) {
    that.y = event.pageY;
  });

  //remove the update function from your code

}

```

I can't really see anything else being a glaring issue. jQuery is using the DOM level 2 events here probably, which means that you're creating and assigning to a mouse event a new callback function each 16ms which never gets cleaned up. This should be the issue and the change i suggested should fix it.

---
Tags: javascript, html-canvas
---


# Question
Title: OpenGL vs DirectX difference from Graphics card perspective?
I want to know the difference in purely hardware level if there is any. For example the most simple question: Is there a chip for DirectX and another chip for OpenGL? What do hardware producers do to make their cards DirectX or OpenGL compliant?

# Answer
No, OpenGL and Direct3D are both APIs that abstract the functionality of the actual hardware. Direct3D is a Microsoft application and standard while OpenGL is an open standard.

Any GPU will work with OpenGL and Direct3D as long as there's a driver for it. The driver is what takes Direct3D/OpenGL calls and does all the really low-level interfacing with the GPU. There is no "DirectX only" GPU and no "OpenGL only" GPU, unless for some strange reason the drivers only support one of the APIs.

From the graphics card's perspective, it's only communicating with the driver. The driver then communicates with all the APIs it supports.

Hardware vendors must write drivers against the Direct3D and OpenGL specifications in order to make their cards compliant with that API.

**EDIT**

If you're looking for some differences in the two APIs, DirectX is more geared towards games while OpenGL is a more general 3d rendering platform. More on that in the Wikipedia article comparing the two.
> 9 votes

# Answer
Direct3D and OpenGL are APIs, they're implemented in the drivers by the manufacturers. For OpenGL, the manufacturer has to implement a set of functions that act in a way described by the specification provided by the Khronos Group. Then the programmer can retrieve the addresses to those functions and use them in the program, the details are OS dependent, it's usually done in C or C++ sine that's what OS APIs mostly use. OpenGL doesn't care how much RAM your graphics card has, so to speak. Direct3D has a more manufacturer friendly philosophy behind it, Microsoft gives more leeway, but it's still just a matter of drivers.
> 1 votes

---
Tags: opengl, directx
---


# Question
Title: How do I implement variation in font letters, like handwriting?
I can use a sprite sheet to automatically use a custom font. What I'd like to do though is to have several versions of each letter, such that the letters can be varied and more natural looking (a la handwriting). I don't know precisely how fonts are internally implemented, but I assume there's some function mapping chars to images. It seems like if that function isn't sealed, it wouldn't be difficult to make that function randomly choose one of "equal" images (that have slight variations).

Anyone know the plausibility of this/what code I'd want to overload to make this work with existing font infrastructure in xna?

# Answer
> 3 votes
Basically this is just a programming question if you abstract this out. If you really want to do this with sprite sheets, here's how I might do it in some quick JavaScript-style pseudocode...

```

// -------------------------------------------------------------------------
// --- Array of sprite sheet offset for letter variants, indexed by letter
// --- Note that it would be pretty easy to dynamically generate sprite
// --- coordinates if you are certain your sheet has all the symbols you
// --- are looking for.
// -------------------------------------------------------------------------
var font_variants = [
  {'a' : {x:0,y:0}, 'b' :  {x:16, y:0},  'c':{x:32, y:0}, ...,  'z':{x:400, y:0}},
  {'a' : {x:0,y:16}, 'b' : {x:16, y:16}, 'c':{x:32, y:16}, ..., 'z':{x:400, y:16}},
  {'a' : {x:0,y:32}, 'b' : {x:16, y:32}, 'c':{x:32, y:32}, ..., 'z':{x:400, y:32}}
];

// -------------------------------------------------------------------------
// --- Call this function with a string to render randomized style text
// -------------------------------------------------------------------------
function render_it (text) {
    // --- Step through each letter in the text
    for (var i=0; i<text.length; i++) {
        // --- Randomly pick one of 3 variants
        var r = Math.random(3);
        // --- If letter is in our set, show it
        if font_variants[r].hasOwnProperty(text[i]) {
            // --- We have the letter
            letter_sprite = get_letter_sprite(font_variants[r][text[i]].x, font_variants[r][text[i]].y);
            // --- Display the letter here however you want to
        } else {
            // --- Requested letter not found
            // --- Handle as you see fit
        }
    }
}

```

I've only put in an example of lower case letters so you'd have to add more as needed. It also assumes some function "get\_letter\_sprite", which when passed an X and Y offset returns a sprite at the given location from some sprite sheet (of letters).

# Answer
> 4 votes
I haven't tried this out, so some experimentation would be needed to see if it actually works.

What I would do:

Start from a vectorized format that follows the drawing direction. As an example, the hershey fonts \- the "scripts" and "scriptc" fonts might be a good starting point:

Next, instead of drawing the fonts as line segments, render them as splines. Estimate the velocity of the pen, and over/undershoot by random (or periodic) amounts. Try to correct mistakes, like you would when doing actual writing (so the errors in the text don't accumulate into random mess).

If you try this out, I'd love to see the results =)

---
Tags: xna, fonts, hand-drawn
---


title: Procedural Generation of Galaxy

text:
# Question
Title: Procedural Generation of Galaxy
I'd like to generate galaxy using seed , with shape changing a bit and positioning X number of stars.

I'd like to make it realistic (as possible). But i have absolutely no idea how i should do that. I'm not talking about procedural content generation , i know a bit about and i can search for it if i need, i talking about formulas to use to generate galaxy and then placing dots (stars) so it can look real.

In my mind i see it this way:

1) place a center

2) generate tentacles (don't know the exact term) (i'd like to set the number of tentacles)

3) place dots randomly around those tentacles.

bonus question : i'd like to move the galaxy ingame (like it move in real) , and i don't get if a rotating would be enough and if the movement is more complex)

# Answer
> 11 votes
Similar to your algorithm, this is the algorithm I would suggest.

Set your variables. Choose `armCount` arms, `radius` radius, `spinFactor` for spin factor, `armR` for arm radius, `starCount` for star count and `point` center point.

1. Place the `armCount` arms pointing straight away from a central point `point`. These should be *roughly* equidistant around the circumference of the circle (with a radius of `radius` entered on `point`) that makes up the galaxy.
2. Divide `starCount` into *roughly* equal `armCount` portions.
3. For each arm place `starCount/armCount` stars randomly inside the cylinder that follows the arm with a radius of `armR`. Star placement should be weighted in the following way:
    1. More likely to be placed towards the core than towards the arm tip.
    2. More likely to be placed closer to the center of the cylinder than the outside of the cylinder.
4. Now you have a galaxy shaped like a star with `armCount` arms. With more stars at the core and the arms somewhat distinct. Time to rotate. For each star, take its distance from the center and multiply that by `spinFactor` to get a `rotationAmount`.
5. Rotate each star by the rotation amount clockwise or counter clockwise around the center point.
6. Marvel at the resulting spiral galaxy.

You could probably combine the rotation and placement steps and just place the start initially at their rotated position. I'd do it in separate steps to start with, just so you can see how things form up without being all twisted up.

Bonus answer: Humans haven't really had the star viewing technology long enough to watch a galaxy rotate, so we don't know exactly how it looks. However, from viewing simulations, it looks like it's spinning at higher speed in the center than the outside. You can try applying the same rotation to each star as you do in step 5. Or you can just slowly rotate the entire galaxy and see how it looks.

# Answer
> 10 votes
Here are two articles that may give you some more ideas.

How Frontier: Elite 2 generated The Milky Way with 513,982,470 unique stars. (archived)

~~Point cloud galaxy generation in Infinity.~~ (broken link)

---
Tags: procedural-generation, mathematics
---


# Question
Title: Why released games usually contain their scripts sources?
AFAIK people like scripting because it's easier, and it makes development cycle faster. But what about when games are shipped. No one expects shipped binaries to be changed, unless there is an update or a DLC. So why developers don't compile their script files before shipping?

**Potential benefits:**

1. Faster run time
2. Obfuscating binary a little mode

and I can't think of any possible draw backs.

Examples:

1. Civilization 5 had lots of lua scripts inside their assets folder.
2. Angry birds also had a lot those scripts along side binary.
3. Age of Mythology had lots of xs scripts for their AI.
4. Civilization 4 had lots of python scripts.

I'm pretty sure the list could have gotten a lot longer if I had more games installed on my device.

# Answer
> 2 votes
I suspect it's because that one of the advantages of using scripts over C++ code is that there is no compile process so it makes for quick and easy editing during development.

Lua also gains no run-time performance from compiling it off-line. It's just load time it speeds up.

Adding the extra compile step in then just slows down development and makes the process more error-prone (e.g. the script can get out of sync with the compiled version).

Compiling all the scripts just before you ship the game has obvious risks that you did all your testing with the scripts in their uncompiled state, and shipping something that's not been tested is a bad idea.

On any single player game there's also no harm done if your users want to modify the game in some way by editing scripts.

# Answer
> 3 votes
The reasons for each game is really only known to the developer. I plan on including the scripts in my game for one simple reason, I want users to be able to customize the game.

There are a few benefits I can think of for not compiling the scripts:

* **User customization**: Allows the users to modify certain aspects of the game play or units in the game. Then users can just drop in new scripts and add a new AI difficulty level or add a custom unit.
* **Localization data**: Allows developers to deploy specific data to specific locals without needing to recompile the binary for each location.
* **Segregation of code**: The people working on creating the code behind the binary are not necessarily the same people working on the scripts. Keeping them separate means the two groups don't rely on each other.
* **Easy updates**: Updating just the scripts is a simpler process and might be easier permission-wise to update files than replacing an executable.

---
Tags: game-industry, scripting
---


title: Best source for sound effects?

text:
# Question
Title: Best source for sound effects?
What is a good source for sound effects for use in an indie game production (C#, XNA)?

* The sounds do not need to be free.
* They, however, should have a clear licence for commercial use.
* The website should allow for searching, browsing and preview (or better: pre-listening).

I already had a look at http://www.1soundfx.com but their collection is not too large. I am specifically looking for sound effects. No music and no ways to make my own sounds.

All help is greatly appreciated!

# Answer
> 1 votes
Personally I use SoundSnap.com they are reputable and have been used by several major companies.

# Answer
> 0 votes
An indie game might be a good place for some old school \[self generated midi sound effects\]..

---
Tags: sound, assets, sound-effects
---


# Question
Title: Anybody know how I can write a game for the dualshock 3 or other gampad in python?
I am a new developer and want to write a game that uses a gamepad like the dualshock 3 I want to write it in python although am willing to learn a little C/C++

I need to identify the buttons and rotaters and send feedback like haptics not to mention the motion control

# Answer
Well, SDL has support for controllers (joysticks) and pygame is a python wrapper for SDL so in theory it should support joysticks. There does seem to be support (http://www.pygame.org/docs/ref/joystick.html) for joysticks but I cannot say how well a dualshock 3 controller maps to it. (Theres some issues around mapping the Xbox 360 controller for example)
> 3 votes

# Answer
You can: http://www.pygame.org/docs/ref/joystick.html

Also: http://thp.io/2010/archive/joystick-gstreamer.py

Extract:
Control GStreamer filters in a pipeline using analog sticks of gamepads Copyright (c) 2010-12-22 Thomas Perl
> 2 votes

---
Tags: python
---


# Question
Title: Problem with alleg42.dll / program crashes / Allegro & Codeblocks
I'm having a serious problem with allegro. The program should display random pixels on the screen and when I build and run it I get the following error message:

Below is the full code of my program:

```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "allegro.h"

#define Text_Color_Red makecol(255,0,0)
int main()
{
    int ret;
    int color_depth = 32;
    int x;
    int y;
    int red;
    int green;
    int blue;
    int color;

    //init allegro
    allegro_init();

    //install keyboard
    install_keyboard();

    //set color depth to 32 bits
    set_color_depth(color_depth);

    //init random seed
    srand(time(NULL));

    //init video mode to 640 x 480
    ret = set_gfx_mode(GFX_AUTODETECT_WINDOWED,640,480,0,0);

    if(ret !=0)
    {
        allegro_message(allegro_error);
        return 1;
    }

    //Display string
    textprintf(screen,font,0,0,10,0,Text_Color_Red,"Screen Resolution is: %dx%d -- Press ESC to quit !",SCREEN_W,SCREEN_H);

    //display pixels until ESC key is pressed
   //wait for keypress
    while(!key[KEY_ESC])
    {
        //set a random location
        x = 10 + rand() % (SCREEN_W-20);
        y = 10 + rand() % (SCREEN_H-20);
        //set a random color
        red = rand() % 255;
        green = rand() % 255;
        blue = rand() % 255;
        color = makecol(red,green,blue);
        //draw the pixel
        putpixel(screen, x, y, color);
    }

    //quit allegro
    allegro_exit();
}

END_OF_MAIN()

```

Error message: AllegroPixels1.exe has encountered a problem and needs to close. We are sorry for the inconvenience.

Error signature: AppName: allegropixels1.exe AppVer: 0.0.0.0 ModName: alleg42.dll ModVer: 4.2.3.0 Offset: 0006c05c

I am using Windows XP inside a virtual machine under Parallels 7.0

# Answer
> 2 votes
Running the debugger pointed to the `textprintf` line being the culprit. You have an extra parameter `10` in there that should not be there. Fixing that solved the problem.

HOWEVER, there are other problems with the code:

1. You are using the old version of `textprintf` use the new version like so:

textprintf\_ex(screen, font, 0, 0, Text\_Color\_Red, -1, "Screen Resolution is: %dx%d -- Press ESC to quit !", SCREEN\_W, SCREEN\_H);
2. You are not calling `acquire_screen()` before you draw to the screen and `release_screen()` after you are done drawing.
3. Most importantly, you are not having `main` `return 0` at the end of the function.

# Answer
> 0 votes
You should debug your program line by line to find the exact line the crash happens. It's been a while since I've used Allegro, but from what I see this should work.

# Answer
> 0 votes
First off, Allegro 4.2 is painfully old. Allegro 4.4 is source compatible. Allegro 5 is recommended, but has a totally different API.

The likely culprits:

1. The DLL you are using is not compatible with your compiler. You cannot mix and match. You cannot use a 4.2.0 DLL with a 4.2.2 program. You cannot use a gcc-built assembly enabled DLL with a C-only MSVC build, etc.
2. Running inside a VM is not going to be very pleasant. In the very least, you should probably use `GFX_GDI` as the graphics driver and `set_color_depth(desktop_color_depth())`.

---
Tags: allegro
---


title: Triangles in the corners of skybox

text:
# Question
Title: Triangles in the corners of skybox
When looking at the corners of skybox this happens:

https://i.stack.imgur.com/AGenQ.jpg

How to get rid of this?

6 skybox textures are 2048x2048px each.

Tried changing Near and Far clipping of the main camera inside the character controller but it was ineffective.

If I look away from the corners the dark triangles dissapear. Only when I look directly at the corners they appear.

# Answer
> 1 votes
In the screenshot I can see three different levels of the skybox, as the stars in the bottom corners are even brighter. I would guess this is related to mipmapping. Looks like different mipmap levels somehow produce different results. Try disabling mipmapping to see if the problem disappears. A possible cause for this effect could be lack of gamma correction for producing the mipmaps, which makes the blurred stars appear darker than the sharp ones.

---
Tags: unity, skybox
---


title: How to load images on startup

text:
# Question
Title: How to load images on startup
I want to load all my game's images on the game's startup and have a loading bar to show it's progress. I already know how to create and display the loading bar, but I can't figure out how to load the images, and then add the image's frames to it's array.

Not using SLick

# Answer
Loading an image in Java is easy:

```
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

BufferedImage image = ImageIO.read(new File(fileName));

```

But I have no idea what you mean by "add the image's frames to it's array".

You are not using Slick, but are you using LWJGL? If so, you need to create a Texture from this image before you can use it. Do you need help with that?
> 1 votes

---
Tags: java, loading
---


# Question
Title: How to link OpenGL with my own static library?
My game project is split up into three parts:

1. Core (lib)
2. Editor (exe)
3. Game (exe)

I'm using OpenGL in both my Core and Game parts, but as soon as I try to call an OpenGL function in my Core library the application crashes. I assume this is because the static library is not being linked with OpenGL. The build process goes like this:

```
# core library
g++  -c  ... -std=c++0x -g  -o ... -I. -I.
ar rcus libCore.a ...

# game exe
g++ -o Game ... -L. -L../Core/Debug/   -lCore -lglew32 -lglfw -lopengl32

```

Where `...` stands for the various files. How can I link OpenGL with my static library?

# Answer
> 4 votes
Were you calling glewInit in your main game before core calls any GL functions? If not all the gl function pointers will be null and destined to seg fault. Is Glew built as a static library as well, or as a DLL? If it is built as a static library, is the GLEW\_STATIC macro defined when you include it in you core lib? Conversely, if GLEW is built as a DLL, make sure the GLEW\_BUILD macro is NOT defined when you include it in your core lib. If nothing is working, make sure you check you can call GL functions from inside you main executable code using GLEW, (and turn off all core library function calls).

---
Tags: c++, opengl, mingw
---


# Question
Title: Will DirectX 10.1 graphics card work with DirectX 11?
I just started learning DirectX, but I have a problem with its version. I have ATI Radeon HD 4830, this card supports only DirectX 10.1, but when I ran `dxdiag` it said that I have DirectX 11, then I realized its probably talking about what version does the OS(Windows 7) support.

Now, I just ran some DirectX 11 benchmark and it worked. Does it mean that my graphics card is capable of running DX11 or it just runs in DX 10.1?

I want to know this, because I don't know what version of DX should I use for programming. I'd like to use DX 11 because of shaders, but don't know whether it's safe. If it's not I'd rather use DX9 with shaders, because I heard that DX 10 is buggy and I should use DX9 rather then 10, if DX 11 not available.

Or does DX 11 support older versions itself, so I can use DX 11 headers but limit myself to older features?

So what is your opinion? Should I use DX 11(code compiles, but I am not sure whether my card supports it), or DX 9?

Thanks in advance.

# Answer
> 3 votes
You can target older graphics cards (as far back as Direct3D 9 era) via the use of feature levels while using the Direct3D 11 API, yes. While I haven't heard Direct3D 10 called "buggy", I'd argue Direct3D 11 tends to be just all around better with various minor improvements to the API... with little to no reason to prefer 10 over 11. As a final note, Direct3D 11 requires Vista SP2 or later.

---
Tags: directx
---


title: Android Game starter

text:
# Question
Title: Android Game starter
I am new and vey much interested in android stuff. please help on how and where to start the development of game.

Any Prerequisite for that.

Awaiting for reply.

# Answer
> 2 votes
You should start by learning java, the language that android is programmed in. Practice it by writing a few non game apps. Then you should look at a game engine, like libGDX or AndEngine. You will also find that a lot of people will recommend that before you write a game on android, you write a few simple ones for your computer, because it is easier to understand and will help you grasp the ropes of game engines.

---
Tags: android
---


title: Blending transition in cocos2d

text:
# Question
Title: Blending transition in cocos2d
In my cocos2d-iphone game, I have 2 backgrounds (CCnodes), each containing a quite complex hierarchy of sprites.

I would like to make a smooth transition between them:

* Initially, only the first background is visible
* At the end, only the second one is visible

Is there a good way to set the opacity of a full hierarchy of sprites ?

I tried to recursively set the opacity of all the contained sprites. It kinda works except that:

* I guess it's not very efficient
* I would like the opacity of overlapping sprites to be 'merged' (as if the background was one single big sprite)

# Answer
> 1 votes
I finally solved it using a `CCRenderTexture`.

You can find the detailed explanation here: http://2sa-studio.blogspot.com/2013/01/fading-node-hierarchy-with.html

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


# Question
Title: Network communication via Sockets. Is there a better way?
I'm building a game engine on the OpenTK framework that needs to support multiple players.

How I have the basic framework established is that there is a Client and a Server. The Server binds and listens on a specified port, and the Clients connect to the Server's IP Address and Port to make a TCP socket. The server then transmits a `World` object to all clients as they connect.

A `World` object contains all of the `Light` objects, `Surface` objects, `Mesh` objects and `Camera` objects. With all of these objects, the `World` is responsible for rendering the game environment.

My idea is that each `Camera` object has a Unique ID, a position (X,Y,Z), and 2 angle values representing Zenith and Azimuth. When any of these values changes (only the camera can move at this point. Basics first!) I want to Serialize and send the updated `Camera` object to the Server, which then transmits this object to all of the Clients. The Client then deserializes the new `Camera` object, uses its Unique ID and updates the existing `Camera` object in the `World`. Since the Camera object consists of only 5 double values (X,Y,Z,Az,Ze) it shouldn't be a lot of data being sent over the network, but my implementation seems to slow down the Game Screen significantly

Is there a better model for Multiplayer network communication? Is there any built in functionality in C# that handles this kind of communication?

Basically, I just need to update all of the other Clients when one Client's `Camera` changes.

Thanks for any help!

# Answer
> 18 votes
Sockets aren't the problem. That's just how TCP/IP networking works. Two things could be wrong. How you are using them and what you are sending?

Serializing a class and sending it and de-serializing seems huge for a game. Just send something like `CBIXYZCE` as in `CB` for camera begin, `I` for identifier, x coord, y coord, z coord, and `CE` for camera end.

When it comes to networking be as terse as possible.

In fact my example may be too big. The camera class should exist on the server and you only pass what changes. Oh and use UDP.

# Answer
> 1 votes
You need consider the strengths and weaknesses of both TCP and UDP connection types. Generally UDP is used to send state data such as player position and actions. TCP is used to send information such as logins, level changes etc. Checkout this simple example of how to create a client server application in minutes using the open source network communication framework networkcomms.net.

# Answer
> 0 votes
Generally speaking, I'm more in favor of using SSL to do the network communications in general. While it may seem unneeded, there have been hacks for some games to use the unencrypted transmission of the packets from the netcode to do some pretty nasty things. SSL would not prevent that completely, but it would add an additional layer of protection to slow it down.

---
Tags: c#, networking, multiplayer
---


# Question
Title: How to enable sound on Base Game Activity in Andengine?
I am developing a game using **Andengine** , I am using a **Base Game Activity** with multiple scenes. I want to load a **background music** in it.But I dont know **how to enable sound in engine** while using Base Game Activity.I found this code in net to enable sound .

```
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE,
   new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera).setNeedsMusic(true));

```

But this one is written in onLoadScene() and I dont know how to impliment onLoadScene() in basegame actvity.Do I can override onLoadScene() in base game activity or is there any other ways to achive this please help me...

Any Suggestions are Valid to me and Advanced thanks to alll....

# Answer
> 0 votes
Solved the issue with the Help of Jmr Here is the code

```
final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED,
            new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
    engineOptions.getAudioOptions().setNeedsSound(true);
    engineOptions.getAudioOptions().setNeedsMusic(true);

```

---
Tags: andengine
---


# Question
Title: HLSL compiler specification (optimizations)
Can I read somewhere about optimizations that HLSL compiler performs?

For example, in some codes I have different variables that get a constant value (just to let myself adjust the shader with other values) and I use them later in some mathematical expressions, but actually it can be precalculated earlier. Does the compiler do such thing?

It's just an example, I would like to know most of these things.

# Answer
I don't think any such spec exists publicly, but you can disassemble your compiled shaders using the D3DDisassemble API function, or using `fxc /Fc` at the command line. If you write some example shaders and look at the disassembly, this will give you some idea of the optimizations it does.

Note that this assembly is a machine-independent intermediate language (IL). Shaders in D3D get compiled to this IL first by Microsoft's compiler, then they get compiled again to the actual GPU machine instructions by the GPU vendor's compiler which is part of their D3D driver. The second stage requires vendor tools to get at, like AMD's ShaderAnalyzer, and NVIDIA's ShaderPerf (although it looks like it hasn't been updated in awhile - no support for the latest NVIDIA GPUs or for 5\_0 profiles). Some further optimizations may be done by the second stage of compilation, and those tools will let you see it to some extent.
> 3 votes

# Answer
The compiler can do some very effective optimization. The best way to find out what it can do is to use a tool like GPU ShaderAnalyzer which will show you the disassembly for a shader.

The one thing that it doesn't do is to move calculations between shader code and CPU code.
> 3 votes

---
Tags: hlsl, directx11
---


# Question
Title: php multiplayer game - server&client model
I'm working on a simple round&web-based multiplayer game. The idea of the game is very simple: The players get an array of audio files which they listen to and write the transcripts for in 5 minutes. the player who sends in the most right transcripts gets the most points. its fairly simple and i was able to implement it locally. at the moment i have the .php file which lets me do all this but only in single player. what i'm trying to say is that whenever a player logs him/herself in, the page is loaded anew. what i want to do is to start the game from the server everytime 3-5 players log themselves in, so that the players can play at the same time and their results can be compared at the end of the round.

the thing is, i don't know how to start with this session or server/client model for a multiplayer game. i have read that php isn't ideal for web based multiplayer games because real time data exchange could be problematic, but since that is not really the case here i don't think that should be a major problem. i googled my problem but i have failed to find a solution. any help or advice would be much appreciated. cheers.

edit: is a node.js server what i'm looking for here?

# Answer
> 2 votes
Socket.io/node.js is precisely what you want. If you want to start a tad simpler, you could use ajax and an timeout to poll the server every 30 seconds or whatever time period to get a response concerning other players around. So really either take the active approach with socket "The server has just told me someone joined, someone answered, etc" or the passive ajax approach "Let me ask the server if anything has happened."

---
Tags: multiplayer, server, client-server, php, online
---


title: Slick2D TileD Map Editor Properties

text:
# Question
Title: Slick2D TileD Map Editor Properties
So I used the following post to help me render my isometric map in Slick2D:

Slick2D Isometric TiledMap Rendering Problem

Big thanks and credit to arminb for the code supplied and for the fix to be able to use it.

My question is, how would I go about getting the properties of the isometric tiles. I have a little character that can walk around on the map, but he can walk on the blocked tiles. I have no code to be able to detect the properties.

This is the code I am using. The map is generated correctly, and the character is generated correctly.

How would I get the properties of a tile that I walk on?

```
import org.newdawn.slick.Animation;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.tiled.TiledMap;

public class Game extends BasicGame {

    private TiledMap map;
    private Animation sprite, up, down, left, right;
    private float x = 350f, y = 250f;
    public static void main(String[] args) throws SlickException {
        AppGameContainer app = new AppGameContainer(new Game());

        app.setDisplayMode(800, 600, false);
        app.setShowFPS(true);
        app.start();
    }

    public Game() {
        super("Test");
    }

    @Override
    public void render(GameContainer arg0, Graphics arg1) throws SlickException {
        map.render(350, 250);
        sprite.draw((int)x, (int)y);
    }

    @Override
    public void init(GameContainer arg0) throws SlickException {
        Image [] movementUp = {new Image("data/wiz_up_one.jpg"),
                new Image("data/wiz_up_two.jpg")};

        Image [] movementDown = {new Image("data/wiz_down_one.jpg"),
                          new Image("data/wiz_down_two.jpg")};

        Image [] movementLeft = {new Image("data/wiz_left_one.jpg"),
                          new Image("data/wiz_left_two.jpg")};

        Image [] movementRight = {new Image("data/wiz_right_one.jpg"),
                           new Image("data/wiz_right_two.jpg")};
        int [] duration = {300, 300};

        up = new Animation(movementUp, duration, false);
        down = new Animation(movementDown, duration, false);
        left = new Animation(movementLeft, duration, false);
        right = new Animation(movementRight, duration, false);

        // Original orientation of the sprite. It will look right.
        sprite = right;
        map = new TiledMap("data/iso.tmx"); //path is valid!
    }

    @Override
    public void update(GameContainer gc, int delta) throws SlickException {
        Input input = gc.getInput();
        if (input.isKeyDown(Input.KEY_UP))
        {
            sprite = up;

            sprite.update(delta);
            // The lower the delta the slowest the sprite will animate.
            y -= delta * 0.1f;

        }
        else if (input.isKeyDown(Input.KEY_DOWN))
        {
            sprite = down;

            sprite.update(delta);
            y += delta * 0.1f;

        }
        else if (input.isKeyDown(Input.KEY_LEFT))
        {
            sprite = left;

            sprite.update(delta);
            x -= delta * 0.1f;

        }
        else if (input.isKeyDown(Input.KEY_RIGHT))
        {
            sprite = right;

            sprite.update(delta);
            x += delta * 0.1f;

        }
    }

}

enter code here

```

# Answer
Read the documentation for the `TiledMap` class. You'll find a method called `getTileID()`. It takes a `x` and `y` position and a layer ID. Pass in the position and layer ID of the player. This will give you the ID of the tile the player is at. Use that ID to retrieve information about the tile.
> 2 votes

---
Tags: java, tiles, isometric, lwjgl, slick
---


title: How do I use music analysis in a game?

text:
# Question
Title: How do I use music analysis in a game?
I'm thinking of writing a game in the vein of BeatHazard (where the music you're listening to affects the game), and after researching the subject of music analysis in programming, I know enough to know that it's a very complex subject. So here are some questions:

1. What concepts do I as an engineer need to know about to do this? What concepts do I probably *not* need to know about?
2. What kinds of analysis are simple, robust, and efficient enough to be used in a game (and preferably in that order - I would greatly prefer simplicity over efficiency and can trade some correctness if it keeps things simple)?
3. What cross-platform open source libraries exist that are easy to build and include? I'm using MonoGame, but I'm willing to use p/invoke for a good library. I've read about aubio, clam, and marsyas, and I'm not quite sure which I'm looking for.

# Answer
This is a very interesting question.

To analyze music, it is important to know exactly how one song differs from the next. Of course, music is a very abstract art field with a lot of incomplete and conflicting opinions and elements, but here is a short list of things that are generally agreed upon as making one song different from the next:

1. Tempo/Rhythm. Basically the speed of the song. How fast you are producing one sound after the other.
2. Pitch/Frequency. The (fundamental) frequency of one tone.
3. Timbre. The 'tone color'. Playing the same tone with the same pitch and length on a different instrument will create a different sound.
4. Amplitude. Basically how loud or soft a certain sound is played.
5. Harmony. When playing multiple sounds together or after oneother, the relation between their different pitches will change the feeling of the music.

The other thing you need to know about is how music is stored inside the computer. A music file consists of, for each sample in time (with many samples per second, 44.1 kilosamples or often higher) the amplitude of the speakers.

It might seem odd that only the amplitude over time is enough to store all four previously-mentioned elements, but this is natural: after all this is the same way sound is stored in the 'air' when it's traveling towards our ears.

**How are these elements all related to amplitude?**

1. Tempo/Rhythm: To put it very crudely the time between two tones is the time between two amplitude peaks. Rhythm is a sequence of these times repeating.
2. Pitch/Frequency, Harmony and Timbre: One amplitude changing over time can also be expressed as a multitude of Sine waves. By using a mathematic formula called the Fast Fourier Transform, computers do this (probably already behind your back) to give you visible harmonics and fun like http://en.wikipedia.org/wiki/Spectrograms. To put it simply:

* Pitch is the fundamental frequency of one tone
    * Timbre are the 'overtones' of one tone
    * Harmony are the relations of different pitches occuring at the same time.

Obviously this is getting complex very quickly, and it is difficult to create robust systems that analyze the Pitch, Timbre and Harmony well(enough).

**What kind of analysis are Simple, Robust and Fast** \- Amplitude/Harmony analysis. It is very straightforward to check how loud the song is(or how loud different frequencies of the song are) at a certain point in time. This is used all the time. Most audio visualisations are based around this approach.

* Timbre analysis. Check what kind of different overtones are loud right now. Depending on even/odd overtones(compare triangle with square and saw waves) you can say something about the general timbre of the sound (if you are hearing a 'lush' sound or a 'screechy' sound for instance).

*About sound engines to use, I will get back to you. I will update and refine this answer shortly with that information. Sorry for the slightly long rant. I hope it might prove helpful.*
> 6 votes

---
Tags: music
---


# Question
Title: Is it possible to render part of the screen in different pixel density using openGL?
Say I have an openGL screen and I want to render part of the screen in different pixel density than the whole screen pixel density. Is it possible and if possible how?

# Answer
> 3 votes
Sure. Figure out which portions of the screen you want to render at what resolutions, and render them into FBOs of appropriate sizes.

Once you have your different elements rendered into separate FBOs, you can then composite them together into the main framebuffer using glBlitFramebuffer().

Or alternately, if you don't want to composite them together as complete rectangles (which is what glBlitFramebuffer() will do), then you can bind the various FBOs as textures, and draw from them to the main framebuffer with triangles, in whatever manner suits your desired effect.

---
Tags: opengl, resolution, pixel
---


# Question
Title: 2D tilemap editor UI--how do I disable editing while save/load dialog is open?
I'm working on a basic 2D tilemap editor in C#/XNA. Currently, it displays the map through a picturebox through which XNA's output is being routed, and editing is accomplished through simply checking mouse position (i.e., Is it within the picture box? If so, what tile is it on?).

The problem I'm having is that this results in the map being edited through other windows. For example, when trying to save a map, any clicks in the savefiledialog window will edit the map square beneath it, including the click on "Ok" or "cancel."

I believe this is the offending snippet of code from the Game1 class:

```
protected override void Update(GameTime gameTime)
    {

        Camera.Position = new Vector2(hscroll.Value, vscroll.Value);

        MouseState ms = Mouse.GetState();

        if ((ms.X > 0) && (ms.Y > 0) &&
            (ms.X < Camera.ViewPortWidth) &&
            (ms.Y < Camera.ViewPortHeight))
        {
            Vector2 mouseLoc = Camera.ScreenToWorld(
                new Vector2(ms.X, ms.Y));

            if (Camera.WorldRectangle.Contains(
                (int)mouseLoc.X, (int)mouseLoc.Y)) //<--right there
            {
                if (ms.LeftButton == ButtonState.Pressed)
                  //....

```

Two questions.

1. Is this even a viable way to display the map in the map editor? I'd like to be able to pan, zoom, etc. in the future, as well as select multiple tiles at once and edit their properties.
2. How do I stop the picturebox from registering clicks while other windows are in focus? I've tried adding `&& PictureBox.Focused` to the `if` statement up there, but that stops it from accepting input at all, regardless of whether there's another window over it (apparently, "focus" doesn't mean what I thought it meant in this context).

Confession: this is my first attempt at Winform programming. Please excuse my lack of experience.

**UPDATE:** `&& pictureBox.Focused` didn't work, but `&& pictureBox.Capture` did. Still feels a little sloppy, but it works now. I have no confidence that this solution is correct, so I'm not closing the question just yet--something tells me there's a more correct way, and I'd like to know about it.

**UPDATE2:** Using Capture has introduced a new bug--right clicks don't register reliably (i.e., only around one in ten clicks) until minimizing and restoring the window, after which they register correctly. Rage.

# Answer
I reworked the code to use the Windows.Forms mouse event methods rather than XNA's input methods, and that solved the click-through problem. Just had to use `PointToClient` and set up offset values (i.e., `int offset = myPictureBox.Location.X`) to subtract from my mouse coordinates.

Here's the relevant code, for anyone who stumbles upon this problem in the future:

```
//constructor
public MapEditor()
    {
        InitializeComponent();
        this.pctSurface.MouseDown += new MouseEventHandler(pctSurface_Click);

        pctSurface_xOffset = pctSurface.Location.X; //private instance variables
        pctSurface_yOffset = pctSurface.Location.Y;
    }

//on click
private void pctSurface_Click(object sender, EventArgs e)
    {
        //convert from screen coordinates to game world coordinates
        Vector2 mouseLoc = Camera.ScreenToWorld(
            new Vector2(PointToClient(MousePosition).X - pctSurface_xOffset,
                        PointToClient(MousePosition).Y - pctSurface_yOffset));

        switch (MouseButtons)
        {
            case System.Windows.Forms.MouseButtons.Left:
            //whatever you need left clicks to do
            break;
            //etc

```
> 1 votes

# Answer
This is an issue I was facing and its not directly built into XNA. One thing you can do is use win32 form controls to check which window is active. Another would be to centralize the dialogs and when one is opened, set a flag to disable input. (You can get the win32 form info by doing

```
var form = System.windows.Control.FromHandle(Window.Handle) as System.windows.Forms.Form;

```

)
> 0 votes

---
Tags: xna, c#, tilemap, windows-forms
---


# Question
Title: Modeling speed of light information propagation in space combat sim
I'm working on a space combat sim that takes place over relatively vast areas (a cube of space ~20 light minutes to a side) and uses (mostly) realistic physics. One of the key elements I want to model is the propagation speed of information across the battle space -- that is, if Player A engages his main drive on one side of the battle space, there's a 20 minute delay before Player B sees it and can react to it

Even for relatively small battle spaces this is an important factor given the speeds involved. A 500m long ship doing 30kps is going to displace itself by its full length in 1/60th of a second, so even targeting an opponent just few tenths of a light second away are going to be affected by light lag.

I've not seen this done before, and I'm wondering if there are some best practices for modeling this. Right now I'm timestamping each event and marking it with a location, putting it into a queue, and then each tick checking to see if any of the objects in the game world are newly at the edge of the light cone and adding the event to their sensor queue. I will (but haven't yet) optimize it by removing any events that have already been sensed by all the objects that can possibly sense it, but still, I think this is going to get cumbersome pretty darn fast, and eat up a lot of cycles if there are hundreds of sensing objects in play (which is pretty routine).

Are there data models which would be better suited for this that I should check out?

# Answer
> 9 votes
Just brainstorming here...

Interestingly enough, network lag is your friend in this case. As in you WANT a delay to occur for some data packets, at least if it's about drawing. But instead of a base lag each player would normally have for all data packets impacted by just their network speed, you need to apply specific lag for each event to each player based on the light-speed delay.

Typically the server would send out updates to all clients at the same time, but what you need is for the server to calculate the "light lag" for each event (based on distance of viewer), and then not send out an update until that time.

So for every event, calculate time delay between event and each player, then queue up that event to not be sent for drawing to that player until the delay time has passed.

This doesn't address the effect of the player changing position or speed after the event occurs, but you could potentially adjust events that had been queued based on player changes. A player begins to move closer, move event closer in time. Player moves away, move away in time.

Doppler shift would be an interesting thing to throw into the mix, based on the movement delta between viewer and event.

# Answer
> 5 votes
The question is: how exact do you need your delayed image to be to how it actually played out? If you're looking for 100% accuracy you're going to need to save either the actions or the state of every object on the map at each tick and, as you say, replay them on a delay based on distance. If you don't care that much about pinpoint accuracy, which you rarely need in games, you can save the state at intervals and extrapolate between them when the delay catches up. You can optimize by not saving identical updates.

Alternatively, you can vectorize all movement and save a path for each object along with a start time seen from a universal observer. Then you can just calculate the expected position of an object for each observer based on the universal time counter the local time based on the path nodes it has saved. When a path node's timestamp goes behind the lightcone of all relevant objects you discard it.

Edit: The above assumes you're going to cheat on basic relativity by having an absolute observer (I assume the player). This would rob you of some of the more Interesting aspects of time dilation but modelling those would be a project in itself \>\_\>

---
Tags: simulations
---


title: When to use pygame.sprite.GroupSingle?

text:
# Question
Title: When to use pygame.sprite.GroupSingle?
I'm doing a game in which i have a ball which is controlled by the keyboard and the goal is to get is out of a maze without touching the walls.

I've added my ball sprite to `GroupSprite`

```
vehicle = pygame.sprite.GroupSingle(Vehicle(70,470))

```

since at the time, i thought that was the right way of doing it. However, i found that all the interaction always goes with the sprite directlly not with the `GroupSingle`. So I end with constantly accessing the sprite throug the `GroupSingle.sprite`:

```
vehicle.sprite.desired_speed_up_down

```

Is there a reason why i shouldn't just remove 'GroupSingle' and define:

```
vehicle = Vehicle(70,470)

```

# Answer
No. If you don't use any features of the `Group`, you can just stop using it.

---

However, nothing is stoping you from storing your player `Sprite` in a seperate field and using your `GroupSingle` for stuff like collision detection/drawing/updating if you maintain a list of `SpriteGroup`s for example to have your code look more uniformly:

```
# initialize
vehicle = Vehicle(70,470)

vehicle_group     = pygame.sprite.GroupSingle(vehicle) # make it clear there's only one vehicle (player) by using GroupSingle
wall_group        = pygame.sprite.Group(YourWallSpritesOrSomething)
other_stuff_group = pygame.sprite.Group(OtherStuffSprites)
all_groups        = (vehicle_group, wall_group, other_stuff_group)
...

# drawing eveything, including player, walls, and stuff...
for g in all_groups:
    g.draw(screen)
...

# updating eveything, including player, walls, and stuff...
for g in all_groups:
    g.update(...)

# test if 'somesprite' collides with anything, including player:
if any(spritecollideany(somesprite, g) for g in all_groups):
    do_stuff(somesprite)

# test if player (vehicle) hits a wall:
if spritecollideany(vehicle, wall_group):
    lose_game()

```

But if the `Sprite` in your `GroupSingle` never changes, a regular `Group` would also be fine, but a `GroupSingle` would nonetheless make the fact clearer that there's *always a single* vehicle.
> 1 votes

---
Tags: sprites, pygame
---


title: Blur offset artifacts

text:
# Question
Title: Blur offset artifacts
I have simple blur shader which I calculate offsets in:

Piece of vertex shader:

```
output.texCoord1 = input.tex + float2( texelSize * -4.0f, 0.0f );
output.texCoord12 = input.tex + float2( texelSize * -3.0f, 0.0f );
output.texCoord13 = input.tex + float2( texelSize * -2.0f, 0.0f );
output.texCoord14 = input.tex + float2( -texelSize, 0.0f );
output.texCoord15 = input.tex + float2( 0.0f, 0.0f );
output.texCoord16 = input.tex + float2( texelSize, 0.0f );
output.texCoord17 = input.tex + float2( texelSize *  2.0f, 0.0f );
output.texCoord18 = input.tex + float2( texelSize *  3.0f, 0.0f );
output.texCoord19 = input.tex + float2( texelSize *  4.0f, 0.0f );

```

However with this manner I have artifacts on the sides of the screen:

I know that it occurs because when the offset goes out from the right it takes pixels from the left appropriately.

So my question is: how is the "standard" way to deal with this? I was trying to saturate() all of the values assigned to output.texCoordX, it removes the artifacts in 95%, but it makes my blur much weaker and with strange sharper edges ("roll my log and I will roll yours"?).

# Answer
> 7 votes
Wouldn't setting your texture's edge mode to clamp (instead of repeat) solve this issue?

---
Tags: hlsl, blur
---


# Question
Title: DX11 application running on Windows XP using only DX9?
I'm developing an application that utilizes DX11. I know that DX11 is only available on Windows 7 (and Vista with SP). I wonder if there is some way to run the application on Windows XP and use only the old DX9? I need to prevent the loading of DX11 dlls when on Windows XP. How can this be done?

I've got an old renderer, that runs entirely on DX9 and a new renderer that uses DX11. My idea is to run the old renderer underr Windows XP and load only DX9 dlls, and to run the new renderer on Windows Vista / 7 and load DX11 stuff as well.

I've heard about a `LoadLibrary()` function that loads libraries at runtime. So far I have my Visual Studio project with all that DX11 .lib files in Additional Dependecies. How should I change this to load it completely at runtime? Do I need to define all symbols in DX11 .dlls manually?

# Answer
> 2 votes
If you use the `/delayload` linker switch, it is safe to link your application against DX11 .libs and run it under Windows XP, as long as you *do not* call any DX11 function at runtime. This is equivalent to using `LoadLibrary` and `GetProcAddress`, except that it is far more convenient: no need to go for the old-fashioned way.

This is for instance what the UDK is doing. Make sure that you check the OS version before you create your renderer, and only use the appropriate DirectX version afterwards.

Another common option is to use different executables, one for DX9, and another for DX11. This is way simpler to setup, but to stay user-friendly this requires a separate launcher that tests the OS version before running the right exe.

---
Tags: directx11, windows, directx9, dll
---


# Question
Title: How to create Elastic rope / Rubber band in box2d?
I am trying to create the rubber band type or elastic rope.

i ant to do something like bellow link. http://heyalda.com/smash-turtle/

Thanks,

# Answer
No one will write the code for you so I think you would be hard up getting an answer. Luckily for you I searched for a tutorial for creating rope with box2d and cocos2d on google and found this really good tutorial on making a cut the rope type game

http://www.raywenderlich.com/14793/how-to-make-a-game-like-cut-the-rope-part-1

EDIT: iPhone game "climbers" https://github.com/haqu/climbers

It isn't exactly what you want. However, I'm sure this is a lot better than what you have now :)

Enjoy
> 0 votes

---
Tags: box2d, cocos2d
---


# Question
Title: How to fill a rectangle with tilable texture in XNA?
So, question in the title. I don't know how to create infinite seamless background.

# Answer
Well, I solved this.

You can wrap your texture with SamplerState

```
        _spriteBatch.Begin(SpriteSortMode.Deferred, null, **SamplerState.LinearWrap**, null, null);
        _spriteBatch.Draw(texture,startPosition, new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, 0);
        _spriteBatch.End();

```

And you will draw a texture just once!

Thanks to David Gouveia
> 3 votes

# Answer
~~I don't think XNA supports such behavior directly (I might be wrong, though I'm pretty sure it's not the case).~~ **(EDIT: This can be done in XNA, see edwing's self-answer.)** You can do this manually however.

The idea is simple: see how many rectangles identically sized to the texture fit into your parent rectangle. Then, draw that many rectangles inside of your parent rectangle. Also check if there is unoccupied space left while drawing (if the parent rectangle could not be evenly divided into texture rectangles). Do the math and see what sizes the divided texture rectangles should be.

Here's a rough drawing to get a better idea on the whole matter:

Some pseudo-code to get you started:

```
CompleteTextureRectsOnHorizontal = ParentWidth div TextureWidth //Integer division
CompleteTextureRectsOnVertical = ParentHeight div TextureHeight //Represents the number of textures that completely fit into the parent rectangle, vertically. The above is the same but horizontally.
ExtraOnHorizontal = ParentWidth - (CompleteTextureRectsOnHorizontal * TextureWidth) //Represents how much space exists between the last texture that fitted perfectly and the rectangle's rightmost bound (if this is 0, then all textures fitted perfectly, horizontally - there's no need to draw half a texture and whatnot).
ExtraOnVertical = ParentHeight - (CompleteTextureRectsOnHeight * TextureHeight) //Same as above, but vertically.

```

You should proceed by doing something like:

```
spriteBatch.Draw(Texture, new Rect(location.x, location.y, TextureWidth, TextureHeight);

```

for complete texture rects. Then, for the textures that don't really fit it completely, you draw like this:

```
spriteBatch.Draw(Texture, new Rect(location.x, location.y, ExtraOnHorizontal, TextureHeight); //For textures that fit in vertically, but not horizontally.
spriteBatch.Draw(Texture, new Rect(location.x, location.y, TextureWidth, ExtraOnVertical); //For textures that fit in horizontally, but not vertically.
spriteBatch.Draw(Texture, new Rect(location.x, location.y, ExtraOnHorizontal, ExtraOnVertical); //For textures that don't fit either way. This is normally the texture in the lower right corner of the parent rectangle.

```

Remember to update the location of each newly drawn texture rect, relative to the previously drawn texture (adding the texture's width to the previously drawn texture's X coordinate gives you your new texture rect's X coordinate, for example).
> 2 votes

---
Tags: xna, tiles
---


# Question
Title: rpg 3d open world map & entity loading-streaming
Hello I'm a web developer and recently I started reading about game development. I followed some tutorials regarding c++ and openGL (whatever I could find online because as you know not many up to date openGL tutorials exist.)

I keep wondering in a case of a rpg game with a huge real world(map) and entities(enemies what so ever) how could it be implemented. Meaning you cant load a huge map and the entities all at once obviously... I was thinking of subdividing the map into blocks and each block to even smaller ones so that each block contains (5x5) 25 sub-blocks.

A map could be consisted of many blocks such as the following one which has 25 sub-blocks:

P = Players current sub-block O = sarounding sub-blocks X = sub-blocks not yet loaded

Entities will be loaded only for the players current sub-block. Keep in mind that P is not just the player is a mesh a piece of map not very big and not as small as the player is.

```
X X X X X
X O O O X
X O P O X
X O O O X
X X X X X

```

And I'm wondering is this a good approach? I suppose each sub-block has to be a different mesh apparently and then stitch them up together?

CASE 2:

What if I stored the map into 1 big height map or a set of height maps and generate the mesh from that. According to the player's position copy the required image height and width where player is always at the center of it and rearrange the data in the vbo?

I'm sorry if this is a silly question but I simply don't now how to approach this and I can't find any references.Also keep in mind that on such a map animations will also happen.

I would really appreciate it if someone could give some references or explain the architecture for a game such as this.

# Answer
Scott Bilas of Gas Powered Games wrote a good document about how they implemented a continuous world in dungeon siege.

Paper: The Continuous World of Dungeon Siege

Slides: The Continuous World of Dungeon Siege
> 5 votes

# Answer
Minecraft is a 3D game with a game world that is extremely large in size (practically infinite). Instead of 3D terrain derived from meshes, the terrain is represented by 3D Cubes. The world is procedurally generated and stored in small chunks, similar to what you described in your first potential solution.

While playing Minecraft, chunks near the player are rendered and updated (including any entities in these chunks), while chunks farther away from the player are saved to the disk and not in memory. While the player travels through the world, saved chunks near the player are loaded into memory from the disk and loaded chunks far from the player are saved to the disk and no longer used. When the player quits the game, all loaded chunks are saved to the disk.

Since individual chunks are relatively small, groups of them are saved to the disk as a single file, labeled "regions". In earlier versions of Minecraft, chunks were saved to the disk as individual files, which were loaded about seven times slower than the region files.

The technical section on the Minecraft wiki has some more information regarding Minecraft's chunks and regions.
> 8 votes

---
Tags: c++, opengl, maps, loading
---


# Question
Title: A good approach on working on player controller for movable platforms?
I have got my player controlling working out decent enough, except with mediocre animation controller for the player, but oh well. All I have done so far is basic input: move, run, jump, multi-jump. How would I approach making my player conform to the movement of the moving platform. I know to move the platform relative to my player on top of adding more force if player has moved. I have looked up some resources on line, but I am confused why they use certain methods.

```
def Platform ():
        //BROKEN
        if (activePlatform != null):
            newGlobalPlatformPoint = activePlatform.TransformPoint(activeLocalPlatformPoint)
            moveDistance = (newGlobalPlatformPoint - activeGlobalPlatformPoint)

            if (moveDistance != Vector3.zero):
                controller.Move(moveDistance)

            lastPlatformVelocity = (newGlobalPlatformPoint - activeGlobalPlatformPoint) / Time.deltaTime

        else:
            lastPlatformVelocity = Vector3.zero

        activePlatform = null

        if activePlatform != null:
            activeGlobalPlatformPoint = transform.position
            activeLocalPlatformPoint = activePlatform.InverseTransformPoint (transform.position)

```

I don't understand why it is important to get local and world positions. Also, I don't understand moveDistance calculation.

My first intuition was doing something like moveDistance.y or moveDistance.x and changing them depending on the hit object positive or negative velocity. Just getting some ideas.

I also use:

```
def OnControllerColliderHit (hit as ControllerColliderHit):
        if (hit.moveDirection.y < -0.9) & (hit.normal.y > 0.5):
            activePlatform = hit.collider.transform

```

to check which platform I have collided with and strictly focusing on the one below the player.

# Answer
> 1 votes
Well, one advantage of parenting your player to the moving platform versus applying constant force is that (at least with Unity) the former is easier to implement. When you want your player GameObejct to behave as if it's on some moving platform, just set its (the player GameObject's) parent to "platform" and then you're good to go. Obviously in this situation, you will always use the player local transforms to move him around.

==UPDATED as per comment==

Ok, don't worry, I've been frustrated by this as well before finally getting it. You need to familiarize yourself with some basic Unity notions:

* what does it mean when you're moving (translating) a GameObject via its global coordinates (which are the same for him and any other GameObject in the scene) vs. moving it via its local coordinates:

Make a Cube. Rotate it a little in all directions. Then make a script in which you make him move slowly in one direction. Switch that translation from local to global. Look at how it changes its movement, something like:

```
//this goes in the Update function of the script you attach to the cube:
    int x = x+10; //adjust the +10 if it moves too fast
    Vector3 translation = new Vector3(x,0,0);

    //comment out one of the above lines to see local vs global translation:
    transform.position += translation; //global translation on the world's x axis
    transform.localPosition += translation; //translation on the objects x axis (which, if you rotated it a little after creation, will not be the same as the world's x axis

```

Also check out the documentation for the Transform class here:

http://docs.unity3d.com/Documentation/ScriptReference/Transform.html

it explains pretty well what you can do with it and how it works.

* How do local and global translations get influenced by the fact that the cube has a parent which is also moving.

Create a large plane. Make the Cube the child of the plane, either by visually dragging it on to the plane in the inspector, or by adding the following code in the Cube's script's Start function:

```
public GameObject plane//drag the plane object here in the Inspector

//inside the Start function:
transform.parent = plane.transform;

```

Now hit play, and for each of the local and global movenents of the Cube, also move (by hand, in the viewport) the plane in various directions. Notice how the Cube global and local translations are influenced by this (or, as the case may be, are NOT at all influenced by this).

* Once you get this, make a simple controller for the cube. Something real basic, like in should translate the Cube forward on its (local) x-axis when you press "W". This should replace the +10 automatic translation we were doing in the original script. Re-do the above examples and see how that works.

Finally, one great newbie tutorial you should watch is Lynda's Unity Essentials, it helped me *A LOT* in understanding the basics of Unity. And it actually has dedicated chapters on how translations work and on how to make your own 1rst and 3rd person controllers.

---
Tags: unity, movement, boo
---


title: How to make a smooth movement in XNA?

text:
# Question
Title: How to make a smooth movement in XNA?
I'm trying to make a nice controls for my game, but I can't achieve enough SMOOTHNESS.

```
if (kbState.GetPressedKeys().Length != 0 && _direction != Vector2.Zero)
    {
        _direction.Normalize();
        _position += _direction * (_speed * (float)gameTime.ElapsedGameTime.TotalSeconds);
    }
    else
        _direction = Vector2.Zero;

    if (kbState.IsKeyDown(Keys.W))
    {
        _direction += new Vector2(0, -1f);
    }
    if (kbState.IsKeyDown(Keys.S))
    {
        _direction += new Vector2(0, 1);
    }

    if (kbState.IsKeyDown(Keys.D))
    {
        _direction += new Vector2(1, 0);
    }

    if (kbState.IsKeyDown(Keys.A))
    {
        _direction += new Vector2(-1, 0);
    }

```

There is the code. Could you help me a little and give an advice how to make character stop smoothly. I tried many options, but could'nt find any that fit.

# Answer
> 1 votes
Here is how I usually simulate friction:

```
    Vector2 Velocity;
    float Friction; // In pixels / second^2

    void ApplyFriction() {
        if (Velocity.X > 0) Velocity.X -= Friction;
        if (Velocity.X < 0) Velocity.X = 0;
    }

```

You then put the function at the end of your character's presumed Update() method.

If you want constant movement, you can set Friction to 0 until you want it enabled again (as in, when you want your character to stop). (y)

PROTIP: You can transform this in a Gravity function by turning the code into `Velocity.Y += GravitySpeed; if (Velocity.Y > TerminalVelocity) Velocity.Y = TerminalVelocity`!

# Answer
> 1 votes
You need velocity Assuming fixed time step:

```
if(noKeysPressed)
{
    _velocity =* 0.5f; //adjust ratio to your needs
}
else
{
    //change velocity how you want
}

_position += velocity; //modify position even if no key is pressed

```

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


title: center location on scanners sweep

text:
# Question
Title: center location on scanners sweep
I want to center location on a place where someone uses their scanners sweep. I know this is possible with the defilers ability dark swarm but i wonder if it is possible with scanner sweep from ComSat Station. There is a unit that is called scanner sweep so maybe it is possible. I tried it with many triggers but none of them seem to work.

Does anybody have an idea how a trigger that would move the location to the scan would look like?

It doesn't matter which player scans I just want the location to move with each scan.

# Answer
> 1 votes
Years ago, when I was making maps for Starcraft 1, I looked into trying to do this. However, I recall being unable to use triggers to explicitly center locations on Comsat scans back then, even with custom map editors.

Instead, I had to place pairs of invisible units for computer and neutral players along the map that shared vision with the player. Then whenever the player used a scan over them (which would reveal them to the player and the player's allies with shared vision), the invisible computer units would move toward the invisible nuetral units to attack them. I had placed 1x1 locations around the computer units, and used triggers that detected when the specific computer units exited their location.

Even though I could only use this method for important locations in the map, this was the best way I could come up for detecting where a player used comsat scans. There may be other implicit ways to detect when the player uses comsat scans.

---
Tags: modding, map-editor, starcraft
---


# Question
Title: What are different types of online game formats besides Flash?
I am currently looking into making a website that hosts various online games and would like to support as many formats as possible no matter how obscure. I was wondering if anybody could inform me on what these different formats(Flash, JavaScript, etc.) may be and possibly even provide me with some insight on how to embed them.

# Answer
> 3 votes
By far the majority of browser-based games are done in Flash. However the newer and growing in importance game format is HTML5 (ie. games programmed in JavaScript that use the new Canvas element).

I've also seen many games that are pretty much just static images and web forms for the UI and the server simply constructs different static HTML pages in response to the player clicking on the buttons.

Up until recently Unity used to be another format for browser games. However the latest version of Unity actually deploys Flash content, making Unity games a special case of Flash games.

The only other format I can think of that has any impact whatsoever in browser games in Java, because that's what Puzzle Pirates used (and even that I'm not 100% sure about). That is a single game that came out years ago, hardly worth worrying about.

# Answer
> 1 votes
There are many file formats that you can put online, like other than swf, there is java (which requires an application for webpage integration) and there are files that probably aren't official, like scratch and GameMaker. There is also Unity3d(http://unity3d.com/) However, if you'd like to go to the most basic format, I would say that is javascript, other file formats probably require download. But as I said, there are many other game engines for online integration.

But then again, Java is insecure, as we already know safari has blocked Java 7.

Good luck on your new site!

# Answer
> 0 votes
Plug-in based:

Others:

Plug-in based technologies are easy to embed. Usually, a game will be packaged in a single file that will be served through HTML via a simple `<embed>` tag. That's the bright side, the dark side is that they're non-standard and thus aren't supported directly by browser vendors, and might require an extra download from your users.

That was the easy part, but plug-in based games are only one side the ecosystem. If you really want to support the widest possible spectrum you'll have to consider other things. HTML5-based solutions are hot today, they are standard, and they can prove worthwhile. But they will be much harder to embed, typically requiring some `iframe` or other hackery. See for instance how Kongregate is now hosting HTML5 games.

Google Native Client might just be the modern ActiveX but it is used in some very interesting browser-based games in the Chrome Web Store.

Last but not least, lots of good games are not very advanced on the client-side, and will do most of the interesting stuff from a PHP/MySQL server (typically). So you might have to consider an offer for server-side hosting (something that is definitely compatible with lots of client-side technologies).

# Answer
> -5 votes
**Edit:** don't support Java. The web applets it provides are completely insecure and probably never will be good enough. There's a reason why it practically doesn't exist on the Internet anymore. I also suggest you disable Java (**not** JavaScript) in your browser too.

You're not interested in file formats. There are many types of those, and usually it's just text or some other binary format you shouldn't concern yourself over. You're interested in technology.

It's not up to your servers to support HTML5, JavaScript, or Flash. You simply need to send the file over the network, and make sure your website conforms to W3C standards.

The client's browser has to support various technologies.

Unless, of course, you're talking merely about *online* games, not necessarily on the WWW. For that, there are various combinations, and that makes this question too ambiguous.

---
Tags: file-format, online
---