# Question
Title: How can I architect my game tools to allow for easy extension?
In the code for the toolkit for my game, I have a concept I've been calling "contexts."

Each context refers to, essentially, different tools (`SelectionContext`, `DrawTerrainContext`, et cetera) and contains contain "actions" which are added/removed from the undo history.

Some pseudo-code:

```
public abstract class Context
{
    public abstract void Initialize();
    public abstract void Destroy();
    public virtual void Update();
}

public interface IAction
{
    void Execute();
    void Undo();
}

public class SelectionContext : Context
{
    public override void Initialiize() { ... }
    public override void Destroy() { /... }
    public override void Update() {
        if(mouseDown && noSelection)
            startSelection();
        else if(mouseDown && !noSelection)
            expandSelection();
        else if(!mouseDown && !noSelection)
            finishSelection();
    }

    private class SelectionAction : IAction
    {
        private List<object> _oldSelection;
        private List<object> _newSelection;

        public SelectionAction() { ... }
        public void Execute() { ... }
        public void Undo() { ... }
    }
}

```

The above context may define things like a `RectangleSelectionAction`, `EllipticalSelectionAction`, et cetera.

Stacking them like this allows me to do things like select a section of terrain then go to a different context to change textures (or what have you), then return to the selection.

While this is an improvement over putting almost everything in one file it still seems a little strange to me having to define small private classes in each context for each of their major actions.

Is there a standard (or better) way of abstracting out different tools from the main toolkit program to allow for easier development of future tools?

# Answer
> 2 votes
Yes, the standard approach is to have some kind of plugin API.

The details of this approach will vary based mainly on the implementation of your overall toolset and the needs of your game and its tools. What you've described here is a reasonable first start at a plugin system for your own tools.

It sounds like it works for you, so you should keep exploring it. Don't resist the design simply because it involves "small classes," because that's not always a bad thing (if a class encapsulates all the data and behavior it needs to perform its designated function, it's probably acceptable).

It also sounds like all your "context" plugins are still resident in the main assembly of your tools. That's fine, as it is straightforward and easy to work with.

In the long run, if you find yourself in a scenario where other developers or users would want to extend your tools with new contexts (but don't/shouldn't have access to the main toolchain code) you can take your plugin API to the next step, which is loading the code from external assemblies.

To do this, you'd extract the bits of your tools that define the context API (`IAction`, the `Context` base class, and whatever else you may have) into a class library that's compiled in a DLL that others can reference. They'd create a class library themselves, with a reference to your plugin API DLL, and implement their new contexts.

They would then place their compiled plug-in DLL in a location you specify, such as a `Plugins` directory next to your application.

Your application then loads, at startup or some other appropriate time, every DLL found in that directory, attempts to find any subclasses of `Context`, creates them (`Activator.CreateInstance` is a simple, though not entirely crazy-efficient, way to do so), and then uses them as normal.

You may find in this scenario that you need to provide addition extensibility hooks to the context API, such as an "initialize" and "shutdown" entry point you can all to allow the context to do some setup work.

But basically you've stumbled on the general principle, just chosen slightly non-standard names for some of your interfaces, but that's fine. It works for you and isn't a horrible broken mess, so you're on the right track.

---
Tags: architecture, tools, editors
---


title: The Decline of 3D Platformers

text:
# Question
Title: The Decline of 3D Platformers
What contributed to the decline of sales of 3D platformers over the past decade? (Other than Microsoft's acquisition of Rareware.) Would it be a mistake for a developer other than Nintendo (or indie developer) to start working on one in 2011?

# Answer
> 7 votes
I think there's a few reasons behind 3d platformers declining in popularity, and thus, declining in sales (and since sales is the defining metric for what types of games are made, you can draw your conclusions from that).

First, Jeff's comment about people simply not comprehending 3d too well on a 2d screen. Now, you could argue that FPS games are 3d on 2d screens, and they've been around for ages. But the key factor there is the camera position. People can translate a first person view better than over the shoulder camera. Now, there's open world games (GTA/Just Cause, etc) that use an over the shoulder camera, and they're still around. But how many times do you need to do precision platforming in those games? Rarely, if ever.

So, the camera is a problem, especially combined with precision platforming that is the stable of most platformer games in general. Which brings up the question of controls. You need good, solid controls, otherwise your game will be considered hard, or frustrating, or just plain bad. This is a problem with any game, but it's definitely true of platformers.

Finally, all those games mentioned in your original question likely were too much. Specifically, I'm talking about Donkey Kong 64. It's a game with too many bad worlds and too many characters who have little to no variety in control or theme. Overall, it's a chore to get through and there's very few 'good' parts. For the same reason adventure games died because of terrible puzzle design, 3d platformers died because they were all collectathons.

Now, all of that said, they're not *completely* dead (Mario Galaxy has sections of 'true 3d'). But creating a good 3d platformer is hard, and the asset creation time would be better spent on creating a more popular game type (like an FPS, at the moment). 2d platformers (even 2.5d like Shadow Complex) are still cheaper to make, and it's too much of a risk to make a full sized 3d platformer at the moment.

# Answer
> 2 votes
Profit. It always comes back to the money.

You make a game sell it for the asking price and start again. this cycle has been broken in the last decade. as consoled have moved online it has offered the opportunity to sell expansions to games in the same way pc games have done for years.

think how long a 3d platformer takes to make and then think how long it takes to make an update for it and how limited the update will be. now consider an fps like cod, they can knock out a half dozen maps in a few weeks and sell them for a few quid to millions all over the world. I don't have numerical proof but I would be willing to bet they have made almost as much on the map packs as they have the game itself if you account for production time.

3D platformers do not lend themselves well to this production model, yes it is possible but not nearly as profitable.

Edit: to your other question there is no reason an indie developer should not make a 3d platformer it just is not the most profitable way of working. having said that as there are so few 3d platformers if you make a good one it may succeed through lack of competition.

# Answer
> -1 votes
I guess not, there are some 3d platformers being developed right now, eg. `bionic commando rearmed 2`, is going to be released feb2011 exclusive on ps3/xbox360. or there was another 3D platformer named `shadow complex` released at 2009 for xbox.

# Answer
> -1 votes
A few things come to mind for me:

1. Recent global economic problems -- people buy less when they don't have money, and in recent years this factor seems to have especially effected many industries that provide "want" products rather than "need" products (it's important to note, however, that a few vendors have been very successful at creating a perceived "need" factor for their products such as Apple with their iPhone, which serves to skew this even further).
2. Lack of variation -- to many people, 3D games are all essentially the same, just with different wepaons/tools and scenery, with the occasional different rule. So you buy a new 3D game, is it really as exciting as it used to be after playing dozens of other 3D games over the past few years?
3. MMORPG addiction -- a lot of people got addicted to some very popular games like World of Warcraft, and spent most of their time on these games instead of purchasing and exploring new titles. When users find a game they really like, they tend to dedicate a lot more time to it, and as long as they continue to be entertained there is far less motive to look elsewhere for new gaming experiences.

# Answer
> -1 votes
Big games require big bucks. Many video game companies get their loans from big banks which give money to only what they think will be sucessful thus are less likely to invest into new niches or genres they are very unsure about. Small companies have the love and heart into it so they are not as afraid as the big bankers which only see dollars in their eyes.

RareWare Inc was such a company but overdid it on DK64 making a large over world but not enough content in them which turned a lot of users away who were not hardcore about it. DK64 DID have a lot of replayable features that you unlocked for multiplayer and you always wondered what the next big feature would be thus making you want to continue the adventure.

Such as getting the film for the camera where you had to take pictures in the game with great accuracy to capture faries and bring them back to the Fairy Goddess or something like that which you are granted extra features for multiplayer which expanded the game big time. Once you got multiplayer unlocked DK64 was a blast in the shooting levels.

Banjo Tooie also had features to be unlocked with shooting levels and I am sure other platformers too.

I wish these kinds of games where you unlock content to make levels replayable and adds multipalyer abilities come again instead of levels being completed one time and that's all you've got.

Like modding for PC games allowing multiplayer features to be unlocked is as close as you can get on a console.

---
Tags: platformer
---


title: A* pathfinding question

text:
# Question
Title: A* pathfinding question
I'm trying to get a grasp on the A\* pathfinding algorithm. Using the image I attached.

If the green square represents the start, and red represents the end. wouldn't the algorithm bring me up towards the top of the grid, and then circle me back around, because of the wall?

It would seem the algorithm would never start by moving downward first because the F cost would initially appear more expensive?

Is this a problem with the basic manhattan heuristic? Or am I just missing something?

# Answer
> 1 votes
A\* keeps a list of visited cells and a frontier. It will first explore the top of grid as you say but once all the possibilities there are explored, the A\* will begin to go downwards. Think of it as a greedy breadth first search. See http://www.redblobgames.com/pathfinding/a-star/introduction.html.

---
Tags: path-finding
---


# Question
Title: model view projection multiplication order
I'm debugging a lighting problem where the camera position is effecting the diffused lighting component on my 3d model. In researching my problem I went back and am reading over all the how to documents. I found that one of my old sources (where I learned open gl 2.0) said this (summarized):

> When creating the modelViewProjection matrix you can't change the order or you'll get unexpected results. First take the View Matrix and post-multiply it by the projection matrix to create a viewProjection matrix. Then post-multiply the model matrix to get the modelViewProjection matrix.

Looking at my code, all this time I haven't been doing this:

```
matrixMultiply(mView, thisItem->objModel, mModelView);
matrixMultiply(mProjection, mModelView, mModelViewProjection);

```

As a test I tried changing it to this:

```
matrixMultiply(mView, thisItem->objModel, mModelView);
matrixMultiply(mProjection, mView, mViewProjection);
matrixMultiply(mViewProjection, thisItem->objModel, mModelViewProjection);

```

...but the result appears the same.

EDIT: To answer a question about what the matrices contain. A snapshot of the matrix values:

EDIT2: As a test I did the math both ways to compare the results and even with moving the camera and model around and rotating the model I'm getting the same results for the final ModelViewProjection.

# Answer
> 3 votes
It depends on the implementation of the multiply operation. The internals will suppose an ordering within your matrices, row major or column major. If the ordering of your matrices is arranged the way the function expects them, then it is up to the second dpendancy: namely the respect of the correct mathematical commutativity. (which they should)

When you have these 2 conditions, then your multiplication order is the reverse of the pipeline. Therefore you do `totalmat = proj * view * model`.

If ever your matrices were to be transposed, you need to reverse this application order. Whenever one component of what I mentioned before is opposed, it commutes the multiplication.

---
Tags: opengl, 3d, ios, opengl-es2, lighting
---


# Question
Title: Sending Client Input to Server (which way?)
I am trying to get networking working for my game, I've read several sources of information about this subject but one thing is still unclear for me.

The way I process client input is by executing a command bound to that input, for example:

Player presses D -\> MoveLeftCommand gets executed which applies a linear impulse to the body of the player.

Since the server codebase and client codebase are almost the same I just reference the commands by bytes, MoveLeftCommand is for example byte 1.

What I have now is when the player presses D it sends the byte of the MoveLeftCommand to the server and the server executes this on the specified entity. I don't believe this is right though since the client will have to send 60 packets per second to the server just to move. It is no problem just send a JumpCommand, this command will get executed once. But I think there is another way to send position.

My question is: what is the common way to send input from a client to a server? I have read about 'sanity checks' on servers but I don't now what is meant by that. Should I do something with client time?

Thanks in advance!

# Answer
> 4 votes
Instead of sending a packet whenever the key is held down, send a packet whenever the key state changes from pressed to released and vice versa. To account for network delays you can implement some kind of extrapolation on the server side and client side utilizing the time the packet was sent and received. For this of course you have to send the time the packet was sent in the packet data.

---
Tags: 2d, networking, multiplayer
---


# Question
Title: How can I draw a line of certain length and direction?
I want to create a line of certain length and direction.

What I mean by this is drawing a line from Point A to Point B. Normally in Unity C# to draw a line from Point A to Point B is simply:

```
Debug.DrawLine(point_A, point_B);

```

The diagram would be something like this

```
A----------------B

```

But I dont want something like this, I want it to draw from Point A to Point B but with a certain length. So I am guessing I need the direction for this to work. But I don't know how to code it.

Here is a basic diagram of how i want it.

```
A--------        B

```

# Answer
> 10 votes
You can simply get the vector pointing in the right direction, then scale it by the distance you want and add that to the initial point. This will define a new end point for your line.

```
//Get the direction of the line
Vector3 direction = point_B - point_A;
//Get a new point at your distance from point A
Vector3 point_C = point_A + (direction.normalized * distance);
//Draw the line
Debug.DrawLine(point_A, point_C);

```

# Answer
> 2 votes
If you know the start and end points as well as the desired length, you can use `Vector3.Lerp`

```
Vector3 midPoint = Vector3.Lerp(startVector, endVector, 0.5f);

Debug.DrawLine(startVector, midPoint);

```

---
Tags: c#, unity, vector, direction
---


title: 2D HLSL World position

text:
# Question
Title: 2D HLSL World position
I'm trying to get world position from my vertex shader to my pixel shader so that I can disable the shader once a preset X coordinate has been passed (no shading once I'm over X).

Getting the screen position is not a problem so far but despite my best efforts to look after it and implement examples the calculations just don't return the preferred world positions I'm looking for.
Update: So got it to somewhat work, after compiling the shaders the output changes to such:

Could anyone explain why this happens?

I should mention that I'm really new to HLSL, been only scripting so far.
Edit:Added matrices.

```
world = Matrix.Identity;
view = Matrix.CreateScale(new Vector3(1, 0.75f, 0)) * Matrix.CreateTranslation(-playerpos.X, -playerpos.Y, 1);
projection = Matrix.CreateOrthographicOffCenter(0, view.Width, view.Height, 0, 0, 1);
Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
projection = halfPixelOffset * projection; <\code>

    texture lightMask;
    sampler mainSampler : register(s0);
    sampler lightSampler = sampler_state{Texture = lightMask;};
    float4x4 World;
    float4x4 View;
    float4x4 Projection;

    struct vs2ps
{
    float4 Pos : POSITION0;
    float4 TexCd : TEXCOORD0;
    float3 PosW : TEXCOORD1;
};

vs2ps VS(float4 Pos : POSITION0,float4 TexCd : TEXCOORD0)
{
    vs2ps Out;
    Out.Pos = mul(Pos, World*View*Projection);
    Out.TexCd = TexCd;
    Out.PosW = mul(Pos, World);
    return Out;
    }

float4 PixelShaderFunction(vs2ps input) : COLOR0
{   float2 texCoord = input.TexCd;
    float4 screenPosition = (input.PosW,1.0f);
    float4 lightColor = tex2D(lightSampler, texCoord);
    float4 mainColor = tex2D(mainSampler, texCoord);
    if(screenPosition.x < 3500)
    {
         return (mainColor * lightColor);
    }
         else return mainColor;
}

```

# Answer
> 0 votes
Okay so, finally achieved my goal.

```
view = Matrix.CreateScale(new Vector3(1, 0.75f, 1)) * Matrix.CreateTranslation(-playerpos.X, -playerpos.Y, 1);
world = Matrix.Invert(view);
projection = Matrix.CreateOrthographicOffCenter(0, view.Width, view.Height, 0, -1, 1);
Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
projection = halfPixelOffset * projection;

texture lightMask;
sampler mainSampler : register(s0);
sampler lightSampler = sampler_state{Texture = lightMask;};
float4x4 World;
float4x4 View;
float4x4 Projection;

struct vs2ps
{
    float4 Pos : POSITION0;
    float4 TexCd : TEXCOORD0;
    float3 PosW : TEXCOORD1;
};

vs2ps VS(float4 Pos : POSITION0,float4 TexCd : TEXCOORD0)
{
    vs2ps Out;
float4 worldPosition = mul(Pos, World);
float4 viewPosition = mul(worldPosition, View);
    Out.Pos = mul(viewPosition, Projection);
    Out.TexCd = TexCd;
    Out.PosW = mul(Pos,World);
    return Out;
    }

float4 PixelShaderFunction(vs2ps input) : COLOR0
{   float2 texCoord = input.TexCd;
    float2 screenPosition = input.PosW;
    float4 lightColor = tex2D(lightSampler, texCoord);
    float4 mainColor = tex2D(mainSampler, texCoord);
    if(screenPosition.x < 3500)
    {
         return (mainColor * lightColor);
    }
         else return mainColor;
}

```

Like this the visual output doesn't change and I get the correct coordinates back.

Thanks to those who tried helping tho, they actually set me on the right path.

I'll leave this here for future reference in case anyone's struggling with the same.

# Answer
> 1 votes
World position is vertex position multiplied by world matrix, not view matrix. So it should be like this in the vertex shader:

```
output.WorldPos = mul(input.Pos,World);

```

Unless you want View position to work with. I haven't checked the code for bugs if you want to use that.

# Answer
> 0 votes
This question already has been answered. See the second link here:

https://stackoverflow.com/questions/12794428/calculating-world-space-coordinates-in-the-pixel-shader

---
Tags: shaders, xna-4.0, hlsl, matrix
---


title: How To Create A Sandbox Video Game

text:
# Question
Title: How To Create A Sandbox Video Game
I have a lot of experience with programming but I'm new in game development world, so I don't know what I don't know.

I want to create a MMORPG sandbox game. When I say sandbox game I have something in mind like Minecraft where you can make changes in the game world and they persist and all the players on the server can see them. Like if you plant a tree it will stay there even if you log out or if you dig the hole in the ground it will be there when you log out and other players would be able to see it.

For now I'm thinking about Unity as a game engine for this game. I also did some research and found some tutorials about RPG game creation. But I haven't found any information about how to create sandbox game. To be more precise about how to create editable world and how to save changes which were made to the initial game world.

Can you point me in the right direction? What should I search for? What would you suggest me to read so I would understand more about the things I'm getting in.

# Answer
> 1 votes
Just save the changes as the user plays? Am I missing something here?

Either instantly (faster as you aren't saving the whole game at once, but the data adds up) or just regularly enough that you only lose a couple of minutes worth of data at a time (slower, as you have to save the entire game regularly, but uses less space)

Or best-case, combine both - save the server state every few minutes, but log the user actions n the meantime so you can "rebuild" the state. Each time you save, clear the log.

---
Tags: unity, architecture, world-design
---


# Question
Title: Controlled rotation on 3D object with mouse movement
I've a scene with a cube that I can rotate around yaw, pitch and roll. I do this by click the circles and drag the mouse on x/y-axis. I want similar functionality as the Unity rotation tool in editor mode.

My problem is that I can't figure out how to transform the mouse movement so the rotation doesn't become reversed if the cube is rotated 180 degrees in some axis. And how to use correct mouse direction depending on how the cube is rotated.

An image of the cube:

Here I get the mouse input

```
var direction = InputHandler.GetMouseDirection();
Vector3 diff = new Vector3(direction.X, direction.Y, 0);

if (selectedIntersect == Intersect.Yaw) //green
    block.Rotate2(diff.X, 0, 0);

else if (selectedIntersect == Intersect.Pitch) //blue
    block.Rotate2(0, 0, diff.Y);

else if (selectedIntersect == Intersect.Roll) //red
    block.Rotate2(0, diff.Y, 0);

```

Here I rotate the cube:

```
public void Rotate2(float yaw, float pitch, float roll)
{
    Quaternion yawrotation = Quaternion.CreateFromAxisAngle(
        Vector3.Normalize(this.WorldRotation.Up), MathHelper.ToRadians(yaw));
    Quaternion pitchrotation = Quaternion.CreateFromAxisAngle(
        Vector3.Normalize(this.WorldRotation.Right), MathHelper.ToRadians(pitch));
    Quaternion rollrotation = Quaternion.CreateFromAxisAngle(
        Vector3.Normalize(this.WorldRotation.Forward), MathHelper.ToRadians(roll));

    Quaternion.Concatenate(ref orientation, ref yawrotation, out orientation);
    Quaternion.Concatenate(ref orientation, ref pitchrotation, out orientation);
    Quaternion.Concatenate(ref orientation, ref rollrotation, out orientation);
}

```

# Answer
I study how Unity editor handles rotation with mouse movements. You can rotate by directly clicking on the object, but I didn't look too deeply to that rotation since it doesn't answer your question.

You can hold the circular handles to rotate on only one local axis.

It proceeds like this:

1. It creates a line from the projection of the point clicked on the handle (your mouse), and the projection of the center of the object (the pink dot)
When moving perpendicularly to that line, it rotates the object. Here, cyan is positive and red negative because...
2. The positive direction of the axis (here, we are rotating around Z axis) is pointing left depending of the projection of the center of the object (the pink dot).
When pointing right, the positive direction is up/right depending of the line angle, else positive is at down/left of the line.

You can easily get the direction of the axis by measuring the angle of it, which you can get by removing its Euler angles from the Euler angles of the camera.
*This only works when you have the Y axis of the camera **pointing up**.*

Another approach would be to use rays and planes (They are both your best friends !) and apply the delta rotation each time the mouse moves. This way, there's no ambiguity.
> 1 votes

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


# Question
Title: How can I disable mipmapping on textures loaded from .X files?
I'm trying to render a plane mesh textured with a simple grid pattern. The problem is that XNA keeps mip-mapping the texture in horrible, horrible ways.

What I'm trying to achieve is to get this grid to look as close to vector graphics as possible (so anisotropic filtering is out of the question, I must use point filtering):

```
SamplerState ss = new SamplerState();
ss.Filter = TextureFilter.Point;
ss.MaxMipLevel = 0;
ss.AddressU = TextureAddressMode.Wrap;
ss.AddressV = TextureAddressMode.Wrap;
GraphicsDevice.SamplerStates[0] = ss;

```

I'm loading the mesh, and it's textures, from an `.x` file so I don't have control over the specifics of the texture loads. Can I disable mip-mapping for the whole rendering process?

# Answer
> 1 votes
If you're using the default content importer, there's no way to control the mipmap generation behavior of the textures.

The `.x` file format doesn't really provide a template that allows control over mipmapping of textures, and XNA's importer assumes you'll want mipmaps for all the referenced textures.

Your two best options are likely:

* Build a custom importer to parse the `.x` file and generate the textures *without* mipmaps.
* Ignore or discard the textures loaded by the content importer for the `.x` file, loading manual copies yourself, in which you disable mipmapping.
* Set the `MipMapLevelOfDetailBias` property of your sampler state to a sufficiently-negative number to ensure mipmap level 0 is always used (in later shader models you could use `SampleLevel` to explicitly specify that mipmap 0 should be sampled, but I don't think XNA supports a new-enough model for this).

The last option is probably the easiest, but also wastes all the memory of the extra mip levels which you'll never sample.

---
Tags: xna
---


# Question
Title: Firing bullets with a time interval between them
How can I make my enemies shoot bullets in intervals?

I already have the enemy shooting bullets, however my problem is that it shoots the next bullet instantly, making it look like a line instead of bullets with gaps between them.

I tried to use `gluttimerfunc` but it didn't work since it just delayed the trigger of the bullet but once the trigger (bool statement) was set to true, it would shoot the max bullets on screen instantly.

# Answer
> 1 votes
You need to store some c (c++) properties for the enemy to support this. You have to ask yourself:

> Do you want each enemy to shoot in sync? Or off sync?
>
> Do you want shooting to be at a set interval or the timing to be somewhat random?
>
> Do you want each enemy to have shooting triggered by some other event so that shooting can be turned on or off? To give the enemies the appearance of intelligence?

If you want them to shoot in sync you can have a single struct for the timing with members like this:

```
typedef struct _FireRate {
    float rate;
    CFTimeInterval lastFire;
    int state;
} FireRate;

```

Then preset your fire rate somewhere in initialization. In your game loop when updating things do something like this:

```
fireNow = 0;
if (fireNow.lastBlink+ fireNow.rate < timeThisRound) {
    fireNow.state = 1;
    fireNow.lastBlink = timeThisRound;
    // if you want the shooting to appear random
    fireNow.rate = rateMinimum + RANDOM_0_TO_1() * rateVariance;
}

```

Then when deciding to fire a shot or not just check if fireNow.state==1.

If you want each individual enemy to have it's own way of doing things add some shooting properties to it. Surely you have properties somewhere for the enemies like where it is on the screen? I would create a big struct with lots of properties for the enemies like position, rotation, and if it's moving and what direction. And for shooting add to that a shooting trigger and something that hold the last time it fired a shot and how long until the next shot is fired. If you want the shooting frequency to appear somewhat random change the rate each time the shot is fired.

It's amazing how REAL your game will appear once you treat enemies like particles that can shoot bullets which are also treated like particles, and give them each their own properties and triggers for actions.

I'm going to add this: **Make it an engine.** Since you're in c you can also have a fireRate struct inside you're enemy struct. And you can stick the fire rate update in a method where you pass a pointer to the fire rate property of each enemy. Then when you loop through enemies do `updateFireRate(&enemy[x].fireNow)`. In the method you'll use `->` instead of the `.` dot to access members. After calling the update check enemy\[x\].fireNow.state to decide if it's time to fire or not.

---
Tags: c++, glut, timing
---


title: Delta time not accurate enough

text:
# Question
Title: Delta time not accurate enough
In my game i have a delta timer based almost exactly on the page from here

http://wiki.lwjgl.org/index.php?title=LWJGL\_Basics\_4\_%28Timing%29

But if the the main loop is fast enough, my delta time variable is 0. This causes problems because it often happens several times in a row. I don't want to force a frame cap either. How can I remedy this?

EDIT: Setting a frame cap works, it only happens when the frame isn't capped. I've set delta to a minimum of 1, but that doesn't make it smooth. I could add a delay of one if it's zero, but that only fixes it for the next frame.

# Answer
Check out this blog entry on fixing your timestep. Essentially the advice here is to use a loop where you draw as much as you can until a fixed threshold of time has passed, then update.

Here is the recommended game loop;

```
double t = 0.0;
double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

State previous;
State current;

while ( !quit )
{
    double newTime = time();
    double frameTime = newTime - currentTime;
    if ( frameTime > 0.25 )
        frameTime = 0.25;
    currentTime = newTime;

    accumulator += frameTime;

    while ( accumulator >= dt )
    {
        previousState = currentState;
        integrate( currentState, t, dt );
        t += dt;
        accumulator -= dt;
    }

    const double alpha = accumulator / dt;

    State state = currentState * alpha +
        previousState * ( 1.0 - alpha );

    render( state );
}

```

From a high level point of view, what is happening is that the loop is interpolating between the last state and the current state and then drawing as much as it can. Each pass accumulates more elapsed time. When this accumulated time is over the 0.01 threshold the system does a full state update.

So if a frame takes less than 0.01s to draw, we can expect \>1 frame to be drawn for each update.

If, however, the last frame lagged and accumulated more than twice the dt then it will do 2 updates or more before the next draw. So when the system lags it will drop frames before it drops updates.

So this loop will, in essence, update essentially every 0.01s, but will draw as much as is possible.
> 2 votes

---
Tags: java, lwjgl, game-loop
---


# Question
Title: How can I implement the ability to 'cut' sprites into arbitrary shapes?
I want to create a game where you have scissors that cut a sprite in a shape that you create by dragging your finger on the screen.

My problem is that I can't figure out how can I cut my sprite in the specific shape that the user creates with their finger.

So far the only solution that I found searching the web is that I'll need to create my own shader that lets me make a specific part of a texture transparent, but don't understand how I can apply that to my scenario?

# Answer
> 0 votes
One way to do this is with mask textures.

When you cut a sprite A, you will divide it into two new sprites (B and C). You can create masks based on where the user dragged to create the cut, and use those masks to represent the transparent portions of the new sprites (the parts that were "cut away").

Say the user traces the following pattern:

You can use a flood-fill algorithm starting at a fixed point (say, the bottom-left) to identify a entire region of the cut:

And then you can invert that image to find the region representing the other side of the cut:

Now you have two mask textures (the last two images).

You can destroy your original sprite and create two new ones. Both use the same base texture, but they also have a mask texture assigned. In the shader, you sample the base texture for the red, green and blue components of the output but you sample the mask texture for the alpha value (in the above examples, you'd use the red component of the mask texture as the final alpha component, and you wouldn't actually want the background of the mask to be grey - I did that only to make it distinct from the site's background).

As you continue to cut a sprite again and again, you should combine the new masks with the old.

This will provide you with a basic implementation. It's relatively simple to implement, and has the advantage of allowing fairly arbitrary cuts in your sprites. However, it's disadvantage is that it requires a lot of per-pixel operations on texture data (flood fills and inverts), which can become a bottleneck as the number of cuttable sprites increases. You can alleviate the problem by using lower resolution textures for the masks, to some degree.

---
Tags: sprites
---


# Question
Title: 2D Collision Resolution getting stuck on walls
I've been writing this collision detection system using a tutorial from an article I read and I just cannot for the life of me get it to function 100% correctly. Here's the code for starters:

```
BoundingBox aBox;
aBox.Convert(a);
BoundingBox bBox;
bBox.Convert(b);

Vector2 aMin = aBox.GetTopLeft();
Vector2 aMax = aBox.GetBotRight();
Vector2 bMin = bBox.GetTopLeft();
Vector2 bMax = bBox.GetBotRight();

Vector2 minDistance;

float left = (bMin.x - aMax.x);
float right = (bMax.x - aMin.x);
float top = (bMin.y - aMax.y);
float bottom = (bMax.y - aMin.y);

// Check for intersection internally
if (left > 0 || right < 0) return;
if (top > 0 || bottom < 0) return;

// Find the minDistance
if (abs(left) < right)
    minDistance.x = left;
else
    minDistance.x = right;

if (abs(top) < bottom)
    minDistance.y = top;
else
    minDistance.y = bottom;

// Null axis with biggest value
if (abs(minDistance.x) < abs(minDistance.y))
    minDistance.y = 0;
else
    minDistance.x = 0;

```

The problem right now is that the character is fine walking and hugging the top of a block and the bottom of a block, but once he has to walk UP two blocks, he gets stuck in between them. Coincidentally, walking down works perfectly fine. Just wondering if anyone has a solution to this problem, it would be much appreciated!

Here's a gif to better display the problem:

# Answer
I think what is happening is this:

```
+---+
| A |
+---+
| B |P (player)
+---+
(A, B are wall "blocks")

```

When the player is attempting to walk to the top-left, and run the collision resolution with blocks A then B, this is what happens:

```
+\--+
| A |  ----- "A: You're hitting me from below! Go left!"
+--\+
    \P

 \
  \
+--\+
| B \P ----- "B: You're hitting me from the right! Go up!"
+---+

```

But since you deal with `A` first, you "listen to" it (go left), and by the time you get to `B` and attempt to move left, you get stopped dead.

Notice that if you had done this in the reverse order (`B` then `A`) it would have worked, which explains why this bug appears only if you're moving up and not down.

### Solution

I think there may be many ways to solve this, but one simple method is this:

* Run collision detection (not resolution) using the original motion vector, on all obstacles in the vicinity (e.g. moving top-left, A says "no", B says "no")
* Since we're moving top-left, try moving top-only and left-only, again running full collision detection:
    + Top: A says "yes", B says "yes"
    + Left: A says "yes", B says "no"

Since moving to the top works, we'll do that.

Note also that this is a method that **only works when everything is AABB** \- all your walls are horizontal/vertical and so on. In the general case, such as when you have diagonal walls, you will need to work out which way the walls go, in order to "slide along" them.
> 1 votes

---
Tags: c++, collision-resolution
---


# Question
Title: How can I compute a "steepness" value for height map cells?
Here's a question related to height map generation. From a 2D height map I want to produce a second map, I guess you can call it sort of a derivative map, which shows the "steepness" of all the discrete values of the map. I plan to use it to quickly determine what kinds of objects can be placed on different locations.

In practice you would have many areas where rise/run is a fractional value, since many places do not have 45 degree angle slopes. But running through the pixels of the height map in any direction, the value differences are all integer values.

So what I planned to do in order to represent smooth slopes of varying degrees is, iterate through the pixels row by row, and find the lengths of all the distances where height does not change, and for every change in height, divide that by the length of the distance. Do the same thing column by column and then average the two results for each pixel. I do have to wonder how accurate this is in situations where a lower elevation is surrounded by two walls/plateaus since the rise/run is technically infinity, as it represents a completely vertical climb.

Is this a reasonable way for calculating steepness? I haven't found any resources on how to produce a 2D array of steepness values from height maps, just things on topographic (real-life maps) with the basic rise/run formula.

# Answer
> 7 votes
You almost have the right idea, but actually it is much simpler than you might think. The simplest way of measuring steepness is by finite differencing:

```
float GetSteepness(float[,] heightmap, int x, int y)
{
   float height = heightmap[x, y];

   // Compute the differentials by stepping over 1 in both directions.
   // TODO: Ensure these are inside the heightmap before sampling.
   float dx = heightmap[x + 1, y] - height;
   float dy = heightmap[x, y + 1] - height;

   // The "steepness" is the magnitude of the gradient vector
   // For a faster but not as accurate computation, you can just use abs(dx) + abs(dy)
   return sqrt(dx * dx + dy * dy);
}

```

This is sometimes called the "Sobel Filter." There are more complicated ways of doing it (such as a difference of gaussians filter), but finite differencing should give you a pretty good result! You will get some issues with aliasing when the height is changing very rapidly (such as at walls). You will also get issues when the resolution is too low for finite differencing to return a smooth result.

EDIT: By the way, this is what the sobel filter (bottom) looks like on a simple height map (top)

---
Tags: heightmap
---


# Question
Title: How can my entities avoid walking on certain tiles?
In my tile map, created with 'Tiled', I placed some tiles that need to be avoided by my mobiles. Tiles like water or obstacles.

The entities "wander" in the map, choosing random directions, and their position are in world coordinates (float), not grid or tile positions (int). To create a more natural effect, the random directions are similar in a period of time, so no abrupt change of direction occurs.

Is there a way to make entities avoid some tile types, or 'Tiled' tile properties, without losing the "wander" behaviour? I mean, choose random directions that do not reach these type of tiles?

# Answer
> 2 votes
At some point during your entity logic, you'll have computed the random destination of the entity.

Before moving the entity there, check the type of tile that exists at that location. If the type is not desirable, abort the move, or try to generate a new random destination.

Often this check is encapsulated in a method on the tile object or the entity object called `isPassable` or `isWalkable` or similar, which can make the decision based on various criteria (such as "does this entity have a special ability that would let it walk on lava?" or whatnot).

---
Tags: libgdx, tilemap, steering-behaviors, collision-avoidance, tiled
---


# Question
Title: How would I go about merging two models together in-game to create a new model?
Let's say I have two models: model 1 is hilt and model 2 is blade. How would I merge these to models together to create a sword?

# Answer
just append the data and adjust the indices:

if the hilt has X vertices and the blade has Y then you first put the X vertices of the hilt and then put the vertices of the blade. Do the same for the indices but add X to each index of the blade.

This will then force you to use only a single texture for the entire model.
> 1 votes

---
Tags: opengl, graphics-programming
---


# Question
Title: Texture Packer - Any way to make it combine intelligently
I am making a Pokemon Clone, using libgdx. I have the different types of sprites: e.g. Back, front, back shiny, and front shiny.

The current way the Texture Packer combines the textures seems to be semi-randomly. I would like to be able to tell it to put the sprites together based on number, because my sprites go:

* 003
* 003b
* 003bs
* 003s

Where the 003 is the pokedex number, and the b is for back, and s for shiny.

Two questions here:

1. Is there a way to get it to sort the textures in some way?
2. Is there a benefit to this sorting?

# Answer
> 4 votes
There's no real benefit to sorting those sprites by not-Pokemon index; the texture packer doesn't care what order the not-Pokemon are in, it cares about minimizing the atlas size. I'd just let it do its thing, the atlas file already specifies the position, dimensions, and other settings for each sprite. All you have to do is reference them by name.

---
Tags: libgdx, textures, optimization, texture-atlas, sorting
---


title: Collision detection/resolution clipping

text:
# Question
Title: Collision detection/resolution clipping
I'm trying to implement a collision detection system, and it is working for the most part, no overlapping (or at most very little overlapping) of characters, and wall collisions. The problem is that I have a bunch of characters following a player and just run into it, and when there are about 15-20 of those characters all pushing at the player, it can lead to the player or other objects being pushed through walls.

My code works as follows, first I update all of the characters, and they check collisions against each other, then I check for any character collisions with the walls. I think the problem is that I'm only ever checking one object against another, where as i need to be able to correctly detect multiple simultaneous collisions.

I've been looking into speculative contact and continuous collisions, but unfortunately i start to get lost when the non-code math equations come up. I don't necessarily need a real code example, but a good pseudo code/explanation would be great.

Code below if necessary, although a thorough explanation of how to mend this is also sufficient.

Character update/collisions:

```
void CharacterManager::updateAll(float elapsedTime)
{
    for(std::vector<std::shared_ptr<Character>>::iterator i = _characters.begin(); i != _characters.end(); i++) {
        (*i)->update(elapsedTime);
    }
    collisions();
}

void CharacterManager::collisions()
{
    for(std::vector<std::shared_ptr<Character>>::iterator i = _characters.begin(); i != _characters.end(); i++) {
        for(std::vector<std::shared_ptr<Character>>::iterator j = _characters.begin(); j != _characters.end(); j++) {
            if(i == j) continue;
            float xi = (*i)->position().x;
            float yi = (*i)->position().y;
            float xj = (*j)->position().x;
            float yj = (*j)->position().y;
            float dx = xi - xj;
            float dy = yi - yj;
            float distSquared = dx * dx + dy * dy;
            float ri = (*i)->xRect().width/2;
            float rj = (*j)->xRect().width/2;
            if(distSquared < (ri + rj) * (ri + rj)) {
                // fix collisions
                float angle = atan2f(dy,dx);
                float overlap = (ri + rj) - sqrt(distSquared);
                if(xi < xj) {
                    if(yi < yj) {
                        (*i)->position(xi - cosf(angle) * overlap/2, yi - sinf(angle) * overlap/2);
                        (*j)->position(xj + cosf(angle) * overlap/2, yj + sinf(angle) * overlap/2);
                    } else {
                        (*i)->position(xi - cosf(angle) * overlap/2, yi + sinf(angle) * overlap/2);
                        (*j)->position(xj + cosf(angle) * overlap/2, yj - sinf(angle) * overlap/2);
                    }
                } else {
                    if(yi < yj) {
                        (*i)->position(xi + cosf(angle) * overlap/2, yi - sinf(angle) * overlap/2);
                        (*j)->position(xj - cosf(angle) * overlap/2, yj + sinf(angle) * overlap/2);
                    } else {
                        (*i)->position(xi + cosf(angle) * overlap/2, yi + sinf(angle) * overlap/2);
                        (*j)->position(xj - cosf(angle) * overlap/2, yj - sinf(angle) * overlap/2);
                    }
                }
                // calc new velocities
                float vxi = (*i)->velocity().x;
                float vyi = (*i)->velocity().y;
                float vxj = (*j)->velocity().x;
                float vyj = (*j)->velocity().y;
                float vx = vxj - vxi;
                float vy = vyj - vyi;
                float dotProduct = dx * vx + dy * vy;
                if(dotProduct >= 0) {

                    float collisionScale = dotProduct / distSquared;
                    float xCollision = dx * collisionScale;
                    float yCollision = dy * collisionScale;
                    float combinedMass = (*i)->weight() + (*j)->weight();
                    float collisionWeightA = 2 * (*j)->weight() / combinedMass;
                    float collisionWeightB = 2 * (*i)->weight() / combinedMass;
                    (*i)->velocity(vxi + collisionWeightA * xCollision, vyi + collisionWeightA * yCollision);
                    (*j)->velocity(vxj - collisionWeightB * xCollision, vyj - collisionWeightB * yCollision);
                }
            }
        }
    }
}

```

Wall collisions:

```
void Stage::characterCrossCollisions(std::shared_ptr<Character> character)
{
    for(std::vector<std::shared_ptr<Tile>>::iterator tile = tiles.begin(); tile != tiles.end(); tile++) {
        if(!(*tile)->walkable) {
            sf::Rect<float> cxr = character->xRect();
            sf::Rect<float> cyr = character->yRect();
            sf::Rect<float> tr = (*tile)->getRect();

            if(!(cxr.left > tr.left + tr.width ||
                 cxr.left + cxr.width < tr.left ||
                 cxr.top > tr.top + tr.height ||
                 cxr.top + cxr.height < tr.top)) {
                float ox = 0;
                if(character->position().x > (*tile)->position().x) {
                    ox = cxr.left - (tr.left + tr.width);
                }
                else {
                    ox = cxr.left + cxr.width - tr.left;
                }
                character->position(character->position().x - ox, character->position().y);
            }

            if(!(cyr.left > tr.left + tr.width ||
                 cyr.left + cyr.width < tr.left ||
                 cyr.top > tr.top + tr.height ||
                 cyr.top + cyr.height < tr.top)) {
                float oy = 0;
                if(character->position().y > (*tile)->position().y) {
                    oy = cyr.top - (tr.top + tr.height);
                }
                else {
                    oy = cyr.top + cyr.height - tr.top;
                }
                character->position(character->position().x, character->position().y - oy);
            }
        }
    }
}

```

# Answer
> 3 votes
You need to put your thinking level one step backward, and try to imagine that there is a different way than the quadratic solve. You can use **iterative solving**. This will not give you a perfect solution in all cases, but when many entities moves relative to each other with 2 or 3 contact points in average, this is the fastest and gives very good results. All physics libraries implement this as default.

Try it like that:

```
for each entity
   determine contact points and store them (e.g. in an array limited to some MAX_CONTACTS like ODE does)
for X in range(1, iterative-steps-limit)
    for each entity
        find a heuristical solution that frees the body from interesections by creating impulses opposed to contact points.
    update positions from impulses

```

then you can add stuff like resting epsilons to let your bodies sleep when they don't move...

---
Tags: c++, collision-detection, collision-resolution
---


# Question
Title: How do I interpret the dot product of non-normalized vectors?
I know that if you take the dot-product of two *normalized* vectors, you get the cosine of the angle between them.

**But if I take the dot-product of two *non*-normalized vectors (or one normalized, one not), how can I interpret the resulting scalar?**

# Answer
> 18 votes
Others have pointed out how you can use the sign of the dot product to broadly determine the angle between two arbitrary vectors (positive: \< 90, zero: = 90, negative: \> 90), but there's another useful geometric interpretation if at least one of the vectors is of length 1.

If you have one unit vector \\$\hat U\\$ and one arbitrary vector \\$V\\$, you can interpret the dot product as the length of the projection of \\$V\\$ onto \\$\hat U\\$:

Equivalently, \\$(\hat U \cdot V)\\$ is the length of the component of \\$V\\$ pointing in the direction of \\$\hat U\\$. ie. You can break \\$V\\$ into a sum of two perpendicular vectors, \\$V = (\hat U \cdot V) \hat U + P\\$, where \\$P\\$ is some vector perpendicular to \\$\hat U\\$.

This is helpful for rewriting a vector from one coordinate system in terms of a different basis, or for removing/reflecting the component of a vector that's parallel to a particular direction while keeping the perpendicular component intact. (eg. zeroing the component of a velocity that would take an object through a barrier, but allowing it to slide along that barrier, or rebounding it away)

I'm not aware of a convenient geometric interpretation of the dot product when both vectors are of arbitrary length (other than using the sign to categorize the angle).

# Answer
> 4 votes
If the resulting scalar is 0; then it means the 2 vectors are perpendicular to each other (angle difference 90 degrees) . If the resulting scalar \> 0; then the angle difference between them is less than 90 degrees. If the resulting scale is \< 0; then the 2 vectors are facing opposite directions ( or angle difference \> 90 degrees).

This can be useful in calculating backstabs for example. Or determine which quadrant one vector is relative to the other.

# Answer
> 2 votes
the dot product is equal to `v1.length() * v2.length() * dot(v1.normalized(), v2.normalized())`

the most you can get out of that is whether the angle is acute or not or pass to other algorithms where you can delay the normalization. But you can get the normalized from the non-normalized by dividing with `sqrt(v1.lengthSquared() * v2.lengthSquared())` (saves a sqrt calculation)

---
Tags: mathematics, vector, geometry, angles
---


# Question
Title: How can I detect connected (but logically distinct) bodies of water in a 2D map?
I have a 2D hexagonal grid map. Each hex cell has a height value used to determine if it's water or ocean. I'm trying to think of a good way to determine and label bodies of water. Oceans and inland seas are easy (using a flood fill algorithm).

But what about bodies of water like the Mediterranean? Bodies of water that are attached to larger ones (where "seas" and "gulfs" differ only by the size of the opening)?

Here's an example of what I'm trying to detect (the blue body of water in the middle of the image, which should be labelled differently from the larger body of ocean on the left, despite being technically connected):

Any ideas?

# Answer
What you're describing is the Segmentation Problem. I'm sorry to say that it's actually an unsolved problem. But one method I would recommend for this is a Graph-Cut based algorithm. Graph-Cut represents the image as a graph of locally connected nodes. It subdivides connected components of the graph recursively such that the border between the two sub-components is of minimal length using the Max-flow-min-cut theorem and the Ford Fulkerson algorithm.

Essentially, you connect all of the water tiles into a graph. Assign weights to the edges in the graph which correspond to differences between the adjacent water tiles. I think in your case, all the weights could be 1. You will have to play with different weighting schemes to get a desirable result. You might have to add some weight that includes adjacency to coasts, for instance.

Then, find all the connected components of the graph. These are obvious seas/lakes and so on.

Finally, for each connected component, recursively subdivide the component such that the edges connecting the two new sub-components have **minimum weight**. Keep recursively subdividing until all the sub-components reach a minimum size (i.e like the maximum size of a sea), or if the edges cutting the two components have too high a weight. Finally, label all the connected components that remain.

What this will do in practice is cut the seas from each other at channels, but not accross big spans of oceans.

Here it is in pseudocode:

```
function SegmentGraphCut(Map worldMap, int minimumSeaSize, int maximumCutSize)
    Graph graph = new Graph();
    // First, build the graph from the world map.
    foreach Cell cell in worldMap:
        // The graph only contains water nodes
        if not cell.IsWater():
            continue;

        graph.AddNode(cell);

        // Connect every water node to its neighbors
        foreach Cell neighbor in cell.neighbors:
            if not neighbor.IsWater():
                continue;
            else:
                // The weight of an edge between water nodes should be related
                // to how "similar" the waters are. What that means is up to you.
                // The point is to avoid dividing bodies of water that are "similar"
                graph.AddEdge(cell, neighbor, ComputeWeight(cell, neighbor));

   // Now, subdivide all of the connected components recursively:
   List<Graph> components = graph.GetConnectedComponents();

   // The seas will be added to this list
   List<Graph> seas = new List<Graph>();
   foreach Graph component in components:
       GraphCutRecursive(component, minimumSeaSize, maximumCutSize, seas);

// Recursively subdivides a component using graph cut until all subcomponents are smaller
// than a minimum size, or all cuts are greater than a maximum cut size
function GraphCutRecursive(Graph component, int minimumSeaSize, int maximumCutSize, List<Graph> seas):
    // If the component is too small, we're done. This corresponds to a small lake,
    // or a small sea or bay
    if(component.size() <= minimumSeaSize):
        seas.Add(component);
        return;

    // Divide the component into two subgraphs with a minimum border cut between them
    // probably using the Ford-Fulkerson algorithm
    [Graph subpartA, Graph subpartB, List<Edge> cut] = GetMinimumCut(component);

    // If the cut is too large, we're done. This corresponds to a huge, bulky ocean
    // that can't be further subdivided
    if (GetTotalWeight(cut) > maximumCutSize):
        seas.Add(component);
        return;
    else:
        // Subdivide each of the new subcomponents
        GraphCutRecursive(subpartA, minimumSeaSize, maximumCutSize);
        GraphCutRecursive(subpartB, minimumSeaSize, maximumCutSize);

```

*EDIT*: By the way, here's what the algorithm would do with your example with a minimum sea size set to around 40, with a maximum cut size of 1, if all the edge weights are 1:

By playing with the parameters, you can get different results. A maximum cut size of 3, for instance, would result in many more bays getting carved out from the main seas, and sea #1 would get subdivided in half north and south. A minimum sea size of 20 would result in the central sea getting divided in half as well.
> 10 votes

# Answer
A quick and dirty way to identify a separate but connected body of water would be to shrink all water bodies and see if gaps appear.

In the example above I think that removing all water tiles which have 2 or less water tiles connected to them (marked red) would provide you with the desirable result plus some edge noise. After you have labeled the bodies, you can "flow" the water to its original state and reclaim the removed tiles for the now separate bodies.

Again, this is a quick and dirty solution, it might not be good enough for the later stages of production but it will suffice to "get this working for now" and move on to some other feature.
> 6 votes

# Answer
Here's a complete algorithm that I think should produce good results.

1. Perform morphological erosion on the water area — that is, make a copy of the map on which each tile is considered water *only* if it and all of of its neighbors (or a larger area, if you have rivers wider than one tile) are water. This will result in all rivers disappearing entirely.

(This will consider the islanded water in the left part of your inland sea to be rivers. If this is a problem, you could use a different rule such as the one vrinek's answer proposes instead; the following steps will still work as long as you have some kind of “delete rivers” step here.)
2. Find the connected water components of the eroded map and give each one a **unique** label. (I assume you already know how to do this.) This now labels everything but rivers and shore water (where the erosion had an effect).
3. For each water tile in the *original* map, find the labels present on *neighboring* water tiles in the eroded map and then:

* If the tile itself has a label in the eroded map, then it is mid-sea water; give it that label in the original map.
    * If you find only one distinct neighboring label, then it is shore or river mouth; give it that label.
    * If you find no labels, then it is a river; leave it alone.
    * If you find multiple labels, then it is a short bottleneck between two larger bodies; you might want either to consider it like a river, or to combine the two bodies under a single label.

(Note that for this step you must keep separate grids of labels (or have two label fields in one structure) for the eroded map (that you read from) and the original (that you write to), or there'll be iteration-order-dependent errors.)
4. If you want to label individual rivers uniquely too, then after the above steps, find all remaining connected components of unlabeled-water and label them.
> 6 votes

# Answer
Following on vrinek's idea, how about growing the land (or shrinking the water) so parts you would originally be connected would be disconnected after the land is grown?

This could be done like so:

1. Define how much do you want to grow the land: 1 hex? 2 hexes? This value is `n`
2. Visit all land nodes, and set all their neighbors up to depth `n` to land nodes (write to a copy, as to not get an infinite loop)
3. Run your original floodfill algorithm again to determine what is now connected and what is not
> 1 votes

# Answer
Do you have an rough idea of where the gulf is? If so, you can modify your flood fill to track the number of neighbouring but unexplored cells (along with a list of visited cells). It starts with 6 in a hex map and whenever that value drops below a certain point, then you know you are hitting a "opening".
> 0 votes

---
Tags: algorithm, procedural-generation, maps
---


title: 3D Unity characters without Maya

text:
# Question
Title: 3D Unity characters without Maya
I have been writing 2D iOS games for a while and I'm looking into getting into 3D. I want to know if Maya is required for making 3D sprites or if you can easily make your 3D sprites using just Unity 3D.

They won't be detailed, just about the size / shape and detail level of *Crossy Road* sprites

# Answer
Maya isn't the only 3D modeling package supported by Unity. Basically, anything that exports to .fbx will work (Unity imports that file format).

The other most common options are 3ds max and Blender, the latter of which is open-source. But again, any tool that exports to .fbx (which is most 3D modeling software) will work.
> 4 votes

# Answer
While Unity doesn't come with any 3D modeling tools, you could (with a bit of work) achieve that visual style just by using the primitives built into it.

Be advised, there are a variety of other 3D Modeling packages that you can use (other than Maya), that are far more affordable (see: free) for a new 3D modeler.
> 1 votes

# Answer
For future reference: Anim8or is a 3D modeling and character animation program in development for over decade. It is very accessible for beginners and hobbyists. It is taught in schools and a lot of tutorials exist.

Example resource:

http://cyberdog.wikispaces.com/Anim8or-Saucer101

Manual:

http://www.anim8or.com/learn/manual/index.html
> 0 votes

---
Tags: unity, maya
---


# Question
Title: Why do my Box2D collisions fail when I have multiple fixtures on one body?
I'm creating my first libgdx / Box2D game where a player moves around using a `mouseJoint`.

My player has two fixtures, "main" and "question".

For some reason when I have these two fixtures, my player is no longer responsive to collisions or touch detection (i.e. I can't drag the player around). If I remove the "question" fixture, everything works.

Why is this? How can I fix it?

---

This is how I create the Player:

```
// create body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(x, y);
bodyDef.fixedRotation = true;
body = world.createBody(bodyDef);

// player main body fixture
PolygonShape polygonShape = new PolygonShape();
polygonShape.setAsBox(bodyWidth / 2, bodyHeight / 2); // setAsBox takes half width, half height as params
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygonShape;
fixtureDef.restitution = 0.3f; // Bounciness - Keep value between 0 and 1.
fixtureDef.density = 3; // Mass p/sqm - Keep value between 0 and 100
fixtureDef.friction = 0.8f; // Slippery - Keep value between 0 and 1
bodyFixture = body.createFixture(fixtureDef);
bodyFixture.setUserData("player");

// player question fixture
polygonShape = new PolygonShape();
polygonShape.setAsBox(questionWidth / 2, questionHeight / 2, new Vector2(0,0), 0); // setAsBox takes half width, half height as params
fixtureDef.shape = polygonShape;
fixtureDef.restitution = 0.3f; // Bounciness - Keep value between 0 and 1.
fixtureDef.density = 3; // Mass p/sqm - Keep value between 0 and 100
fixtureDef.friction = 0.8f; // Slippery - Keep value between 0 and 1
fixtureDef.friction = 0.8f; // Slippery - Keep value between 0 and 1
fixtureDef.isSensor = true;
questionFixture = body.createFixture(fixtureDef);
questionFixture.setUserData("question");

```

I assume I'm doing something silly here—I'm still very much a noob when it comes to libgdx / Box2D.

# Answer
Well on your question fixture def, you set sensor true which makes it ignore collisions.

```
fixtureDef.isSensor = true;

```

Unrelated but as a side note, I think you need to dispose your polygonShape at the end after creating everything.

```
polygonShape.dispose()

```
> 1 votes

---
Tags: collision-detection, libgdx, box2d
---


# Question
Title: How can I create a screen-space distortion effect?
I am trying to create a screen-space distortion effect using shaders. This image demonstrating the effect I'm after is from Nvidia:

Let's consider that I have access to the background texture. How can I create this kind of effect? What should I do in the vertex and fragment function?

It seems that I need to retrieve screen-space normals of my object, but how?

# Answer
Simple lens shader that uses object's normals to distort the background. Render texture without this object, use it as "ScreenMapSampler" and then render all scene including this object in final frame. Not best implementation, but it works.

```
struct PS_OUTPUT{float4 Color : COLOR0;};

struct VS_Lens
{
float4 Position: POSITION;
float4 ScreenMapSamplingPos: TEXCOORD0;
float3 Normal: TEXCOORD1;
float4 RefractionPosition: TEXCOORD2;
float Depth : TEXCOORD3;
};

    VS_Lens vs_Lens( float4 inPos : POSITION, float3 vNormal: NORMAL)
{
VS_Lens Output = (VS_Lens)0;
float4x4 preViewProjection = mul (matView, matProjection);
float4x4 preWorldViewProjection = mul (matWorld, preViewProjection);

matrix viewProjectWorld = mul(matView, matProjection);
viewProjectWorld = mul(matWorld, viewProjectWorld);

float4x4 worldViewProj = mul(matWorld, matView);
worldViewProj = mul(worldViewProj, matProjection);
Output.RefractionPosition = mul(inPos, worldViewProj);

Output.ScreenMapSamplingPos = mul(inPos, preWorldViewProjection);

Output.Position = mul(inPos, preWorldViewProjection);
Output.Normal = vNormal;
Output.Depth = Output.Position.z;

return Output;
}

    PS_OUTPUT ps_Lens(VS_Lens In)
{
PS_OUTPUT Output = (PS_OUTPUT)0;

float4 TextureCoords = In.RefractionPosition;
TextureCoords.xyz /= TextureCoords.w;
TextureCoords.x = 0.5f*TextureCoords.x + 0.5f;
TextureCoords.y = -0.5f*TextureCoords.y + 0.5f;
TextureCoords.z = .1f / TextureCoords.z;
Output.Color = tex2D(ScreenMapSampler, TextureCoords.xy - TextureCoords.z * In.Normal.xz);

return Output;
}

technique Lens
{
pass Pass0
{
VertexShader = compile vs_3_0 vs_Lens();
PixelShader = compile ps_3_0 ps_Lens();
}
}

```
> 2 votes

---
Tags: shaders, post-processing
---


# Question
Title: It possible to render a true quad (without triangles) using OpenGL?
Is it possible to render a "true" quad in OpenGL? By that I mean a square which is *not* made out of two triangles.

# Answer
> 5 votes
No.

You can use the `GL_QUADS` primitive type instead of `GL_TRIANGLES` and draw four vertices instead of three.

But even with this, OpenGL will internally render with triangles.

---
Tags: opengl
---


# Question
Title: How can I obtain information about the GPU in Cocos2d-x?
I'm trying to obtain information about the GPU that is running the game in order to use the correct texture compression for that GPU:

```
std::string GPUInfo::getTC()
{
    std::string TC;
    cocos2d::Configuration::getInstance()->gatherGPUInfo();
    if(cocos2d::Configuration::getInstance()->supportsPVRTC())
        TC = ".pvr.ccz";
    else if(cocos2d::Configuration::getInstance()->supportsATITC())
        TC = ".dds";
    else
        TC = ".png";
    CCLOG("Texture compression format -> %s", TC.c_str());
    return TC;
}

```

But this keeps causing this error:

```
call to OpenGL ES API with no current context (logged once per thread)

```

Is there another way to obtain details about supporting GPU features on the current device?

# Answer
If you take a look at your `AppDelegate::applicationFinishedLaunching` function, it begins with these lines of code:

```
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
    glview = GLView::create("My Game");
    director->setOpenGLView(glview);
}

```

You should check for supported compression after those lines are executed.
> 2 votes

---
Tags: opengl-es, cocos2d-x
---


# Question
Title: Is there a pattern for handling multiple game states?
I'm experimenting with writing a multiplayer game, almost from scratch (I'm using C++, OpenGL, ENet, and platform-specific APIs) with a client/server networking model where the server is authoritative.

The server and clients each run their own deterministic simulation of the game. The server sends periodic snapshots of the entire game state to clients. When a client receives the snapshot, it forgets everything it knows about the game (except for the player's input after the snapshot was taken), loads the snapshot, and replays the player input that was generated after the snapshot was taken.

Now, say I want to send deltas instead of full snapshots. The server needs to remember the previous snapshot it sent, so that it can compare the current snapshot against the previous snapshot. Clients also need to remember the previous snapshot to reverse the delta. Each snapshot is a copy of the complete game state, and the server and clients now need to handle at least two of them (the previous snapshot, and the current game state).

A game state conceptually follows this pseudo-code:

```
class GameState {
    vector<unique_ptr<GameObject>> objects;
    vector<unique_ptr<Player>> players;
    TerrainTile terrain[TERRAIN_WIDTH][TERRAIN_HEIGHT];
}

abstract class GameObject {
    vec3 position;
    vec3 velocity;
    abstract void doPhysicsTick();
    abstract void render();
}

class Player {
    GameObject controlledObject;
    string username;
}

class HumanCharacter extends GameObject {
    void doPhysicsTick() {...}
    void render() {...}
}

... etc ...

```

Is there a pattern to store multiple independent copies of the game state from different times, so that they can be easily compared?

What if I wanted the server to run an identical simulation to each client (delayed by network latency)? The server would then need to manage at least N+1 game states, where N is the number of clients - and they would be active simulations, rather than static copies. (One practical use for such a system might be to only send values that the client has predicted incorrectly, rather than all values that have changed).

# Answer
> 2 votes
As https://gamedev.stackexchange.com/users/30331/ben points out in his comment, this may not be the best way, especially if your state info is big.

Otherwise:

> Is there a pattern to store multiple independent copies of the game state from different times, so that they can be easily compared?

Have a look at the Memento pattern.

You could have Mementos implement a `Comparable` interface.

---
Tags: networking, design-patterns, client-server, synchronization, game-state
---


# Question
Title: Why is my DX9 render target restricted to 512×512?
When I use a render target higher in resolution than 512×512, I receive an image with black borders, depending on how big this texture was.

Why is this? How can I fix it?

---

Here's how I create the texture and render target surface:

```
p_Device->CreateTexture(512, 512, 1, D3DUSAGE_RENDERTARGET,
    D3DFMT_A16B16G16R16, D3DPOOL_DEFAULT, &p_renderTexture, NULL);
p_mainRenderTexture->GetSurfaceLevel(0, &p_renderSurface);

```

And this is the main render-to-texture function:

```
void RenderSceneToTex(LPDIRECT3DDEVICE9 p_Device, D3DCOLOR clearColor,
        LPDIRECT3DSURFACE9 p_renderSurface, D3DXMATRIX matView,
        D3DXMATRIX matProjection, bool drawWater, bool drawTransparent,
        bool drawSkybox, LPSTR renderTech) {
    p_Device->SetTransform(D3DTS_VIEW, &matView);
    p_Device->SetTransform(D3DTS_VIEW, &matProjection);
    effect->SetMatrix("matView", &matView);
    effect->SetMatrix("matProjection", &matProjection);
    p_Device->SetRenderTarget(0, p_renderSurface);
    p_Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
        ((clearColor != NULL)?clearColor:D3DCOLOR_XRGB(0, 0, 0)), 1.0f, 0);
    p_Device->BeginScene();
    DrawSceneObjects(p_Device, drawWater, drawTransparent,
        drawSkybox, renderTech);
    p_Device->EndScene();
    p_Device->SetRenderTarget(0, p_dx_mainRenderSurface);
}

```

# Answer
The problem was inside present parameters - I forgot to set backbuffer's width and height.

```
dx_PresParams.Windowed = TRUE;
dx_PresParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
dx_PresParams.BackBufferFormat = D3DFMT_UNKNOWN;
dx_PresParams.BackBufferWidth = 1024;//Width
dx_PresParams.BackBufferHeight = 1024;//Height
dx_PresParams.EnableAutoDepthStencil = TRUE;
dx_PresParams.AutoDepthStencilFormat = D3DFMT_D24S8;
dx_PresParams.MultiSampleType = D3DMULTISAMPLE_8_SAMPLES;

```

But to be exact, the root of the problem was auto depth stencil being a surface in resolution of 512x512, so it didn't let me render scene in the whole texture.
> 2 votes

---
Tags: c++, rendering, directx9, rendertargets
---


# Question
Title: How can I tell if an object in a tile grid is surrounded?
I'm making a game which uses a 10x20 matrix to store the position of the objects.

I have a castle object, represented by a number in a matrix. It is randomly deployed in some cell of the matrix. I also have a wall object, represented by a different number, which the user will deploy into the matrix by clicking on cells. The idea is to surround the castle.

Basically it'll look like this:

```
0 0 0 0 0 0 0
0 1 1 1 1 1 0
0 1 0 0 2 1 0
0 1 1 0 0 1 0
0 0 1 0 0 1 0
0 1 1 1 1 1 0
0 0 0 0 0 0 0

```

(2 is the castle, and 1 is the wall.)

How can I tell if the castle is surrounded by walls?

# Answer
Sounds like you're after something like a flood fill algorithm.

Basically, something like the following algorithm (you can see other examples on the wikipedia page):

```
 1. Add your castle to the Checklist
 2. Get the first item from the Checklist
 3. For each surrounding position
  4. If not on Complete list
    5. If `0` add to Checklist
    6. If `1` continue
 7. Add position to Complete list and remove from Checklist

```

If at any point you reach an outside boundary, your castle is not surrounded by walls. If you complete your Checklist without touching an outside boundary, your castle is surrounded by walls.
> 7 votes

---
Tags: algorithm, tiles, python
---


title: Rotating an image in Python

text:
# Question
Title: Rotating an image in Python
So I am making an "Asteroids" like game and I can principally get my sprites image to rotate but when I do, the image gets kinda torn apart. This is the method I am using for rotation. Any help would be appreciated.

> def turnLeft(self):
>
> ```
>    rotatedSurf1 = pygame.transform.rotate(self.image,10)
>    rotatedRect1 = rotatedSurf1.get_rect()
>    rotatedRect1.center = (25,25)
>    self.image.blit(rotatedSurf1,rotatedRect1)
>
> ```

# Answer
I'm not familiar with pygame, but likely it does not like the image being repeatedly rotated and blitted onto itself.

Check out if this answer on StackOverflow works for you.

**Explanation**

Rotating an image is inaccurate. Unless you rotate exactly by multiples of 90 degrees, you never get an exact pixel-to-pixel mapping. In other words, you loose a small amount of information when you rotate. Since you replace the original image with the rotated version, this information is lost forever. Thus, the effect gets worse the more you rotate.

You should *never* modify the original image. Instead, store the rotation angle in a variable, increase/decrease this angle when pressing left/right, and rotate by that angle. Then, you can store the rotate image (`rotatedSurf1`, `rotatedRect1`) as a member variable and blit it to the screen when drawing the scene. Do *not* blit the rotated image back onto the original!

```
def turnLeft(self):
    self.angle += 10
    self.rotatedSurf = pygame.transform.rotate(self.image, self. angle)
    self.rotatedRect = self.self.rotatedSurf.get_rect()
    self.rotatedRect.center = (25, 25)

```

Don't forget to initalize self.angle to 0. In the drawing function instead of doing something like `display.blit(self.image)`, now do `display.blit(self.rotatedSurf, rotatedRect)`.
> 1 votes

---
Tags: python, image, rotate
---


# Question
Title: How can I stop transform.position from being modified when adding a child object?
I suspect there is a well-known and easy to explain reason for the behavior I'm seeing, but I am having difficulty explaining it (and likely not able to Google for the answer).

When adding a child `GameObject` to a translated parent, the child's `localPosition` is modified so that the child's `position` stays the same *after* the parent's transformation is applied. Is there a way to *not* have this be the case?

In the following example, I create a parent object and move it to `(1,1,1)`, and then attach the child. I would like the child's position to be `(1,1,1)`, that is `(0,0,0)` relative to the parent. However, the child's position is modified to be `(-1,-1,-1)` so that it is `(0,0,0)` relative to the world.

Here is a repro:

```
// Create parent.
GameObject parent = new GameObject();
parent.name = "Parent GameObject";
parent.transform.parent = foregroundObject.transform;

// Move the parent.
parent.transform.Translate(1, 1, 1);

// Add a child under the parent GameObject.
GameObject child = (GameObject) GameObject.Instantiate(guildiePrefab);
child.name = "Child GameObject";

child.transform.parent = parent.transform;

// PROBLEM: localPosition is set so that the "global" position is (0,0,0).
// How can I add the child object and have its position be (1,1,1)?
this.Assert(child.transform.localPosition.ToString() == "(-1.0, -1.0, -1.0)");
this.Assert(child.transform.position.ToString() == "(0.0, 0.0, 0.0)");

```

Is there a different way I should be adding `child` as a child of `parent`? Or, should I *always* zero-out the position of `parent` before adding a child? If that is the case, any reason why I need to do this? What is the rational for this design choice?

# Answer
When you instantiate using the default constructor for `Instantiate`, the position is set to (0,0,0). You can use the alternative constructor for `Instantiate`, and supply a position and rotation. If you want the child object to be position at zero relative to the parent, you can supply the parent position as the position to instantiate to.

```
GameObject child =
   (GameObject) GameObject.Instantiate(guildiePrefab,
                                       parent.transform.position,
                                       parent.transform.rotation);
child.name = "Child GameObject";

child.transform.parent = parent.transform;

```

Or if you have a specific offset you're interested in simply add it to the position when you instantiate:

```
GameObject child =
   (GameObject) GameObject.Instantiate(guildiePrefab,
                                       parent.transform.position + offset,
                                       parent.transform.rotation);

```

Either way, the child's position shown in the Inspector tab will be the child's position relative to the parent. The child's position found through `transform.position` will be the world position.
> 5 votes

# Answer
There is a different way.

Instead of:

```
child.transform.parent = parent.transform;

```

Use:

```
child.transform.SetParent(parent.transform, false)

```

The false argument specifies to not perform the relative adjustment you are talking about.

I'm guessing the reason it doesn't do this by default is because the code is most typically called from the editor, in which case you probably don't want the object you are assigning to a new parent to suddenly relocate when you drop it on the parent.
> 4 votes

---
Tags: unity, transformation
---


# Question
Title: moving object on game background after scaling it based on screen size
I am creating a game using `Corona SDK`, I have a map with a ball and another other object that moves on the map.

I use the the ultimate config.lua file for scaling background based on device screen resolution.

My problem is that I want to arrange some objects on this map. I have created specific assets for a specific device resolution, but on devices with aspect ratio lower than 1.72 the map is stretched horizontally so that appears wider than other assets.

Also when I want to arrange an object to a specific location on top of the map the result is that things don't line up right because of the scaling issue. For example, when i set `myobject.y=100` on a device with aspect ration more than 1.72 it set on the right place but when I do the same thing on device with aspect ratio less than 1.72 my object is off the map.

I tried to convert my pixels to inches using device DPI but it's still the same.

# Answer
First, I don't know corona but hopefully this method will still help out.

I'm moving all my games to more of a zone based layout to handle screen real estate. With all the different iOS devices sizes now and considering the possible port to android you need to start moving away from pixel based. I still am doing somewhat of a merge between the two but leaning more towards using percentages.

The fact is though that there are really still only a couple of different sizes. So you don't have to worry about like a 1:10 screen or anything crazy like that. Most screens are somewhere between 4:3 and 16:9. Based on how your game operates and how you're using the real estate.

I went back in to my most recent game and looked at the zones I set up for it.

The most important zone here is the menu zone. The title and the footer can be reduced if the screen is more squarish and it will still look fine.

I'm in C and objectiveC, so all these zone sizes (percentages) I stick in a bunch of #define's. Then I can go back and tweak them as necessary and see the results without having to change any of my formulas. Every item that is getting placed also has an object.position.xyz that I stick the results in and draw from.

You take your screen width and height, this can be pixels or inches or whatever unit you use in your game, and multiply it by the percentages to get how many units each item or zone is. When centering items in a zone you're going to use a lot of `* .5`s to find the placement location. Any percentage * screenUnitsHeight will be a conversion to units on the y axis. Here is my exact code for the placement of the title:

```
float screenTop = screenUnitsHeight/2.0;  // /2.0 because the center is 0,0
float screenLeft = -screenUnitsWidth/2.0;
titleLocation = vec3Make(0.0, screenTop - screenUnitsHeight * .5 * ZONE_TITLE, -800.0);

```

Since zone title is 31% down from the top of the screen I can start there and move down half the height of the title. But then I also have to scale the title to fit in there. BTW, this title is a graphic and not text.

```
float titleMaxH = screenUnitsHeight * ZONE_H_MAX_TITLE;
float titleMaxW = screenUnitsWidth * ZONE_W_TITLE;
titleScale = min(titleMaxH / TITLE_SIZE_H, titleMaxW / TITLE_SIZE_W);

```

The title can't be bigger than what will fit in either the width or height, so I calculate each one and then use `min()` to get the smallest of the two. In this case my `ZONE_H_MAX_TITLE` is .4 to leave some boarder between the graphic and the edge of the zone.

Here you can see how things squish down to fit even on an iPad which is 4:3:

Since all the heights are percentages thing will always fit. The width ends up with extra space but it looks fine. In another game I want the main gameplay area to take precedence. In that case I have both a `ZONE_MAX_W` and a `ZONE_MIN_W` and use `max()` and `min()` functions to dial everything in.

You can see above that on the footer I had designed it for some overlap with the weasel and the title when on a new iPhone and I let things fall where they may on the iPad. The weasel and gear are each side justified and the company title is center justified. It's all just math.

Notice this, when you deign your main look that's going to be exactly what it is (even pixel for pixel) when on the device you designed it for. But then on other devices it should also look better. Test out each end of the spectrum and adjust things to make it look ok on that device, then go back to the main device and recheck that.

**Your Map**

Use the `min()` function to make sure your map doesn't change aspect ratio no matter what the ratio of the device is. You might need to figure out what will be the background when it's shrunk to fit. Once you have the position and scale of the map you can use these factors to apply that same scale to both the position and scale of the items you're placing on the map.

Remember that `scale factor you have to draw at = size it needs to be / size that it is`. So once you get the target sizes using the above methods you stick this in for the `size it needs to be' and the`size that it is`is (in my apps) a hardcoded`#define\` statement. Or you could read everything in from an xml. Lots of ways to do that.
> 1 votes

---
Tags: corona-sdk
---


# Question
Title: Why does RGB order differ between color formats?
On the reference page for `SurfaceFormat`, it indicates that the **Bgra4444** format is an unsigned format which is 16-bits long, with 4 bits per color with alpha. Further down the page, it describes the **Rgba64** format as being 64-bits long, with 16 bits per color (including alpha).

Why does one format list R-G-B as the color order, while the other lists it as B-G-R? I understand it likely has to do with the underlying hardware, but there certainly needs to be a reason that it wants it in a reversed order for the other format.

# Answer
> 4 votes
"Just because."

Byte ordering is more-or-less arbitrary. Some hardware will do it one way, other hardware will do it another way... there's basically an equally valid argument in both directions so you just pick one.

There's no particularly relevant technical reason why some formats are in RGB order and others in BGR. It likely comes down to when the format support was needed, it was asked for in that order (because that was the client preference, or because somebody was mimicking or emulating older hardware that did it that way).

---
Tags: xna, color, file-format
---


# Question
Title: Height and Width of Player Depth View using Kinect SDK
This code shows that how we can find the player from the depth Image:

```
this.depthData = new short[frame.PixelDataLength];

frame.CopyPixelDataTo(this.depthData);

    for (int depthIndex = 0; depthIndex < depthData.Length; depthIndex++)
    {
            player = depthData[depthIndex] & DepthImageFrame.PlayerIndexBitmask;
    }

```

I wanna ask about how can I find Width and Height of Depth View of the player ? Thanks

# Answer
This link will give you a starting point.

http://www.codeproject.com/Tips/380152/Kinect-for-Windows-Find-User-Height-Accurately
> 0 votes

---
Tags: c#, kinect
---


# Question
Title: How can I ensure GLFW callback events only happen once in the main loop?
The problem is that the mouse and keyboard events can be triggered before the main loop(in which the program starts to render and update content) takes place. In the program if the moues button is pressed, there will be a sound effect. And the code looks like this

```
void main()
{
// Here I initialize everything including parsing model files,
// so when the window appears it's initially plain white(loading files and not
// drawing stuff). I set up the callback functions with glfwSetKeyCallBack()
// and glfwSetMouseButtonCallBack().
// The next line is the main loop

 while (!glfwWindowShouldClose(window))
 {
 // Here I draw all the content and this is supposed to be only the place that the events
 // can be triggered
 }

glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}

```

When I debug the program, the window will appear and if then I click the mouse, the sound effect will appear when the program starts drawing stuff on the window. But I want the callback functions to process events only when window enters the main loop. It should not receive or process events during the initialization part. Is there a way to prevent the callback functions to receive or process events before the main loop?

# Answer
To my knowledge of GLFW documentation and internals, events should only be dispatched in response to calls to `PollEvents`/`WaitEvents`. GLFW2 used to `PollEvents` in `SwapBuffers`, but that is gone in GLFW3.

In any way, there's two possible solutions to your problem:

* Register your callbacks in the main loop, predicated on a boolean to ensure you do it once.
* Register your callbacks early, but test a boolean in the callbacks to see if the program is ready or not. You may save up event information if you want to avoid losing it, or just discard events until ready.
> 1 votes

---
Tags: glfw
---


# Question
Title: How can randomly paired players fairly select a map?
I'm developing a website for a board game that revolving around user-created boards. Matches are currently created by selecting two people who have been waiting in a queue the longest and creating a match for them. We will later implement matchmaking with specific users.

What is an appropriate way to select a map when a match is created with two random people?

* Should one player be allowed to pick the map?
* Should a random map be selected?
* Maybe the players should rank a collection of popular boards by preference, then select the one with the highest average rating?

# Answer
You can also weight the maps based on a number of factors, first of all you can look at maps with a low level of quits (quits per started game) and use that for how "fun" maps are.

Secondly you can weight based on fairless, is one player winning more often then the other, if so then reduce weight of that map

thirdly you can keep track of arranged games (rather then quick games) and keep track of what maps are most often played there and use those more often.

Fourthly you can look at what maps players have recently played and avoid doubles.

Fifthly you can put in some kind of gradient for average game duration, usually games that last less then a certain time or more then a certain time aren't that much fun.

Lastly you can ask players to rate maps and use this in order to determine what maps are good, if you want to do this really well you could even look into matrix factorization in order to predict for each player which map he/she is going to like the most.
> 1 votes

# Answer
A map can just be randomly selected. Many online games including World Of Tanks, War Thunder, and others use this sort of technique. I personally however notice that I dont like some of the maps, and so am annoyed that I have to play on it. In my opinion, you should have the maps randomized but have configuration options for the player to be able to pre-set that they cannot join certain maps. If you dont want to do that, then in my opinion random is the best thing. I would not recommend manual map selecting mainly because it is an extra process. Also what if player 1 selected a map more advantageous for him than player 2?
> 0 votes

# Answer
This is going to depend on your game and what you're going for. Until you can answer that in detail, it's best to keep it simple, and tweak once you see issues.

The only thing I'd pre-empt is that with **user-generated content**, you want to **curate** it. You might maintain a collection of pre-approved maps that are allowed in random match-ups, unless the participants opt out. You might allow users to specify their own blacklist of maps.

When picking a map, *fairness is not the only concern!* Here are some things to consider:

* Is it **fair?**

Depends on your game, but players may have different play styles, some of which are (dis)advantaged by the map choice. You will need to make a decision on what kinds of play styles you'll encourage.

+ Can players avoid maps that place them at a severe disadvantage?
    + Giving players more control over picking maps encourages them to specialise on a few maps; random or fiat choices encourages players to be versatile.
    + Consider fairness between experienced and novice players; older maps with more tactical depth will advantage experienced players.
* Is it **fun?**

In general, fair is fun, but sometimes you can go overboard.

+ For example, you might overdo fairness and end up with a scheme that always causes the same, boring (but super-balanced) map to be played.
    + Sounds like it doesn't apply in your case, but consider whether it's fun for spectators. This includes random observers, e-sports audiences, LP watchers, or potential players researching your game.
    + Although unfair for single games, if games extend over multiple games (such as in tournament settings), you might deliberately choose less-balanced maps, as this creates variety and interest. Consider that some of the most popular sports and games have a high degree of uncertainty, giving underdogs bigger chances of winning.
* Is it **good for the community?**

This is keeping your players happy and engaged, and also keeping the game attractive for new players.

+ If your scheme picks controversial maps (loved by some, hated by others), it may be good for some but it may upset others so much that it creates a toxic atmosphere.
    + People don't want to play the same thing repeatedly, but if you let them choose in a competitive setting that's what they tend to do. Does your scheme help overcome that, and introduce new maps (without forcing duds on players)? New content like maps usually meet with initial resistance, but they help the longevity of the game, by keeping the game interesting as well as helping less-experienced players.

Again, simple is probably best here, and most games solve this problem in simple ways. Nevertheless, here's some examples of (very elaborate) schemes for you to think about, not only *what* they did but *why* they did it:

* Map choice rules in a Starcraft 2 tournament; here two players play on a series of maps in a best-of-X tournament:

> 1. All Map Vetoes and Map Choices must be made prior to the start of a Match.
>     2. The higher seeded Player must choose to act as Player A or Player B. Player A must veto one Map first, then Player B must veto two Maps, and then Player A must veto one more Map. The vetoed Maps will not be played in the Match. Player B must choose the Game 1 Map and then Player A must choose the Game 2 Map. The Game 3 Map will be the Map that hasn’t been chosen or vetoed.
>     3. No Map may be played more than once in a Match.
>     4. No Map will be considered to have been used in a Game that is forfeited according to General Rules #3.

As a prize competition, fairness is a very high priority, but so is making the game interesting to watch. Note the features they used: **a pre-approved pool of maps** (curation); **vetoes** to eliminate the most unfair choices; **picks** so that each player has a good chance of winning at least one game.
* Hero picks in a MOBA (Dota 2); here the captains of two 5-member teams take turns picking and vetoing heroes, which are assigned to their team members out of a pool of dozens (I'm analogising between heroes and maps here):

In most MOBAs, heroes have very different abilities and their selection has a large influence on the game's outcome. Thus there's an elaborate series of **picks** and **vetoes** to eliminate the choices that are too good. This forces players to be proficient at a range of heroes and keeps the game interesting. Some even enjoy the hero pick as a meta-game. Note that this scheme reinforces the strategic complexity of MOBAs and strongly disadvantages new players, which is acceptable for hardcore games.
> 0 votes

---
Tags: maps, balance, matchmaking
---


title: Using GetTickCount (to shoot missiles)

text:
# Question
Title: Using GetTickCount (to shoot missiles)
I have some difficulties to understand how to correctly use GetTickCount() as I have some problems in my little game. I have to place on a case a space ship. This one will shoot with a certain frequence some missiles.

Edit: It works good now, I edit the code below. However there is an other problem, I don't know why there is only one shooting space ship.

I hope someone has an explanation for that.

---

```
MyGameEngine::MyGameEngine(...) : tickTime(0) {}     // for the constructor...

DWORD prev_frame_tick;
DWORD curr_frame_tick = GetTickCount();

// function called everytime (loop)
void MyGameEngine::idle() {

    prev_frame_tick = curr_frame_tick;
    curr_frame_tick = GetTickCount();
    tickTime += curr_frame_tick - prev_frame_tick;
    int i;

    // SPACE SHIP
    for (i = 0; i < ship->size(); i++)
    {
        // verify if tickTime > freqShoot : if true return new missile with correct positions
        Missile* m = ship->at(i)->tick(tickTime);

        if (m != NULL) {
            missiles->push_back(m);
            std::cout << "new miss" << std::endl;    // I have to put this, however nothing on screen
            tickTime = 0;
        }
    }

    // MISSILES ANIMATION
    for (i = 0; i < missiles->size(); i++)
    {
        missiles->at(i)->tick();

        if (missiles->at(i)->getBordDroitX() > 1.0f) {
            missiles->erase(missiles->begin() + i);
        }
    }
}

```

---

```
Missile* Ship::tick(DWORD t) {
    Missile* m = NULL;
    if (t > freqTir) {
        m = new Missile(posX, posY, width, height, numCase);
    }
    return m;
}

```

# Answer
> 0 votes
Looks to me its some kind of timer function that returns the time elapsed since the start of program.

As for how to shoot missiles at set intervals, you do this:

give your object a cooldown property; On update step:

```
cooldown -= dt;
if (cooldown <= 0) {
    shootMissile();
    cooldown = missileCooldown;
}

```

---
Tags: c++, game-loop
---