title: Determining Poker Hands

text:
# Question
Title: Determining Poker Hands
I have been making a Texas Hold'Em game as a part of an assessment, and I have been mulling over how to examine the 7 available cards and determine if hands exist.

The only possible method I can think of is to sort the cards numerically, then examine each possible group of 5 cards and check if they match a list of every single possible hand. That would take a long time snd would only be feasible for determining pairs, as the suit is irrelevant.

The cards are each strings, made up of a number/a/j/q/k, and a suit `(char)3` (that makes a little spades symbol).

Does anyone have any suggestions, formulas, or links I could use to help create a hand-analysing system?

Don't worry about ranking hands against each other yet, that's a different kettle of fish.

# Answer
> 20 votes
I think you can find the majority of poker hands by simply making a couple of tables of how many cards in the hand there are of each rank and suit.

In other words, create an array mapping card ranks (numbers and A/J/Q/K) to the count of cards of that rank in your hand. If the player has a pair or three-of-a-kind, there will be an element in this array equal to 2 or 3, etc. They have a full house if there's one element that's 2 and another that's 3, and a straight if there are five consecutive elements equal to 1 in this array.

Likewise you can make a similar array of the count of cards of each suit, and use it to detect flushes.

Once you've detected the presence of a specific hand it's pretty easy to then go back and find the specific cards in the hand, for highlighting them in the UI or whatever you need to do.

In pseudocode:

```
int countByRank[13] = { 0 };        // Initialize counter to zero for each rank
for (cards in hand)
    countByRank[card.rank] += 1;    // Increment counter for this card's rank
if (countByRank.find(2))
    // There's a pair
else if (countByRank.find(3))
    // There's a three-of-a-kind
// etc...

```

# Answer
> 18 votes
It's a little tricky because there's so many combinations. Luckily you have a processor that can check a great number of combinations in a very short time.

You'll need a few different strategies, for detecting different types of hands. Luckily, a few of the different types can overlap strategies. I would search through, in order by rank of the hand.

1. Straight flush
2. Four of a kind
3. Full house
4. Flush
5. Straight
6. Three of a kind
7. Two pair
8. One pair
9. High card

`2`, `3`, `6`, `7`, `8` are all simple counting. Using a list of cards Ace to King, simply place the number of each value in the list, incrementing for each additional card found. Then check the list for 4s, if there's no 4s, you don't have a 4 of a kind. Check it for 3s, if there's no 3s, you don't have a 3 of a kind. If you have a 3, check for a 2 (indicating full house). And so on...

For `1`, `5` you can use the same list and look for sequences where all cards have one or more entries in the list for a sequence of 5 cards. If they also have the same suit, it's a straight flush.

`4` can have the same list setup but this time you're counting the suit. Look for numbers of 5 or higher.

Finally, `9`, you have the highest card, which should be a simple matter of looking at the last highest value from one of your lists above.

You can break out once you've found a match if you search in order. Though it would be trivial to continue the search and find all the matches if you want to provide all that information to the user.

---

Essentially, you're filling buckets. Then checking the buckets for combinations. To illustrate:

Starting with an array, with a bucket for each card, iterate through the cards and count the instance of each card. Then you can easily iterate the array and check for certain combinations. In this example, it's clear that there's a 4 of a kind because one of the buckets has 4 items in it.

# Answer
> 6 votes
I bumped into this algorithm once. It multiplies prime numbers to determine hands and is a very interesting reading. Cactus Kev's Poker Hand Evaluator

# Answer
> 2 votes
To supplement the excellent answers this question has already gotten, I thought it would be helpful to offer one of the most straightforward ways of comparing hands once the basic classification technique in place. First of all, you'll want to tag hands with their **class**, as numerous answers have suggested - most of your comparisons of 'is hand X better than hand Y?' can then be done just by comparing the two hands' classes and seeing which class is better. For the rest, you'll actually need to compare on a card-by-card basis, and it turns out that a little bit more work in classification will make this easier.

As the baseline case, consider the situation where both hands are 'high card' hands; in this case, you'd compare the two highest cards first, then (if they matched) the next two cards, etc. If you assume that each input hand is sorted from highest to lowest card, this approach leads to code that looks like this:

```
int CompareHandsOfSameClass(Hand h1, Hand h2) {
  for ( int i = 0; i < 5; i++ ) {
    if ( h1[i].rank > h2[i].rank ) {
      return -1;
    } else if ( h1[i].rank < h2[i].rank ) {
      return 1;
    }
  }
  return 0;
}

```

Now, the good news: it turns out that this *lexicographical ordering*, suitably tweaked, works for comparing two hands in *any* of the classes, as long as their class is the same. For instance, since the way of comparing pairs is to compare the pairs first, then the other three cards, you can sort your hand to put the pair first (or even one card of the pair first!) and run this same comparison. (So, for instance, a hand like A9772 would be stored as either 77A92 or, better yet, 7A927; the hand A9972 would be stored as 9A729, and comparing with the above code you'd start by pitting 7 against 9 and find that A9972 won). A hand of two pair would be stored with the higher of the two pairs first, then the lower, then the 'kicker' (so, e.g., A9977 would store as 97A97); three of a kind would be stored with one card of the three first, then the kickers, then the other cards (e.g., A7772 would be 7A277); a full house would be stored with one of its three and then one of its two (e.g., 99777 would be stored as 79779); and straights and flushes can both be stored in 'direct lexicographical' order since they're both compared just like high-card hands are. This leads to a straightforward outer comparator function that works for all classes of hands with the already-given function:

```
// Compare two hands, returning -1/0/+1 as hand 1 is less than, equal to,
// or greater than hand 2. Note that this function assumes the hands have
// already been classified and sorted!
int CompareHands(Hand h1, Hand h2) {
  if ( h1.handClass > h2.handClass ) {
    return -1;
  } else if ( h1.handClass < h2.handClass ) {
    return 1;
  } else {
    return CompareHandsOfSameClass(h1, h2);
  }
}

```

Hopefully this will be of some help!

# Answer
> 1 votes
There are some parallelisations possible using suitable card representations and bit-twiddling. For example, this Java code evaluates 7-card hards returning an integer which can be used for comparing two hands. It could be adapted to report the type of the hand in a more user-friendly way. The core ideas come from Cactus Kev's page referenced in an earlier answer.

If you're only interested in possible implementations for naming the hand in various languages rather than efficiency and code clarity, you could also look at the Name the poker hand challenge on codegolf.SE.

# Answer
> 1 votes
First, you need to know the rank and suit of all the cards; trivial but necessary.

Then, spin through these 7 cards and create two histograms; one by rank (using an array with 13 indexes, all initialized to zero and incremented by 1 if and when a card in the hand with that rank is found) and one by suit (using an array of four elements constructed similarly as for rank). These are linear operations and you can do both operations for each card for only one set of traversals.

You can then determine whether any of the following hands exist by simply examining each histogram for buckets matching the criteria, and/or a simple follow-up test:

* Pair: Does exactly one rank bucket have a value of exactly 2, with no other bucket having a value above 1 and no flush?
* Two Pair: Do two or more rank buckets have a value of exactly 2, with no bucket having more than 2 and no flush? (obviously three pair is not a hand, but it's a possibility given seven cards; the strongest two pair is the player's hand)
* TOAK: Does exactly one bucket have a value of exactly 3, with no other bucket having a value greater than 1 and no flush?
* Straight: Do five consecutive rank buckets have a value of 1 or more with no flush? (Don't forget that Aces are both high and low; you could use a rank histogram of 14 elements and count Aces in two buckets if you'd like)
* Flush: Does any *suit* bucket have 5 or more cards? (if so, scan the hand for cards of that suit and choose the top 5)
* Full House: Does any one rank bucket have a value of 3 and any other bucket have a value of 2 (with 7 cards, a flush is impossible with a full house unless you're playing with a Pinochle deck)
* Four of a Kind: Does any one rank have a value of 4? (no other combination should be possible)
* Straight Flush: Is there both a straight *and* a flush indicated by the histograms? If so, is there at least one card in the indicated flush suit with a rank matching each rank of the indicated straight? (this is probably the most computationally expensive, but it should be simple to count how many consecutive ranks there are, and you should only have to scan the hand once for 5 concecutive ranks, twice for 6 and three times for 7)

You can, quite naturally, combine several of these checks:

* Is there a flush?
* Is there a straight?
    + If there are both, is it a straight flush?
    + If it's a straight flush, does it have both an Ace and a King?
* Is there a four-of-a-kind?
* How many three-of-a-kinds are there? (Two, it's a full house. One, check pairs)
* How many pairs are there? (With two or more, it's two pair. With one, if there's also a three it's a full house, otherwise it's a pair)
* None of the above (high card).

Basically, if the answers to these yield any hand, set the resulting "hand strength" value to the strength of the hand found, *if* the value is not already higher. For instance, if you have a full house, strength 7 of 9, then you also have a three of a kind, strength 4, and a pair, strength 2.

There are a few shortcuts and fast outs, but overall it's not really *that* expensive to just run all the checks.

# Answer
> 0 votes
You can do poker hands relatively easily with a simple iterative approach.

For each card, check if there is one or two or three others with the same face to check for pair or three/four of a kind.

Full houses are similar. Or if you find both a pair and three of a kind that aren't the same face, flag a full house as found.

For flushs, check each suit to see if there are five of the same suit.

Checking straight is easy, even if unsorted. For each card, check if there is one higher, and repeat until five consecutive cards are found or not.

Royal flushes and straight flushes can be found similarly to straights. Royal flushes have some extra conditions in that lower valued cards can be ignored.

Yes, this approach is inefficient, but for most poker games, that is irrelevant. You're checking a tiny handful of players every half minute or so, not checking thousands of hands per second.

Better methods exist but may take more time to code, and you likely have more important things to spend time/money on that'll make for a better game from players' perspective besides cleverness and efficiency of an algorithm.

# Answer
> 0 votes
a simple way to find pairs, double pairs, toaks, full houses, pokers etc is the following:

compare each card with each other in a nested loop like this one:

```
int matches=0;
for (int i=0;i<5;i++)
   for (int j=0;j<5;j++)
      if (i!=j && cardvalue(card[j])==cardvalue(card[i])) matches++;

```

matches will hold the following:
2 for a pair
4 for two pairs
6 for toak
8 for a fullhouse
12 for a poker

to speed optimise this: it's not needed to run the j-loop up to 5, it can be run to i-1. the comparison "i!=j" can then be removed, the values for match are then halved (1=pair, 2=2pair etc.)

---
Tags: c++, card-game, poker
---


title: Alpha Blending performance on IOS

text:
# Question
Title: Alpha Blending performance on IOS
I've got few questions without responses about my game development, can you help me? Here is the questions:

* In my game when a large object appear on the screen, the GPU go to his limits, my framerate become very slow. How can I handle that? (I'm working on mobile). ( Currently, I'm sorting object from back to front)
* I've read some stuff about batching (How to draw efficiently large number of objects with alpha blending?), how can I handle batching when my game need to draw my scene from back to front with alpha blending?
* What is faster: Add a condition to test pixel transparency in fragment shader or enable Alpha blending? (I've got colors around my sprites without alpha blending or condition)

Thanks!

# Answer
> 6 votes
* The best way to sort your scene is actually to do it in at least two stages/buckets. It is true that you need back-to-front sorting for translucent geometry for proper alpha-blending, but you want front-to-back sorting for best Z-buffer performance on opaque geometry. You can often get away with not bothering to sort opaque objects at all, leaving them unsorted should give better performance than sorting them back-to-front.

The whole point of batch processing is to identify geometry that is opaque or translucent, or that requires a certain texture, shader or state, and then before submitting the draw commands to the GPU you can cluster all of the similar geometry into batches. This way you only have to bother with depth sorting the hand full of batches that have a combination of states that actually require it, and you can sort in the proper direction.
* Alpha blending and alpha testing are actually two separate things.

1. Blending occurs after a fragment is shaded and when its result is combined with something else in the color buffer to produce a new blended pixel.
    2. Alpha testing is used to determine whether a fragment should be kept or discarded.

    + On newer hardware it can be done in a fragment shader, using `discard`
        + On older versions of OpenGL and OpenGL ES, you have the option of using the fixed-function alpha test.
* As for which is faster, ***neither***. Even if you perform an alpha test in a fragment shader at the very beginning of the shader and `discard`, the sad truth is that most of the time your fragment shader will keep on executing and it is only after execution that the GPU actually discards the results of shading.

If your program is limited by the performance of blending, rather than fragment shading, then alpha testing might help. This is because any fragment that is rejected after fragment shading does not have to be blended. Usually fragment shading is the bigger bottleneck, though.

If you are thinking that alpha blending and alpha testing are the same thing, then chances are you are actually just using an alpha mask. In which case, depth sorting is not always necessary and you do not need to use alpha blending. Alpha blending is used when you have fragments with alpha values that lie somewhere inbetween 0.0 and 1.0.

Also note that you are dealing with tile-deferred rendering on iOS, because Apple uses all PowerVR GPUs. The only geometry you should sort using the CPU is translucent geometry on PowerVR GPUs, otherwise you are defeating the purpose of TBDR (tile-based deferred rendering).

---
Tags: opengl, ios, performance, alpha-blending
---


title: Javascript tile map -> bitmap or JSON

text:
# Question
Title: Javascript tile map -> bitmap or JSON
I would like to know which idea is better in terms of performance.

The map is 5000x5000 tiles and I plan to expand it even more. It is split into 50x50 regions and camera doesn't move with player, the map just switches to next one when player reaches border of the screen.

I have few possible approaches to store and load a big map like this.

Case 1: I store every 50x50 region in a seperate JSON file, and just load them dynamically with XHR when player reaches border of the screen (native not jquery, since it is much faster)

Case 2: I store every 50x50 region in a seperate bitmap files, and then load that image dynamically using canvas and read it's pixels to generate map.

Case 3: I store images in bigger chunks (ex. 1000x1000) and preload them all at the beginning of game and also read pixel by pixel when needed.

Which case is possible/best? I need performance, it comes first before code readability etc. My main concerns are the memory leak of XHR, and also which is faster: XHR loading and parsing JSON or loading and reading image pixel by pixel.

Thank you!

# Answer
> 1 votes
A two-dimensional JSON array with integer values for all tiles would have quite a lot of overhead, but abusing an image to transfer binary information would also add some wrapping information you don't need.

To reduce the amount of data which needs to be sent over the network, you could use XHR, but return a single BLOB or arrayBuffer with the binary map data. This data could be compressed with an algorithm like DEFLATE (which is the same compression algorithm used by PNG) to reduce the size. Depending on how your maps are designed, another stock algorithm might have better results, or you could even try to create your own when you think you can create something more appropriate.

---
Tags: javascript, performance, tilemap, image
---


# Question
Title: Trouble using Ray.Intersect method on bounding boxes in a 2D XNA game
I am trying to use a ray and bounding box to determine if a box is between the player and the mouse pointer in 2D space. When I try testing the code, the collision will return true when pointed at the box but it also returns true under other circumstances where it shouldn't.

For instance. If I have a player on the left and a box directly to the right, I can put the mouse pointer a few hundred pixels above the box or a few hundred below and it will still return true. Also, I can put my mouse pointer to the left of the player and in a certain area it will still return true. Does anyone have any idea what might cause this?

I have left out definitions for some of my members and properties just to make this code sample easier to read. The position property is just a Vector2 for where each object is located.

```
ray = new Ray(new Vector3(player.Position, 0), new Vector3(mouse.Position, 0);
box = new BoundingBox(new Vector3(box.Position, 0), new Vector3(
new Vector2(box.Position + box.Width, box.Position + box.Height), 0);

if (ray.Intersects(box) != null)
    collision = true;
else
    collision = false;

```

# Answer
I'm not certain this is the cause, but I do notice an issue when I looked up `Ray`'s documentation. `Ray`'s first argument is a position (so okay there). `Ray`'s second argument expects a `Vector`. Coding-wise, the two are interchangable, but concept-wise, they're very different. Basically, the second argument should just indicate which *direction* for that Ray to face from its starting point; not which position it should point towards.

I think `mouse.position - player.position` should do it.
> 1 votes

# Answer
The problem is that the bounding box has the same Z in Max and Min, so there is no volume.

Changing this:

```
 box = new BoundingBox(
    new Vector3(box.Position, 0),
    new Vector3( new Vector2(box.Position + box.Width, box.Position + box.Height), 0);

```

To this:

```
 box = new BoundingBox(
    new Vector3(box.Position, 0),
    new Vector3( new Vector2(box.Position + box.Width, box.Position + box.Height), 1);

```

Should work..

I thing your over complicating things a bit... Is easier using a rectangle for this without using rays and boundingboxes:

```
Reectangle bounds = new Rectangle((int) pos.X, (int) pos.Y, 0,0);
bounds.Inflate(size/2, size/2);

if (bounds.Contains(mouse.X, mouse.Y) {
  ....
}

```

Or using distance if it's suitable:

if (Vector2.Distance(playerPos, mousePos)
> 1 votes

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


# Question
Title: Splitting game into multiple standalone parts
I'm digging into Starling's CitrusEngine game engine. I try to understand the idea of structuring the game.

If you take a look at chrome.angrybirds.com or puddingmonsters.com you see that games load states (StarlingState's assets) dynamically which is smart. When the game starts a splash-screen displays, then you get a pre-loader which loads the main state (home, settings and choose-level view) and when you select a level a pre-loader displays again which loads the level state. This looks like they've constructed multiple parts for the game and then connect them together where the pre-loader is displayed when switching from one part to other.

How should we do that in Starling/CitrusEngine? What's the logic here? Flash games usually load all assets at the beginning which is not smart on mobile devices. Is it wise to have multiple StarlingCitrusEngine classes or you should handle the whole game in a single StarlingCitrusEngine class? Please explain in details.

Many thanks for answers.

# Answer
You're comparing apples to oranges. The games you list are done in html5/javascript not flash. So it might be difficult to do the same in flash.

Additionally: Flash is dead on mobile. Steve Jobs basically banned it from the IPhone. It can be installed on later versions of android, but doesn't run very well (at least that's what I heard). Either use Html5/Javascript or develop directly for the mobile OS you're targeting.
> 1 votes

# Answer
You can do runtime asset-loading using Flash/AIR just as well as embedding the assets into your game. Personally, I like to embed the theme-related stuff into the app, because as soon as you do runtime loading, you'll want some sort of progress-bar, and that's where you'll need the theme.

All other assets, like further images, sounds, etc. can be loaded using the existing Flash APIs. In Starling, there's even a very handy class for that purpose, called `AssetManager`. It greatly facilitates loading of common game assets.

Here's an example:

```
var assetManager:AssetManager = new AssetManager();

// assuming there's an "asset" folder within your application directory
var myAssetFolder:File = File.applicationDirectory.resolvePath("assets");

// enqueue the asset folder, you can also add individual files
assetManager.enqueue(myAssetFolder);

// load all the enqueued assets (this will load all assets from the folder)
assetManager.loadQueue(function(progress:Number):void {
    // tracing the loading progress in the callback. Here you'll want to update
    // your loading-progress bar.
    trace("Loading progress is: " + progress);
});

```

There's also an article in the starling wiki with a slightly more detailed example.

Ideally, your scenes know about the assets they need and you can load/free these whenever necessary.
> 1 votes

---
Tags: flash, starling
---


# Question
Title: How should I provide a navigation system for a world with infinite space?
The world is generated by perlin noise chunks and will only be saved once that chunk has been generated. It will also not necessarily have one obvious (to the user) central point anywhere in the world, but the chunks start at 0,0 and go in all directions.

What would work to help people find their relative position to another user or buildings?

A few ideas that have crossed my mind:

* Area names - creating the names procedurally might be an issue though (?) and doesn't entirely solve the issue (until you're used to the names, they will mean nothing to you)
* A grid system, then there is something to be relative to - from a user's point of view, this is pretty tedious and I can't imagine it is really a good solution (UI-wise)
* A compass that shows the direction to chunk 0,0 and the distance from it, this is the closest solution for me so far
* A mini map of the environment would work, but only for local areas otherwise the minimap would end up taking up the entire screen or having to scroll for ages to reach other areas

Or some combination of the above.

Any thoughts on the above or other suggestions would be greatly appreciated.

# Answer
> 5 votes
What about a grid system centered on the player? That is, just indicate locations as, say, "13 foos south and 6 west of you." That way, you don't need to designate any specific location as the origin.

Arrows pointing to nearby interesting things (and more distant bigger things) and giving the distance to them could also help with local navigation, and could complement the grid system nicely. Letting the player designate and/or name locations could also work.

For mini-maps, Philipp's suggestion of allowing zooming seems good.

# Answer
> 0 votes
It isn't really possible to have an 'infinite' space. You need some way to index the positions, so if you used an int then the maximum size would be MAX\_INT.

You can use bigger index data types. Maybe a long or even something more esoteric like a long long long long. There are some ways to have numbers that can grow arbitrarily but they will add performance/memory overhead.

At the end of the day you will still be bound by the memory of the system.

Do avoid floats/doubles at they loose precision the further away from 0.0 you go. Look at the Minecraft end of the world videos.

So it's probablly better to use a 'fixed' sized world and just make it very very very big. With a fixed sized world you could use a GPS system. You can also make the world 'wrap' around so it's like a sphere.

Having said that I wouldn't give the player raw coordinates to have to deal with. You are just making them remember stuff and giving them extra work. Place names seem hard to implement in a procedural system. Seems like they would come out too uniform (ie you would be naming square regions rather then points of interest).

It seems like having a 'waypoint' would be the way to go. Combine A map, compass markers, plus a list of waypoints that the player can turn on/off and possibly a 'pillar of light' at the position' so it can be seen on the horizon (that only makes sense for 3D games) and a fined grained marker at the point on the ground. Also let them set their own waypoint.

As a simple version would just have a direction (an angle, or arrow that points there) and distance to target. The problem with that is the player sometimes has to go around the long way to avoid obstacles rather than straight in the direction.

You can also use the waypoint system for 'points of interest' within a range like Skyrim does for dungeons.

---
Tags: algorithm, maps, gui
---


# Question
Title: Perlin Noise for generating terrain in a 2D side-scrolling game. Is there a way to make variations in noise's amplitude?
For example if my generated levels look roughly like this:

But once in a while I would like to have the "amplitude" rise say 10 times than the rest of the level, so that it would look something like:

That is, once in a while there are deep "trenches" in the level. Now I know that my terrain's Y values are always between for example 200 and 1000 pixels. I there a way for them to mostly be in that range, but once in a while there is a drop to for example 10000 pixels?

# Answer
> 9 votes
Add another layer of noise to control the amplitude. Scale the noise up (on the X axis) to make the changes in amplitude gradual. Further, you can apply the amplitude changes in a exponential fashion. By applying them in this way, the difference in the noise values of .3 to .4 are not nearly as significant as the difference in the values .9 to 1. This strategy ensures that you do get some deep trenches, but you don't get them frequently.

Note that this method can easily be applied to also cause high mountains if desired.

---
Tags: procedural-generation, perlin-noise
---


# Question
Title: How does Unity's multiplayer support stack up compared to other engines?
I am currently starting development on a FPS game. I haven't decided on a developement tool. I am really drawn to Unity 3D but not sure how good the software is compared to others (the game has to have smooth multiplayer). Does Unity have multiplayer support? I couldn't really tell from the website.

# Answer
If you are at this junction for hobbyist programming or self-teaching, my advice is to simply dive in. You will learn a lot simply making any decision. In particular you will learn that no engine is a magic bullet for building your game. You will see useful things already built for you, and you will see shortcomings requiring raw development time for logic specific to your game.

If this is for a professional project or you are simply worried about investing time in a particularly poor fitting system by mistake, I think you can look at the adoption, community size, and multiple platforms of support offered by Unity and deduce that it's a mediocre choice *at worst*. Personally, I have been using Unity for about 6 months now and find the engine to be time saving and enjoyable, and the community to be active.

Unity does have multiplayer/networking support however I have not personally used it yet. From a few minutes of Googling, this PDF *Unity Multiplayer Tutorial* looks useful and up-to-date enough.

See also:
> 7 votes

# Answer
Unity3D is indeed a very popular platform and is becoming increasingly popular among indies and studios. Multiplayer network games though are not so prevalent currently. I believe this is mostly because it is difficult and requires a lot of development effort to get right. First there is all the socket programming on the client, managing buffers, threads etc. in Unity3D. Secondly you will need a server for routing, discovery, matchmaking etc. Thirdly on the client side, developers need to add handling for latency and use prediction techniques.

There are some cloud solutions which aim to resolve the first two problems i.e. client side networking and server side infrastructure. This does make it easy for developers to get started with their multiplayer games on Unity3D and dive straight into whatever business logic they want in their games.
> 1 votes

---
Tags: unity, multiplayer
---


# Question
Title: Replacing 4 additive sprite layers with a single shader. Just can't get it right
I'm using directx9 and have 4 textures I want to draw on top of each other. if I do this:

PDevice-\>SetRenderState(D3DRS\_SRCBLEND,D3DBLEND\_SRCALPHA); PDevice-\>SetRenderState(D3DRS\_DESTBLEND,D3DBLEND\_ONE);

SetTexture(0,texture1); DrawSprite();

SetTexture(0,texture2); DrawSprite();

SetTexture(0,texture3); DrawSprite();

SetTexture(0,texture4); DrawSprite();

I Get *EXACTLY* the cool effect i want. but I suspect this level of blatant overdraw is inefficient. I'm sure this can be compressed into a single draw call somehow, and run faster. The trouble is, everything I try does not look the same, whether I try a fixed-function muyltitexturing approach setting the 4 textures as different texture stages, or whether I try to implement it inside an fx file as a shader. Nothing has the same effect.

Is it even possible? I'm guessing within a shader it could be done by just mulitplying the sampled texture at each stage with the current screen value, but tbh I'm not sure if that is accessible to the shader (or how). My current code works, but it bugs me I'm drawing 4 huge textures separately :D

# Answer
> 3 votes
Lets look at what your blend setup is actually doing:

```
PDevice->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);
PDevice->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_ONE);

```

This means that your colors are calculated by:

```
ScreenPixel = OldPixel + NewPixel * NewPixel.a

```

So expanding your blend sequence gives you:

```
color += texture1 * texture1.a;
color += texture2 * texture2.a;
color += texture3 * texture3.a;
color += texture4 * texture4.a;

```

---

This is trivial to simplify down to a single blend operation, you sum the textures:

```
color = texture1 * texture1.a +
        texture2 * texture2.a + // Multiply by SRCALPHA manually
        texture3 * texture3.a + // as you sum your texels.
        texture4 * texture4.a;

```

Now your alpha is premultiplied as well and uses a simpler blend function:

```
PDevice->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_ONE);
PDevice->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_ONE);

```

# Answer
> 1 votes
**Tuns out that this is not accurate, as it's for a different alpha blend type.**

I'm going to give this one a shot, primarily since there aren't any answers for you yet. I'm not completely certain that my answer is accurate or complete, but it's going to be too big to supply as a comment, so here we go.

The biggest feature you need to preserve is the order-dependent nature of these draw calls. A completely opaque texture drawn on top of another completely opaque texture demonstrates the importance of preserving the order.

I've sketched out some equations that will work, or at least be close.

What I propose trying is this: (assuming your colors are floats from 0 to 1)

For each texture you take the existing color for that pixel, multiply by (1-a), where a is the alpha of your new texture, then add in (a\*newColor), for each channel. Then the total alpha of the resulting texture will be (1 - product(1-a(i))).

In other words:

```
for each Texture(Color,a)
  TotalAlpha*=(1-a)
  for x=0 to 2
    colorOut(x)=colorOut(x)*(1-a) + Color(x)*a

TotalAlpha=1-TotalAlpha

RESULT: (colorOut(1),colorOut(2),colorOut(3),TotalAlpha)

```

Again, this is just some equations I've sketched out, but I think it's pretty close.

---
Tags: shaders, directx9, blending
---


# Question
Title: Orthogonal projection matrix affecting z-buffer on one device
I am experimenting using `Matrix.orthoM` for a isometric projection, rather than `Matrix.frustumM`.

On one device, the z buffering does not appear to be working correctly and I get a cut away effect seen below on the wheels in particular. Both devices work fine with frustum projection.

Sorry not much to go on, just hoping someone will just be able to take one look and recognise the problem.

Sony Xperia Z:

LG P920:

Sony Xperia Z:

LG P920:

# Answer
> 2 votes
It was a near and far problem. I had way too large a range 2 near, 24000 far.

The high res of the one device highlighted the problem.

http://www.opengl.org/wiki/Depth\_Buffer\_Precision

---
Tags: android, opengl-es2
---


title: OpenGL and constant buffers

text:
# Question
Title: OpenGL and constant buffers
I'm doing a small direct3d11 project for "fun". I know d3d11 quite well but not really any opengl. My program is designed for d3d11 but I would like it to be easy to port to opengl at some point so I'm trying to keep to abstractions that are somewhat portable. The concepts of vertex buffer, index buffers, vertex shaders, pixel shaders, and some form of input layout structures all seem to map pretty well.

But what about constant buffers? all of the examples I see of opengl shaders have code getting "pointers" to named variables in the shader and setting them whereas my code for d3d11 just creates a big c++ struct and copies it into a constant buffer. This then maps directly to a cbuffer in the shader.

Does the same concept exist in opengl? I've been unable to find it with any quick searches. Or do I have to set named variables only?

# Answer
> 5 votes
The OpenGL most closest equivalent of constant buffers might be the Uniform Buffer Object.

More details in the link above.

---
Tags: opengl
---


# Question
Title: How do I orbit one object around another?
I am trying to do animation using glut. I have 2 squares overlapping to each other and i want other square to rotate around this central object without rotating themselves. I want to rotate in orbit manner. I am calculating circular path using parametric equation and translating that one of the square to that distance. i am calling this function in a loop.

Here is my code in which the motion of other square is not in a orbit instead it moves along a diagonal of middle one. Let me know where it is going wrong. I have added expected image as well

# Answer
> 4 votes
First some little tips:

1) Instead of:

```
if (i > 360) i=0;

```

Try

```
i %= 360;

```

2) glPushMatrix and glPopMatrix are useless in your code, as you apply them on the identity matrix.

3) User GL\_TRIANGLES or GL\_QUADS instead of GL\_POLYGON

4) Avoid global variables, they cause a lot of problems.

**Solution:**

Probably a typo:

Change

```
glTranslatef(distance_x, distance_x, 0.0);

```

To

```
glTranslatef(distance_x, distance_y, 0.0);

```

---
Tags: opengl, glut
---


# Question
Title: Create extra bullets, offset according to angle of spaceship?
I am trying to create a weapons upgrade for my Spaceship, using libGosu and Chingu (in Ruby). This question is about how to deal with this issue specifically in Ruby, and more specifically in libGosu.

In the player class I have tried several variations of the following:

```
def fire
  Bullet.create(:x => @x, :y => @y, :angle => @angle)
  Bullet.create(:x => @x + Gosu::offset_x(90, 25), :y => @y + Gosu::offset_y(@angle, 0), :angle => @angle)
end

```

It sort of works, but not exactly how it ideally should. For reference, this is what the Bullet class looks like:

```
class Bullet < Chingu::GameObject
  def initialize(options)
    super(options.merge(:image => Gosu::Image["assets/laser.png"]))
    @speed = 7
    self.velocity_x = Gosu::offset_x(@angle, @speed)
    self.velocity_y = Gosu::offset_y(@angle, @speed)
  end

  def update
    @y += self.velocity_y
    @x += self.velocity_x
  end
end

```

How should I construct "def fire" in order to get the extra bullets to align properly when the spaceship rotates?

In the first image (above) the bullets are separated as intended.

In the second image the bullets are clumping together when the spaceship is rotated.

# Answer
Here's a little explanation as to what the mistake was.

What you wanted to do is shoot a bullet that started with an offset relative to the rotation of your ship. You knew that the direction of the ship is `angle`, so if you want to shift it perpendicular to that and you're in the origin already then you only need to add 90° to you angle and go in that direction by whichever offset you want.

As you said, you "can use cos and sin" but you honestly already are, here's the definition of `offset_x` and `offset_y`:

```
double Gosu::offsetX(double angle, double radius)
{
    return +std::sin(angle / 180 * pi) * radius;
}

double Gosu::offsetY(double angle, double radius)
{
    return -std::cos(angle / 180 * pi) * radius;
}

```

Here's also a handy little diagram which hopefully explains it a little bit more (just pretend it's a perfect circle and the blue and black line are the same length, hehe)
> 3 votes

---
Tags: 2d, ruby, libgosu, chingu
---


title: Different Attack Systems in RPG

text:
# Question
Title: Different Attack Systems in RPG
I'm making a 2d rpg game with libgdx and java, and I'm wondering how I would organize different attack systems - magic, melee, etc. (it's not a turn-based rpg). I have a PlayerClass enum, a Player2D class(2d representation), and a Player class (for storing player data). Would I make an Attack class, with MagicAttack and MeleeAttack? Then have a method in Player2D like attack(Attack attack)? I've considered a few options, but I want to be sure. Thanks!

# Answer
I would recommend you to create an abstract base class or interface `Attack` which defines a method `perform(Combatant user, Combatant victim)`.

`AttackMagic` and `AttackMelee` would extend this class with their own implementations of this method.

The method would then extract all necessary attributes from the user and the victim, calculate how much damage the victim receives as well as any other consequences from using the attack, and update the victim accordingly.

In the project I am currently working on (an MMORPG server in Java) I did however use a different, very non-object-oriented, approach. I have a single class `GameSystem` which includes methods for calculating all combat mechanic rules. It has a static method `performAttack(Combatant attacker, Combatant victim, Attack attack)` with lots of `if-else` and `switch` statements for the different kinds of attackers, victims and attacks.

This is usually how you would do things in a procedural language like C, not in an object-oriented language like Java. My reason for doing it this way is that I wanted all game mechanic formulas in a single file and not spread over several, so that it's easier for me to find and change things during the balancing process.
> 0 votes

---
Tags: java, 2d, game-design, libgdx
---


title: "Align" a rotation to a direction

text:
# Question
Title: "Align" a rotation to a direction
Good day all.

I have a 3d object with a random rotation. I can express that object's rotation both through a quaternion or through an euler rotation.

Then I have a vector3 normal that I get from a raycast.

What I need, is to apply a rotation that will make a chosen axis of the 3d object, coincide with the normal vector3 from above.

The closest I got to the solution is this (trying to align the 'up' vector):

```
Quaternion q;
Vector3 a = Vector3.Cross(3dobject.up, varnormal);
q.x = a.x;
q.y = a.y;
q.z = a.z;
q.w = Mathf.Sqrt((3dobject.up.sqrMagnitude) * (varnormal.sqrMagnitude))
       + Vector3.Dot(3dobject.up, varnormal);

3dobject.rotation = q * 3dobject.rotation;

```

But when the normal is negative on the y (e.g. 0,-1,0), the object aligns with its y pointing up instead.

What's wrong with the formula? Is there a better solution maybe?

Thanks in advance.

# Answer
> 3 votes
Your formula is correct. I would suggest normalising the quaternion at the end, though, or any stage involving interpolation will likely be messed up.

What I believe is happening is that your `up` vector is (0, something, 0) and your normal vector is (0, -1, 0). In this very specific corner case (when the input vectors are opposite to each other) there is no unique solution to your problem so you will need to choose an arbitrary rotation around any vector that is orthogonal to `up`.

If you have a `left` vector in your `3dobject`, you could do the following:

```
Quaternion q;
Vector3 a = Vector3.Cross(3dobject.up, varnormal);
float d = Vector3.Dot(3dobject.up, varnormal);
if (d < 0.0 && a.sqrMagnitude == 0.0) /* Replace with a real epsilon test */
{
    q.x = 3dobject.left.x;
    q.y = 3dobject.left.y;
    q.z = 3dobject.left.z;
    q.w = 0.0;
}
else
{
    q.x = a.x;
    q.y = a.y;
    q.z = a.z;
    q.w = Mathf.Sqrt((3dobject.up.sqrMagnitude) * (varnormal.sqrMagnitude)) + d;
}

3dobject.rotation = q * 3dobject.rotation;

```

# Answer
> 3 votes
To illustrate, look at this image generated by Wolfram Alpha:

You have your 3 local coordinate axes and you want to coincide any of them with a given forth vector (for instance (1/2, 1/2, 1/2) as in the image). To do that, you need to rotate your object. A rotation is best described as a combination of an angle and axis to rotate around. So how do we find out those two components?

Let's assume that you need to coincide the **x** axis with a normal vector named **n**.

**The angle** to rotate with can be calculated from either the cross or the dot product, but it is easier with the latter. Since a dot product of vectors *u* and *v* is *|u||v|cos(u,v)* we can calculate the angle between our vectors using this simple formula (in pseudocode):

```
float angle = Math.Acos(Vector3.Dot(x, n) / (x.GetLength() * n.GetLength()));

```

**The axis to rotate around** is as simple as the angle. Basically, the 2 vectors of ours and the origin of the object define a plane. A plane defines a 2d coordinate system and all we need is to actually rotate in that system. Rotation in 2d is done by rotating around a vector perpendicular to the plane and a vector perpendicular to the plane is the cross product of the vectors defining the plane:

```
Vector3 axis = Vector3.Normalize(Vector.Cross(x, n));

```

Now that we have both components, use your favourite math library to create the need rotation:

```
Quaternion rotation = Quaternion.CreateFromAxisAngle(axis, angle);

```

---
Tags: rotation, axis
---


# Question
Title: Representing feelings such as temperature, pain, smell, taste, hunger, and thirst immersively
In a totally immersive, simulation-type role-playing game, the player should not look at bars or numbers to keep track of his or her stats, so another method of showing these stats is needed. For example, the player needs to know when to eat, because games (currently) cannot incite a real feeling of hunger. The player also needs to know if they are hurt, so they can take appropriate measures.

Somehow, these feelings must be represented visually or audibly. I'm not a fan of coloring and blurring the screen to show feelings like how most first-person shooters show that you have been shot. What are some ways to represent these feelings immersively?

# Answer
The elements you can use to present emotions I can think of are:

### Visual

* character animations (walking upright, bowed or hobbling, arms near the body when cold)
* especially facial expressions
* textures or decals (injury, blood, scratches)
* particles (sweat, blood)

### Gameplay

* player abilities (movement speed, jumps, reaction time, attack strength)
* body reactions (dizziness, falling over)

### Environment

* reaction of NPCs (stare at player of avoid looking at him, making comments, disgust, pity)
* of course level design (snow, vegetation and sun for temperature)
* tone mapping of the whole scene (warm or cold colors for temperature, desaturated for fear)

### Auditive

* ambient sounds (blizzard, howling wind for cold, dry/firey crackling sound for heat)
* background music
* bodily function sounds (ggrowling stomach for hunger, panting breath for exhaustion, chattering teeth for cold)
* changes to voice of character (scratchy voice and often clear throat when thirsty, stutter or shiver voice in cold)
> 13 votes

# Answer
The answer by danijar already has some good ideas, but I have another one.

Unless you want to go for a silent protagonist, you could have the player-character monologue about feelings of discomfort. First just occasionally ("I could need a snack right now") and then more frequent and demanding ("Hunger! I'm starving! Food! Please!"). The player will feel obligated to fulfill the needs of the character just because the constant lamenting will become distracting (just like an empty stomach in real-life).

When you want to do this, it would be good to find a talented voice actor who is able to convey the desperation of the player-character well.
> 6 votes

---
Tags: game-design, simulations, character, ui-design
---


title: Moving bounding box in 3D using libGDX

text:
# Question
Title: Moving bounding box in 3D using libGDX
How do I go about moving a bounding box in libGDX?

I want to make the bounding box capture my character and move with him.

So ideally I want to be able to copy my vector 3 from my model instance and set it on the bounding box.

There doesn't seem to be any method like setToTranslation() on the BoundingBox class. How am I supposed to do it?

# Answer
From the documentation it looks like you have a few options.

1. Use the `set` method to set the min and max bounds. So, you can move the box by moving both the min and max. Something like `box.set(box.min + moveAmt, box.max + moveAmt);`
2. Use the `mul` to multiply the bounds by a matrix. Create a translation matrix to translate the bounds by your movement amount. Something like `box.mul(new Matrix4(moveAmt, QuaternionIdentity, Vector3Ones)`.
> 4 votes

---
Tags: java, android, 3d, collision-detection, libgdx
---


title: Rendering large and high poly meshes

text:
# Question
Title: Rendering large and high poly meshes
Consider an huge terrain that has a lot polygons, to render this terrain I thought of following techniques:

* **Using height-map instead of raw meshes**: Yes, but I want to create a lot of caves and stuff that simply wont work with height-maps.
* **Using voxels**: Yes, but I think that this would be to much since I don't even want to support changing terrain..
* **Split into multiple chunks and do some sort of LOD with the mesh**: Yes, but how would I do that? Tessellation usually creates more detail not less.
* **Precompute the same mesh in lower poly version (like Mudbox does) and depending on the distance it renders one of these meshes**: Graphic memory is limited and uploading only the chunks won't solve that problem since the traffic would be too high.

IMO the last one sounds really good, but imagine the following process:

1. Upload and render the chunks depending on the current player position. \[No problem\]
2. Player will walk straight forward
3. Now we maybe have to change on of the low poly chunk with the high poly one
4. So, Remove the low poly chunk and load the high poly chunk \[Already to much traffic here, I think\]

I am not very experienced in graphic programming and maybe the upper process is totally okay but somehow I think it is too much.

And how about the disk space it would require.. I think 3 kind of levels would be fine but isn't that also too much?

(I am using OpenGL but I don't think that this is important)

# Answer
> 2 votes
The chunks approach is very common. Almost every large-scale outdoor terrain renderer does this. Even with voxels, you need chunks of voxels in order to properly cull and optimize the rendered scene. Spatial partitioning is vital to graphics, physics, AI, almost every part of the game, and uniform chunks are one of the easiest for outdoor scenes. More complicated approaches like quadtrees or the like work too; you'd have to profile and test to see if they improve things at all for your specific game.

Split your map into largish chunks. This typically will not produce too many new triangles as you'll only be clipping them near the edges. Now you can programatically create lower-poly versions of each chunk. Use LOD to select the right version. Use frustrum culling to completely avoid drawing chunks outside of the view frustrum. You can even use various forms of occlusion culling to hide invisible chunks in the frustrum, such as those occluded by hills or mountains.

For caves and other indoor-ish areas, consider a completely different rendering approach. You can render indoor areas using BSP trees or a portal engine very efficiently, and you can seamlessly rendering indoor/outdoor areas using two different renderers easily enough. Again, this is what almost every major game engine does. The problems are different enough that a single solution is not really a best fit.

Voxels can also work, but the looks may not be what you're going after. Smoothly rendering highly-detailed worlds with a voxel representation underneath is not a task for the feint of heart. The few engines I know that do this cheat pretty heavily at it, too. EverquestNext seems to have a pretty high-quality look with voxels underneath, but I don't know what approach they're using.

# Answer
> 0 votes
You should use voxels. In your question you explained that you don't want to change the terrain. I guess that's not totally true. Even if you don't want to support realtime editing, there is a point where the terrain have to be created first. This might be done with an editor application and for that, a voxel representation would become very handy.

The get a smooth polygon mesh out of your voxel data, I suggest using algorithms like Marching Cubes. Before implementing such an algorithm, you could just create a mesh with cubes for each voxel, like Minecraft does, for testing.

When it comes to rendering, you should first implement a draft, as already suggested in the comments. Then improve if it truly is too slow. If so, you would have to divide the terrain. Therefore you could use chunks or octree data structure. Note that this is a must if your terrain would be infinite, which for you seems to not be the case because you spoke about a hand crafted world. By the way, reducing the view distance of chunks would significantly improve performance.

If that is still to slow, which is very unlikely I think, then you'd need an level of detail system. Provide low detail meshes for far away chunks and more detailed meshes for nearer chunks. You said that you think changing a chunk with a more detailed version would cause too much traffic to the GPU. This is not true. At some point you have to load the most detailed version which a lot of vertices anyway, right?

In other words, you already know about the needed techniques, they just had to be ordered. Additionally, I think you problem is to imagine how much data you actually have, which isn't easy. Maybe you should estimate the expected amount of data by calculation. For example, a float is sized 4 bytes (thanks to MickLH's comment). For a vertex, you need 3 floats for the position and depending on your requirements, 3 (or at least 2) floats for the normal vector and 2 for the texture coordinate. In this example case, we'd have 32 bytes per vertex.

Update: Of course there are ways to even speed this up, but I think this is too much for the start and you should consider that later and only if truly necessary. Mesh compression is your keyword then. For example, detailed smooth meshes can be stored in very small size by backwards calculating subdivision. This way, your mesh becomes a weird shape that results in the desired terrain when being heavily tessellated. This would also speed up rendering because you could cull away lot of the terrain and only tesslate data in the player's view.

---
Tags: rendering, mesh
---


title: Player Rope Swing?

text:
# Question
Title: Player Rope Swing?
I'm trying to implement a rope swinging mechanism for my custom UDK Pawn class. What I am trying to do is have the player be able to attach and swing as if by a rope attached to a hook entity in the map.

Searching online I managed to find this article which perfectly captures what I am trying to accomplish, but where I need help is implementing it specifically in UDK with the pawn class.

Two requirements I have are that it isn't done using physical simulation and should be able to work in a network multiplayer environment.

This is my attempt at implementing the technique presented in the article in UDK:

```
class UTPawn_Grapple extends UTPawn;

DefaultProperties
{
}

simulated event Tick(float DeltaTime)
{
    local UTPlayerController_Grapple myController;
    local vector testPosition;

    myController = UTPlayerController_Grapple(self.Controller);
    testPosition = Location + (Velocity * DeltaTime);

    if (myController.TargetedHook != None)
    {
        if (VSize(testPosition - myController.TargetedHook.Location) >= myController.TargetedHook.ropeLength)
        {
            testPosition = Normal(testPosition - myController.TargetedHook.Location) * myController.TargetedHook.ropeLength;
            Velocity = (testPosition - Location) / DeltaTime;

            WorldInfo.Game.Broadcast(self, "Velocity: " $ string(Velocity)); // DEBUG
            WorldInfo.Game.Broadcast(self, string(Location) $ "-->" $ string(testPosition)); // DEBUG
        }
    }

    Super.Tick(DeltaTime);
}

```

Unfortunately the resulting behaviour is that my character rapidly accelerates towards a specific point on the map that is far from the hook and far outside the rope length, each time it's always the same point.

And here is the debug info output I get during this:

One thing that stands out to me is the huge velocity vectors, but why am I getting numbers these big? Why is my character always pushed towards this seemingly arbitrary point on the map?

So my big question is: How can I fix this implementation or is there a better way to do it?

# Answer
> 3 votes
Turns out that getting the difference between two vectors gives me a vector RELATIVE TO THE WORLD ORIGIN (DUHR) so that "arbitrary" spot on the map I was getting pushed to was just \<0,0,0\> + Unit Vector * ropeLength.

In short:

```
 testPosition = Normal(testPosition - myController.TargetedHook.Location) * myController.TargetedHook.ropeLength;

```

should actually be

```
testPosition = myController.TargetedHook.Location + (Normal(testPosition - myController.TargetedHook.Location) * myController.TargetedHook.ropeLength);

```

---
Tags: udk, unreal
---


# Question
Title: how to design and develop game level(stages)
I need some expert opinion about game level design. I've been developing android game(2D) using LibGDX framework inspired from below sample game.

LibGDX sample Drop game

I've customized this game and made several changes as I am novice in gaming industry. Now, I need some help related to level(stages) design. I've just implemented level-1. As level increases , complexity increases. Should I'll have to implement new screen for each and every level and write separate code related to that screen. Or, there is some better approach? I want there should be single game play screen(except splash, menu and help screen etc) that should override sprite as level changes. I've searched a lot but didn't find useful article. Looking for useful links, article or online tool anything.

what should be the best design approach as performance is really matters. Should file reading is good approach or use sqllite ? What should be the best practices while designing these things as I am the one man army. Is there any level editor that will help.

# Answer
You want a "Data Driven" system. This means that you have one game screen used over and over for every level.

When you want to load a level, read a file to decide what to do, the code should not know in advance because you might want to send out new level files later (ala DLC).

For this drop game, it would be pretty simple, your level file would probably just be numbers for how often and fast to send drops, and a list of your sprites for that level.

---

P.S. How to design is subjective, good luck with having that in your question. Artists usually hate having to mess with code though, so really get on that Data Driven system.

---

EDIT: To clear up the definition of "Data Driven", there's a topic right here on SO: What is data-driven programming?

Which has a great link in the comments section of the question: http://homepage.cs.uri.edu/~thenry/resources/unix\_art/ch09s01.html , which features a sweet and simple explanation:

> ...in data-driven programming, the data is not merely the state of some object, but actually defines the control flow of the program.
> 7 votes

# Answer
The best way that I've personally seen this done is to build a few things:

## Level Importer

Essentially you could build a parser that looks for specific things. A way I've done this is I've started the line with a key word, and added data corresponding to it afterwards. So an overly simple example would be:

```
Level: 1
Bots: 2
BotLevel: 3
BotLevel: 6
Map:
1 0 1
1 0 1
1 1 1

```

So when it hits `Level` it expects the next token to be an integer. When it hits `Bots` it expects an integer and then that many lines corresponding to the levels. When it hits `Map` then it parses till the end of file. You can just add **Keys** and some sort of **expected values**. Of course it's very important to handle if the expected value, say an integer, is a string.

## Levels

After you finish how your importer should look, you start building a few levels. You can go back and add things to the importer that fit your needs.

## Level Editor (Extra)

An extra feature for yourself or your team would then to build an independent program to create the levels for you. This could be pretty simple, or could turn into a rather complex program depending on how advanced your game is. It will especially help if you have people helping you that aren't programmers.
> 1 votes

---
Tags: android, game-design, libgdx, level-design
---


# Question
Title: Is the corporate video game development industry habitable?
After a bit of research, I realized that almost every article about video game development portrays the industry in a terrible light. In these articles, companies abuse workers with unpaid overtime. Developers are left out to dry when studios fall. Developers have a terrible quality of life, and few stay on board for very long (10 or more years).

What are the real working conditions actually like (regular 40-50 hour work weeks, stability, treated well, ect.)? Are there any statistics about job satisfaction in the in game development industry?

# Answer
I’ve been working in the industry professionally for 15 years across a variety of companies and on multiple continents. The work environment all comes down to being in a position to choose the right company and/or right project. Some are good, some are bad. There are always signs which can inform which a company/project is likely to be before you go to work there. Unfortunately, knowing which companies/projects are being run well requires a degree of skill and insight you can often only get by working in the industry and working for a bad, or at least poor, company.

While you do see news about bad situations get a lot of publicity, if you start doing the math on the number of companies/projects receiving publicity vs. the total number of development companies, perceptions about the number of good vs. bad companies/projects changes.

**Edit:**

If anyone wants to check out some empirical data, look up the IGDA quality of life SIG and whitepaper. Here’s a link to get you started: http://www.igda.org/quality-life

Additionally, here are a number of questions I ask companies when trying to decide whether their development environment and methodology might be a good fit. Under each I’ve listed reasons for asking the questions and/or answers which might increase my concerns. Of course this is highly subjective and a negative answer to one question shouldn’t be an immediate deal breaker or a sign that a company/project would be a bad place to work.

If others have good interview questions which can inform people about the quality of life potential feel free to edit and add them or post them in the comments.

***At what stage of development is the project?***

This is generic feeler question which helps interpret answers to all of the other questions. One reason I like to ask it as it allows me to layer my own definitions of terms like prototype, production, vertical slice, alpha, beta, etc. onto the company’s. This helps me see whether my definitions match the company’s, and potentially see if they are overly optimistic about the state of a game.

***What is the estimated release date?***

If you have a chance to see the game demoed, you can frequently get a good idea about the amount of work required to complete it. If a company tells you a game needs to ship in 6 months, and it looks like it has a tremendous amount of work left to complete, the chances are much higher than you are looking at a crunch situation to get it out the door.

***How was the release date determined? Is it based on publisher/company requirements to ship a game within a certain timeframe? Is it based on the projected time to complete a list of required features?***

This question helps give an idea about how firm a game’s ship date is. Suppose a game is a licensed IP tied to a movie and the game’s release needs to be concurrent with the movie’s launch. It is unlikely the game’s release date will be pushed back. If the game seems like it needs a lot of work to get it out the door, the chances are high that a lot of crunch will be required to meet the launch deadline. Alternatively, if a game is being developed to a certain number of features or a certain quality bar, and a company is particularly well funded, the risks of crunch go down (as long as the money keeps flowing).

***What is the company’s/project’s current headcount, how has it grown in the past and how do you expect it to grow in the future?***

I like this question as it can provide a lot of information about how much work is required to finish a game. If you look at some recent MMORPGs, they have hired a tremendous number of contract developers late in the project. The contractors were required to produce a prodigious volume of content in a relatively short amount of time. If a project has added a tremendous number of people, and needs to add a lot more, it increases the likelihood that the team will be working long hours to complete all of the work required.

The inverse can also hold true. If a project has a small team, an epic scope and only minimal hires planned, it can be a sign that they are trying to do a lot more with a lot less.

Of course, rapid hiring is not a firm indication a team will need to crunch long hours. Rapid hiring can be due to a company’s success and the hires are needed to fuel to companies increased growth.

***What are your personal thoughts on crunch?***

This is pretty much self-explanatory.

***Have you had any situations where key milestone features were slipping and milestone deadlines were likely to be missed? How did you handle it?***

This is a useful question as it asks for a situation where crunch could have occurred, yet does not specifically ask ‘do you crunch’. How they answer will give you a good idea about how similar issues will be resolved going forward.

***What process is used to determine which features are going to be added to the game and how does a potential feature become a candidate for inclusion?***

I personally like this question as it can give an idea about how prone a company/project is to feature creep. Rampant feature creep is a risk factor, especially when coupled with fixed deadlines as it increases the potential for crunch and/or buggy/unfinished games.

***How much experience does the company/team/leadership have in making games?***

This question can often be answered through a bit of research and doesn’t need to be asked directly. The more experience a team’s key leaders/ staff have with a particular genre, the more confidence you can have that they know the work required to release their game and, theoretically, will have planned features/headcounts/timelines appropriately.

***Does the project have milestones? If so, how long are the milestones and how are milestone features and goals determined? How often are all the milestone goals met?***

Milestones, and the ability for a project to hit them, are a great indicator of how well development is tracking. If a company tells you they consistently miss milestone deadlines, or need to drop features from the milestone deliverables, that can be a cause for concern. If that project has a fixed release date it is an especially high risk factor as the team will need to drop features from the release list or crunch to have all features in the shipping game.

***Do you schedule specific bug fixing times?***

Personally I have always felt that regularly scheduled bug fixing periods are very important to a project. Formal bug fixing periods help ensure that issues are fixed as opposed to sweeping all of the bugs under a rug and ignoring them until the last minute.
> 12 votes

---
Tags: game-industry
---


title: Twitchy sprite movement

text:
# Question
Title: Twitchy sprite movement
I'm having an issue with sprite movement, and I'm not sure how to deal with it.

When I set a destination for my player sprite (by clicking the screen), it sets the player moving in that direction. Unfortunately, the player sort of oscillates. He sort of shivers along the path.

I've set up a test project using just graphics primitives (`graphics.fillRect(x,y,w,h)`), and it's really easy to see. Here's an example:

My code looks like this

```
public void tick() {

    if (InputHandler.leftClick.heldDown) {
        dest.setLocation(InputHandler.leftClick.xPos, InputHandler.leftClick.yPos);
    }

    direction.setLocation(dest.getX() - position.x, dest.getY() - position.y);
    direction.normalize();
    position.add(direction.multiply(velocity));
}

```

This is a really really basic movement system because I'm having the same issues elsewhere and I wanted to work on them in a more controlled environment.

The weirdest part about this is that when the player arrives, he still just sits on one point, shivering madly.

Can anyone help?

# Answer
> 1 votes
Well he appears to be "overshooting" the target. Basically the size of your discrete step (`velocity`) is probably too large.

Try reducing `velocity` by *a lot* (by the way, if `velocity` is a scalar quantity, it should actually be called `speed`). Try increasing it a bit until he is moving at the correct speed, but not overshooting the destination point.

When the distance to the destination is very close (ie *smaller*) than your `velocity` step size, you can either reduce velocity drastically, so he creeps into the final spot, or just *set* his final position *at* the destination. That'll prevent overshoot.

# Answer
> 1 votes
I had a similar problem not too long ago. Here is the question (which also holds answer):

Jittery Movement, Uncontrollably Rotating + Front of Sprite

It's using the SFML 2.0 framework for C# but it should be translatable.

---
Tags: java, 2d, sprites, vector
---


# Question
Title: xna model scaling - model is bigger than world
I'm having trouble scaling my model in XNA with C#. The model is bigger than the world itself and I can't seem to scale it down. Below is the code I'm using and an attached screenshot. How can I scale my model down?

```
       private void DrawModel(Matrix currentViewMatrix)
    {

        Matrix[] bones = animationPlayer.GetSkinTransforms();

        // Compute camera matrices.
        Matrix view = Matrix.CreateTranslation(0, -40, 0) *
                      Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation_model)) *
                      Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) *
                      Matrix.CreateLookAt(new Vector3(0, 0, -cameraDistance),
                                          new Vector3(0, 0, 0), Vector3.Up);

        float fieldOfView = MathHelper.ToRadians(4);

        Matrix projection = Matrix.CreatePerspectiveFieldOfView(fieldOfView, device.Viewport.AspectRatio, 1, 100000);

        // Render the skinned mesh.
        foreach (ModelMesh mesh in currentModel.Meshes)
        {
            foreach (SkinnedEffect effect in mesh.Effects)
            {
                effect.SetBoneTransforms(bones);

                effect.View = view;
                effect.Projection = projection;

                effect.EnableDefaultLighting();

                effect.SpecularColor = new Vector3(0.25f);
                effect.SpecularPower = 16;
            }

            mesh.Draw();
        }
    }

```

**edit**: when I change the following lines, I'm able to scale the model, however when I turn my model, it rotates in a circle; the model isn't properly scaled. If I do not scale the model, it turns properly around itself.

How can I fix this?

```
Matrix view = Matrix.CreateTranslation(0, -50, 0) *
                      Matrix.CreateScale(0.01f, 0.01f, 0.01f) *
                      Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation_model)) *
                      Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) *
                      Matrix.CreateLookAt(new Vector3(0, 0, -cameraDistance),
                                          new Vector3(0, 0, 0), Vector3.Up);

```

# Answer
> 2 votes
You should first scale and rotate, and then translate:

```
        Vector3 objPos = new Vector3(0, -50, 0);
        Vector3 camPos = objPos - Vector3.One * cameraDistance;
        Matrix view =
                  Matrix.CreateScale(0.01f, 0.01f, 0.01f) *
                  Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation_model)) *
                  Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) *
                  Matrix.CreateTranslation(objPos) *
                  Matrix.CreateLookAt(camPos, obsPos, Vector3.Up);

```

EDITED: Because camera was placed where object was not.

---
Tags: xna, c#, models, scale
---


# Question
Title: Prevent instances from overlapping gamemaker studio
I have a game where multiple instances of an enemy move towards a player in their step process. There can be as many as 50 instances on screen.

The issue is that the instances all end up in 1 big group as they follow the player. I would like to prevent them from getting more than 2 pixels of each other.

the code is as follows:

```
if distance_to_object(player) < 160 {
  direction = ppoint_direction(x,y, player.x, player.x, player.y)
  p_potential_step(x,y, player.x, true);
}

```

If I put a distance check of 2px in this code, the instance starts making jerky movements and spins. I would like the instance to continue following the player, but just not allow themselves to overlap.

# Answer
> 1 votes
I had success preventing this by adding a collision event with the enemies own type.

Inside this event, make the enemy step into a direction where there is space. You can determine that via `place_free` for example. In my case of a space game, it is rather easy since I can just let them step in any direction until they have enough space to operate.

But even a simple

```
x = xprevious
y = yprevious

```

can help a lot with this issue.

---
Tags: ai, path-finding, game-maker
---


title: Unlimited inventory system?

text:
# Question
Title: Unlimited inventory system?
I am working on a small game, I need to add an unlimited inventory to the game but I am not sure how to do it.

I have an inventory system with a specific amount of slots, here it is:

```
<?xml version="1.0"?>
<player>
 <username> XXX </username>
 <password> XXX </password>
 <slot1> X </slot1>
 <slot2> X </slot2>
 <slot3> X </slot3>
 <slot4> X </slot4>
 <slot5> X </slot5>
</player>

```

I am open to switching to SQL or another data storage system, but I need a solution that would let players have as many items in the inventory as they would like; with no limit.

# Answer
> 5 votes
**You'll want to use a `List`.** Probably a `List<InventoryItem>` or similar.

The documentation for `List<T>` is here.

Here is a set of answers on how to serialize a list to XML (you didn't say how you were saving your XML - this link gives you some options).

An XML file can store the list of items "inline", so it might end up something like:

```
<Inventory>
    <Item>...</Item>
    <Item>...</Item>
    ...
</Inventory>

```

---

On the other hand, if you switched to a database (using SQL), the traditional way to store something like this would be to have **player** table (with a "key" value, like an ID number) and a **inventory** table for every item in the game - each having an "owner" value that matches the ID of the owning player.

You would then use SQL to query for all the items in the inventory table owned by a given player (ie: having the matching ID). Something like:

```
SELECT item_name,item_whatever FROM inventory WHERE owner_id = <whatever>

```

---

The correct solution probably depends on the scale of your game. But if you're unsure - go with the XML to begin with - it is easier to implement - you can alway change later if the need arises.

# Answer
> 2 votes
Theres two basic ways to do this:

1. **The Magic Bag**
Containers themselves have fixed sizes, but there's no limit to your ability to put "bags" inside other "bags". Thus the only practical limit on your inventory is your ability to get more "Bags"

*This has the advantage that containers have fixed capacity (which might be easier to implement), and that you can "throttle" players inventory capacities by controlling the price or availability of extra "bags".*
2. **The Holdall**
This seems to be closer to what you are asking for; the player has a single "main inventory" of essentially infinite capacity.

*This has the advantage of minimising overhead and micromanagement for the player, though might complicate implementation depending on you game's structure.*

in either case, you will need to be familiar with your programming languages' relevant `List` or `Array` types.

---

As for storage, your problem is simply that you feel the need to specify carried (but not equipped) items as being in specific slots; *this is completely unnecessary*. in XML, simply have multiple \<item\> tags. This is perfectly legal.

In SQL-based databases, the main solution that I've seen is to have a table of items, each of which has field denoting who "owns" them, or what "container" they are inside.
This is trivially queryable.

---
Tags: c#, xml, data, sql, inventory
---


title: Resize texture in code

text:
# Question
Title: Resize texture in code
I need to change texture size from for example 800x600 to 80x60. I have two ideas of how to do that, but i have problems with both approaches. 1) changre render target then draw and save resized. the problem is blinking screen while this method is working.

```
public static Texture2D Resize(Texture2D image, Rectangle source)
        {
            var graphics = image.GraphicsDevice;

            var ret = new RenderTarget2D(graphics, source.Width, source.Height);
            var sb = new SpriteBatch(graphics);

            graphics.SetRenderTarget(ret); // draw to image
            graphics.Clear(new Color(0, 0, 0, 0));

            sb.Begin();
            sb.Draw(image, source, Color.White);
            sb.End();

            graphics.SetRenderTarget(null); // set back to main window

            return (Texture2D)ret;
        }

```

2) use Texture.SaveAsPng(); this aproach is extremly stupid but it works

```
public static Texture2D Resize(Texture2D banner,Rectangle rectangle)
        {

                using (var file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var IsolatedStream = new IsolatedStorageFileStream("banner.te2", FileMode.Create, file))
                    {
                        IsolatedStream.Position = 0;
                        banner.SaveAsPng(IsolatedStream, rectangle.Width, rectangle.Height);
                        IsolatedStream.Close();
                    }
                }

                if (IsolatedStorageFile.GetUserStoreForApplication().FileExists("banner.te2"))
                {
                    using (var file = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        var IsolatedStream = new IsolatedStorageFileStream("banner.te2", FileMode.Open, file);
                        IsolatedStream.Position = 0;
                        banner = Texture2D.FromStream(Consts.GraphicsDevice, IsolatedStream);
                        IsolatedStream.Close();
                    }
                }
                return banner;

        }

```

I'm looking for a clean fast solution, any suggestions? Resizing in `Draw()` method is not solution for me.

# Answer
> 2 votes
Setting the render target, by default, will clear the render target that you set. (In this case, `null` specifies the backbuffer as the render target - it gets cleared too).

You can change this by setting `RenderTargetUsage.PreserveContents` on the appropriate backbuffer. To do this, you need to respond to the `PreparingDeviceSettings` event at startup and set `GraphicsDeviceInformation.PresentationParameters.RenderTargetUsage`.

If you are on any platform other than Windows (so, on Windows Phone or Xbox 360), then this is ***not*** recommended because it's very, very slow - which is why it is not the default.

Rather than changing modes, you should simply do all your render target operations at the *start* of your frame, before you draw your scene to the backbuffer. In your `Update` method is acceptable.

Note that "`return (Texture2D)ret`" doesn't turn your render target into a regular `Texture2D`. It's still a `RenderTarget2D` object and you must respond correctly to `IsContentLost` (or redraw it every frame, or copy it into a `Texture2D` with `GetData` and `SetData`).

---

**A better solution than all of this**, however, is probably to simply copy the original `Texture2D` into another `Texture2D` using `GetData` and `SetData` (performing whatever transform you want to apply on the CPU - if it is a simple crop operation, then this will be very fast).

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


title: Nape physics - Moving a body

text:
# Question
Title: Nape physics - Moving a body
Hey I'm currently getting started with physics engines and I set up a body (box shaped) which represents my character.
**Question: Which methods can I use to move a Nape.Body aka my char?**

I tried so far to manipulate the *velocity*, *addLocalForce* / *Impulse* but I don't know which method is the best for moving a character.

# Answer
You want either velocity or applyImpulse(), as a rule.

Setting velocity is a tricky business, because it flat out overrides any existing velocity the body might have and thus reduces or cancels the effect of any other forces acting on the body (such as gravity). It would also require you to do extra calculations if you want to do things like accelerate or decelerate.

Thus, applyImpulse, which is meant to apply a momentary force. The vector you use for that impulse should have its magnitude multiplied by your timestep; otherwise, the net force will vary depending on your timestep and be harder to predict.

For character movement, you also probably want to cap the movement speed, as a continuous force will accelerate the body indefinitely for as long as it's applied until a collision or another force counteracts it. So you cap the magnitude (length) of your body's velocity after you apply the impulse. Here's a sample method you might call at onEnterFrame or whatever you're using to advance your Nape space:

```
// Play with these values.
private const acceleration:Number = 300;
private const maxSpeed:Number = 300;

// Helper constants so you can keep your movement direction straight.
private const LEFT:Boolean = false;
private const RIGHT:Boolean = true;

protected function move(/* direction:Number */ direction:Boolean, /* angle:Number, */ delta:Number = 1/20):void {
    var impulse:Vec2 = Vec2.weak();

    if(direction == LEFT) {
        impulse.x = -acceleration * delta;
    } else {
        impulse.x = acceleration * delta;
    }

    /* var impulse:Vec2 = Vec2.fromPolar(acceleration * delta, angle * Math.PI / 180, true); */

    this.body.applyImpulse(impulse);

    if(this.body.velocity.length > maxSpeed) {
        this.body.velocity.length = maxSpeed;
    }
}

```

Commented stuff is for movement in any direction instead of just left/right. We're assuming that `angle` is in degrees; remember that Nape works in radians.

EDIT: We're also assuming that you have a built-in way to stop, such as friction or drag. And speaking of friction, remember that your force will have to counteract it for platform movement. Read up on Nape Materials. Many developers like to set their bodies to zero friction when they start moving and set it back when the movement command ends so the body automatically slows to a stop.

```
private const zeroFriction:Material = new Material(0,0,0);
private const normalFriction:Material = new Material(0,1,2);

protected function onStartMoving():void {
    this.body.setShapeMaterials(zeroFriction);
}

protected function onStopMoving():void {
    this.body.setShapeMaterials(normalFriction);
}

```
> 1 votes

---
Tags: actionscript-3, physics
---


# Question
Title: Having to check collisions twice per game tic
I have vertically moving elevators (3 solid tiles wide) and static solid tiles. Each are separate entities and therefore have their own respective collision routines (to check for, and resolve, collisions with the main character)

I check my vertical collisions after characters vertical movements and then horizontal collisions after horizontal movements.

The problem is that I want my platform to kill the player if it squashes him from the top, and also if he's on a moving platform (that is moving up) that squashes him into a solid block.

**Correct behaviour, player on solid blocks being squashed from above by decending elevator**

Here is what happens. Gravity pushes character into solid block, solid block collision routine corrects characters position and sits him on the solid block which pushes him into the moving elevator, elevator routine then checks for collision and kills player.

This assumes I am checking solid blocks first, then elevator collisions.

However, if it's the other way around, this happens....

**Incorrect behaviour, player on accending elevator gets pushed into solid blocks above**

Player is on an elevator moving up, gravity pushes him into the elevator, solid block CD routine detects no collision, no action taken. Elevator CD routine detects character has been pushed into elevator by gravity, corrects this by moving character up and sitting him on the elevator and pushes him into the solid blocks above, however the solid block vertical routine has now already run for this tic, so the game continues and the next solid block collision that is encountered is the horizontal routine. This detects a collision and moves the character out of the collision to the left or right of the block which looks odd to say the least (character should get killed here).

The only way I've managed to get this working correctly is by running the solid block CD, then the elevator CD, then the solid block CD again straight after. This is clearly wasteful but I can't figure out how else to do this.

Any help would be appreciated.

# Answer
There are a couple of ways to go about this.

**Method 1:** The method that I've seen floating around sort of looks like your solution, but would only happen if you do collide with the walls... Something like:

```
if collide(walls, player)
    if overlap(platforms, player)
        squish()
    else
        separate()
if collide(platforms, player) separate()

```

**Method 2:** Most of my game Objects have a bitwise flag for 'touching' which tracks which of their sides are being touched at any given moment. I don't know if you have something similar, or can set it up. What I would do is first do the regular wall collision and adjust your player to not pass through the floor. Then, when you check collision with platforms, if your `player.touching == FLOOR`, then squish them.
> 1 votes

---
Tags: java, android, collision-detection, collision-resolution, moving-platforms
---


title: Color grading, shaders and 3d textures

text:
# Question
Title: Color grading, shaders and 3d textures
I'm trying to implement color correction with the 3d lookup table. The lookup table is actually just a 2d texture 256x16 and consists of 16 squares which one is 16x16.

When it comes to rendering, I pass 2 textures to shader: first one is whatever I rendered on the screen and the second is a lookup table. Shader takes RGB components of the rendered image, and uses it to find a replacement in a lookup table.

And there is two problems: first, I can't use filter to smooth colors (16 for each dimension is not enough) because it also smoothes the line between two contiguous 16x16 squares and that's inappropriate; second problem is no interpolation for a B-component.

Using a **volume texture** could solve both problems, but, unfortunately I'm short on time and there are not so many information about using 3d-textures in shaders. So, here's my questions.

1. Is it possible to pass a 3d-texture to shader (HLSL)?
2. If it is possible, could the filter be applied to the 3d dimension?
3. Maybe there is a better way to implement color-grading that I don't know?

# Answer
Yes, you can use a volume texture in HLSL and get hardware interpolation along all three axes.

* In D3D9, create a `sampler3D` variable and use the `tex3d` function to read it in the shader.
* In D3D10-11, create a `Texture3D` variable and use its `Sample` method to read it in the shader.

In either case you must have created the texture as a 16x16x16 3D texture from the main application, not as a flattened 256x16 2D texture.
> 2 votes

---
Tags: directx, hlsl, graphics-programming, fragment-shader
---


# Question
Title: Creating a light that follows the player
How do I create a point light that follows the player character when they walk around? The light should shine on the player and not on a fixed point.

# Answer
> 5 votes
The simplest way to do this, is to make the light a child of the character. Position the light where you want it to be in relation to the player, then in the Hierarchy view, drag the light so that it becomes a child of the player.

Now when the player is moved, all of its children are moved as well (including the light).

---

Another option is to use one of the built in scripts called "Smooth Follow". On your light object, in the Inspector, click on the Add Component button.

Find the "Smooth Follow" script and add it to the light.

Then set the player as the follow target:

Do that by dragging the player object from the Hierarchy view and dropping it on the Target (Empty) variable.

Now the light object will follow the player with a little bit of smoothing.

---
Tags: unity, lighting
---


# Question
Title: Large vertex buffer vs multiple draw calls
I'm just getting started with OpenGL, and I'm attempting to use it to create a 2D game. In this game, I have a hexagonal grid made up of a very large variety of differently-colored hexagons. As a newbie OpenGL programmer, I see two ways of drawing this grid:

1. Using a vertex buffer with the data for a single hexagon, then using a uniform offset value and iterating on the CPU to draw the same program many times until I have a grid.
2. Creating a singular very large pre-calculated vertex buffer that draws all the hexagons in a single call.

What's the most efficient method? Is there a better way of doing this?

# Answer
There are indeed a few ways to make such a grid.

The most efficient way would be instancing. This way you make your hexagon only once in a VBO, and render this a hundred, a thousand or a million times. You can do it manually using shaders with uniforms as you said in point 1, but there also is a built-in OpenGL functionality for it. For that, take a look at glDrawElementsInstanced.

Note that instancing is only faster than other methods if you draw more than a certain amount of instanced objects. For example drawing 300 can be faster using 1 big VBO, but drawing 2 million can be faster if you use instanced rendering.

If you use instanced rendering you can send per-object data using Attribute Divisors. In your case you would want to send the position and the color.

A good tutorial on instanced rendering: *click*

Really the best way is to try both methods, and check the amount of milliseconds it takes to draw 1 frame. This way you also learn both ways, which is always good.

Also note that instanced rendering is a modern OpenGL functionality, and that you will have to use shaders to use it. But it's always best to learn it the correct way from the beginning.
> 9 votes

# Answer
Method 1 is simpler to code and will be fine as long as you don't have too many hexagons in view at once. You might want to stick with this since you're new to OpenGL, to avoid putting too much complexity on your plate at once.

If there are a large number of hexagons (like several hundred or over a thousand) in view at once, a lower-overhead method would be necessary to avoid the CPU overhead of doing so many individual draws. Method 2 would work for this, or even better, use instancing. I'd expect instancing to be faster than method 2, or certainly no worse, since you only have to update a buffer of per-instance data rather than a (much larger) buffer of vertex data for all the instances.
> 3 votes

---
Tags: opengl, shaders
---


# Question
Title: XNA soundEffectInstance set to loop, does not loop
Using the code below I can play background music, this works. Eventhough I've set 'IsLooped' to 'true', the sound won't loop.

What Am I doing wrong?

```
protected override void LoadContent()
    {
        // background music
        SoundEffect bgEffect;
        bgEffect = Content.Load<SoundEffect>("background_music");
        SoundEffectInstance soundEffectInstance = bgEffect.CreateInstance();
        soundEffectInstance.IsLooped = true;
        soundEffectInstance.Play();

```

# Answer
You've stored your `SoundEffectInstance` as a local variable. Which means that it will go out of scope when your `LoadContent` method exits.

When the garbage collector runs, later, it will notice that nothing is referencing your `SoundEffectInstance` \- so it cleans it up. This, of course, stops the sound from playing.

The fix is simple. Simply move the variable declaration outside of your `LoadContent` method, making it a member of your game class:

```
SoundEffect bgEffect;
SoundEffectInstance soundEffectInstance;

protected override void LoadContent()
{
    bgEffect = Content.Load<SoundEffect>("background_music");
    soundEffectInstance = bgEffect.CreateInstance();
    soundEffectInstance.IsLooped = true;
    soundEffectInstance.Play();
}

```

This will keep the reference around for as long as your game class is around.

(Note that I've moved `bgEffect` out as well, in the above code. But technically you don't have to, because `Content` keeps a reference internally to everything it loads, until you call `Content.Unload()`.)
> 6 votes

---
Tags: xna, c#, sound-effects
---