# Question
Title: Determining the end location for AI movement in groups in a 2D RTS
I have written an RTS game (a demo for a game engine of sorts, actually) in which the user's basic interaction with the game is to select a bunch of soldiers and then right-click on the map to move them to the specified location. This is in JavaScript and you can play with it here (code).

Ignoring the problem of how the soldiers move from their current location to their destination, my question is about determining what their actual destination is. Here is what I've tried so far:

* Attempt 1: Tell all selected soldiers to move to the coordinates the mouse clicked. This has the odd behavior that all the soldiers will then go cluster around the target unnaturally.
* Attempt 2: Find the average coordinates of all selected soldiers, then find the offset from that center point for each soldier, and finally translate that offset around the mouse coordinates. This works fine except that if your selected soldiers are far apart they will not get close to the target.
* Attempt 3: Build a grid around the mouse coordinates and place each selected soldier into a cell of the grid. If each soldier makes it to their assigned cell, this works great. However, soldiers are assigned to grid cells in the order the soldiers were spawned, so sometimes they collide (i.e. all the soldiers on the right side will try to go to the left side) which looks unnatural.
* Attempt 4: Use a grid like before, but first sort the soldiers by location so that they line up sensibly, i.e. if you clicked below the group then the soldiers at the bottom of the group will end up on the bottom of the grid when they reach their destination. This works pretty well but there are glitches sometimes and I'm not sure why.

Here is the function that determines the destination coordinates:

```
function moveSelectedSoldiersToMouse() {
  var w = 0, h = 0, selected = [];
  // Get information about the selected soldiers.
  myTeam.soldiers.forEach(function(soldier) {
    if (soldier.selected) {
      selected.push(soldier);
      w += soldier.width;
      h += soldier.height;
    }
  });
  var numSelected = selected.length, k = -1;
  if (!numSelected) return;
  // Build a grid of evenly spaced soldiers.
  var sqrt = Math.sqrt(numSelected),
      rows = Math.ceil(sqrt),
      cols = Math.ceil(sqrt),
      x = Mouse.Coords.worldX(),
      y = Mouse.Coords.worldY(),
      iw = Math.ceil(w / numSelected), // grid cell width
      ih = Math.ceil(h / numSelected), // grid cell height
      wg = iw*1.2, // width of gap between cells
      hg = ih*1.2; // height of gap between cells
  if ((rows-1)*cols >= numSelected) rows--;
  w = iw * cols + wg * (cols-1); // total width of group
  h = ih * rows + hg * (rows-1); // total height of group
  // Sort by location to avoid soldiers getting in each others' way.
  selected.sort(function(a, b) {
    // Round to 10's digit; specific locations can be off by a pixel or so
    var ax = a.x.round(-1), ay = a.y.round(-1), bx = b.x.round(-1), by = b.y.round(-1);
    return ay - by || ax - bx;
  });
  // Place the grid over the mouse and send soldiers there.
  for (var i = 0; i < rows; i++) {
    for (var j = 0; j < cols; j++) {
      var s = selected[++k];
      if (s) {
        var mx = x + j * (iw+wg) - w * 0.5 + s.width * 0.5,
            my = y + i * (ih+hg) - h * 0.5 + s.height * 0.5;
        // Finally, move to the end destination coordinates
        s.moveTo(mx, my);
      }
    }
  }
}

```

You can paste this function into your browser's JavaScript console when viewing the demo and mess around with it to change the soldiers' behavior.

My question is: **is there a better way to determine the target location for each soldier to move to?**

# Answer
Here are my suggestions on your ideas:

Attempt 1: To fix this situation, you could implement the "close enough" idea Spencer brought up. I would do something like drawing a bubble around the end point, that grows based on a ratio of the number and size of the units already in it. Say the bubble starts the size of one unit, then when the first gets there, the radius doubles for the next two units, etc.

Attempt 2: A fix for this one, would be take the average distance of the group from each other, then cut the distance of the outliers to that, so the group ends up more bunched than they originally were (the metric could be shorter/longer than the average, whatever makes it look decent, or possibly set a maximum form size based on the number/size of troops again) The only thing you'd have to worry about is when you alter the path of an outlier, you'd have to check and make sure it doesn't interfere with the other paths

Attempt 3: You improved on this one in attempt 4

Attempt 4: Sounds like this one would work fine if you find whatever glitches are throwing it off. I would recommend playing with spahes other than just a grid formation, though, to make the movement look a bit more natural, unless you're going for a realism/military style, in which case it might be neat to have them "form up" before moving, but that might get annoying to the player after a while.

Attempt 4 seems the closest to removing the milling behavior in your problem, but in terms of keeping the movement flowingwithout any adjusting other than what's necessary, my favorite would probably be attempt 2.

But as a different solution entirely, you can have two types of objects when it comes to pathfinding; each unit, as well as an invisible "squad" object.

Squad- You build the squad object at the center of the group, like the other solutions, and use your pathfinding to direct it towards the objective.

Units- The units ignore the goal entirely, and instead use the pathfinding to keep within a certain distance (or formation, or any other metric ends up making the movement look best) from the squad object.

This separates the different aspects of the pathfinding, and allows you to tweak either side in isolation for more control on how it looks.
> 1 votes

# Answer
Attempt 3 could work, but it needs a bit of a refinement.

Think about the concept of a formation (your grid is a start). A formation should have a location (i.e. the click coordinates, or the target soldier/building) and a rotation (this could be fixed, random or deterministic). The formation must have the same number of positions as the number of selected soldiers.

A simple example formation may be a circle around the target. Space positions equally around and increase the circle radius to fit all the soldiers without colliding.

The next problem is to decide which soldier walks to which position in the formation. A simple solution could be to make each soldier move to the position which is closest to him. If that one is already 'chosen' by another soldier, take the next closest position, etc.

Formations can become quite interesting. Below is an image of the 'bull horn formation' used with great success by Shaka the Zulu. (The image comes from the TotalWar Formation Mod)
> 2 votes

# Answer
Upon user click, draw a vector from every soldier to the clicked location. Get the average vector angle from the vectors drawn for each soldier and move each soldier the length of their individual vector in that direction with the same angle. This should give the appearance of the units moving in formation to the point and should keep the units from clumping up.

If you want the units to move out of formation, you can point every soldier's angle directly at the clicked location. However, without collision the units will start to converge. To counter this, add collision and force the units to stop moving once they're "close enough" to the point clicked. The first units to arrive will be exactly on the point and the last ones to arrive should be directed to stop moving once they are either close enough or a certain amount of time has passed.

You could calculate the length of the path and unit speed to determine when a single unit should arrive and then force the unit to stop moving if it exceeds that time by a certain amount. You'll need to play with that number a bit.
> 0 votes

---
Tags: javascript, ai, movement, rts
---


# Question
Title: get the new vertices after rotating in JOGL
I had rotate an object with openGL (JOGL). Is there a simply way how I can get the new vertices?

# Answer
There is a way, but it is not easy: set up an transform feedback buffer, and have it gather all the points emitted by the geometry shader. Perform the matrix calculation on the vertex shader, pass the calculated vertices to the geometry stage and then emit them so that the transform feedback buffer catches them. It's hardly worth it though, I'd go with what the other dude said: calculate it on the CPU.

Why do you want the vertices back? Do you want to apply additional transformations on them? If so, you can just multiply the model matrix you used to draw the last frame with an matrix that corresponds to whatever transformations you want to do this frame.

For example, say that you want to rotate an object around the Y axis, making one loop every 10 seconds. Then you just create an identity matrix and save this matrix, as "modelmatrix". For every frame, assuming that delta miliseconds has passed since the last frame, you create a new identity matrix, and rotate it around ((delta/10000.0f) * 3.14f * 2.0f) radians around the Y axis. Then you multiply your previously saved modelmatrix with this matrix, and make sure that this operation mutates modelmatrix, eg: modelmatrix = modelmatrix * rotationmatrix.

Then you throw your rotation matrix away (or better yet, save it, and mutate it to the identity matrix so you don't need to allocate/deallocate the memory for 4\*4 floats all the time).
> 1 votes

# Answer
The easiest way to do this is to keep a copy of the vertices on the CPU-side, and perform the same transformations to your "local" copy. This can usually be done by accumulating the rotations and translations in a transformation matrix, then applying the transformation matrix to each vertex whenever you access them locally.
> 1 votes

---
Tags: opengl, java, rotation
---


# Question
Title: Outlining external edges on a complex shape made of cubes?
A gallery of my problem can be found here. I had to do it this way as it won't let me post more than 2 links due to my reputation.

I'm trying to use 3D cubes to generate an isometric cube world.

I got that working great and I merge only the visible vertices/indices into a buffer and draw from that.

Only problem is, as with any isometric game, it becomes difficult to differentiate between heights. For example in the first image: this archways top merges with the cubes below.

I ended up finding this shader and got it working by using it against a rendered normal map (second image) of the cubes.

You may be able to guess my problem from that image. The final result looks like the third image. The back edges are not draw with an outline, which are the most important. Which based on the normal map also means that diagonals also have the same problem on their sides (fourth image).

Is there any solution I can do for this? Either in the shader itself or perhaps when calculating the normals? I almost need to add something to the normal to distinguish their depth/height so faces on similar planes don't merge on edge detection. Or maybe there's a totally different option I could use.

Ideally I was aiming more for only edges to the air to be outlined so the archways bottom edges would not be outlined like they are now =/

# Answer
> 0 votes
(Answering from my comments to get this off the unanswered list)

My strong preference would be for a 'world-space' solution over a 'screen-space' one; that is, rather than trying to do the work of outlining in a shader, instead do it in your engine: for each edge in your figure, determine whether the edge should be highlighted on-screen. You can use whatever criteria you like for whether an edge should be highlighted; for instance, a simple one would be to highlight each edge where the faces on the two sides of the edge point in different directions with respect to the camera (that is, one pointing towards the camera and one pointing away). It would be nearly as easy to highlight each 'reflex' edge - that is, a concave edge of your figure, one where the two faces on either side are pointing towards (rather than away from) each other; etc. Your criteria don't have to be specifically graphical, either - for instance, it's easy to 'reject' any edges on your figure adjacent to the ground.

Keeping track of the edges is a little bit tricky, but not too bad - there are a few special cases (for instance, if you can have a 'figure-eight' edge where two diagonally-adjacent cubes share the edge but no two facially-adjacent cubes do), but in general building an edge list is relatively straightforward.

Once you have the (sub)list of visible edges, there are a couple of different ways to handle displaying them; probably the most straightforward is also a world-space approach, where for each edge you render another rectangular box, ; for instance, if the edge runs from (x, y, z) to (x+1, y, z) then you might render a box that goes from (x-.05, y-.05, z-.05) to (x+1.05, y+.05, z+.05). If you do this, make sure to take care in how you construct the 'end caps'; the particular version that I note there has the advantages that boxes from adjacent edges will align correctly at their endcaps, but non-uniform coordinate deltas might not.

---
Tags: xna, shaders, isometric, outline
---


# Question
Title: What is the best way to follow this book using XNA 4.0 instead of XNA 2.0
I found a reference to this book on the Microsofot Indie games forums: http://www.amazon.com/dp/1430209798/ref=pe\_385040\_30332200\_pe\_309540\_26725410\_item

I'm really interested in it, because the example project is very close to the style of gameplay I'm looking for in my next game. The downside is, I was hoping to write the game in XNA 4.0 and maybe even Monogame.

Would the best option here be to just follow along with the book using xna 2.0, and then try to rewrite/update the app in xna 4 or monogame? Or, would it be better to start my project as an XNA 4.0 project, and then code along with the book, fixing any discrepancies as I come across them?

# Answer
> 1 votes
It depends on the features you're using from 2.0 and how they differ from those in 4.0. Likely the best option is to take it one step at a time. Start out with a 4.0 project, try using the book as is. When you come up against a problem, search specifically for that problem. Find out how to perform the required 2.0 exercise in a 4.0 way.

Since you ultimately want to use 4.0, I don't see a reason to learn 2.0 just because the book is written using that. It's likely what really interests you about the 2.0 book is the high level designs for the game made in the tutorials. In your goal of learning 4.0, finding out how to implement these high level 2.0 designs in 4.0 should be beneficial to you.

---
Tags: xna, xna-4.0, books
---


# Question
Title: Web single player 2d top-down RPG - background image, sprites, and new level loading
I'm making a web single player 2D top-down rpg using JavaScript (create js library) and have a couple questions.

For the background image, I've currently loaded a 1000x1000 bitmap to represent the background for my rpg world (per level). It's drawn in relation to the camera (aka the canvas - 500x500) so not all of it is on the screen at the same time. If it's not on the screen, is it still using resources to be drawn? I eventually want to have a much larger "world", which will require a much larger bitmap... What is the best way to load a background image?

And what about sprites? I'm assuming if I create several sprite objects with bitmaps... even if they aren't on the camera, they are still using resources? This may slow down the game.

---

Level loading: If I walk to another level, or go inside a building, I'd like to load that bitmap... Is there a specific way to architect level loading?

Thank you!

# Answer
> 3 votes
> If it's not on the screen, is it still using resources to be drawn?

Yes

> I eventually want to have a much larger "world", which will require a much larger bitmap... What is the best way to load a background image?

The best way is not have 1 image be your entire level but to have 1 image that contains tiles you piece together to create your level. This is called a tilemap. There are a lot of tools (personal favorite is Tiled) for this and its pretty easy to find a library to load and draw the tilemap for you.

> And what about sprites? I'm assuming if I create several sprite objects with bitmaps... even if they aren't on the camera, they are still using resources? This may slow down the game.

Everything you draw uses resources. The simple solution to this is to see if its on the screen and only draw it when it is visible.

> Level loading: If I walk to another level, or go inside a building, I'd like to load that bitmap... Is there a specific way to architect level loading?

Kinda. Usually people use a Finite State Machine or something logically equivalent to handle state. A FSM with a begin and end event allows you to load content that state needs and then clean up after yourself afterwards.

---
Tags: game-design, javascript, rpg
---


# Question
Title: Trouble figuring out some attack/defense formulas. What should I change?
I'm working on something which requires a hunter to attack an animal. This is what I have so far.

Attacker/Weapon POV

1. **Level** \- 1 to 50
2. **Base** \- base attack level of the weapon
3. **Weapon Impact** \- determines size of prey it can kill - base = 10, +10 every level
4. **Marksmanship** \- this is a skill which the hunter acquire with time. higher level animals will require a higher skill, Let's say it starts off at 50. Then the hunter can buy level 2 which will be let's say 150..so on..
5. **Ammo** \- different types of ammo will give different types of bonuses. Some will increase impact, some skill, some both.
6. **Random multiplier** \- need this to make everything a bit of a gamble. Can't allow users to figure out how the formula works

Animal POV

**Defense** \- based on: base defense of the animal + weight factor + skill required to shoot him down

This is what I have in mind. Now..I tried to come up wth some formulas to represent all this..I made some simulations in excel. They seem to work but I don't know if I took the right approach determining this. It was mostly guess work..trial and error until I got some results which seemed ok. Any advice is welcome !

Each animal has a weight between **min** and **max**. However, the **Weapon Impact** will limit that weight at Weapon Impact / 10 kgs. =\> 10 Impact = 1 kg max, 20 impact = 2 kg max..etc. To avoid hunters shooting down an animal every time, I will generate animal weights between min and Impact max + a small percentage. For example let's say an animal is between 1 and 10 kg. With 50 impact the animal which we can shoot will have a weight between 1 and 5kg. however i will generate weights up to 5.5..to make hunters miss from time to time because the animal was to large for his level..etc.

Now to determine if a hunter shoots down an animal I compute an attack factor and a defense factor. If attack \> defense.. asta la vista baby !

Attack Formula: Weapon Base + Impact + Ammo Bonus + Weapon Base \*(lvl/max lvl) * multiplier

multiplier is randomly generated between 0.8 and 1.2 so it could help..or it could harm...

Defense formula = Base Defense + Base Defense\*weight

... not sure how this will scale .. any ideas? where do ppl start to generate formulas like this ?

# Answer
When doing game design, it's important to start out with a list of goals, what you expect the design to accomplish. That way, when you've created the design, you can analyze it against your list of goals to see if it actually does what you wanted it to.

For example:

> Weapon Impact - determines size of prey it can kill - base = 10, +10 every level

OK, you have this "impact" stat. And you want this stat to "determine size of prey it can kill". I can only assume this means that the prey will have some corresponding "size" field, and if the "size" exceeds the impact, the hunter can't kill them.

So that appears to be your goal with the design. So let's look at the implementation to see if that achieves that goal:

> Weapon Base + Impact + Ammo Bonus + Weapon Base \*(lvl/max lvl) * multiplier
>
> vs
>
> Base Defense + Base Defense\*weight

If the goal of "impact" is to prevent the player from being able to kill creatures beyond a certain "size", then this doesn't do that. Impact is not being compared against size (or weight or whatever). It's just a bonus thrown in.

Furthermore, if it's supposed to be "impact" vs. "weight", it would seem that "weight" is *far* more effective than "impact". Each unit of "weight" multiplies into the base defense. Whereas each unit of "impact" only adds to the base attack.

Judging by the actual design you've come up with, "impact" is really just the character's "Base Attack Bonus", to use D&D terms. You compute the attack power based on three factors:

* Character-specific info
* Weapon-specific info
* Ammo-specific info

Each of these factors plays a role. The weapon provides the "weapon base". The ammo provides an "ammo bonus". But the character seems to be pulling double-duty, providing both a "level" multiplier (not very much) *and* this "impact" stat. That's not necessarily a bad thing, assuming you have means of buffing the "impact" stat besides leveling up (equipment, buffs, etc).
> 0 votes

---
Tags: mathematics
---


title: watching for changes in object state

text:
# Question
Title: watching for changes in object state
I'd like to know what others do to watch for changes in object states while the game is running.

Say you have an object and that object has a timer. The timer completes. What is the best way to know that the timer has completed?

something like?

- \- add all timers to a vector.
- \- set a bool when the timer completes
- \- loop over the vector continuously or at a short interval and watch for the bools?

Seems simple, but is it really that simple? What is the best way to loop over the vector continuously? C++11 thread and detach it from the main?

# Answer
> 3 votes
How about instead of threads or continuous looping, you use an event system to notify listeners (people who care about when the timer/action is 'finished').

*Edit:* This pattern is called the observer pattern. There are many ways to implement the function callback system, including delegates and function pointers. It is up to you which one you use, though here is a resource on delegates: http://www.codeproject.com/Articles/13287/Fast-C-Delegate

**Advantages over continuous looping:**

1. Continuously looping means more code for calling classes (classes that use your objects), versus simply delegating a particular function as a handler with only the absolute minimum functionality contained within.
2. The object (or underlying timer, in this case) could very well be able to tell, much better than the calling classes can (or should), when the operation or action may complete. In this case, an event system could very well be more efficient. In addition, if your timer or action is itself a thread based process, then it will no longer have to check whether it is finished at all, logic flow will naturally result in completion and thus an event notification.

**Advantages over checking periodically:**

Checking periodically is only fine if the fact that the operation(or action) has completed has no implications for the rest of your game or other objects. For instance, doing this wouldn't be acceptable if you needed to respond instantly.

**Advantages over threads:** Much of this is the same as continuous looping, but, one area where threads are superior to the other approaches, is, of course, the fact that they allow exceution to continue while checking is done. On the other hand, you may then need to perform locks etc and in this case I couldn't justify the extra complexity for such a simple process.

*Sidar: Beat me to it.*

---
Tags: c++, game-mechanics, state, objects
---


# Question
Title: Play audio in javascript with a good performance
I'm developing a browser game where the player can shoot. Everytime he shoots it play a sound.

Currently i'm using this code to play sounds in JavaScript:

```
    var audio = document.createElement("audio");
    audio.src = "my_sound.mp3";
    audio.play();

```

I'm worried about performance here. Will 10 simultaneous sounds impact my game performance too much?

Will all audio objects stay in memory even after they are played?

# Answer
You could attach the audio element to the `body` (Firefox won't play it else) and detach it, when it stops. So you can be sure it doesn't exist in the DOM anymore.

If you do it this way,

* No, 10 sounds won't impact the performance because they're gone after playback.
* No, they won't stay in memory because they get detached.
> 2 votes

# Answer
Use the Web Audio API.

The HTML5 audio tag was designed and implemented with use cases in mind of: streaming music, playing podcasts, and offering visual controls to users. The use case of playing many samples and triggering them at specific times was addressed later, and web standards discussions have evolved to offering that functionality in the Web Audio API.

The downside of the Web Audio API is complexity, but the additional power and quality is well worth it.

Check out samples.

Consider using a sound library to simplify use, e.g. search for "html5 audio library for games". Some results include SoundJS and SoundManager2.
> 5 votes

# Answer
I did a lot of research into the Audio API awhile back. The main problem I found with the Audio API is the fact that any time an Audio element is declared, it *will* download the Audio file, regardless if that file had been downloaded before. This means that if you use `new Audio('file.mp3').play()`, this will cause an HTTP request to the audio file every time. Even if you use `audio.cloneNode().play`, it will download the file every time. Since the sound you want is a sound effect, it will probably play many times throughout the game. The longer the game runs, the more HTTP requests you will make to the server.

Since you want to have overlapping sound effects, you must have multiple Audio elements. A solution I came up with was to create the minimal amount of Audio elements you need (the maximum number of sounds that can overlap at any given time), and then just reuse the elements when you can. This will save on HTTP requests in the long run and be the most conservative for performance. I still don't know if this is the best solution, but I haven't run into any other solutions that take into account the HTTP request problem.
> 3 votes

# Answer
Instead of pointlessly trying to manipulate the DOM, use the Audio object to play sounds instead of the HTML tag.

```
var audio = new Audio();

audio.addEventListener('canplaythrough', function(){
   this.play();
});

audio.src = 'my_sound.mp3';

```

Also, why can't you reuse the audio object to play the same sound multiple times? There's no need to create multiple audio objects, unless you want your sound to be able to overlap with itself.
> 1 votes

---
Tags: javascript, html5, audio
---


title: Camera coordinate system flipped?

text:
# Question
Title: Camera coordinate system flipped?
I'm looking do make an FPS-like camera, but I'm encountering some problems. If I'm first rotating and then translating the camera, everything works fine, but the coordinate system. For example, if I want to go backward with the camera, I have to set the Y coordinate positive. But when I'm translating a model matrix on the Y coordinate in a positive direction, it is moving forward. So somehow the coordinate system is flipped.

When I'm first translating the camera and then rotating, the coordinate system is the same, but now the camera is rotating around the origin, which makes sense, but when I'm looking at examples, everyone does that and no one is complaining about rotating around the origin.

I hope you understand what I mean and I hope you can give me some advice.

# Answer
To me, this sounds like you're thinking about it the wrong way. Translating the camera to a positive direction "moves the world forward", not the camera backwards, as basically the world is multiplied by the camera matrix. So when you translate an entity forward, it actually goes forward, so the direction is the same.
> 1 votes

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


title: Java network game - synchronize state

text:
# Question
Title: Java network game - synchronize state
I'm creating a networked frame-based game (like Tetris battle), using the Java Sockets API, and right now my main concern is how to 'synchronize' the game state between two players. I've already implemented a multi-client chat, just to warm up.

In turn-based games (like chess), a simple solution is to send a 'move packet' and wait for the other player to send a 'received move' packet, so that the game can continue in a consistent state. Now, in a frame-based game (not real time though), I'm not sure if this is the best solution (the game will run in a local network, but I could scale it later).

Should I use this same technique? What are the other options? I'm new to networking, so I appreciate any help.

# Answer
> 1 votes
There are multiple options to this, but one popular one is to encode everything you do in a game as actions transmitted over the network and putting their "time of execution" slightly to the future. The core idea here is to give the action (such as player moving a tetris tile) some time to reach the other player's program before executing it from a queue or such.

The latency between clients can then be adjusted to fit the network speed. In case of an out of sync packet arriving, there are a few options depending on how your game is constructed. If it's something simple like tetris, you can probably just implement a resync that sends over the current gamestate in some neat format. Another option if the actions player can take are limited is to simply resync the delta since some unit in time. This requires you to keep some amount of history of the gamestate in the memory.

The solution can vary depending on how your game actually is like. Stuff like tetris blocks not being 100% in sync is not a big deal while victory conditions are. By this I mean that having a way to verify who wins first is more important, but other kind of resyncs can be done on the fly without affecting the player's experience vastly. In a game like Tetris (sorry for getting hung up on that), the player could technically be playing against a recording without ever knowing it (also an used technique in games like this, but not fit for all games that want to be more "real-time").

If you're using TCP sockets, missed packets will be fixed on their own so you're saved that trouble.

I think that in order to receive more specific information on the subject, you probably have to describe the context in a bit more detail.

---
Tags: java, networking
---


# Question
Title: Simple collision detection for 2D match 3 gems game
I'm building simple match 3 game.
I have the parts where I move the gems with the mouse only in the straight X or straight Y, up and down and both sides, no 45 degrees movements on grid.
I'm looking for simple collision detection algorithm for the situation when for example:

a gem is moved up or down or left or right and there is another gem. How can it detect it touched a gem and which gem it is?

# Answer
> 1 votes
You could have all your gems contain their position (you probably do) and attach a method to the setter of that position so that it checks its surroundings for the gems around it.

In C# it would probably look something like this

```
private Vector2 mPos = something; // position of the gem
public Vector2 Position {
  get { return mPos; }
  set { mPos = value; GemMoved(mPos); }
}

public void GemMoved(Vector2 pPos)
{
   var sameneighbours = map.FindNeighbours(this.Position, this.Color);
   ...
}

```

Another approach would simply to be check the board through for connected areas once a move is made. It's quite fast to check connected areas every time something happens unless your map is massive. By doing something like

```
bool[,] boardMarked = new bool[width, height];
boardMarked.Fill(false);
for(int x = 0; x < width; x++)
  for(int y = 0; y < height; y++) {
    if(!boardMarked[x,y]) {
      int count = FindAndMarkConnected(x,y);
      if(count >= 3) EliminateAreAndGivePoints(x,y);
    }
  }

```

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


title: Level Representation in a 2D Game

text:
# Question
Title: Level Representation in a 2D Game
I would like to create a 2D game, where a character should move on a stage/level. My stage would be static, constructed some little cubes, similar to the well-known Mario game: some of the elements should represent an element of the way where the character can step, but if the element is missing, the character should fall.

My problem is, how to represent this programmatically? My first thought was to represent the stage with a vector, which should contain boolean elements, depending on the state of the element on the stage - if it's missing or not. But this means, I have to verify at my character's x or y position change if it has a stage element under or not (if not, to simulate the falling of the character) - I think it is not the best practice, it's not the beautiful solution.

Can you help me with some advice, how to represent the stage?

# Answer
The vector of booleans may work. And I think check the tile below the player character every frame is perfectly valid solution until you get to a point in your project where that does not work any more. For most games that may never happen.

A more evolved version is what I'm doing in my latest HTML5 canvas experiment to find the right collision method to use in a game I want to create.

My levels are also in tiles of same size and always aligned, only character and enemies may not be tile aligned.

I represent the level as a string constant, soon functionality to load from text file will be added. For example:

```
// First line
var level =  "         x                x                 ";

// Then we check the width of the level by checking numbers of characters
var level_width = level.lenght;

// Then we add the next of the level. Note we are adding more characters not replacing.
var level += "   aaaa        aaaaaaaaa aaaa          aaaaa" +
             "          aaaaaaaaaaaaaa aaaa          aaaaa" +
             "          aaaaaaaaaaaaaa aaaa          aaaaa" +
             "                                            " +
             " bbbbbbbbbb            bbbbbbb     bbbbbbbb ";

// Now we calculate the height of the level
var level_height = level.length / level_width;

```

I have to calculate the level rectangle because I'm using a raw format to represent the level but you can use end of line characters (\n) to know where a line ends and avoid these calculations.

Meaning of characters:

x: enemies. Starts tile aligned, due to restriction of level format, but can move to any pixel latter during game.

a: tile type 1. Actually blue boxes.

b: tile type 2. Actually green boxes.

Both a and b don't allow the player sprite to pass.

Certain type of tiles are passable and certain ones are not. Your engine must know what ones are passable.

The idea begin this is not to code a level editor if formats to represent level already exists.
> 2 votes

# Answer
You have a set of options actually. If your map is of preset size, you could simply have a 2-dimensional array of tiles. Depending on the programming language they could be booleans, structs, classes and so on depending on what kind of properties you want them to have.

The good thing about a 2-d array is that you can easily round the coordinates of the players to get tile coordinates. For example:

```
var plrTileXstart = player.X / TileWidth;
var plrTileXend   = (player.X + player.Width) / TileWidth;

var plrTileYend   = (player.Y + player.Height) / TileHeight;

if(map[plrTileXstart, plrTileYend] || map[plrTileXend, plrTileYend])
   // There was a collision - Adjust player Y coordinate to be on surface
   player.Y = plrTileYend * TileHeight - player.Height;

```

The tiles could be something like

```
class Tile {
  int X;
  int Y;
  Color color;
  ...
}

```

Instead of a bool too.
> 1 votes

---
Tags: 2d, architecture, level-design
---


# Question
Title: Does Facebook give new games any free promotion?
I would like to understand, if Facebook gives some free out of the box promotion for new games? I see "New Games" section in Facebook App Center, does every new game gets in there?

# Answer
The shortest answer is "no", Facebook almost never gives away such placement for free. This is, literally, where they get all their money; Zynga (the big game developer) is the largest source of revenue Facebook has.

While not universally true, a good rule of thumb is that if you see it, its for sale. The largest amount I've ever gotten free was $100 in 'free' advertising, usually for registering for some service or paying for a domain name or hosting plan somewhere, etc.

That platform is available for free, the tools/code/SDK is available for free, the code samples, tutorials, and some forums are available for free; basically the whole development/building side of things is free.

Its the marketing and the advertising that is anything but free. It's very much like a search engine; they'll list you on their own, but if you want anything better you are gonna have to pay.

And there are many, many ways to pay for exposure on Facebook.

However, there are some things that are provided by the Facebook platform that don't cost you dollar bills directly.

To get the free stuff you need to name your app appropriately (like putting "solitaire" in the title), use any tag/description features efficiently with keywords, and apply the right "categories" so your card game doesn't end up listed as a hidden object game.

The other 'free' listing is Friends and Trending, but the only way to get Trending is massive viral explosion (don't count on it, especially without paying for it) and Friends only comes into play as people already start playing your app, helping it slowly spread (but, again, don't count on it).

With permission people can post from your game to their feed and walls, and this is also 'free' in that people do your marketing for you. You can also promote apps from within your own app, but of course that only matters when you have other apps that have a sizable player base.

But as far as big banners, "new on Facebook" promotions, top billing on "suggested for you" pages, etc, that costs money. Big, fat, filthy wads of it. Some features are per view/exposure, like sidebar ads, and some are features they don't even mention in obvious places because they only offer them to people who are already swinging large spends on their sites- kind of like buying front page ads on Youtube.

According to the big players, it costs 50 cents to $3 in advertising to get one new install of a game. That's when things 'work', of course, so it's good to keep this in mind; a free promotion that would get 1000 people playing your game has a market value of $500-3000, and that's a lot to hope to get for free from a for-profit company.

For "guerilla" advertising, where you spend your time instead of money to get the word out on your game, there are lots of resources out there that talk about this; I don't have one I personally endorse off hand, but I think most reputable website/software bloggers do a good job of talking about the basic principles of marketing and how they relate to the game business.

The general idea is to work existing networks of "taste makers" - critics, bloggers, review websites, gaming sites, etc. They don't all require payment to talk to you, and if you are a good communicator sometimes you can talk people into an article, full blog post, etc. YMMV, and sometimes you get little/no traffic out of it.

Bottom-line, "if you build it, they will come" applies to magic baseball fields - not Facebook games, or games of any type. As with all other networks of this type, if you release a decent game its not uncommon to get a few hundred or thousand views/plays in the first month (Kongregate, Armor Games, Facebook, app stores on Android and iTunes, etc), and that can be pretty much it. Anything else takes work + a special game that proves more interesting than about 70-90% of 'released' online games.

But sometimes that amount is just fine! At one point I had the most downloaded/used modification for CivIII on the internet for about a year, and while that 'only' amounted to something like 5-10k downloads across all versions, that seemed pretty darn awesome to me for something I made for fun and just on a forum.

And if that's ok with you, then maybe that's a great start and you can move on to your next project, and maybe if you find a small growing base of players you can use that to help promote your next project. :)
> 4 votes

---
Tags: marketing, facebook, social
---


title: Difficulties with zoom point

text:
# Question
Title: Difficulties with zoom point
I want to zoom about an arbitrary zoom point. For example, if the player tabs on a place on his windows phone display, this place(position) should get the new center of his viewport. In addition, the camera zooms so that the place looks bigger. If the player tabs again in zoom mode, the camera just needs to zoom out and the center of the viewport rests the same like in zoom mode.

I'm doing a 2D point and click adventure, so it is very important to examine the environment.

If I tab on a place, it's not getting the center of the viewport. The center of the viewport always is somewhere else. What is wrong with my code?

I found the camera class in this tutorial: http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/

How can I do the zoom? I found a similar question on stackoverflow but I don't understand how they solved the problem: https://stackoverflow.com/questions/9348866/xna-2d-camera-with-arbitrary-zoom-center

Camera class:

```
public class Camera2d
{
    protected float _zoom; // Camera Zoom
    public Matrix _transform; // Matrix Transform
    public Vector2 _pos; // Camera Position
    protected float _rotation; // Camera Rotation

    public Camera2d()
    {
        _zoom = 1.0f;
        _rotation = 0.0f;
        _pos = Vector2.Zero;
    }

    // Sets and gets zoom
    public float Zoom
    {
        get { return _zoom; }
        set { _zoom = value; if (_zoom < 0.1f) _zoom = 0.1f; } // Negative zoom will flip image
    }

    public float Rotation
    {
        get { return _rotation; }
        set { _rotation = value; }
    }

    // Auxiliary function to move the camera
    public void Move(Vector2 amount)
    {
        _pos += amount;
    }
    // Get set position
    public Vector2 Pos
    {
        get { return _pos; }
        set { _pos = value; }
    }

    public Matrix get_transformation(GraphicsDevice graphicsDevice)
    {
        Viewport viewPort = graphicsDevice.Viewport;
        _transform =
          Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                                     Matrix.CreateRotationZ(Rotation) *
                                     Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                                     Matrix.CreateTranslation(new Vector3(viewPort.Width * 0.5f, viewPort.Height * 0.5f, 0));
        return _transform;
    }
}

```

How I use the camera:

```
GestureSample gs;
cam.Pos = new Vector2(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2);
TouchPanel.EnabledGestures = GestureType.Tap;

 void UpdateZoom(float newZoom)
     {
       Vector2 currentMouseTarget = new Vector2(cam.Zoom * gs.Position.X, cam.Zoom * gs.Position.Y);
       Vector2 nextMouseTarget = new Vector2(newZoom * gs.Position.X, newZoom * gs.Position.Y);
       cam.Pos += (nextMouseTarget - currentMouseTarget) * newZoom;
       cam.Zoom = newZoom;
     }

    protected override void Update(GameTime gameTime)
    {
        while (TouchPanel.IsGestureAvailable)
        {
           gs = TouchPanel.ReadGesture();
           switch (gs.GestureType)
            {
                case GestureType.Tap:
                    UpdateZoom(2.0f);
                    break;
            }
        }

        base.Update(gameTime);
    }

 protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin(SpriteSortMode.BackToFront,
                    BlendState.AlphaBlend,
                    null,
                    null,
                    null,
                    null,
                    cam.get_transformation(graphics.GraphicsDevice));

        spriteBatch.Draw(TestSprite, new Rectangle(200, 200, TestSprite.Width,TestSprite.Height), null,Color.White,0,new Vector2(TestSprite.Width/2,TestSprite.Height/2), SpriteEffects.None,1);

        spriteBatch.End();

        base.Draw(gameTime);
    }

```

# Answer
You should calculate the target position with the previous zoom, and calculate it again with the new zoom, and then add the difference to the camera position.

Should be something similar to this (not tested):

```
 void UpdateZoom(float newZoom) {
      currentMouseTarget = Zoom * MousePos;
      nextMouseTarget = newZoom *  MousePos;

      CameraPos += (nextMouseTarget - currentMouseTarget) (/ or *) newZoom;

      Zoom = newZoom;
 }

```

EDIT:

If you want to zoom about a certain point (target) and translate camera to the meet center of viewport... your code should similar to this:

```
  Camera.Position += ( Target.Position * Camera.Zoom - Camera.Position ) * 0.1f;

```

This way it will interpolate with easing to move the camera to the target.Position
> 0 votes

---
Tags: xna, c#, windows-phone-7
---


# Question
Title: Face-Click Detection ( like in Minecraft )
I am working on a box-based game engine like minecraft and I was wondering how to detect the "clicked face" when placing blocks.

I have created this engine in C++ ( DirectX / D3D ), C# ( XNA ) and Flash ( away3d & papervision3d ).

The engine code is pretty much the same on each, however as one is C# and the other C++ I'm just looking for the pseudo code, theory or advice on how to "snap" placed blocks on the face that has been clicked on.

How should I get its orientation and then place a block on that face in that position with the corresponding orientation.

**UPDATE**

For now, I've decided to go with a simple but effective method:

First I've remembered the basic 3D to 2D Projection Algorythm.

If I now have a click-point on the screen, I can simply trace a line from the camera ( eye ) through the screen, up to a specific distance.

With this line "in mind" and a modified ( 3D ) version of Bresenham's ( 2D ) line algorithm, I was now able to see, if my imagined line is "pointing" onto a Block in my 3D grid.

thx for all of your suggestions.

**UPDATE 2**

I hope it explains my solution. ( red is the original algorythm, green is my modified version )

also: with "rounded" i mean that the original algorythm is just rounding the x-y-factor-value to get the nearest pixel. hope u guys know what i'm talking about.

# Answer
> 4 votes
If your ray tracing through a grid, you can simply iterate over the cells that the ray would pass through, in order. I found this to be extremely fast compared to dealing with a bunch of AABB's in a large world.

For each cell you can see if it is considered solid, if it is, given the previous cell coordinates you have the face as well. You can also have a maximum distance and calculate the entry and exit points for each cell.

You can combine this with some more complex collision testing for non-cube cells (e.g. you know the ray goes through this cell with a fence, so you can then do detailed testing to see if you hit the fence or passed through a gap.

There is a blog post here that gives some details and an implementation in 2D. I managed to create my own 3D version without any real problems.

http://playtechs.blogspot.co.uk/2007/03/raytracing-on-grid.html

EDIT:

Note that it can be important to consider where the ray starts from within a cell, e.g. consider the image below with a ray starting at the red point and heading towards the green one. The start and end cells are are the same, but I changed the position in the cell which then changed some of the cells in between picked. The blue dots are the intersection points, I calculated those with "start + time * heading", and stopped iterating once I passed time = 1 (in this case direction is not a unit vector. Of course if it was a unit vector then time = distance so you could iterate up to some distance that way).

# Answer
> 1 votes
The idea is to cast a ray and see what face it hits. This is pretty much a ray to AABB intersection test, in which you find the initial point of contact.

A good resource (which I'm looking at as I write this) is in the book Real-Time Collision Detection by Christer Ericson. The idea is to use 3 slabs and test the ray against them. A slab would be a region between two planes (being opposite sides of the AABB). If the ray intersects all three slabs, it intersects the AABB and a point of contact and time t can be returned.

Using this point of contact determining which face most faces this point can be done easily, especially if the AABB is stored implicity. If the AABB is implictly defined, then the face can be outright computed, as you know the point of contact lies upon that face.

If your box has an orientation, the problem can be transformed into ray vs AABB by transforming the ray into the basis of the oriented box.

This calculation can be greatly sped up with the use of some sort of broad phase tree structure using bounding boxes. AABB trees or dynamic AABB trees are great for these sort of ray cast queries.

Since you're clicking with your mouse this is also commonly referred to as "picking".

I hope this helps! I haven't implemented raycasting myself yet, so I can't write out the psuedo-code for the implementation myself, but at least referred you to a great resource.

# Answer
> 1 votes
This question seems similar to how I managed a selection block in TechCraft:

```
public void RenderSelectionBlock()
{
    //Get exact centre vector
    Vector3 position = player.currentSelection.Value.position.asVector3() + new Vector3(0.5f, 0.5f, 0.5f);

    Matrix matrix_a, matrix_b;
    Matrix identity = Matrix.Identity;                       // setup the matrix prior to translation and scaling
    Matrix.CreateTranslation(ref position, out matrix_a);    // translate the position a half block in each direction
    Matrix.CreateScale((float)0.51f, out matrix_b);          // scales the selection box slightly larger than the targetted block

    identity = Matrix.Multiply(matrix_b, matrix_a);          // the final position of the block

    // set up the World, View and Projection
    _selectionBlockEffect.World = identity;
    _selectionBlockEffect.View = camera.View;
    _selectionBlockEffect.Projection = camera.Projection;
}

```

This gives us the WVP matrix for rendering the mesh at the chosen block. But, we still need to determine which block to place adjacent to that selection block.

This is done by using a vector3 to that position:

```
private float setPlayerSelectedBlock(bool waterSelectable)
    {

```

// 0.5f = min distance to check // 8f = max distance to check. Further, there wont be a selection block

```
        for (float x = 0.5f; x < 8f; x += 0.1f)
        {
            Vector3 targetPoint = camera.Position + (lookVector * x);

            Block block = player.world.BlockAt(targetPoint);

```

// Shouldnt be attempting to select or place adjacent to water or other fluids

```
            if (block.Type != BlockType.None && (waterSelectable || block.Type != BlockType.Water))
            {
                player.currentSelection = new PositionedBlock(new Vector3i(targetPoint), block);
                return x;
            }
            else
            {
                player.currentSelection = null;
                player.currentSelectedAdjacent = null;
            }
        }
        return 0;
    }

```

// Now we can get the ray to the adjacent block properly:

```
    private void setPlayerAdjacentSelectedBlock(float xStart)
    {
        for (float x = xStart; x > 0.7f; x -= 0.1f)
        {
            Vector3 targetPoint = camera.Position + (lookVector * x);
            Block block = player.world.BlockAt(targetPoint);

            if (player.world.BlockAt(targetPoint).Type == BlockType.None)
            {
                player.currentSelectedAdjacent = new PositionedBlock(new Vector3i(targetPoint), block);
                break;
            }
        }
    }

```

# Answer
> 0 votes
There is a straightforward precise algorithm for visiting the cubes that a ray passes through in a grid-based world like Minecraft; see this answer for full source code.

---
Tags: xna, c#, c++, 3d, directx
---


title: Making a game for multiple platforms

text:
# Question
Title: Making a game for multiple platforms
I am making a game with web, iphone, and android front-ends. I want to make them all able to interact well through the back-end so that any user can play with any user.

To do this I've decided to make an "API" or really just a Ruby on Rails back-end (with the rails-api gem). **Which option fits best**:

## 1. Back-end First

Process would be building entire back-end functionality, one feature at a time until it is complete (can always expand missing features later). Can test it using different types of tests.

## 2. Back-end alongside one platform (web)

Process would be building one feature in the back-end, then using it in the front-end to make sure it works. Would be easy to build with web because most Rails projects already have views.

## 3. Back-end alongside each platform

Same as option 2, but building the feature in each platform before moving on to the next one. Would allow fixes for cross-platform problems as you go along, being able to narrow it down precisely.

---

Essentially I know possible ways to go about it, but have never made an API or cross-platform game

# Answer
If you are like 99.9%+ of people who try their hand at game development (and I am one too), your #1 biggest challenge is getting something playable, followed by #2 getting something other people enjoy playing too.

The problem with simultaneous platform development is that you are putting both of these milestones farther off, in exchange for largely illusory gains; the illusion being that having so many balls up in the air will make the total project time less. If it does its only because something got dropped, and possibly the whole project was scrapped.

Planning for multiple platforms is fine, however. You need to have this in mind when you are picking technologies, as imagine making a game 4 years ago in Flash with a goal being deploying it to iPhones; that would have required a lot more work than starting with a different platform, or cutting it and making it a wish list item for the sequel.

As to what methodology, I would recommend a version of your #2, but with the front-end first. The front-end ***is*** the game to the player, and that's what matters. A flawless back-end with a bad front-end is not really a game at all.

So I would suggest picking the platforms you know you want to target (browser \[Firefox, IE 7+ only, and Chrome?\]), iOS \[version 5+?\], Android \[4+ only?\]), Ruby web server as a back-end tech sounds just fine. Make sure what you want to do is seemingly doable on your target platforms; now a days it probably is, but if you are thinking anything tricky with 3D it gets a bit more dodgy.

Knowing your target platforms allows you to intelligently pick engines, design tools, etc.

Then I suggest picking the platform you feel like you'd be most comfortable in for maximum development speed. Prototype a feature on the front-end (the game), probably by faking the server call with a dummy, and when you are happy with the feature and how it works/plays then implement the real thing on the backend.

This way you isolate the source of errors, and you might find that a feature you thought was a good idea doesn't make sense at all when you playtest, allowing you to cut the feature completely and skip having to implement it on the backend at all.

If your chosen technology makes it easy to compile over to a different platform, then at various milestones you might want to give it a test drive on a mobile device and see how it's going. It won't be perfect, but it helps to keep you from designing the whole thing with platform-specific features that flat out won't work on other platforms. I practice this with web development and browser versions, and it keeps endless platform testing to minimum while keeping me realistic about how big of a deal its going to be to support platform X.

You might want to support Android 2.2, for instance, then find out its going to be a huge time sink for some reason and decided to just drop support and save yourself the headache; or maybe its works great and iOS is making you wonder if it is worth it at all, etc.

Once you have a version you are proud of and people like to play in the browser, you can then know approximately how big of a deal mobile versions will be, and whether or not you even want to bother. You will be more likely to finish, less swamped with minutiae (how iOS vs Android handles screen refresh is NOT important to having a successful game on the browser), and probably find the whole experience more enjoyable and less overwhelming.
> 0 votes

---
Tags: software-engineering, cross-platform
---


# Question
Title: Combining Animations for Colllada export
I need to export an animated character to the Collada file format in Blender. My .blend file has the individual animations (idle, walk cycle, attack, etc) each as separate actions. I discovered after creating it that the Blender Collada exporter cannot export multiple actions, so I need to merge them into one action which can be exported. I have tried the NLA editor, but the resulting NLA track which I create isn't exported at all. Is there any way to convert the track back to an action? Is there another, better way to achieve the result I want?

# Answer
Turns out you can use "Bake animation" to get an action back out of the NLA editor.
> 1 votes

---
Tags: blender, collada
---


title: Creating specular maps for textures

text:
# Question
Title: Creating specular maps for textures
How does one usually go about this? Is this something that generally an artist has to do manually, or are there decent procedural methods (such as with normal mapping where one can look for gradients in the texture) to generate specular maps for textures?

# Answer
An approach I've seen taken is to simply convert the diffuse texture map to grayscale, or copy one of its RGB channels, and then fuss with it a bit (for instance, altering the levels, inverting part or all of the image, etc.) This can be useful if the specularity is reasonably well correllated with the diffuse color.

It's still a manual process though; it's much faster than painting a new texture from scratch but still requires an artist's judgement as to how exactly to do it. I'm not aware of an *automated* process that can generate a reasonable spec map from any old diffuse map.

An alternative method for generating all sorts of maps is to use material layering. This takes a bunch of initial investment to get going, but can really pay off in productivity later. In this approach you don't paint the diffuse, normal, spec maps directly; instead you have a library of "pure" or "raw" materials and you paint a set of masks that control where different materials appear in the texture.

For example, in painting a brick texture, you'd have brick and mortar as raw materials, each with their own diffuse/normal/spec maps already set up; the spec map here might simply be a solid color or some homogeneous noise, as it represents a single material. Then you paint a mask that determines where brick and mortar appear, and use Photoshop or some other software to combine the raw material textures using the mask, generating diffuse/normal/spec maps for the brick wall.

Ready At Dawn is using this sort of approach for their new game and they gave a SIGGRAPH presentation about it: see "Crafting a Next-Gen Material Pipeline for The Order: 1886" from the Physically Based Shading course page.

However, this does require you to author your textures using this layering method from the beginning, so it's not easily applicable to existing textures that weren't created that way.
> 4 votes

---
Tags: textures, content-generation
---


# Question
Title: What's wrong with reversing an action like this?
I'm working on an undo and redo system map editor and have come across a major issue. If I place a tile down, move right a tile, and then move back to that tile I previously placed everything works fine. Until I try and Undo, Redo, and then Undo again.

This is the state when they're placed:

```
Executing:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Executing:
X: 1
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Executing:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:

```

The undo redo stack looks something like:

```
Unexecuting:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
41
Unexecuting:
X: 1
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
-1
Unexecuting:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
-1
Executing:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Executing:
X: 1
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Executing:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Unexecuting:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
-1
Unexecuting:
X: 1
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
-1
Unexecuting:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
41

```

I don't want this to be a code dump or "debug my code for me". I understand the problem is located at the bottom most segment where it assigns the tile an ID of 41 once again - since that's what it's previous value was. This works the first time - but not the second as seen. I'm confused to why the algorithm fails. If anyone has written something similar, feedback would be appreciated. I don't need code-fixed - just hints as to where I can find a working algorithim or a rational explanationa s to why this happens. It's just a simple pencil tool that should write tiles the grid.

```
  public new void Execute(GameMap gameMap)
{
    Console.WriteLine("Executing: ");
    PrintState();

    _previousTiles.Clear();

    // Get vertical portion
    var curTexture = MapEditorGlobals.CurrentActiveTexture;

    // We need to loop over the width of the editor
    for (int w = 0; w < SelectedTiles.Width / 32; w++)
    {
        for (int h = 0; h < SelectedTiles.Height / 32; h++)
        {

            var gX = SelectedTiles.X / 32 + w;
            var gY = SelectedTiles.Y / 32 + h;

            var tY = (gY) * curTexture.Width / 32;
            var tX = gX;
            var tileID = tY + tX;

            _previousTiles.Add(gameMap.Layers[Layer].MapTiles[X + w][Y + h].TileId);
            gameMap.Layers[Layer].MapTiles[X + w][Y + h].TileId = tileID;
        }
    }

}

  public new void UnExecute(GameMap gameMap)
        {

            Console.WriteLine("Unexecuting: ");
            PrintState();

            List<int> newTiles = new List<int>();

            // Get vertical portion
            var curTexture = MapEditorGlobals.CurrentActiveTexture;

            // We need to loop over the width of the editor
            for (int w = 0; w < SelectedTiles.Width / 32; w++)
            {
                for (int h = 0; h < SelectedTiles.Height / 32; h++)
                {

                    var gX = SelectedTiles.X / 32 + w;
                    var gY = SelectedTiles.Y / 32 + h;

                    var tY = (gY) * curTexture.Width / 32;
                    var tX = gX;
                    var tileID = tY + tX;

                    newTiles.Add(gameMap.Layers[Layer].MapTiles[X + w][Y + h].TileId);
                    gameMap.Layers[Layer].MapTiles[X + w][Y + h].TileId = _previousTiles.Last();
                    _previousTiles.Remove(_previousTiles.Last());
                }
            }

        }

```

# Answer
> 3 votes
Don't get overly clever with your storage. For each operation, store the old value, the new value, and *what* changed. Something like:

```
class Edit:
  int x
  int y
  tile_t old
  tile_t new

  void apply_undo():
    set_tile_at(x, y, old)

  void apply_redo():
    set_tile_at(x, y, new)

```

You will want this to store whole (not necessarily rectangular) regions of tiles as any decent tile editor can do operations on multiple tiles. The hardest one, IMO, being "flood fill".

Essentially, each `Action` should store the *delta* of the map after applying its corresponding changes as completely but narrowly as possible. That means you need all the information to both apply the action and undo it, such as including the old and new tile values as shown. For other types of edits you could just store a big grid or 2D array of tiles so long as you have a way of marking a particular tile in said grid as "not changed." This ability isn't immediately apparent but it has uses later.

Note that a naive first-draft implementation can just store the entire map at each edit point. You can avoid saving the old map for each edit as it will be given by the previuos edit (the delta is implicit in the edit history). You will need an "initial state" item added to the history in this case. I don't recommend this particular approach, but it can help to visualize what's going on.

You now need to keep a history of your actions, including the level of undo you're at. Every time you do an Undo, apply the current level's undo action then step back one item. When you do a Redo, step forward one and apply the redo action. If you perform a new action, you probably want to truncate the history first to the current undo level and then add the new record (this is what most undo/redo systems do).

```
class History:
   Action list[]
   int level

   void undo():
     if level > 0:
       level = level - 1
       list[level].apply_undo()

   void redo():
     if level < list.length:
       list[level].apply_redo()
       level = level + 1

   void add(action)
     list.truncate(level)
     list.add(action)
     level = list.length

```

That simple. Note that depending on how you build and apply your actions, you can just make an `Action` instance and then call its apply\_redo() to do its action for the first time. Some actions like flood fill might generate its undo/redo data while being applied, though, depending on how you implement it.

Some of the harder actions to implement include the aforementioned flood fill, canvas resizes, and the manipulation of non-tile objects in the world. Making `Action` an abstract interface that you can implement in multiple ways will come in handy as you add more complex operations to your editor and hence need more complex ways to undo/redo things.

---
Tags: c#, algorithm, map-editor
---


title: Game Scene Manager

text:
# Question
Title: Game Scene Manager
I'm starting to code my engine's Scene Manager, and after some research in the internet I've found (surprisingly) various posts **against** the use of a SceneGraph.

It does make sense, and the concept itself is quite old, so what are the alternatives and/or some examples of it?

# Answer
What you are **probably** reading is that it's seen as a mistake to reuse a graphics scene graph as the managed scene data structure for the rest of the program to work with.

For a long while, back in the stone age, memory was tight and there was only one data structure holding a level together and it served rendering and game logic. Now we have a little room to work with and performance and easier coding of more complex features means that we need and can use structures appropriate to the algorithms.

For example, a quadtree is great for graphics operations but it would be ridiculously bad if you needed a list of all active enemies.

Beyond that simple example I think that you need to really think about what you are asking and add a lot more detail (and a glossary) to the question before you'll get any replies useful to you.
> 2 votes

---
Tags: scene
---


# Question
Title: Day and Night mode according to user's real local time
How do I make it so the texture of my plane is a black sky when it's night according to player's local time (say from 10 PM to 5 AM it's going to be black, and from 6 AM to 9 AM it's going to be a blue sky)?

Blue sky texture name is "bluesky" Black sky texture name is "blacksky"

Thanks.

# Answer
See How do I blend 2 lightmaps for day/night cycle in Unity? for a previous question about fading 2 lightmaps for day/night cycles. It includes an answer that seems to indicate how to do it. Your challenge will be to get the current time, figure out how much day/night sky you want given that time, and make it so.

In the answer given to the linked question, the shader has a "\_Blend" value that you can set between 0.0 and 1.0. 0.0 is fully one skybox, and 1.0 is fully the other. What you'll want to do is have it be one value during the day, and the other during the night. Then as the sun goes down, change to the other. As it rises the next day, change back.
> 2 votes

# Answer
Check if `System.DateTime.Now.Hour` is between the hours you consider to be the night (it is 24h based) and change the skybox texture accordingly and dim all natural lights as well.
> 0 votes

---
Tags: unity
---


# Question
Title: Implementing a skybox with GLSL version 330
I am trying to get a skybox working with OpenGL 3.3 and GLSL version 330.

I could not find a completely modern OGL skybox tutorial anywhere on the web, so I modernised an older one (using `glVertexAttribPointer()` instead of `gl_Vertex` for vertices, etc.). It's mostly working, but for 2 major details:

The skyboxes are more like sky triangles, and the textures are badly warped and stretched (they are supposed to be star fields, I get while lines on a black background). I'm 99% sure that this is because I didn't port the old tutorials completely correctly.

Here is my skybox class:

```
static ShaderProgram* cubeMapShader = nullptr;

static const GLfloat vertices[] =
{
    1.0f, -1.0f,  1.0f,
    1.0f,  1.0f,  1.0f,
    1.0f,  1.0f, -1.0f,
    -1.0f, -1.0f,  1.0f,
    -1.0f, -1.0f, -1.0f,
    -1.0f,  1.0f, -1.0f,
    -1.0f,  1.0f,  1.0f,
    -1.0f,  1.0f, -1.0f,
    1.0f,  1.0f, -1.0f,
    1.0f,  1.0f,  1.0f,
    -1.0f,  1.0f,  1.0f,
    -1.0f, -1.0f,  1.0f,
    1.0f, -1.0f,  1.0f,
    1.0f, -1.0f, -1.0f,
    -1.0f, -1.0f, -1.0f,
    1.0f, -1.0f,  1.0f,
    -1.0f, -1.0f,  1.0f,
    -1.0f,  1.0f,  1.0f,
    1.0f,  1.0f,  1.0f,
    -1.0f, -1.0f, -1.0f,
    1.0f, -1.0f, -1.0f,
    1.0f,  1.0f, -1.0f,
    -1.0f,  1.0f, -1.0f
};

Skybox::Skybox(const char* xp, const char* xn, const char* yp, const char* yn, const        char* zp, const char* zn)
{
if (cubeMapShader == nullptr)
    cubeMapShader = new ShaderProgram("cubemap.vert", "cubemap.frag");

    texture = SOIL_load_OGL_cubemap(xp, xn, yp, yn, zp, zn, SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS);

    glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

    glGenVertexArrays(1, &vaoID);
    glBindVertexArray(vaoID);
    glGenBuffers(1, &vboID);
    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glBindVertexArray(0);

    scale = 1.0f;
}

Skybox::~Skybox()
{

}

void Skybox::Render()
{
    ShaderProgram::SetActive(cubeMapShader);
    glDisable(GL_DEPTH_TEST);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
    cubeMapShader->Uniform1i("SkyTexture", 0);
    cubeMapShader->UniformVec3("CameraPosition", Camera::ActiveCameraPosition());
    cubeMapShader->UniformMat4("MVP", 1, GL_FALSE, Camera::GetActiveCamera()->GetProjectionMatrix() * Camera::GetActiveCamera()->GetViewMatrix() * glm::mat4(1.0));
    glBindVertexArray(vaoID);
    glDrawArrays(GL_QUADS, 0, 24);
    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}

```

Vertex Shader:

```
#version 330
layout(location = 0) in vec3 Vertex;

uniform vec3 CameraPosition;
uniform mat4 MVP;

out vec3 Position;

void main()
{
    Position = Vertex.xyz;
    gl_Position = MVP * vec4(Vertex.xyz + CameraPosition, 1.0);
}

```

Fragment Shader:

```
#version 330 compatibility

uniform samplerCube SkyTexture;

in vec3 Position;

void main()
{
    gl_FragColor = textureCube(SkyTexture, Position);
}

```

Here's an example of the glitches. If anyone could take a look who knows GLSL well (I'm still learning it), or skyboxes, I would appreciate any help you could give. Also, kudos if you can teach me how to use non-deprecated functions in the fragment shader so I don't have to use the compatibility profile of glsl 330.

---

EDIT: Immediately found the problem with the stretching textures: I was using `Position = Vertex.xy`**`x`** instead of `Position = Vertex.xy`**`z`** in the vertex shader. Oops. But the triangle error still exists.

# Answer
While this answer does not tell what is wrong with your approach, it presents a simpler way to render skyboxes.

# Traditional way (textured cube)

A straightforward way for creating skyboxes is to render a textured cube centered to the camera position. Each face of the cube consists of two triangles and a 2D texture (or part of an atlas). Due to texture coordinates each face requires own vertices. This approach has problems in the seams of adjacent faces, where the texture values are not interpolated properly.

# Cube with cubemap texture

Like in the traditional way, a textured cube is rendered around the camera. Instead of using six 2D textures, a single cubemap texture is used. Because the camera is centered inside the cube, the vertex coordinates map one to one with the cubemap sampling vectors. Thus texture coordinates are not needed for the mesh data and the vertices can be shared between faces by using index buffer.

This approach also fixes the problem of seams when GL\_TEXTURE\_CUBE\_MAP\_SEAMLESS is enabled.

# Simpler (better) way

When rendering a cube and the camera lies inside it, whole viewport gets filled. Up to five faces of the skybox can be partially visible at any time. The triangles of cube faces are projected and clipped to the viewport and cubemap sampling vectors are interpolated between the vertices. This work is unnecessary.

It's possible to fill a single quad filling the whole viewport and calculate the cubemap sampling vectors in the corners. Since the cubemap sampling vectors match the vertex coordinates, they can be calculated by unprojecting the viewport coordinates to the world space. This is the opposite of projecting world coordinates to the viewport and can be achieved by inverting the matrices. Also make sure you either disable z-buffer write or write a value that is far enough.

Below is the vertex shader that accomplishes this:

```
#version 330
uniform mat4 uProjectionMatrix;
uniform mat4 uWorldToCameraMatrix;

in vec4 aPosition;

smooth out vec3 eyeDirection;

void main() {
    mat4 inverseProjection = inverse(uProjectionMatrix);
    mat3 inverseModelview = transpose(mat3(uWorldToCameraMatrix));
    vec3 unprojected = (inverseProjection * aPosition).xyz;
    eyeDirection = inverseModelview * unprojected;

    gl_Position = aPosition;
}

```

`aPosition` is the vertex coordinates `{-1,-1; 1,-1; 1,1; -1,1}`. The shader calculates `eyeDirection` with the inverse of model-view-projection matrix. However the inversion is split for projection and world-to-camera matrices. This is because only the 3x3 part of the camera matrix should be used to eliminate the position of the camera. This aligns the camera to the center of the skybox. In addition as my camera doesn't have any scaling or shearing, the inversion can be simplified to transposition. The inversion of the projection matrix is a costly operation and could be precalculated, but as this code is executed by the vertex shader typically just four times per frame, it's usually a non-issue.

The fragment shader simply performs a texture lookup using `eyeDirection` vector:

```
#version 330
uniform samplerCube uTexture;

smooth in vec3 eyeDirection;

out vec4 fragmentColor;

void main() {
    fragmentColor = texture(uTexture, eyeDirection);
}

```

Note that to get rid of the compatibility mode you need to replace `textureCube` with just `texture` and specify the output variable yourself.
> 33 votes

---
Tags: c++, opengl, glsl, cubemap, skybox
---


# Question
Title: 2D Camera doesn't work when I have split my code into DrawableComponents
I have the following camera written:

```
public class Camera
{
    public Vector2 Position;

    Viewport Viewport;

    public Matrix Transformation
    {
        get
        {
            return Matrix.CreateTranslation(new Vector3(-this.Position.X, -this.Position.Y, 0)) *

            Matrix.CreateRotationZ(0f) *
            Matrix.CreateScale(new Vector3(1f, 1f, 1)) *
            Matrix.CreateTranslation(new Vector3(Viewport.Width * 0.5f, Viewport.Height * 0.5f, 0));
        }
    }

    public Camera(GraphicsDevice device)
    {
        this.Position = Vector2.Zero;

        this.Viewport = device.Viewport;
    }
}

```

Now while this does work in tutorials where you have all your drawing in the Game.Draw like this:

```
protected override void Draw(GameTime gameTime)
        {
            this.GraphicsDevice.Clear(Color.SkyBlue);

            this.SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, cam.Transformation);

            this.Player.Draw(this.SpriteBatch);
            this.World.Draw(this.SpriteBatch);
            this.Enemies.Draw(this.SpriteBatch);

            this.SpriteBatch.End();

            base.Draw(gameTime);
        }

```

It fails when you have your code organized in DrawableGameComponents (which I have). Now, technically speaking I could add the Camera as a service in the game, retrieve it in the constructor of my DrawableGameComponents, add it as a field within the Component and then edit the spriteBatch.Begin() within the Draw of each component like it is shown above. So actually that it WOULD look like this:

```
public class TestComponent : DrawableGameComponent
    {
        Camera Camera;

        SpriteBatch Batch;

        public TestComponent(Game game)
            : base(game)
        {
            this.Camera = (Camera)this.Game.Services.GetService(typeof(Camera));
            this.Batch = (SpriteBatch)this.Game.Services.GetService(typeof(SpriteBatch));
        }

        public override void Draw(GameTime gameTime)
        {
            this.Batch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, this.Camera.Transformation);

            // draw the component

            this.Batch.End();

            base.Draw(gameTime);
        }
    }

```

But as you might already have guessed this is a bad idea because it's basically redundant.

Is there a way I can maintain this at a central location?

# Answer
The answer is simple

In your Game code:

```
    public override void Draw(GameTime gameTime)
    {
        this.Batch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, this.Camera.Transformation);

        base.Draw(gameTime);

        this.Batch.End();
    }

```

tl;dr: Call Begin, call base.Draw(), call End. There seems to be the logic to dispatch the Draw and Update methods of all components in the base class Game.
> 0 votes

# Answer
I would it do the following basic way:

You have components and for each Component-Type you have a Class which does something with the components.

So this means for this particular question that you need a Class which knows the Camera transformation and does have a datastructure (the simplest is a array, followed by list or tree) with *all* Renderables.

UML style:

```
+ configure(Camera OfCamera)
+ renderAll()
- renderRenderable(Renderable OfRenderable)
+ add(Renderable Component)
+ remove(Renderable Component)

- Array<Renderable> Renderables
- Camera OfCamera

```
> 1 votes

# Answer
If you care about constructor redundancy, you can create some base class DGCBase, which will inherit from DrawableGameComponent and every component will inherit it. Members (variables, functions, also constructor), which are common for all components will be in this DGCBase. And special functions will be in specific components.

But this.Batch.Begin will be in every component. Maybe after some time you will want to change it's parameters. But I think that this is not a lot of code to "copy".

Maybe you can create some functions like BeginDraw and EndDraw (which are part of Game class) and call them in each component's Draw function (at the beginning and end).
> 0 votes

---
Tags: xna-4.0, camera
---


# Question
Title: My FlxGroup does not change it's visibility status
So, I found I needed a different type of button for my game, which I am making using Haxe, OpenFL and HaxeFlixel. After sometime fliding with Haxe, I got following button done, which works just fine. It's not the most sophisticated button, but it gets the job done.

```
class ArrowButton extends FlxGroup
{
    private var spriteUp:FlxSprite;
    private var spriteDown:FlxSprite;
    private var onClick:Void->Void;
    private var x:Float;
    private var y:Float;
    private var traced:Bool;

    public function new(x:Float = 0, y:Float, up = true, onClick:Void->Void = null)
    {
        super();

        this.x = x;
        this.y = y;
        this.onClick = onClick;

        if (up)
        {
            spriteUp = new FlxSprite(x, y, Assets.getBitmapData("assets/ArrowUp.png") );
            spriteDown = new FlxSprite(x, y, Assets.getBitmapData("assets/ArrowUpPushed.png") );
        }
        else
        {
            spriteUp = new FlxSprite(x, y, Assets.getBitmapData("assets/ArrowDown.png") );
            spriteDown = new FlxSprite(x, y, Assets.getBitmapData("assets/ArrowDownPushed.png") );
        }
        add(spriteDown);
        add(spriteUp);
        buttonUp();
    }

    private function buttonDown():Void
    {
        if (pressed != true)
        {
            spriteUp.visible = false;
            spriteDown.visible = true;
            pressed = true;
        }
    }

    private function buttonUp():Void
    {
        if (pressed = true)
        {
            spriteUp.visible = true;
            spriteDown.visible = false;
            pressed = false;
        }
    }

    private function isClicked():Void
    {
        //trace("Mouse X:Y" + FlxG.mouse.screenX + ":" + FlxG.mouse.screenY + ", button X:Y " + x + ":" + y);

        if (onClick != null && FlxG.mouse.screenX > x && FlxG.mouse.screenX < x + 16 && FlxG.mouse.screenY > y && FlxG.mouse.screenY < y + 16)
        {
            buttonUp();
            onClick();
        }
    }

    override public function destroy()
    {
        super.destroy();
    }

    override public function update()
    {
        if(FlxG.mouse.justReleased())
        {
            isClicked();
        }

        if (FlxG.mouse.pressed() && FlxG.mouse.screenX > x && FlxG.mouse.screenX < x + 32 && FlxG.mouse.screenY > y && FlxG.mouse.screenY < y + 32)
        {
            buttonDown();
        }
        else
        {
            buttonUp();
        }

        super.update();
    }

}

```

Now, I got problem: I can't hide the button. I add this button as a member of another FlxGroup, called systemView. I got several views that I hide and show, depending what menu player is in. So when I move out of systemView, I call function called hideStuff()

```
private function hideStuff():Void
{
        sideMenu.setAll("visible", false, true);
}

```

now, this works fine for everything else, EXCEPT my own button. That one it misses, for some reason. Any ideas why this happens and how to fix it?

# Answer
> 2 votes
Not sure what went wrong there. Just tested that `setAll("visible", false)` call on a `FlxGroup` and it seemed to be working fine.

A few other things though:

* You should not need to do a `setAll()` for visibility on a `FlxGroup` at all. FlxGroups have a `visible` property themselves, because they extend `FlxBasic`!
* The button you're trying to implement, having a sprite for the `onUp` and one for the `onDown` state, seems extremely similar to `FlxButtonPlus`. Have a look at that!
* You don't need to use `Assets.getBitmapData()` when loading a graphic for a `FlxSprite`. You can just pass the path to the asset as a `String`!
* There's a handy plugin called `MouseEventManager` which lets you create callbacks for mouse events on a `FlxSprite` (`onUp`, `onDown`, `onOver`, `onOut`). Check the demo out here. Please note that the demo code only works with the dev version of flixel currently, and that the plugin is still called `MouseInteractionMgr` in the haxelib release (2.0.0-alpha.3). Either way, this plugin would help avoid those region checks in the `update()` function, which could become expensive for a lot of these buttons.

Have fun using HaxeFlixel! If you run into any other issues in the future, it's probably a better idea to post to the official HaxeFlixel forums. You're way more likely to get help there, since the engine is not all that well-known currently.

---
Tags: flixel, haxe
---


# Question
Title: How do I tell if an object is currently colliding with another object?
I can't figure out how to tell if a `GameObject` is currently colliding with another in Unity. I've looked online and can't find any tutorials or answers that work.

Also, what's the difference between a `Collision` and a `Collider` w.r.t. Unity?

---

My dilemma:

I have a third person controller set up and want it to wall jump. I already have an isGrounded function, I just need to test if I'm hitting anything other than the floor. Otherwise I want it to wall jump backwards.

I've already tried:

```
if (this.OnCollisionEnter){
     ...
}

if (Collider.OnCollisionEnter){
     ...
}

```

But it did not work. I now tried:

```
function OnCollisionStay(){
   Debug.Log("Collision");
}

```

I checked my logs, console and still can't find anything.

# Answer
1. The function `MonoBehavior.OnCollisionStay()` (link) is called every frame for every collider that is touching another collider there are also `OnCollisionEnter()` (link) and `OnCollisionExit()` (link) for similar behavior at the start and end of contact. If you want to do something while your object is being collided with, put that function in a script on that object and put your code in there.
2. A Collider is the object that does the colliding. The Collision is the event/data that tells you about the collision. Some explanation can be found here and other places in the Unity docs.
> 4 votes

# Answer
Based on Unity script reference, Collision is a class representing all the information about a collision. It's a parameter passed to `Collider.OnCollisionEnter`, `Collider.OnCollisionStay` and `Collider.OnCollisionExit` events. Collider on the other hand is everything that has a physical representation.

So if you want to know whether an object is colliding with any other object in the game, you have to define a *collider* for both of them, and implement OnCollisionEnter event for the object you are interested in.
> 3 votes

# Answer
Are you sure that at least one of the colliding objects have a non-kinematic rigidbody attached? It did the trick for me.

http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionEnter.html
> 0 votes

---
Tags: unity, collision-detection
---


# Question
Title: Square collision: Detect which side of the wall it collided
I'm using a standard square collision in my 2D game. The player shoots little balls, and when they hit any wall it should bounce.

The problem is that I know when it hits a wall but I don't know if the collision happened on the side or top/bottom of the wall.

Here's my collision algorithm (pseudo code):

```
If
A.x < (B.x + B.width) AND
B.x < (A.x + A.width) AND
A.y < (B.y + B.height) AND
B.y < (A.y + A.height)
Then a collision happened

```

Is it easy to detect if the collision happened on a side or top/bottom? If yes how should I do it?

# Answer
The easiest and most common way is to maintain information of the current and last position of the moving projectile. You can get a direction vector. If you know that and the length of a timestep that passed since it was last updated, you can even determine the point of collision, reverse the appropriate speed (and apply friction and such if you wish) and move the object to that direction the remaining amount in the timestep. It makes the model more accurate.
> 0 votes

---
Tags: algorithm
---


title: Triple buffering and jittering

text:
# Question
Title: Triple buffering and jittering
John Carmack has a tweet:

"Triple buffering adds latency and jitter; it should be avoided. The Answer is non-isochronous display updates."

Can anyone explain what he meant by adds latency and jitter?

# Answer
I have an idea of where the jittering comes from with vSync and triple buffering. The easiest way to show this is visually.

The first example would be 30fps with a 60hz refresh rate vSynced with Double buffering. The pipes are new frames and periods are duplicated frames.

|.|.|.|.|.|.|.|.|.

This gives an even ~33ms between each new frame, which makes it appear smooth (for 30 fps anyway). You can see how fitting 60fps into the same situation fits perfectly into the timing interval, allowing for a new frame every refresh.

Now, lets see how it would look running 45fps at a 60hz refresh rate vSynced with Triple Buffering:

|||.|||.|||.|||.|||.

You can see here that there is an uneven interval between frames. In this case, the frame times are 16,16,16,33,16,16,16,33. Since the monitor only updates once every ~16ms, if a new frame isn't ready for a particular update, it still has to wait a whole additional ~16ms, even if its ready 1-2ms after the previous update.

However, I think the whole TB situation is still debateable and depends on the situation. Personally, I'd rather see 55fps with no tearing with occasional dropped frames than to go all the way down to 30fps to get even frame timing.

As a side note, this is a good example of how a 120hz monitor can increase smoothness of a game running at ~45fps since there is a higher frequency of times that a new frame can be displayed to the screen.
> 2 votes

# Answer
It adds latency because you've got 3 buffers involved instead of 2, so it takes one more frame for your rendered image to get to the screen.

I have *no idea* what kind of "jitter" Carmack is talking about here, though.

**EDIT**

Maybe, just maybe, this could make sense in a highly variable framerate context: frames rendered with a given delta-time but displayed later with a different delta, resulting in a visible jitter?
> 1 votes

---
Tags: double-buffering, latency
---


# Question
Title: When is a good point to revise a project?
I am currently working on a project. Some time ago I realized that I do achive my goals but the more code and prototypes I add the more I feel like there is no going back. For example some of the data-structures, methods and parts of architecture I implemented could be made more productive and reusable. But this would need a refactoring nearly from scratch.

So I wonder, is it a good decision to reedit a project as soon as I realized it's flaws or should I finish all the prototypes and then create a final and clean version?

I think it does matter that I am a solo developer.

Thanks in advance.

# Answer
> 2 votes
Well, this is what I do. It works for me, but other people might find they use different methods.

**Refactoring pays off**.

Continuously refactor and rework the code. Code is more like clay, where you continuously remold it, than some kind of brittle structure that you set up once and use forever. You can always go back and improve bits you don't like. That said, you have to be extra careful not to break anything in the process of refactoring. There may be a point of spagettiness beyond which a body of code may be nearly unsalvageable -- ie when *even reasonable* refactoring exposes bugs that you *never* would have guessed would pop up. If your code base is in that state, then you have 2 options:

a) Sit down and refactor, fixing bugs as the appear

b) Don't refactor, push the project to the end, and next time make sure to write better code!

# Answer
> 2 votes
Generally the earlier you fix the flaws, the less money/time you lose compared to fixing them later. These errors/inefficiency tends to stack up. There's plenty of literature on agile development though and working iteratively. That being said, refactoring should be a part of your work cycle.

# Answer
> 2 votes
Two conditions matter:

If you're working on a single, long lived project then refactor as soon as a good case can be made for the change. And by "good case" the criteria should be how many new systems will have to work against this code, how often does the code surrounding this change, will this change actually make it easier to use or is it just to be pretty? Will it save you time?

If you're working on multiple, sequential projects then simply mark it for a refactor and do the work when you start the next project that uses it.

The big point is that you recognize a real need versus just wanting to do it differently because, as a single dev, your time is precious. And once the need is determined, do it inline with your other work so it's part of your normal workflow. Continuously evaluate how well your code fits together and serves its purpose and continuously improve code if it meets the criteria above.

At some point also look at your overall architecture; if changing one section of code requires lots of external changes then modules are too tightly bound and that may be what's causing you to need big rewrites...

# Answer
> 1 votes
I think that you shall do a continuous refactoring throughout your project. That's part of the normal work flow. Do it in small steps, and continuously!

I always leave a TODO comment where something can be improved, and then I can do those improvements when I feel for it. I try to keep the number of TODOs at a manageable number. Maybe around 50 items. Larger redesign work is put in my backlog.

One more comment. I think the most important thing is that the code and structure is clean, with good responsibilities to classes etc. That's more important that reusability. You can do the reusability modifications *if* the code in question will be reused. Most code won't be reused :)

# Answer
> 1 votes
For further reading, you should study the chapter *A Pragmatic Philosophy/Software Entropy* from *The Pragmatic Programmer* by Andrew Hunt & David Thomas. It deals exactly with your problem here. I will drop this quote from the book:

> One broken window, left unrepaired for any substantial length of time, instills in the inhabitants of the building a sense of abandonment—a sense that the powers that be don't care about the building. So another window gets broken. People start littering. Graffiti appears. Serious structural damage begins. In a relatively short space of time, the building becomes damaged beyond the owner's desire to fix it, and the sense of abandonment becomes reality.

...

> Don't leave "broken windows" (bad designs, wrong decisions, or poor code) unrepaired. Fix each one as soon as it is discovered. If there is insufficient time to fix it properly, then board it up. Perhaps you can comment out the offending code, or display a "Not Implemented" message, or substitute dummy data instead. Take some action to prevent further damage and to show that you're on top of the situation.

Are you going to throw away all of the prototype's code? If not, and you're going to build upon it, then don't make your life harder by leaving broken things pile up. You may find comfort in thinking that you'll repair things later, but this also makes you oblivious to the piling, and you might just overlook serious and otherwise obvious flaws.

**Tip 1:** After you're done writing a method, read it again, start-to-end, and see if it cannot be refactored.

**Tip 2:** When you're not actually writing code, and have the time, take a few minutes to look over your code and see what can cause trouble and what can't. If you can afford it, fix everything on the spot. If not, then at least set a TODO there, and write down what can go wrong and why, so you remember the next time you're visiting the code. I call these 'quick refactoring sessions', and I perform them quite often.

I find that the most important ingredient in refactoring early and properly is willpower. Be sure to have some ready!

My third tip is extracted from the book itself.

> Don't Live with Broken Windows

# Answer
> 1 votes
The real thing you want to consider is *why* you're refactoring. If there's some tangible benefit you get out of it, sure, refactor when you see the need. If not, you can put it aside.

For example, I tend to do major architectural refactorings project by project: I commit to small project (order of months), and any major changes (like moving towards an entity/component architecture or a data-driven design) I commit to when I start on the next project.

On the other hand, for long-lived projects, the bigger driving force is technical debt. Like financial debt, it can slow you down or even kill you off. In this case, as soon as you know there's a problem, and it makes sense, fix it.

When does it make sense?

* When there's some value you get out of the change (eg. makes it easier to do X)
* When you know the change is inevitable (*must* be done)
* When there isn't a looming deadline (intermediary release, milestone, etc.)
* When you can afford the time to finish the change

To summarize, **it really depends on the needs of the project and your availability.** Personally, I try to integrate small refactorings as I go, and leave major ones for the next project (which is not too far off).

---
Tags: refactoring
---