# Question
Title: Good techniques for syncing gameplay actions to specific animation timings?
So I've come across an issue in the game I'm working on, but it seems to be a pretty fundamental thing that probably comes up in a lot of games.

My game requires that some gameplay function occurs at a very specific point in time during a character animation. And so, as the title says, I'm wondering what are some good techniques and fundamental strategies for syncing gameplay-related events/functions/actions to specific points in a character's animation.

Here are some simple examples of what I'm talking about in various types of games:

* Your character *reloads their gun in a shooter*. Your character plays his/her 'reload' animation, but it's important that the function that sets the currentAmmo variable is only called at the *exact moment after the magazine is swapped and the gun is cocked.* This might be some point in the middle of the reload animation.
* In a *turn-based RPG* your characters stand in a line facing a line of enemies. When commanded to attack, one of your characters runs/jumps up to one of the enemies and slashes their giant sword before running/jumping back to their standing place. You want to make sure that the *enemy is damaged at the exact moment that the slashing animation* is played - some point between running up and running back.
* In a *stealth game*, your character can sneak up and interact with computers and buttons in the world. Maybe there is a button that turns off the power supply to the lights of the outpost that you're infiltrating. When the action button is pressed, your character reaches out and pushes the button and then returns to their idle stance. *You want the lights to turn off at the exact point in the 'push\_button' animation when the button is pushed in.*

Admittedly, *my particular case is most like the second example*, in which I have created an animation where my turn-based character lunges forward during an attack and I want the *damage to be applied at the exact moment that the animation seems to be making contact.* Because my game using a turn-based system (imagine something like Final Fantasy or Fire Emblem) I want the damage/healing/magic/etc. to be applied at the correct time during each character animation even though I'm not actually using collision/hitboxes.

I should mention that I'm making my game in a popular game engine, and that right now I'm handling this by using their animation events or notifies to achieve something close to the desired results - my character performs a certain command and triggers a command-specific animation (i.e.: 'attack\_command') and the animation assets for each one of my commands must include an animation event/notify 'callback' into my characters ExecuteCommand function. In other words - *the character tells the attack animation to play, and then the attack animation emits an event/notify callback into the character at the exact moment during the animation when the damage should be dealt.*

Honestly, this works for now, but it just *feels wrong* \- like I'm missing some part of the bigger picture here! Part of the reason that this method feels wrong is that it couples the game logic with the animation assets; if my animation asset forgets to include an ExecuteCommand() event/callback, the command wont execute properly and extra code is needed to check if a command animation finished without executing the command. It's messy and it means that my gameplay has a strange dependency on its assets. Of course I want the damage to occur at a specific point during my attack animation, but I feel really weird about calling gameplay code inside animation assets..

**So what am I overlooking here? What are some good general techniques for handling these types of situations in which you want certain important gameplay actions to occur at specific times during animations?**

*Edit: To clarify, this isn't an engine-specific question nor am I looking for engine-specific designs/techniques. I'm interested in general animation/gameplay synchronization techniques that one might use in your game projects regardless of technologies used.*

# Answer
For synchronisation, you need to decide who (your code, animations, or neither) is the *timing authority*—the "beat" that everyone else "dances" to.

Different arrangements suit different games:

* **Animations are the timing authority** (your current setup)

The game code may trigger animations. When animations reach certain points, they raise events (e.g. reloading done) that the game code may react to (e.g. reset available ammo).

If the precise timing of animations (independently of game state) is an important part of your game, or you specifically want your animators to control timing, consider this approach.

Animation tools Blender (3D) and Spine (2D) allow the animator to define events that game code can subscribe to.
* **Code is the timing authority**

Inverse of the above: Events happening in the game world (e.g. the player choosing to reload their weapon) cause animations to be run and to be passed parameters (e.g. time until reload should be finished). Each animation uses the supplied parameters to modify how it looks (e.g. running the animation at an appropriate speed such that the "reloaded part" happens when specified).

Animations might also be listening for game events (e.g. player cancels reload or player crouches while reloading) and modify their look accordingly.

If your animations can afford to be flexible about timing, your game relies heavily on procedurally generated content, or you specifically want your programmers to control timing, consider this approach.

*Overgrowth*'s character animations are largely structured this way: David Rosen explains it in his GDC 14 talk (see specifically the *Movement* and *Movement Continued* segments).
* **Implicit timing (external authority)**

In rhythm games or other situations where timing is controlled from an external source (in rhythm games, the music track's beat), it may make sense to model things as such. The game code and animations can both read a global timestamp and game state, then behave accordingly without communicating.

If your game state and animations are largely dependant on an external timing authority, consider this approach.

You might of course want to use different approaches for different systems in your game. (For example, rhythm games frequently use the beat of the song as an external authority, but animations still listen to player interaction events to cancel or change the look of held notes.)
> 5 votes

# Answer
I've read somewhere that almost all computation problems can be solved with an additional abstraction layer, and I don't see your case being different.

For this requirement I generally see a layer to control the State of the character. This way the character will have a current Animation and a current State. Each one with its own responsibility.

The animation is responsible only for the visual, and the state handles the game specific logic for that action.

In my fighting game, the state is a object that inherits from BaseState class and has an Update() method. Each character has a collection of states, but only one can be assigned at a time. And the Update() method of the current state is called once per frame.

It's inside the Update() of the state where I do all that logic: set the velocity of character at a specific frame, increment/decrement health etc.
> 0 votes

---
Tags: architecture, animation, events, timer
---


# Question
Title: LibGDX: Issue with unitScale for Tiled and Box2D
I've got the following: I use a `TiledMap` (loaded from a `.tmx`), each tile 32x32 pixels in size and generate the Box2D bodies for collision from the TiledMap's `ObjectLayer`. That all works fine, no errors or issues. The only thing is a very strange behavior of the `OrthogonalTiledMapRenderer`: It gets a `unitScale` with the value `1 / 32` (because one unit is 32 pixels) as advised on the LibGDX GitHub wiki page. The same unit scale is used for Box2D. Thought in theory this should work just fine it renders the map very small (same is the case for the Box2D bodies, they're shown very small by the `Box2DDebugRenderer`):

Here is my code (more or less simplified):

```
public class MainScreen {
    private OrthographicCamera camera;
    private ScreenViewport viewport;
    private SpriteBatch batch;
    private World world;
    private TiledMap tiledMap;
    private OrthogonalTiledMapRenderer tiledMapRenderer;

    public MainScreen() {
        this.batch = new SpriteBatch();
        this.world = new World(new Vector2(), true);
        float unitScale = 1.0f / Constants.TILE_SIZE;

        this.camera = new OrthographicCamera();
        this.camera.setToOrtho(false, Gdx.graphics.getWidth() * unitScale,
            Gdx.graphics.getHeight() * unitScale);
        this.viewport = new ScreenViewport(this.camera);
        this.tiledMap = (new TiledMapLoader()).load("level/test-level.tmx");
        this.tiledMapRenderer = new OrthogonalTiledMapRenderer(this.tiledMap,
            unitScale, this.batch);

        // Create bodies in world based on map
        Collisions.create(this.world, this.map, unitScale);
    }

    public void render(float delta) {
        // Clear the screen
        Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        this.world.step(delta, 6, 2);
        this.camera.update();
        this.tiledMapRenderer.setView(this.camera);
        this.tiledMapRenderer.render();
    }

    public void resize(int w, int h) {
        this.viewport.update(w, h);
    }
}

```

I've got no idea why this is happening... Thanks in advance :)

# Answer
I just stumbled upon the answer:

I checked my `ScreenViewport` and seemingly the viewport somehow ignores the `setToOrtho(false, width, height)` and the method `setUnitsPerPixel(unitScale)` has to becalled first...

I never saw an example in which a viewport was used together with box2d, tilemap and unitScale, so I didn't even know about that method.

The greatest thanks to @Shiro for his help! :)
> 2 votes

---
Tags: java, libgdx, box2d, tilemap, scale
---


title: GLSL: #define vs const

text:
# Question
Title: GLSL: #define vs const
What is the difference between `#define NAME VALUE` and `const int NAME = VALUE` in GLSL `410 core`?

As far as I can see, they both create a constant integer.

# Answer
> 14 votes
`#define NAME VALUE` is a macro, where all instances of `NAME` are replaced with `VALUE` by the pre-processor.

The compiler handles constants. This ensures type safety.

---
Tags: glsl
---


# Question
Title: Outline of plane slice of arbitrary object
How would you extract the outline of a shape from slicing a plane through an arbitrary object?

Note: This is related to my Unity Answers question, but not exactly the same.

# Answer
> 2 votes
This blog post describes an effect where the intersection between two object is highlighted. However, both object are rendered. I'm guessing in your case, you don't want the plane to be rendered. You could set the alpha for the plane's color to be 0. I think that will put the plane in the depth buffer, but not color it. But still, your object might intersect with any other object that was rendered before it.

Alternatively, you could create a texture that contains the depth map of just the plane, and within the fragment shader, sample the the plane depth, and if the fragment's depth is close, highlight that fragment's color.

I think you can use a secondary camera and a RenderTexture to get the depth map. I'm not sure how to make the second camera only render the plane.

A geometry shader might not be necessary.

# Answer
> 0 votes
I came up with a simplistic solution to this a few years ago in a non-realtime context (mesh slicing for 3d printing).

Given a plane defined in world coordinates by a point (origin) and a vector (normal). First setup a matrix that transforms your mesh into the coordinate system of the plane. Now do a z-bounds check of all the edges of the mesh (i.e. `min(v1.z, v2.z) <= 0 and max(v1.z, v2.z) >= 0`).

Each edge that passes the test is either in the plane (creates a line), or passes through at one point (creates a point). The point of intersect is the normalized vector from min point toward max point times the distance of the min point to the plane (z=0) as a percent of the change in the z axis along the edge...

```
# Pseudocode
low = v1 if v1.z < v2.z else v2
high = v2 if low is v1 else v1
zdelta = high.z - low.z
dist = abs(low.z) # Distance of low.z from plane
vec = normalize(high - low) # Assumes operator overload for vector arithmatic
intersect = vec * (dist/zdelta) # The x and y coord are all you need

```

Once you have a list of edges that create points in the plane you need to check for pairs that are part of the same face, draw lines connecting these. Also check both vertices of in-plane edges against other edges and connect those dots too.

This method works for arbitrary non-manifold meshes with ngon faces. In the context I wrote it I had access to half-winged edge mesh data with easy checks for membership. Given a closed triangle mesh you could probably simplify some of the checks?

old code

---
Tags: unity, shaders, procedural-generation, geometry, geometry-shader
---


# Question
Title: How can I create random noise that is seamless across modular game assets?
Does anyone know how I can create a texture for a modular tile, such that when the tiles are arranged, random weathering effects such as scratches will be continuous across seams?

An example photo below shows the ideal result. The scratches are continuous between different tiles. Is creating weathering effects like this possible using any procedural software?

# Answer
A tough one. Let's try.

1. Let noise be your (infinite) noise function.
2. Let Seam\_noise be a seamless noise function in the dimension of your tiles. (here is an example , you can download c# code with a seamless perlin noise implementation ) Follow an example of seamless perlin repeated 4X4 times (the red quad is your tile dimension)
3. Consider a "filter" function like this
4. and the "inverted filter"
5. Multiply (2) and (3) and you get something like :
6. multiply (1) and (4) and get the noise smothed in the borders
7. Mix (5) and (6) and get something like (image zoomed x2):

As you can see is far away from your sample image. You can work on noise quality, in the grid intensity, in the mix function to refine things a bit.
> 2 votes

---
Tags: textures
---


# Question
Title: Spritekit - gradually apply force vector in different direction (space ship turning)
I have a space ship that I'm applying a force vector to using a joystick for control. I would like this to smoothly fly around when I'm switching directions.. Exactly like minisquadron if you've ever played that..

Let's say I move the joystick to the far right and apply a force on the physics body of (1,0) and then I abruptly switch directions without circling the joystick around and apply a force of (-1,0). The ship will move to the right and then slowly lose speed before switching in a linear fashion.

What I want is for it to slowly transition between those two vectors so that it flies in a tight circle.

I'm trying to figure out the best way to write this.. maybe using a loop.. but I could use some help.

**pseudo code:**

```
func joystickMoved(){
    let point = pointVector;
    self.moveShip(pointVector);
}

func moveShip(pointVector: pointVector){

    // get current angle
    let curAngle = self.ship.physicsBody.velocity.toAngle()

    // get joystick angle
    let newAngle = pointVector.toAngle

    // while there is a sizeable difference in angles..
    // this loop needs to occur with some delay
    // so transition doesnt occur too quickly
    while fabsf(newAngle - curAngle) > 0.5 {

        // make tiny transitions towards newAngle.. this needs more detail
        curAngle += 1
        let newVelocity = CGPoint(cos(curAngle), sin(curAngle))
        self.ship.physicsBody.velocity = CGVector(dx: newVelocity.x, dy: newVelocity.y)

    }
}

```

# Answer
> 1 votes
* First, the behavior you're describing is that of an aerodynamic vehicle with a single vector of force. A spaceship, flying in space, would operate in an entirely different manner.

If this is still the desired behavior:

* Second, to utilize SpriteKit's efficiency, it might be best to use actions on your nodes. This isn't a requirement, but they exist for a good reason.
* Third, what you want is a single vector of force applied (say, from 0.0 to 1.0) in a single direction. The direction of the joystick should be the desired direction of the ship, the change of which is distributed over a time. If the joystick is analogue, the distance from center/rest would be the magnitude of the force applied.

This would look something like:

```
[spaceship runAction: [SKAction rotateToAngle:joystickAngle duration:joystickAngle/turnSpeed]];

```

Ensure, for the "tight circle" to be the effect, to keep the forward velocity/force applied throughout the duration.

# Answer
> 0 votes
My poor way of moving towards the touched location.

```
SKAction *rotation = [SKAction rotateToAngle:angle duration:.2 shortestUnitArc:YES];
SKAction *run = [SKAction moveTo:touchLocation duration:.01 * distance];

[ship removeAllActions];
[ship runAction:rotation completion:^{
    [self changeShipTextureWithType:@"run"];
    [ship runAction:run completion:^{
        [self changeShipTextureWithType:@"idle"];
    }];
}];

```

PS: You wanna move while rotating, right? As in Space Rangers (video game)?

---
Tags: 2d, ios, physics, vector
---


title: Texturing issues in cry engine sdk

text:
# Question
Title: Texturing issues in cry engine sdk
Sup?

I've been working on a new environment scene inside 3ds max. It looks something like this -

When I used the cry engine exporter to export my assets onto my level, I've been getting very weird shadow/texture problems. Do any of you know why that's happening? I'm pretty new to all of this, especially cry engine. Here's a screenshot of the same environment inside of cry engine sdk. If you look to the left of the environment, you can see how I'm getting weird results. The area I'm having issues with is highlighted with a faint blue line.

# Answer
Those models look extremely detailed. If this was done with subdivision, it would not be too hard to step over the 65536 vertex limit (I'm guessing that the game could be using 16-bit vertex indices for these models).

It only takes a grid of 256x256 vertices to be right on the limit, 8 subdivision levels on a quad would go over it.
> 1 votes

# Answer
I am guessing that you mean that the pipes' insides are invisible. This is because backfaces are culled on polygons. It is usually disabled either by turning off backface culling, or just duplicate the polygons with reversed winding order (or scaling them by -1).
For Cryengine, specifically I don't know how would you disable backface culling (in DirectX you can disable it in the Rasterizer state object), but the second option can easily be done in the modeling tool of your choice.
> 0 votes

---
Tags: models, level-design, 3dsmax, cryengine
---


title: TileMap or Voxel collision detection

text:
# Question
Title: TileMap or Voxel collision detection
I have a conceptual question: In the case of Tile Map, each block has the information from the enemies who are going about it. But what if some of these enemies are far greater than the block? I have to have the same element in each of the information blocks? And updating the position must clear each block? If I have large and small enemies, it means that each block will have a list of enemies?

Now, in the case of Voxel Map: In Minecraft, for example, its character and most enemies x and z dimensions is smaller than one block, but its height (y) is greater than one block. This means that these elements will record information in two blocks? and in the case of a "Gast," which is much larger?

I'm using Google Translate, so sorry if my english is very bad. Thanks in advance.

# Answer
> 0 votes
Using Minecraft again, as an example:

It's not true that each block contains a list. *All* non-block objects are likely contained in a single list, or perhaps one list per *chunk* to help with occlusion. For simplicity's sake, we'll ignore chunks for now.

There are two kinds of entity I'll call blocks and objects.

* Blocks are just a numbers indicating what kind of block it is, contained in a three dimensional array.
* Objects are things like enemies, and they have a position that does not correspond to the positions allowed by the block array.

If a block moves, like the sand block when it falls, the block is actually removed from the array (set to zero) and an object entity that looks like it is created in its place so that it can move fluidly. When it lands, the object is destroyed and the block where it landed is set to the sand block number.

Since objects aren't constrained by the block array system, they can have rotations and positions independent of blocks. However, objects are more expensive than blocks to simulate because they have extra information associated with them.

An simple example in code might look like

```
struct Object
{
    float3 Postion;
    float4 Rotation;
    int Model;
}

enum Block
{
    Empty,
    Sand,
    Dirt
}

Block[,,] Blocks;
Object[] Objects;

```

So you only have two collision cases:

---
Tags: collision-detection, tilemap, voxels
---


# Question
Title: How to calculate final force vector for the SKSpriteNode
I am creating space game which has an effect similar to black hole's gravitational effect. Wherever the spaceship is going, the black hole will attract it, summing up all the vectors together.

I know SKFieldNode has a method customFieldWithEvaluationBlock: that allows to calculate everything myself, but might it be another way to do that?

I have tried almost every type in SKFieldNode, but nothing helped.

1. There are some side effects that don't suit me (i.e. If I use an electric or magnetic field, the object repels from the black hole)
2. Moreover, moving with SKAction (i.e. for the spaceship) doesn't allow me to sum all movement vectors together (I cant do `- (void)moveTo:duration:` actions simultaneously, even with grouping the actions)

What can you advice me? !

# Answer
> 1 votes
to simulate a black hole, I suggest to use SKFieldNode and vortexField(), adjust its strength and falloff property (default is 2).

Setting a big number for strength will makes a big *perpendicular* force which simulates an angular force too (tangant to its imaginary orbital path around the black hole).

And let the physics handle the rest, just dont touch any thing else and only use physics rules.

> Do not apply any force vector manually

---
Tags: ios, objective-c, spritekit
---


title: City-region generation

text:
# Question
Title: City-region generation
I am currently making a procedural generated map and wanted to add regions to the cities indicating their reach, the way I am achieving it currently is by expanding outwards from the city center until either the reach of the city is exceeded or water/mountain terrain is met, a bit like raytracing I assume:

This gives the issues seen above, making big ugly/unnatural holes and not filling areas out of "sight" but arguably within the city's reach. City regions are supposed to be blocked by mountains ranges and larger bodies of water, but should curve around small lakes/rocks in a natural way. I can provide my current code put I believe it's fundamentally flawed for what I want to do, and is not usable.

Basically the desired region I want to great should look something like this:

I am at a bit of a loss what to search for to find literature about this topic, whether it be something like an algorithm or hints of some sort, so basically I am asking what this is called. (Any tips/tricks would also be greatly appreciated)

# Answer
> 3 votes
To follow up on comments by @Ranth & @JackFrost, a breadth first search spreading away from the point of origin should give you the desired result. When doing so:

* Use an 8 way neighborhood (I.E. allow diagonal search movement)
* Use a Euclidean metric for distances to encourage 1 diagonal movement over 2 cardinal movements
* Limit the search by whatever you want the maximum radius to be
* Make obstacles impassable or increase the movement cost of their cells

Because the search will need to either wrap around obstacles or move more slowly through them, you won't get a perfect circle around your point of origin. If things still look too smooth &/or you have an area without obstacles, you could always add some fake obstacles for the running the city perimeter search.

As with most PCG stuff, you'll probably need to experiment a bit to find what you want. I like to use Perlin / simplex noise &/or Poisson disk distributions for that sort of thing, but to each their own.

# Answer
> 2 votes
I believe this could be achieved using the flood fill algorithm that basically calculates all connected areas in a given space, depending on how you want it to work however as it might lead to areas say opposite a river (where the river runs all the way along the largest area that the city can take) not being included in the area that would need special handling.

In terms of growth you could simple increase the radius of the circle and let the flood fill select the area inside that circle.

In terms of implementation the best way is to follow a tutorial but Wikipedia also has a decent Pseudo code implementation: https://en.wikipedia.org/wiki/Flood\_fill#Pseudocode

# Answer
> 0 votes
As stated Kyranstar in his comment maybe Cellular automaton can be a solution.

Claim new terrain using some random logic that check terrain type, water presence (a city usualy grows near a river or seacost) ..

---
Tags: java, algorithm, procedural-generation
---


# Question
Title: How does a "debug console" handle dependencies/access objects?
I'm trying to get my head around how to create a debug console and have a hard problem to figure out how it access different objects in my game.

Say for example I want the console to be able to:

* Add new enemies on current map -\> This requires access to the current map or some entity service
* Add a new component to a current entity -\> This requires access to some current entity list.
* Change settings -\> This require access to some settings service/manager
* Change map -\> This requires access to some map service/manager
* Start a new game event -\> This requires access to maybe some maps event handle.
* etc

It seems like this list may just grow and grow with new commands with new dependencies and I wonder how you structre this? How does for example the Half-life console work?

It feels a bit rough to just have something like this:

```
var console = new DebugConsole()
console.AddCommand(new AddEntityCommand(entityService))
console.AddCommand(new SettingsCommand(settingsService))
etc

```

But maybe that's the way to do it?

# Answer
> 1 votes
That's pretty much the way to do it.

The debug console API should have a method to associate commands the user types in it (such as `spawn zombie`) with actions. The command pattern, which you've already discovered, is one such method of implementing that association. The debug console exposes an `addCommand(string, ICommand)` method which associates a string ("spawn") with an instance of a command -- which could just be a delegate or function pointer, it need not actually be some concrete `ICommand` subclass or whatever. That command is invoked by the console, and the command parses the remaining arguments the user typed ("zombie") to determine what to do.

As for actually hooking up the commands? There's no magic. At some point you're going to have a big list of `DebugConsole.AddCommand("spawn", new SpawnCommand(currentMap))` style code. The two basic options are

* put it all in *one* place, so it's easy to find it all and extend or modify it.
* put the bindings for each subsystem (map, spawning, camera, combat, whatever) within that subsystem itself, possibly by requiring the subsystem to implement some `attachDebugCommands(DebugConsole console)` method that is called during startup or whatever.

There are pros and cons to both. Depending on what information you need each command implementation to have available, it may make more or less sense to take one approach over the other.

Note that in some cases you may need to expose "debug only" APIs out of a subsystem to implement these commands. Languages with preprocessors, like C or C++, can help you ensure that relevant code is only available in debug builds if you like. In other cases, the second of the above two options often lets you expose debug commands that otherwise access private APIs of the subsystem since the subsystem itself is doing the registration.

---
Tags: architecture, console
---


# Question
Title: Better to send multiple small packets or one large packet?
I'm developing a network game with node.js and I have the choice between these three options:

1) Send each point individually (very user responsive)

2) Send an update every 25 points or so (decent compromise)

3) Wait until the user is done with his path and send it in its entirety (clients don't see until entire path is complete)

Now I know node.js is very good for quickly sending data back and forth rapidly and even sending a point at a time on my local connection is instant with no lag at all but I'm thinking down the line. What if there were thousands of people playing? Would it deny service based on how many packets were going through or is node.js with socket.io good enough to handle even such loads? What do most people do when they encounter this situation?

# Answer
> 1 votes
None of the options you listed is really a good choice.

Nagling is turned off by default so each packet you send will be an individual packet. A good rule in game networking is to find a send rate and don't go over that. That is perform your own nagling of packets. Essentially don't send 30 individual packets one after another for individual points. (You'd be eating header overhead and routing overhead).

It's not clear how your "points" system works or the rate at which points are created. Depending on your game you might be fine just updating at a fixed 100 Hz. So queue up your points and then in your update loop build your packet with the points data and send it along with other data to the player.

# Answer
> 0 votes
First off, you have to decide what performance characteristics are most important from a user experience point of view and then understand the technical issues involved in delivering that experience at scale/load.

So, the operative question for your game may be something like: "At what delay does the experience for others start to deteriorate?". Some games would be basically ruined if the delay in update of other's moves was 1 second and other games could easily tolerate 5-10 seconds as it entirely depends upon the game and what the networked data you are transmitting means to the experience of the receiving player.

So, in your specific game, you need to figure out what the goal is. Do you need to deliver updates to other players within 300ms, will the experience still work just fine at 2 seconds or is the info being sent periphery to the experience and even 10 seconds is OK?

Then, whatever time delay you find still acceptable for a decent experience, you can build your client so that it collects points for about 2/3 that time minus whatever the usual transmission time is and then sends what it has when that timer fires. This will give you batching for the most efficient transmission at larger scale, but should deliver most packets in a fast enough time to deliver the user experience you want.

A more advanced implementation would gauge the activity level and deliver a faster experience (shorter batching time period) when load is light and allow the batching time period to go update when the activity level is high. This assumes that batching more updates into a single packet is the more efficient way to deliver things from a network point of view and client/server processing point of view so you want to move that direction when load is high and move more to the low lag side of things when load is low.

Let the desired experience drive your design goals, then figure out what technology solutions are needed to deliver that desired experience at load and design a self regulating backoff for very high loads.

---
Tags: node.js, user-experience, websocket, packet
---


# Question
Title: How do I dynamically grow a voxel world in all directions with chunks?
I've organized a Voxel world already but the problem is that it can only "grow" outwards. As a result, there is a single corner where it grows from, then outwards from there on. I want to be able to grow the world from all directions.

I figured this would be best done by maintaining a list of chunks with their world position, but that would require iterating through each chunk just to find the one I'm looking for and checking which chunks need to be created (or just to do anything involving that chunk) and it would be a mess to figure out which ones are loaded and which ones aren't.

How do existing Voxel games (such as Minecraft) deal with this issue?

# Answer
I once wrote a voxel game (clone of Minecraft). What I did was using of course using negative coordinates. To have on O(1) access time to the chunks, I used two mapping functions:

1. From Z (whole numbers) to N (natural numbers).
2. From (NxN) (couple of natural numbers) to N (natural numbers).

For (1), use a simple function that multiplies by 2 for positive and multiplies by -2 and adds 1 for negative numbers. For (2), take a look at Cantor's pairing function.
> 1 votes

# Answer
Basically its what @DanielHolst said, you can use negative coords and expand in all directions.

As for storing your loaded chunks for fast access and checking you could use `std::unordered_map`, Just `#include <unordered_map>`, then your code looks something like this:

```
std::unordered_map< std::pair< int, int >, Chunk* > ChunkMap;

// For adding a chunk, first checks if it exists.
if( ChunkMap.find( std::make_pair( newcoord.x, newcoord.y ) ) == ChunkMap.end() )
{
    ChunkMap[std::make_pair( newcoord.x, newcoord.y )] = new Chunk(newcoord);
}

```

Please note that you might want to use your own vec2 class directly, and might need to supply your own hash function for `unordered_map` to be able to use it as key. Also if you want 3D infinity, then you should use a vec3 not a vec2 obviously, and supply a hash function for that. (A hash function takes a coordinate and creates an unique ID from it.)
> 0 votes

---
Tags: c++, performance, optimization, voxels
---


# Question
Title: 2D motion synthesis for a human character
I want to make the player controlled character of my two dimensional sidescroller responsive to environmental forces, while still being controllable.

I read about the commercial software product Euphoria, which is used to synthesize the motions of characters for example in GTA IV.

I realize that three dimensional motion synthesis is so complex that I will not be able to use it in my games. Luckily I am creating a two dimensional sidescroller. I assume that it is a lot easier to synthesize motion in two dimensions.

Actually I found a relevant scientific paper from 1994 about exactly this topic. After a quick flip it is a rather complicated and not a fully complete (ready to be ported to C#) concept. But is it outdated? What are common approaches to solving this problem in the 21st century? Do you know 2D games using a motion synthesis concept?

# Answer
The article you mentioned seems to be intended to use physical simulations to help in generating articulated movement animations. Ragdoll physics, for instance, is a form of physical simulation that can be used to animate a dead body (just like a rag doll falling!), but due to computing resource limitations (specially in mobile devices) those effects are sometimes pre-calculated with physics engines and recorded as animation clips for later use during gameplay. I didn't understand if you want something like that, but you can check these very good physic engines: Box2D (2D) and Bullet Physics (more useful for 3D games). Here you can find a nice ragdoll example with Box2D: http://www.jangaroo.net/files/examples/flash/box2d/

You didn't explain in details what your needs are, except by mentioning that you want your character to be influenced by the environment. That might means a lot of different things, but I am really imagining that you want the make the movement of your character harder by effect of opposed wind or easier by effect of a sliding surface (ice), for instance.

*By the way, you could update your question and make it a little clearer (or more direct to the point), so it will be easier for you to get more answers and help from other people.*

Considering that I understood correctly what you want, the common approach for achieving changes in character movement is programming the environmental effects yourself. That is relatively easy to do, consume significantly less resources than using physics engines, and allow you to have more control of the effects of environmental events (which are normally related to the game mechanics). If your character is controled by simple vector math, the environment effects can be introduced as changes in the charecter current velocity vector. I suggest you to study the different "steering beahviours" and try to combine them to achieve what you want. The following references might help you with that:

EDIT: In case what you want is indeed related to affecting articulated parts of a character, you can add local colliders at each part and calculate the "environmental effects" yourself at each part using force vectors, and them compose the forces in a similar fashion to what I've suggested at this post: How to calculate new velocities between resting objects (AABB) after accelerations?
> 0 votes

# Answer
So, how i see it, and from the Wikipedia mentioned above, there are two games to look at:

QWOP: 2 legs ( google it) CLOP: 4 legs ( manual control)

I don't think there are other "powered ragdoll games" .. if someone knows add it here.
> -3 votes

---
Tags: animation, ai, character, inverse-kinematics
---


# Question
Title: SteamCMD Failed to get application info app
I am trying to push my first build to a depot and I keep getting this error and I can't figure out why.

```
Logged in OK
Waiting for license info...OK
[2015-05-17 20:11:58]: ERROR! Failed to get application info for app <appID> (check login and subscription)

```

I am using SteamCMD obviously, and I am logging in with the account that I use to login to Steamworks.

Has anyone had this problem before? If so, what is the fix? Thanks.

# Answer
> 1 votes
This appears to be a configuration problem on Steam's side. If you contact them through the SteamDev Group discussion on this error. That link goes to a private page for Steam Developers, so anyone with this problem should already have access and can follow the link. If you contact them, it looks like they can get it resolved fairly quickly. On the order of 24 hours.

---
Tags: steam
---


# Question
Title: Basic game loop, what does Update() and HandleInput() mean to you?
I have been developing a game and until now I have been handling input like so:

1. Player presses a key
2. HandleInput() acknowledges a key is pressed calls a function within the `Player` class which increments the Players position by a pre-determined amount.
3. Update() sets the players sprite to be at the players position.
4. Draw() renders the players sprite.
5. Return to Step 1.

Now my question is this, should I continue to run my loop in this way or should I implement the following:

* HandleInput() sets a state within the `Player` class which when Update() is called the Player object checks if it is in a state of motion and updates its location appropriately, before updating the sprite to its new location.

This question arose within me while I was altering my loop so that only the Update() function had a maximum refresh rate (60 cycles per second) and I realized I was unsure how I should appropriately communicate events to the objects on how they should act.

*I did not include any code as we're discussing in pseudo-code if you feel some is required let me know.*

# Answer
> 0 votes
The second possibility seems better, for two reasons:

## Each part does have its own job.

The `Update` function should have every sprite movement handling, while `HandleInput` should only listen input and tell `Update` what to do.

## Give more possibility

Imagine that you would want to give some inertia to your player. The code to make it move would become more complex, maybe something like that:

```
const sf::Vector2f& movement = player.currentMovement();
if (player.isMoving())
{
    player.speed += 1.0;
}
player.speed *= 0.95;
player.move(movement * player.speed);

```

Instead of a simple `player.move(movement)`.
So here the code become longer. And it would become even more if you do a more complex movement system.

This piece of code in `HandleInput` function would seems to not be at its place, as it is clearly a data update. But it would look better to see it in `Update` function, while `movement` variable and player moving boolean would be initialized in `HandleInput`, depending of which keys are currently pressed.

---
Tags: movement, game-loop, input, sfml
---


# Question
Title: How to preserve generated textures in XNA?
My game generates small "minimaps" for each room you go to, which are rendered onto render targets then stored in textures and displayed on the world map. When the game is saved, each new minimap is saved on the hard drive. If the game is in full screen and the user minimizes the game, the minimaps that were generated, not loaded off the hard drive, will become blank.

Since I don't know exactly what render targets are doing in the background, I have no idea how to prevent this, or restore the textures if they are lost.

How can I prevent/workaround this problem?

EDIT:
I did do

```
textureToDisplay = (Texture2D) textureRenderTarget;

```

but alas, this conversion doesn't seem to prevent the issue from occuring. I believe this is because `textureToDisplay` is still a reference to a render target. Perhaps I need to perform a deep clone? If so, how?
Also, the preserve contents thing doesn't work for this situation either.

# Answer
> 0 votes
I found a fix:

```
Texture2D texture = createBlankTexture(128, 128);
Color[] data = new Color[128*128];
renderTarget.getData<Color>(data);
texture.setData<Color>(data);

```

If my understanding is correct, this moves the memory from VRAM into RAM. Casting the render target to a texture does not move the memory into RAM, so it was still subject to VRAM shenanigans.

# Answer
> 0 votes
Store the rendertarget into a Texture2D like this:

```
Texture2D texture = (Texture2D)renderTarget;

```

The graphics device clear clears all rendertargets, so that is why you need to store it elsewhere. You could do a rendertargetusage.preserve ( https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.rendertargetusage.aspx ) but that comes with a performance cost. Rendertarget2D is based on Texture2D so the cast is usually better.

---
Tags: c#, xna, textures, rendering
---


# Question
Title: Can I use the graphics or music of an abandoned game in my game?
I was wondering that if a game has been officially closed by the owner can I use their graphics or music they used in their game?

# Answer
> 5 votes
No, you can not.

Just because a piece of media is no longer used commercially does not mean that its copyright is void. Even when the company which originally held the copyright does no longer exist, their assets are not safe to use because as part of the liquidation of the company those rights might have gotten transferred to some other company.

---
Tags: graphics, music, licensing
---


# Question
Title: LibGDX: Content appears stretched although I'm using a ScreenViewport
I just fixed another issue regarding the scaling inside a `ScreenViewport`. And yet another problem arises:

If I'm understanding the wiki correctly, a `ScreenViewport` does not scale or stretch the content in any way. In my case it somehow does:

When the game is started, it looks like this:

And after resizing the window (e.g. making it wider) it looks like this (obviously stretched...):

(The code is mostly still the same as in the linked question).

Since I couldn't find a example of using a `ScreenViewport` with `unitScale` yet, I have no idea how to make this work... Thanks in advance :)

# Answer
So, to make it work I needed to call `useCustomViewport(x, y, width, height)` on the `rayHandler` inside of `resize(width, height)`.
> 0 votes

# Answer
You should call viewport.update(width, height); inside resize method of screen.

```
@Override
public void resize(int width, int height) {
    viewport.update(width, height);
}

```

More info here https://github.com/libgdx/libgdx/wiki/Viewports
> 1 votes

---
Tags: libgdx, camera, viewport
---


# Question
Title: How can I forward GLFW's keyboard input to another object?
I'm having trouble trying to execute keyboard events in a another class with GLFW3. The problem I'm having is that GLFW3 uses a static function for input as shown:

```
static UI u;
...
...
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    u.controls(window, key, action);
}

```

`u` is also static and controls holds the the input for WSAD keys (the only way I could get get key events). From here, pressing a key works displaying which key is pressed in the console window. The trouble I'm having is trying to used the key pressed to manipulate a variable in another class.

I have another class called MainMenu that has the function `update().` Is there a way I can use my UI class within this function?

# Answer
> 18 votes
You're taking the wrong approach with a static UI class. The usual way to "bounce" from a static callback to an instance function is to store something capable of making the jump in a place that is accessible from the static callback.

Most APIs, like GLFW and native Win32, that require these sorts of static callbacks provide a way to make the association above. GLFW windows have a pointer-sized block of storage that you can assign to: the *user pointer*. You can get or set this user pointer as needed.

A very common pattern is to have some kind of `Game` class that has methods like "HandleKeyPress(Key key)" or whatnot. When you program starts, you create the `Game` object and do all your GLFW initialization, then stuff the `Game` pointer into the user data storage:

```
int main () {
  GLFWindow * window = ... create GLFW window ...
  Game game(... game constructor parameters ...);

  glfwSetWindowUserPointer(window, &game);

  ... main game loop ...
}

```

Then, your keyboard callback (and all other static callbacks) can unpack the `Game *` from user pointer storage and forward to it:

```
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
  Game * game = reinterpret_cast<Game *>(glfwGetWindowUserPointer(window);
  game->HandleKeyDown(...);
}

```

The `HandleKeyDown` method on the `Game` instance can forward along to your UI object if needed (or, if you really *only* need keyboard input for the UI object you could just stuff a pointer to your UI object in the user storage, however, stuffing something like the game or something higher-level is generally better since you only have one pointer per window to use).

# Answer
> 0 votes
The way I got around that for now was in using a singleton object, when I needed to access the class I could just retrieve the pointer to the singleton:

```
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    InputManager * in_manager = InputManager::get_instance();
    in_manager->handle_key_press( params)
}

```

Somehting like that.

---
Tags: opengl, c++, keyboard, glfw
---


title: SSAO all jagged

text:
# Question
Title: SSAO all jagged
So I've been working on SSAO for awhile, and I thought I had it right, untill I loaded up the sponza scene that accompanied the SAO technique I'm implementing (http://graphics.cs.williams.edu/papers/SAOHPG12/)

Here's the fully rendered picture:

And here's the SAO texture (couldn't disable the other channels for previewing, so its very red)

The crease in the cloth in the middle should be smooth, not all jaggedy. Even after the blurring, it's still jaggy, compared to the screenshots in the document.

I can't quite fathom why it is nor why these symptoms occur. I've implemented it pretty much as the technical document says.

The normals are reconstructed, but so are they in their shader code, so that shouldnt be the problem.

```
#ifndef SSAO_PIXEL_HLSL
#define SSAO_PIXEL_HLSL

#include "Constants.h"
#include "Common.hlsl"

static const float gNumSamples = 11.0;
static const float gRadius = 1.0;
static const float gRadius2 = gRadius * gRadius;
static const float gProjScale = 500.0;
static const float gNumSpiralTurns = 7;
static const float gBias = 0.01;
static const float gIntensity = 1.0;
// If using depth mip levels, the log of the maximum pixel offset before we need to switch to a lower
// miplevel to maintain reasonable spatial locality in the cache
// If this number is too small (< 3), too many taps will land in the same pixel, and we'll get bad variance that manifests as flashing.
// If it is too high (> 5), we'll get bad performance because we're not using the MIP levels effectively
static const uint gMaxOffset = 3;
static const uint gMaxMipLevel = 5;

cbuffer SSAOConstants : register(CBUFFER_REGISTER_PIXEL)
{
    float4x4 gInvProjMatrix;
    float2 gScreenSize;
};

Texture2D gDepthTexture : register(TEXTURE_REGISTER_DEPTH);
SamplerState gPointSampler : register(SAMPLER_REGISTER_POINT);

float3 reconstructNormal(float3 positionViewSpace)
{
    return normalize(cross(ddy(positionViewSpace), ddx(positionViewSpace)));
}

/** Read the camera - space position of the point at screen - space pixel ssP + unitOffset * ssR.Assumes length(unitOffset) == 1 */
float3 getOffsetPosition(const int2 ssC, const float2 unitOffset, const float ssR) {
    // Derivation:
    //  mipLevel = floor(log(ssR / MAX_OFFSET));

    // TODO: mip levels
    int mipLevel = 0; //TODO: clamp((int)floor(log2(ssR)) - LOG_MAX_OFFSET, 0, MAX_MIP_LEVEL);

    uint2 ssP = uint2(ssR*unitOffset) + ssC;

    const float2 texCoord = float2(ssP.x / gScreenSize.x, ssP.y / gScreenSize.y);

    float depth = gDepthTexture.Sample(gPointSampler, texCoord).r;
    float3 P = reconstructViewPosition(depth, texCoord, gInvProjMatrix);

    // Divide coordinate by 2^mipLevel
    //P = gPositionTexture.Load(int3(ssP >> mipLevel, mipLevel)).xyz;
    //P = mul(gViewMatrix, float4(P, 1.0)).xyz;

    return P;
}

float2 tapLocation(int sampleNumber, float spinAngle, out float ssR)
{
    // Radius relative to ssR
    float alpha = float(sampleNumber + 0.5) * (1.0 / gNumSamples);
    float angle = alpha * (gNumSpiralTurns * 6.28) + spinAngle;

    ssR = alpha;
    return float2(cos(angle), sin(angle));
}

float sampleAO(uint2 screenSpacePos, float3 originPos, float3 normal, float ssDiskRadius, int tapIndex, float randomPatternRotationAngle)
{
    float ssR;
    float2 unitOffset = tapLocation(tapIndex, randomPatternRotationAngle, ssR);
    ssR *= ssDiskRadius;

    // The occluding point in camera space
    float3 Q = getOffsetPosition(screenSpacePos, unitOffset, ssR);

    float3 v = Q - originPos;

    float vv = dot(v, v);
    float vn = dot(v, normal);

    const float epsilon = 0.01;
    float f = max(gRadius2 - vv, 0.0);

    return f * f * f * max((vn - gBias) / (epsilon + vv), 0.0);
}

float ps_main(const float4 position : SV_Position) : SV_Target0
{
    const uint2 screenSpacePos = (uint2)position.xy;
    const float2 texCoord = float2(screenSpacePos.x / gScreenSize.x, screenSpacePos.y / gScreenSize.y);

    float depth = gDepthTexture.Sample(gPointSampler, texCoord).r;
    float3 originPos = reconstructViewPosition(depth, texCoord, gInvProjMatrix);
    float3 normal = reconstructNormal(originPos);

    // Hash function used in the HPG12 AlchemyAO paper
    float randomPatternRotationAngle = (3 * screenSpacePos.x ^ screenSpacePos.y + screenSpacePos.x * screenSpacePos.y) * 10;
    float ssDiskRadius = -gProjScale * gRadius / originPos.z;

    float ao = 0.0;
    for (int i = 0; i < gNumSamples; i++)
        ao += sampleAO(screenSpacePos, originPos, normal, ssDiskRadius, i, randomPatternRotationAngle);

    float temp = gRadius2 * gRadius;
    ao /= temp * temp;

    float A = max(0.0, 1.0 - ao * gIntensity * (5.0 / gNumSamples));

    return A;
}

#endif

```

EDIT: added additional picture, SSAO of a lions head. Surely it looks abit off? does it say anything of what could be wrong?

# Answer
A little late I guess but anyway it can be helpful, so here's my thought.

# The problem

I think your problem might be caused by the fact that you project a ray from your hemisphere (or sphere) to sample depth, like this **in theory** :

But in practice, your surface isn't going to be a smooth line (like shown above), but it's going to be jagged like so :

In red, you can see what the surface actually looks like when you sample from it. Here, a problem arises : you'll have rays that are, **in theory**, above the surface but in practice will be under the surface and then get occluded.

Of course, the problem gets worse when the resolution of the depth buffer is low.

# Potential solution

A solution to this problem would be to limit the area of where to account for rays under or above the surface. Here's a picture of what I'm talking about :

(Yes, every pictures are done with MS Paint...)

The areas in gray are the surfaces that you're not going to discard in your computation of the effect.

To do that I would compute the dot product of the ray and the surface normal and discard the ray if it is under a certain threshold set beforehand. Also, try playing with this value until you get a decent result.

In doing so, you'll not get falsely occluded rays and you'll avoid your heavily occluded areas.

Hope this helps anyone ;)
> 1 votes

# Answer
this looks like a depth encoding precision issue. check your near and far. this is just causing some steps because the quantization is bad, your AO is evaluating corners where there are none. I doubt the problem is caused by `ddx` and `ddy` where I first (and I guess you too) suspected, because the patterns are rotating ! this is impossible with ddx, you would get screen aligned artefacts. (2.2 quads) so definitely here, check your framebuffer formats, and the projection matrix to reduce the depth range (most importantly, push the near away).
ALso check that your HLSL is executing fp32 (single) and not fp16 (half float).
> 0 votes

---
Tags: directx, directx11, ssao
---


title: Unity 5.2 --- Animator window / tab

text:
# Question
Title: Unity 5.2 --- Animator window / tab
I have downloaded the latest `Unity 5.2.0f3` so I wondered if it is just me or others are having a similar problem: When I double-click on an `animator controller` to launch it, the animator tab/window appears, but when I run the editor, I don't get the usual flow, operations, etc... I only get a static view of the states and transition arrows between them. My parameters do not show the changes they go through either.

I have multiple animations and can switch between them when certain game conditions occur, but nothing really shows when I do so, to see the flow of control, what happens, what goes wrong, the switching, the progress bar, etc...

# Answer
Its the age old problem. Don't know whether it can be called a problem tho :P . So what you need to do is , once you start play in the editor , and have the animator window docked on one side. Just go and click the object in the hierarchy for which you want to analyse the animation flow. And the animator window will start showing the states and the progress bar.
> 1 votes

---
Tags: unity, mecanim
---


title: How do I play a video file in OpenGL?

text:
# Question
Title: How do I play a video file in OpenGL?
Is there a library that will let me load a movie file and play it in an OpenGL application? Or maybe just a code sample that someone has lying around? I'm also using GLUT, if that makes a difference. I guess file format doesn't matter, although currently my movie is in AVI format.

# Answer
Well, there's this very ancient tutorial that plays an AVI video using fixed function GL and the Windows API.

**I don't recommend** using this setup, since it is very outdated, but the concept is basically valid. Get each frame of the video and use it to update an OpenGL texture. That simple.

If you run into performance issues, then you can start thinking about optimizing with things like Pixel Buffer Objects.
> 4 votes

# Answer
If you're happy to use the ogg theora format, then you could use the TheoraPlay lib. There's a fully functioning plugin for the Duality engine here that you could use for reference - https://github.com/Andrea/DualityOgvPlayerPlugin. It works with opengl.
> 1 votes

# Answer
First off, you might want to check these questions / answers out. I don't know how much of either is iOS specific, but they might help:

Beyond that, limitz/AV3D is a somewhat recent C++ project uses libavcodec to stream a movie into an OpenGL texture
> 1 votes

---
Tags: opengl, video
---


# Question
Title: How to design programatically a game map like Risk?
I'm making a quiz-game based on map territories with a system similar to the Risk game (except there are no tanks but tickets).

The map isn't the world but a custom map that I designed and I'll finish in the future, I just made the logic links among territories.

There are 10 territories who represent 10 different matters. The game I'm developing is for Android (Java), but I'm writing a prototype of the map in C# with Visual Studio to see if the idea of the map is good.

Now, I'm not asking for C# code to use in my app, I'm asking for a programming strategy I should use to implement my map in Code.

I wrote the class `Zone` to define each territory. I also wrote the class `GameMap` which implements 10 different Zones.

In the game logic, it's expected that just as risk, to attack 1 territory, you must have one near it. **How can I implement at best this concept, of near and far territories in a dynamic and not long-static way?**

The final result of what I want would be: I decide which territory attack in order to my owned territories. How can I proceed being as much as dynamic as I can and not write really long and in-efficient code?

EDIT: I'm no more looking for C# help. I'm directly implementing the map in Java and Javascript in both Client and Server sides.

# Answer
> 4 votes
Like @Anko suggested, you should use a graph as data structure for your game map. If you use the this implementation of a graph in Java as a starting point you can represent your map as follows:

```
Graph<Zone> gameMap = new Graph<>();

Zone zone1 = new Zone("Zone1");
Zone zone2 = new Zone("Zone2");
Zone zone3 = new Zone("Zone3");
Zone zone4 = new Zone("Zone4");
Zone zone5 = new Zone("Zone5");
Zone zone6 = new Zone("Zone6");
Zone zone7 = new Zone("Zone7");
Zone zone8 = new Zone("Zone8");
Zone zone9 = new Zone("Zone9");
Zone zone10 = new Zone("Zone10");

gameMap.addEdge(zone1, zone2);
gameMap.addEdge(zone2, zone3);
gameMap.addEdge(zone2, zone4);

```

If you want to check if you can attack zone2 from zone1 you can just do

```
// can attack zone2 from zone1
gameMap.hasEdge(zone1, zone2);

```

**Edit:** I reimplemented the Java version in Javascript. You can use it like the Java version.

Here you can find the complete implementation of the above example in Java and Javascript.

# Answer
> 0 votes
I think you would have to manually define which zones are neighbouring each other - unless you can programmatically parse your map to figure this out automatically.

For example with a class attribute like `int neighbouringZonesIds[];` that you have to fill.

# Answer
> 0 votes
Here's an alternative to the graph approach, if your map is made up of large grids (I've never heard of Risk played similar games to what you've described).

Have a `World` containing `Zone` objects. Each `Zone` has an X and Y coordinate. This saves you the trouble of having to add edges.

If Zone 1,1 only has the neighbour Zone 1,2 then the player may only cross between these two - you get the idea.

---
Tags: c#, maps
---


# Question
Title: How can I implement child objects that follow the movement of a parent?
I'm looking for a way to have a character, let's call it "root," with a number of other similar characters attached to it. Let's call them children. When the root changes position the children follow and update their own position by their movement patterns.

My objective isn't for the child objects to move 1:1 like the root but to react to it's movement and follow the object loosely. So if the root moves upwards then child follows afterwards with it's own velocity.

Could someone guide me about how to achieve this kind of behavior of objects moving relative to others? About what sort of architecture would fit best for this kind of problem?

# Answer
The A\* path finding algorithm can be used by the "Children" to arrive at a certain destination. You could use this algorithm and only use the next node (since the destination's position isn't necessarily static, aka the "Children" follow the "Root" even whilst it is moving). **Path finding is expensive as it is. Here, you'd be (re-)running the algorithm whenever the "Root" changes position.**

Another approach is to make the "Children" walk in the direction of the "Root", ignoring the fact that there may be barriers in-between them and the "Root". **This is a cheap approach but the "Children" may become stuck.**

To make the "Children" loosely follow the "Root", only instruct them to follow the "Root" when they are X distance away from them, aka not immediately. Make them stop following when they are less than X distance away from "Root" again, perhaps making them walk Y or 2Y in a random direction, once they get close enough, to make things seem more real and "Loose".

To make the following seem more "Loose", increase the speed of the "Children" slightly when they are further away from the "Root". For example, when the "Root" moves away, the "Children" start slowly following and gradually speed up.
> 1 votes

---
Tags: physics, libgdx
---


# Question
Title: Strange SSAO effect (wrong position/normal textures in view space?)
I try to create an SSAO effect in my game engine (DirectX 11, C++), based mainly on gamedev.net tutorial by José María Méndez. Unfortunately, it doesn't cover texture-creating problem (normals, position).

In the first pass I create the normal texture and then I also read the depth buffer as texture (it's possible since I create the shader resource view and unbind the depth buffer in second pass). **Both should be in view space.**

I've not implemented blur yet (I will do it later), but I have some problems right now. I believe it's due to **wrong calculation of textures or wrong method of transforming data from them**, rather then incorrect formula or **parameters' values**.

My guesses of what could went wrong:

* normal texture calculation (in view space) - but it looks **ok**,
* position texture calculation (in view space) & depth to position transformation,
* inverted projection matrix calculation,
* something is not normalized or saturated and it should be,
* parameters (however they should not have such an impact on output)?

## My textures

Diffuse (`textures[0]`, not really used here, just for comparison):

Normal (`textures[1]`, should be in view space):

I get them in first pass **vertex shader** (pixel shaders do just `output.normal = input.normal`):

```
output.normal = float4(mul(input.normal, (float3x3)world), 1);
output.normal = float4(mul(output.normal, (float3x3)view), 1);

```

Depth buffer texture (`textures[2]`, it's hard to see anything because of low differences in values, but I believe it's ok):

To display it I use:

```
float depth = textures[2].Sample(ObjSamplerState, textureCoordinates).r;
depth = (depth + 1.0f) / 2.0f;
color.rgb = float3(depth, depth, depth);

```

After contrast correction in external program (I don't use it shader, but it's better for eyes):

The depth buffer description:

```
//create depth stencil texture (depth buffer)
D3D11_TEXTURE2D_DESC descDepth;
ZeroMemory(&descDepth, sizeof(descDepth));
descDepth.Width = settings->getScreenSize().getX();
descDepth.Height = settings->getScreenSize().getY();
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = settings->isDepthBufferUsableAsTexture() ? DXGI_FORMAT_R24G8_TYPELESS : DXGI_FORMAT_D24_UNORM_S8_UINT; //true
descDepth.SampleDesc.Count = settings->getAntiAliasing().getCount(); //1
descDepth.SampleDesc.Quality = settings->getAntiAliasing().getQuality(); //0
descDepth.Usage = D3D11_USAGE_DEFAULT;
descDepth.BindFlags = settings->isDepthBufferUsableAsTexture() ? (D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE) : D3D11_BIND_DEPTH_STENCIL; //true
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;

```

And far/near plane (they have an impact on depth buffer texture) are set to `nearPlane = 10.0f` (`1.0f` does not change too much and objects are not so close to camera) and `farPlane = 1000.0f`.

Based on it I create the position in view space (I don't save it to texture, but if I output it to screen it looks like that):

Each pixel here is computed by:

```
float depth = textures[2].Sample(ObjSamplerState, textureCoordinates).r;
float3 screenPos = float3(textureCoordinates.xy* float2(2, -2) - float2(1, -1), 1 - depth);
float4 wpos = mul(float4(screenPos, 1.0f), projectionInverted);
wpos.xyz /= wpos.w;
return wpos.xyz;

```

And `projectionInverted` is transferred to shader with:

```
DirectX::XMFLOAT4X4 projection = camera->getProjection();
DirectX::XMMATRIX camProjection = XMLoadFloat4x4(&projection);
camProjection = XMMatrixTranspose(camProjection);
DirectX::XMVECTOR det; DirectX::XMMATRIX projectionInverted = XMMatrixInverse(&det, camProjection);
projectionInverted = XMMatrixTranspose(projectionInverted);
cbPerObj.projectionInverted = projectionInverted;
....
context->UpdateSubresource(constantBuffer, 0, NULL, &cbPerObj, 0, 0);
context->VSSetConstantBuffers(0, 1, &constantBuffer);
context->PSSetConstantBuffers(0, 1, &constantBuffer);

```

I believe that `camera->getProjection()` returns good matrix, as I use the same one to build the `viewProjectionMatrix` for objects which is ok (I see the right vertices in right places). Maybe something with transpose?

Random (`textures[3]`, normal) - it's the texture from tutorial, just in `.tga` format:

The random texture is tile-less (it's repeatable, when you put one texture next to another). If I render it with `getRandom(uv)` for the whole screen I get (the `float2` result displayed as red and green):

And the result:

It looks like "some shading" **but nothing like SSAO component** (it's not yet blurred or mixed with light/diffuse anyway). I guess it's more similar to phong shading then to actual SSAO (no shades around "deep corners" etc.)

The SSAO (second pass) shader:

```
//based on: http://www.gamedev.net/page/resources/_/technical/graphics-programming-and-theory/a-simple-and-practical-approach-to-ssao-r2753

Texture2D textures[4]; //color, normal (in view space), position (depth), random
SamplerState ObjSamplerState;

cbuffer cbPerObject : register(b0) {
    float4 notImportant;
    float4 notImportant2;
    float2 notImportant3;
    float4x4 projectionInverted;
};

cbuffer cbPerShader : register(b1) {
    float4 parameters; //randomSize, sampleRad, intensity, scale
    float4 parameters2; //bias
};

struct VS_OUTPUT {
    float4 Pos : SV_POSITION;
    float2 textureCoordinates : TEXCOORD;
};

float3 getPosition(float2 textureCoordinates) {
    float depth = textures[2].Sample(ObjSamplerState, textureCoordinates).r;
    float3 screenPos = float3(textureCoordinates.xy* float2(2, -2) - float2(1, -1), 1 - depth);
    float4 wpos = mul(float4(screenPos, 1.0f), projectionInverted);
    wpos.xyz /= wpos.w;
    return wpos.xyz;
}

float3 getNormal(in float2 textureCoordinates) {
    return normalize(textures[1].Sample(ObjSamplerState, textureCoordinates).xyz * 2.0f - 1.0f);
}

float2 getRandom(in float2 textureCoordinates) {
    return normalize(textures[3].Sample(ObjSamplerState, float2(1980,1050)/*screenSize*/ * textureCoordinates / parameters[0]/*randomSize*/).xy * 2.0f - 1.0f);
}

float doAmbientOcclusion(in float2 tcoord, in float2 textureCoordinates, in float3 p, in float3 cnorm) {
    float3 diff = getPosition(tcoord + textureCoordinates) - p;
    const float3 v = normalize(diff);
    const float d = length(diff)*parameters[3]/*scale*/;
    return max(0.0, dot(cnorm, v) - 0.2f/*bias*/)*(1.0 / (1.0 + d))*parameters[2]/*intensity*/;
}

float4 main(VS_OUTPUT input) : SV_TARGET0{

    float2 textureCoordinates = input.textureCoordinates;

    //SSAO

    const float2 vec[4] = { float2(1,0),float2(-1,0), float2(0,1),float2(0,-1) };

    float3 p = getPosition(textureCoordinates);
    float3 n = getNormal(textureCoordinates);
    float2 rand = getRandom(textureCoordinates);

    float ao = 0.0f;
    float rad = parameters[1]/*sampleRad*/ / p.z;

    //**SSAO Calculation**//
    int iterations = 4;
    for (int j = 0; j < iterations; ++j) {
        float2 coord1 = reflect(vec[j], rand)*rad;
        float2 coord2 = float2(coord1.x*0.707 - coord1.y*0.707, coord1.x*0.707 + coord1.y*0.707);

        ao += doAmbientOcclusion(textureCoordinates, coord1*0.25, p, n);
        ao += doAmbientOcclusion(textureCoordinates, coord2*0.5, p, n);
        ao += doAmbientOcclusion(textureCoordinates, coord1*0.75, p, n);
        ao += doAmbientOcclusion(textureCoordinates, coord2, p, n);
    }
    //ao /= (float)iterations*4.0;
    //ao /= (float)parameters[1]/*sampleRad*/;
    ao = 1 - (ao * parameters[2]/*intensity*/);

    //ao = saturate(ao);
    //**END**//

    //Do stuff here with your occlusion value ??ao??: modulate ambient lighting, write it to a buffer for later //use, etc.

    //SSAO end

    color = ao; //let's just output the SSAO component for now
    return float4(color.rgb, 1.0f);
}

```

I provide those parameters (I was trying to play with them, they change the result quality etc. but not the overall effect):

```
getShader()->setParameter(0, 64.0f); //randomSize
getShader()->setParameter(1, 10.0f); //sampleRad
getShader()->setParameter(2, 1.0f); //intensity
getShader()->setParameter(3, 0.5f); //scale
getShader()->setParameter(4, 0.0f); //bias (also 0.2f sometimes)

```

Note that I've commented out `ao /= (float)iterations*4.0; ao /= (float)parameters[1]/*sampleRad*/;` just because that way I can see anything (in other case the differences in SSAO component tones are too tiny - but that can be an problem with wrong parameters).

## edit #1

As `@AndonM.Coleman` suggested I output the normal texture to screen with `textures[1].Sample(ObjSamplerState, textureCoordinates) *0.5f + 0.5f` instead of just `textures[1].Sample(ObjSamplerState, textureCoordinates)`:

Also, I tried to remove `*2.0f - 1.0f` part from `getNormal(...)` and it gave me another result for SSAO component:

It's still wrong, I don't know if it's closer or further from "good". Maybe, according to `@AndonM.Coleman` (if I've understood him) it has something to do with the formats of the buffers? My formats are:

```
#define BUFFER_FORMAT_SWAP_CHAIN DXGI_FORMAT_R8G8B8A8_UNORM

//depth buffer
//I don't use it: #define BUFFER_FORMAT_DEPTH DXGI_FORMAT_D24_UNORM_S8_UINT
#define BUFFER_FORMAT_DEPTH_USABLE_AS_TEXTURE DXGI_FORMAT_R24G8_TYPELESS
//I don't use it: #define BUFFER_FORMAT_DEPTH_VIEW DXGI_FORMAT_D24_UNORM_S8_UINT
#define BUFFER_FORMAT_DEPTH_VIEW_AS_TEXTURE DXGI_FORMAT_D24_UNORM_S8_UINT
#define BUFFER_FORMAT_DEPTH_SHADER_RESOURCE_VIEW DXGI_FORMAT_R24_UNORM_X8_TYPELESS

#define BUFFER_FORMAT_TEXTURE DXGI_FORMAT_R8G8B8A8_UNORM

```

I really don't want to use slower formats if it's not necessary.

## edit #2

Changing the `1 - depth` to `depth - 1` output new (and strange, I guess) position texture:

And the SSAO component changes to:

Note that I still have the original `ao /= (float)iterations*4.0; ao /= (float)parameters[1]/*sampleRad*/` commented out to see anything.

## edit #3

Changing the buffer format for texture (and only for it) from `DXGI_FORMAT_R8G8B8A8_UNORM` to `DXGI_FORMAT_R32G32B32A32_FLOAT` gives me nicer normal texture:

Also, changing bias from `0.0f` to `0.2f` and sample radius from `10.0f` to `0.2f` gave me:

It looks better, isn't it? However, I have shadows around objects on the left and inversion of it on the right. What may cause that?

# Answer
To my knowledge, your position output is wrong in both cases. If should look like this:

Or this:

Depending on if you are using Left hand or Right hand coordinate system. You should create a position buffer and skip trying to calculate it from depth until you know what's working and what's not. Create a new rendertarget in the GBuffer pass and just output the position like this:

```
output.Target3 = float4(input.PosV.z, input.PosV.z, input.PosV.z, 1.0f);

```

Your last screenshot looks like a normal problem, are you sure the normals are in view space? If not, the wall to the right should stay dark even if you turn the camera 180 degres and the wall is on the left. Does it or is it still dark on the right side?

If moving the view just slightly causes the dark portions to appear and disappear, it's most likely a projection problem. Like this: (it's the same corner of a room)

Try switching your projection matrix from LH to RH or vice versa, you might have got it mixed up.

Besides that make sure you only decompress normals with "\* 2.0f - 1.0f" if you also stored them with "\* 0.5f + 1.0f". You covered that in the comments but it's worth checking one more time.
> 3 votes

---
Tags: c++, directx, directx11, hlsl, ssao
---


title: XNA 4.0 - Bounding Boxes

text:
# Question
Title: XNA 4.0 - Bounding Boxes
So I'm kind of new to programming and I'm trying to check collision using bounding boxes. I'm currently stuck as to how to call my bounding box within my bounding box function as shown below

```
 public BoundingBox BuildBoundingBox()
    {
        // Create initial variables to hold min and max xyz values for the mesh
        Vector3 meshMax = new Vector3(float.MinValue);
        Vector3 meshMin = new Vector3(float.MaxValue);
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (ModelMeshPart part in mesh.MeshParts)
            {
                // The stride is how big, in bytes, one vertex is in the vertex buffer
                // We have to use this as we do not know the make up of the vertex
                int stride = part.VertexBuffer.VertexDeclaration.VertexStride;

                VertexPositionNormalTexture[] vertexData = new VertexPositionNormalTexture[part.NumVertices];
                part.VertexBuffer.GetData(part.VertexOffset * stride, vertexData, 0, part.NumVertices, stride);

                // Find minimum and maximum xyz values for this mesh part
                Vector3 vertPosition = new Vector3();

                for (int i = 0; i < vertexData.Length; i++)
                {
                    vertPosition = vertexData[i].Position;

                    // update our values from this vertex
                    meshMin = Vector3.Min(meshMin, vertPosition);
                    meshMax = Vector3.Max(meshMax, vertPosition);
                }
            }

            // transform by mesh bone matrix
            meshMin = Vector3.Transform(meshMin, meshTransform);
            meshMax = Vector3.Transform(meshMax, meshTransform);
        }
        // Create the bounding box
        BoundingBox box1 = new BoundingBox(meshMin, meshMax);
        return box1;

    }

```

I'm trying to call box1 (my bounding box) in my update method to check collision however I can't seem to call box1 as it's not in the context of my class.

# Answer
> 1 votes
box1 only resides in that method, but it get's returned so you just have to assign a new BoundingBox object the return value. Then you can access that object in your update function. I'm guessing you have something like this:

```
class MyGame{
 BoundingBox theBox = null;

 public MyGame(){
   theBox = BuildBoundingBox();
 }

 public bool Update(){
   //Do stuff with theBox here:
   theBox.intersects(someOtherBox);
 }
}

```

---
Tags: xna, collision-detection
---


title: Dialog/event system in Java/libGDX

text:
# Question
Title: Dialog/event system in Java/libGDX
I hope that I'm posting this correctly as I'm new to the site, feel free to correct me if I'm in the wrong spot.

As for my issue: I'm working on an 2D side-scrolling platformer game in libGDX, and I've run into an issue that I've considered before but never received a solid answer. Here's an example of what I'm wondering about: In games like, say, the Legend of Zelda, when the player steps on a switch, or catches a torch on fire, this can open a door or release a monster or cause a myriad of other things to happen.

Now, I imagine that this utilizes some sort of Event-trigger relationship or messaging system, but it seems that it would be insane to hardcode all of these events into the game engine itself, even when utilizing an event-based system.

The same goes for tutorial and dialog systems: the player interacts with an NPC, or some sort of in-game object, and the dialog/tutorial continues at certain points.

In my game, I will specifically need to be able to have events triggered after a character does a certain thing, and I will need to be able to have series of dialogues triggered. I think that I know how I could hardcode these things, but I'm going to have numerous levels that I wish to develop with a level editor such as Tiled, instead of hardcoding them. Because of this, I don't know how I would integrate events into such a system.

My questions are: what do game programmers do to avoid hardcoding these things into their games? With something like a massive quest system with tons of dialog, or numerous levels with switches and events to trigger, how are these integrated into the game?

Thank you for any answer you can give me, I'm really stumped on this one :)

P.S. If you need any more clarity on what I'm asking for, please tell me so I can give more detail if needed.

P.P.S I saw this post Level editor event system, how to translate event to game action but I've seen on other pages that people go back and forth on whether to use a scripting language, or some sort of file format like XML or JSON, and it's very confusing...

# Answer
Well, you have to essentially make your engine able to load logic from disk somehow. You could actually code that into your program, but more often people devise a data file format for these purposes.

What in end effect it boils down to is creating a very simple (and not necessarily turing-complete, and not necessarily text-form) programming language. That's why so many game developers just use a scripting language like Lua.

But what you really only need is to build the basic operations into your engine (e.g. spawn a monster, despawn a monster, show a dialog tree, move a monster, add a mission objective, resolve mission, whatever your game requires). Then you give each situation an event or trigger (like "monster killed" or "player inside" or "dialog choice selected").

Then build a data structure that can be used to describe each basic operation. In your on-disk representation of a level, save such a data structure for each event of every object. Whenever an event happens, load the data structure (probably an array of 'em) and do the things it describes.

Many games can get away with this. Some also need some sort of counter variables (plus increment/decrement commands), and maybe a conditional (easiest way to implement: Just give it a variable and a value to check it against, then have it trigger another event). If you're going beyond that, you might probably as well use a real scripting language.

What you save the data structure as in the end doesn't really matter. You can use XML, stick it line-wise in text files, build a binary data structure, whatever you want.

Your data structure can be as easy as an int to describe the operation (i.e. 1 = spawn monster, 2 is despawn etc.), and two strings naming which objects to operate on.
> 2 votes

---
Tags: java, libgdx, game-mechanics, events, data-driven
---


# Question
Title: convert mouse coords to zig-zag isometric
I was wondering, how do I convert mouse coordinates to zig-zag isometric coordinates?

I already know how to convert to isometric using the Diamond approach, so I just need to know about the zig-zag approach. I also know how to get the mouse coordinates as well.

Here is the zig-zag approach (copied from the link below):

Here is the link I used for the definition of drawing both the Diamond and zig-zig isometric approaches.

https://stackoverflow.com/questions/892811/drawing-isometric-game-worlds

Help is greatly appreciated, thanks.

# Answer
I finally managed to solve my own question, by doing some simple linear algebra.

In case anyone is curious, Here is how I solved my problem:

Here is the drawing code:

```
public void drawZigZag(Graphics g)
{
    int offset = 0;

    for(int x = 0; x < mapWidth; x++)
    {
        if(x % 2 == 1)
        {
            offset = tileWidthHalf;
        }
        else
        {
            offset = 0;
        }

        for(int y = mapHeight - 1; y >= 0; y--)
        {
            int sx = (tiles[x][y] % 3) * 64;
            int sy = (tiles[x][y] / 3) * 64;
            int sw = sx + 64;
            int sh = sy + 64;

            int dx = (y * tileWidth) + offset;
            int dy = x * (tileHeightHalf / 2);
            int dw = dx + tileWidth;
            int dh = dy + tileHeight;

            g.drawImage(tileImage, dx, dy, dw, dh, sx, sy, sw, sh, null);
        }
    }
}

```

Here is my final code for selecting a tile's coordinates based on the mouse position:

```
public void getZigZagPos(int x, int y)  // x = mouseX, y = MouseY
{
    int sx = x / tileWidthHalf;
    int sy = y / tileHeight;

    int off = (sx % 2 == 1) ? tileWidthHalf : 0;

    // Solved for y here:

    // dx = (y * tileWidth) + offset
    // dx - offset = y * tileWidth
    // (dx - offset) / tileWidth = y

    // Solved for x here:

    // dy = (x * (tileHeightHalf / 2))
    // dy * 2 = x * tileHeightHalf
    // (2 * dy) / tileHeighHalf = x

    int isoX = (2 * y) / tileHeightHalf;
    int isoY = (x - off) / tileWidth;

    tiles[isoX][isoY] = 2;
}

```
1. I first took the code for drawing the isometric tiles, and solved for y in dx = (y * tileWidth) + offset;
2. Then I took the code for drawing the isometric tiles, and solved for x in dy = x * (tileHeightHalf / 2);
3. Finally just substitute the equation results for the tile's coordinates:

The equation that I solved for x is Substituted for the tile's X coordinate

The equation that I solved for y is Substituted for the tile's Y coordinate

Note, that this method is not pixel-perfect, it simply calculates the tile's bounding box ( Not the actual diamond shape of each tile).
> 1 votes

---
Tags: java, tilemap, isometric, coordinates, mouse
---


# Question
Title: LibGdx Sound start to give an error after loading GameScreen multiple times
I have a LibGdx game, where the user taps on the screen, and a Sound will play. When the user taps on the screen, a texture will "fire" another texture as a missile, and can hit a target, when this target "dies", another sound will play.

I use these two Sounds often in the game, Shooting Sound, and Hit Sound. When I load the game, everything works fine - the sound doesn't get an error when I load multiple instances of the Sound/Textures on level 1 - so it doesn't seem to be related to memory, because this error can appear when I use a lot less instances of sound/textures, but when I have loaded the "game screen" more times, it starts to appear.

The error is only related to two sound-files, one when the user taps the screen, and the other when the "target" dies. So it does only happen when I load Sounds a lot of times.

The problem only occurs when I go to higher levels, and load the game screen more times. I load the same game screen over and over, only with more instances of "targets".

**Error:**

```
W/SoundPool﹕ Sample was not loaded. Waiting for 30ms.
W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
com.mygdx.game.android E/AudioTrack﹕ AudioFlinger could not     create track,     status: -12
com.mygdx.game.android E/SoundPool﹕ Error creating AudioTrack

```

**I load my Sound like this:**

```
 Sound playDeadSound;
 public void playDeadSound(){
 soundDead = Gdx.audio.newSound(Gdx.files.internal("dead.ogg"));
 soundDead.play();
 soundDead.dispose();
  }

```

**Things I have tried**

* To instantiate the Sound file in the create method, and then use the same object over and over.
* I have tried to call soundDead.resume(); instead of play(); to load the sound.
* I have tried to re-sample my audio to 48KHz, and to the lowest (which was around 5-8KHz IIRC).
* I have tried to start out with 40 targets, and I get no errors, and I have tried to start out with 5 targets, and errors start appearing when I go a few levels higher and the targets are 10-15.
* I have tried to remove all other sounds except one of the Sounds that creates the error (Shooting Sound/Hit Sound).
* I have tried to stop and then dispose the sound, and then create it when I call it.
* I have tried to have 2 sound files, and then call them one after another, so they doesn't get used at the same time.

The files are 5KB big each, and around 1 second long. Any ideas on what could cause this error? Thanks!

**Solution:**

The problem was that I reloaded the Sound over and over when I started a new level, hence why the problem never occured when I was at level 1. The problem got fixed when I used the same sound during the whole app's lifetime. A big thanks to Alesegdia for coming up with the answer.

# Answer
If you just dispose the sound, you're trying to play something unexistent.

Also, this is a bad practice because you're constantly creating and destroying a sound when playing it, and that's not needed. Try to get the dispose to the end of the game, place your sound somewhere available and just play or stop it when needed.

This is some sketching code, not saying that's the best designed way.

```
public class Sfx {
    private static Sound deadSound;
    private static long deadID;
    public static void Initialize() {
        deadSound = Gdx.audio.newSound(Gdx.files.internal("deadSound.wav"));
        deadID = deadSound.play(0);
    }
    public static void PlayDeadSound() {
        deadSound.stop(deadID);
        deadID = deadSound.play(1f);
    }
}

...

// at Game::create(), make sure it's called just **ONCE**
Sfx.Initialize();

// somewhere at your game
Sfx.PlayDeadSound();

```
> 3 votes

---
Tags: android, libgdx, sound
---


# Question
Title: Bloom only colors with at least one value equal to 1,
I want to bloom/blur any color that has a 1 in it,

like (1,0,0) and (1,0,1) etc.

The script bellow blooms any color over a threshold, but what I want blooms only specific colors.

'Selective bloom'

```
uniform sampler2D bgl_RenderedTexture;
const float BRIGHT_PASS_THRESHOLD = 0.55;
const float BRIGHT_PASS_OFFSET = 0.08;

#define blurclamp 0.002
#define bias 10.8
#define KERNEL_SIZE 6.0

vec2 texcoord = vec2(gl_TexCoord[0]).st;

vec4 bright(vec2 coo)
{
  vec4 color = texture2D(bgl_RenderedTexture, coo);
  color = max(color - BRIGHT_PASS_THRESHOLD, 0.0);
  return color / (color + BRIGHT_PASS_OFFSET);
}

void main(void)
{
  vec2 blur = vec2(clamp( bias, -blurclamp, blurclamp ));

  vec4 col = vec4( 0, 0, 0, 0 );
  for ( float x = -KERNEL_SIZE + 1.0; x < KERNEL_SIZE; x += 1.0 )
  {
    for ( float y = -KERNEL_SIZE + 1.0; y < KERNEL_SIZE; y += 1.0 )
    {
      col += bright( texcoord + vec2( blur.x * x, blur.y * y ) );
    }
  }
  col /= ((KERNEL_SIZE+KERNEL_SIZE)-1.0)*((KERNEL_SIZE+KERNEL_SIZE)-1.0);
  gl_FragColor = col + texture2D(bgl_RenderedTexture, texcoord);
}

```

is the script I was trying to edit, but I don't know GLSL (I know python)

# Answer
> 3 votes
I'm not entirely clear on what you're asking. When you say "only colors with a 1 in them", are you including colors that have other values but also have a 1 in them? For example, do you want to include a color such as (1.0, 0.5, 0.25)? If so, you can do something like this:

```
vec4 bright(vec2 coo)
{
    vec4 color = texture2D(bgl_RenderedTexture, coo);
    float max = max(max(color.r, color.g), color.b);
    if (max >= 1.0)
    {
        max = 1.0;
    }
    else
    {
        max = 0.0;
    }
    color = color * max;
    return color;
}

```

If you only want colors where the values are exactly 0 or 1, then you need to do some more work. Something like:

```
vec4 bright(vec2 coo)
{
    vec4 color = texture2D(bgl_RenderedTexture, coo);
    bool threshMult = 0.0;
    if (((color.r == 1.0) || (color.r == 0.0)) &&
        ((color.g == 1.0) || (color.g == 0.0)) &&
        ((color.b == 1.0) || (color.b == 0.0)))
    {
        meetsThreshold = max(max(color.r, color.g), color.b);
    }

    color = color * threshMult;
    return color;
}

```

---
Tags: glsl
---


# Question
Title: When someone joins or leaves a room, send the entire user list or just the delta?
I'm developing a game that has a lot of rooms and most rooms will have between 2 and 15 users. On the UI there is a list of all the players currently in the room. I'm wondering, when someone joins a room, should the server send the entire list of players (admittedly not much) to everyone, or just the delta?

Option 1) Send the entire list to the new person joining because he needs all of them and send the one user to the rest of the players because they already know who else is in the room. Possible synchronization issues and harder to code.

Option 2) When someone enters or leaves a room, resend the entire list of players to everyone. No synchronization issues, much easier to code and test, but increased packet sizes.

Which option would you choose or is there a third one? For reference I'm using node.js and socket.io.

# Answer
> 1 votes
Send the whole list. It will probably fit in the minimum packet size of your network.

For example, Ethernet packet size is usually 1500 bytes, and Wifi is usually 2312 bytes. Your upper bound list of 15 user ids (names?) should fit in one, or maybe two what with various overhead & metadata you might have.

And, just generally, get it working, and let evidence guide further optimizations...

# Answer
> 0 votes
A third option of sorts: Sufficiently large (or privacy minded) IRC channels may not send a user list, and may not even send join/part notifications. The IRC client can build up a user list by adding anyone missing when they chat, since e.g. their nick is encoded into the chat message anyways.

The IRC server *may* be configured to send join/part messages, and *may* be configured to send a user list on joining, but it's no big deal if it doesn't. You just end up with an empty user list that's only populated by people actually chatting. The client *may* request a user list and overwrite it's local list *if* it receives a response - but again, no big deal if there's no response.

Different IRC clients end up with only partial user lists in these cases as a result, but that's not actually a big deal. And when the server does send the necessary information, the only sync issues I've run into, when implementing IRC clients and bots, had to do with not properly handling case insensitive identifiers, or mishandling "myself" - nothing to do with the specific protocol style used.

I imagine the server side is similarly straightforward. Doubly so in nodejs, where you don't have to worry about multithreading.

---
Tags: node.js, websocket
---


# Question
Title: How can I compress resources into a single file in Java?
Today I've finished my game, but there's a problem. There're more than 500+ images in my resources folder and I want to compress them into a single file, like other games do (for example put everything in a .pak file). I've searched on the internet, but I can't find something that tells about how to do it with Java.

There's maybe a library that I can use to avoid that problem?

Thanks.

# Answer
> 2 votes
Put all of the resources in a ZIP archive.

Rename the file from `example.zip` to `example.pak` (or whatever else you want).

Lastly, uncompress the archive and load all of your resources.

```
ZipFile zipFile = new ZipFile("/external/path/to/test.zip");

Enumeration<? extends ZipEntry> entries = zipFile.entries();

while(entries.hasMoreElements()){
    ZipEntry entry = entries.nextElement();
    InputStream stream = zipFile.getInputStream(entry);
}

```

You can also read an archive from inside of your JAR file.

```
URL url = new URL("jar:file:/path/of/file.jar!/resources.pak");

```

The location of the running JAR can be easily retrieved (as long as the class that this is called from has been loaded from that JAR).

```
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

```

---
Tags: java, assets, compression
---


# Question
Title: Before I change position I want to check if the gameobjects are collinding
For starters I'm new to Unity3d. So my question is when I click on an object I want to change its position but without collinding with the other objects and I need a function to check that. I already added a box collider 2d and checked is trigger.

# Answer
Unfortunately in Unity there is no way to see if an object is currently colliding. What you need to do is record the last "Good" location & try to move the object. Then override OnCollision and of it is colliding with an object it shouldn't be, move it back to the good location. If you do this you will also want to set a flag (`bool moving`) saying that you are moving it, and once it is at that location (and hasn't collided) remove that flag.

All that being said, if you are trying to manually move an object & using the collision system you are probably doing it wrong. It would be better to set the velocity of the object such that it move the object in the correct direction & then stop it from moving once it has collided.

More details on what you are doing would also help other craft a better answer.
> 0 votes

# Answer
You can enable and disable the collider on the player to get the desired effect. For example my player is climbing a ladder and I would like him to move through the grounds box collider while he is on the ladder so I create a bool isClimbing and when he connects to the ladder and is climbing is true I would

```
player.GetComponentInChildren<BoxCollider2D>().enabled = false;

```

and when he leaves the ladder than re-enable it.

edit- note that if your player does not have a parent then you would use

```
player.GetComponent<BoxCollider2D>().enabled = false;

```
> 0 votes

---
Tags: unity, c#, 2d, collision-detection, game-mechanics
---


# Question
Title: What's the fastest way to copy a texture to another texture in OpenGL?
Here's the options I've found:

* glBlitFramebuffer: Create framebuffers for the textures, bind textures as GL\_READ\_FRAMEBUFER and GL\_DRAW\_FRAMEBUFFER, call glBlitFramebuffer().
* glCopyTexImage2D: My research so far says this method is probably slow.
* Shaders: Make a framebuffer and render target, render the source texture to the dest texture.

# Answer
> 2 votes
You didn't specify a version of OpenGL.

The fastest is likely to be glCopyImageSubData. However, that's only available in recent versions of desktop GL.

---
Tags: opengl
---