# Question
Title: How to generate arrays of item types knowing just the ratio of distribution
I'm stuck to find a good solution about spawning enemies. Think of it as a tower defense game.

What I'm trying to do is:

Create keypoints for enemy types and spawnrates, as

* Wave0 = Enemy0 * 1.0
* Wave5 = Enemy0 * 0.5 + Enemy1 * 0.5
* Wave10 = Enemy1 * 0.5 + Enemy2 * 0.5

Interpolate these values and spawn enemies so that Wave3 would be Enemy0 * 0.7 + Enemy1 * 0.3

I'm trying to end up with a multidimensional array of int, representing enemy types and waves, such as;

```
EnemyWaves[0] = {0,0,0,0...} // array length = 20
EnemyWaves[3] = {0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0}
EnemyWaves[5] = {0,1,0,1,0,1...}
EnemyWaves[10] = {1,2,1,2,1,2,1...}

```

# Answer
First of all you need to interpolate Enemy ratios for level you need. This is quite trivial - for each enemy type, interpolate between ratios of known levels.

Knowing exact ratios for the level (e.g. `(0.45, 0.45, 0.1)`), there are several ways, each good for specific usage scenarios:

**Batch**

Add N items for Enemy0, where N = RoundUp(Enemy0\_Ratio * ArrayLength). Repeat for Enemy1 and etc. We round up to make sure array is filled completely. You will end up with an `(0,0,0,0,0,1,1,1,1,1)` pattern. To make sure smaller ratios are not ending up outside the array - fill array with smaller ratios first, then reverse it. `(0,0,0,0,1,1,1,1,1,2)`

**Interleaved**

Add temp variables and make a `while` loop in which add EnemyX\_Ratio to a variable X. When any X variable exceeds 1 add that EnemyX type to array and subtract 1 from X. Exit the loop once array is filled. This way you will have a fair distribution of enemy types alike `(0,1,0,1,0,1,2,0,1,0)`

**Fairly Randomized**

Do everything as in **Batch** approach, but add a final step to it - exchange random elements pairs with each other. This way you will have a randomly filled array, but with a proper ratio between item types. e.g. `(1,0,2,0,1,1,0,1,0,1)`
> 1 votes

# Answer
This problem is a bit complex. There are multiple approaches you can take. None of them are "wrong", per se, but each one is better suited for a certain number of enemies/level layout/(etc.).

Regardless of the approach you take I find it very useful to extend Unity's editor for cases like this. The approach I'd use for a simpler tower defense game would be based on a timeline file.

I wrote a small demo for a friend who was new to Unity using this approach.Excuse the naming conventions, which are all over the place for some reason that I can't recall. (Can I blame MonoDevelop?):

First I defined the spawned types in an enum:

```
public enum SpawnableTypes
{
    enemy_NullValue,
    enemy_Sponger,
    pickup_SlowTime
}

```

As you can see I only have one enemy type, and one pickup type (NullValue is just there to indicate a blank enemy).

I also used a convention that I'm not particularly proud of (this is a rather old, quick and dirty example I wrote). Each name starts with a prefix that defines the type of the spawned object. So the "enemy\_" prefix actually has meaning. I wouldn't do that this if I were to do this again.

Each type would have to be defined here (part of why this is better suited for a simple tower defense game, where each enemy shares some common characteristics)

After I defined the enum, I defined a `SpawnManager`, and various `SpawnController` objects:

* SpawnControllers are objects that spawn one of the types above. There might be one for enemies, one for powerups, and so on. It has a method `SpawnChild` that accepts a value of the type `SpawnableTypes`. The controller is to create a GameObject of the correct type when this method is called.
* The `SpawnManager` is an object that will load up a file, read the timeline of objects that needed to be spawned over the course of the level, then call `SpawnChild` child on the appropriate `SpawnController`. It knows which `SpawnController`to call `SpawnChild` on using the prefix I mentioned above (again, there are *many* more elegant ways to do this).

This defines the basis of generating waves. The `SpawnableTypes` don't have to be enemies and pickups. It'd be very easy to define one to display a message when a new wave is started, and actually defining a new wave is as simple as defining a large delay between two objects in the timeline.

Now I have to backtrack to how the time line is defined:

I used a simple file format (from the comments of my editor):

```
/* File Format:
 * Line 1: Object 1     Prefab Name
 * Line 2: Time until Object 2 is spawned

 * Line 3: Object 2     Prefab Name
 * Line 4: Time til Object 3 is spawned
 * ...
 */

```

While it is human readable, it would also be a tedious and error-prone process to generate this file by hand. So I wrote a small editor to generate it automatically:

The script is rather simple. I posted it up here so you can take a look, but it's reflects the questionable choices I made, just use it as a base of how to form your GUI.

I have an example of all of this in motion:

The webplayer.

The timeline file that demo uses.

I'm avoiding posting the implementations of the `SpawnManager` and `SpawnController` classes because they probably won't be useful. They're somewhat specific to the type of demo I was doing, and they aren't indicative of how they should be implemented (*what* they do is correct, but *how they do it* is suboptimal at best)
> 0 votes

# Answer
I had a very similar requirement for a game I'm working on. Here are some code snippets (although its in Swift and not C#) with some explanations:

Input state:

```
before filling in gaps
wave 0 = [1.0, 0.0, 0.0, 0.0]
wave 1 =
wave 2 =
wave 3 =
wave 4 =
wave 5 = [0.5, 0.5, 0.0, 0.0]
wave 6 =
wave 7 = [0.3, 0.3, 0.3, 0.0]
wave 8 =
wave 9 = [0.75, 0.0, 0.0, 0.25]

```

Output state:

```
after filling in gaps
wave 0 = [1.0, 0.0, 0.0, 0.0] --> [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
wave 1 = [0.9, 0.1, 0.0, 0.0] --> [1, 1, 1, 1, 1, 1, 1, 2, 1, 1]
wave 2 = [0.8, 0.2, 0.0, 0.0] --> [2, 2, 1, 1, 1, 1, 1, 1, 1, 1]
wave 3 = [0.7, 0.3, 0.0, 0.0] --> [2, 1, 1, 1, 2, 1, 1, 1, 2, 1]
wave 4 = [0.6, 0.4, 0.0, 0.0] --> [1, 1, 2, 2, 2, 1, 1, 1, 2, 1]
wave 5 = [0.5, 0.5, 0.0, 0.0] --> [2, 1, 1, 2, 2, 2, 2, 1, 1, 1]
wave 6 = [0.4, 0.4, 0.15, 0.0] --> [2, 1, 1, 3, 3, 1, 2, 1, 2, 2]
wave 7 = [0.3, 0.3, 0.3, 0.0] --> [2, 3, 2, 1, 1, 2, 3, 1, 3]
wave 8 = [0.525, 0.15, 0.15, 0.125] --> [2, 4, 1, 1, 1, 1, 3, 3, 1, 2]
wave 9 = [0.75, 0.0, 0.0, 0.25] --> [1, 4, 1, 1, 1, 4, 1, 1, 1, 4]

```

**Some basic data structures**

A basic function to interpolate two values

```
/// interpolates a value between start and end, for specified step
/// step varies between 0 and 1.0
/// for step = 0.5 for start 0 and end 10 should give 5
func interpolate(start:Double, end:Double, step:Double) -> Double {
    return start + (step)*(end-start)
}

```

Represents a wave, takes in an array of double values that represent the enemy distribution for a wave. It also has a utility function that generates a set of enemies of a specific size based on the distribution

```
class Wave {
    var distribution:[Double]

    /// initialize with the distribution
    init(distribution:[Double]) {
        self.distribution = distribution
    }

    /// get a set of enemies of specified size
    // based on the distribution
    func enemies(size:Int) -> [Int] {
        var e = [Int]() // list of enemies to generate
        for (index, d) in enumerate(distribution) {
            let count = Int(round((d * Double(size))))
            for i in 0..<count {
                e.append(index+1)
            }
        }

        // due to round up , we can have e.count > size
        // e.g. if distribution is 0.25, 0.75, for size 10, we end up with 11 elements
        if e.count > size {

            // remove an item from the largest distribution
            var dlargest = distribution[0]
            var largetEnemyType = 1
            for (index,d) in enumerate(distribution) {
                if dlargest < d {
                    dlargest = d
                    largetEnemyType = index+1
                }
            }

            // now remove one element from e where e[x] == largestEnemyType
            var indexToRemove = 0
            for (index, enemyType) in enumerate(e) {
                if e[index] == largetEnemyType {
                    indexToRemove = index
                    break
                }
            }

            e.removeAtIndex(indexToRemove)
        }

        return e
    }

    var description:String { return "\(distribution)" }
}

```

A simple struct used to hold interpolation blocks for between waves. An interpolation block is used to identify missing chunks of waves.

```
struct InterpolationBlock {
    var start:Int
    var end:Int
}

```

**Algorithm**

To start off, initialize our waves array to empty. This example assumes 10 waves

```
// initialize our waves with nil
var waves = [Wave?]()

for var i = 0; i < 10; i++ {
    waves.append(nil)
}

```

We define 4 enemies, so all distributions will have 4 values. Also, once the waves are initialized to nil (empty) pick and set which waves we need. For this snippet example, we need to have the first and last waves set to some values in the minimum. All other intermediate values for wave distributions will be interpolated.

```
let totalEnemies:Int = 4

// set up specific wave distributions
// the first and last ones must be defined
waves[0] = Wave(distribution: [1.0,0,0,0])
waves[5] = Wave(distribution: [0.5,0.5,0,0])
waves[7] = Wave(distribution: [0.3,0.3,0.3,0])
waves[9] = Wave(distribution: [0.75,0.0,0.0,0.25])

```

**Pass 1** \- identify missing wave chunks and store them in interpolation blocks

```
var blocks = [InterpolationBlock]()
var currentBlock = InterpolationBlock(start: 0, end: 0)
for var i = 1; i < waves.count; i++ {
    if waves[i] != nil {
        currentBlock.end = i
        blocks.append(currentBlock)
        currentBlock.start = i
    }
}

```

**Pass 2** \- fill up the waves array using interpolatation to find missing waves using the block start and end indexes

```
for block in blocks {
    // for current block, find out how many missing waves
    // needs to be filled up
    let missingWaves = Double(block.end - block.start)

    let startWave = waves[block.start]!
    let endWave = waves[block.end]!

    for var missingWaveIndex = block.start+1, i=1; missingWaveIndex < block.end; missingWaveIndex++, i++ {
        // interpolate values for missing
        // enemy distribution
        var missingDistribution = [Double]()
        for var ed = 0; ed < totalEnemies; ed++ {
            let start = startWave.distribution[ed]
            let end = endWave.distribution[ed]
            let step = Double(i)/missingWaves
            let gapFill = interpolate(start, end, step)
            missingDistribution.append(gapFill)
        }
        waves[missingWaveIndex] = Wave(distribution: missingDistribution)
    }
}

```

At this stage, all waves are filled up. To generate a set of enemies, say 10 enemies, we could call `wave[2].enemies(10)` which would give `[1, 1, 1, 1, 1, 1, 1, 1, 2, 2]` and if you want a randomized set, use a shuffle algorithm like Fischer-Yates.
> 0 votes

---
Tags: c#, unity
---


# Question
Title: Draw lines from the center of the screen at specific angles
I want to draw multiple primitive lines which start at the center of the screen and end at the edges of the screen, traveling at specific angles:

How can I set the angle for each line?

Here is my code where I draw only one line from the middle of the screen to the top of the screen.

```
LineVertices = new VertexPositionColor[2];
LineVertices[0].Position = new Vector3(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2, 0);
LineVertices[0].Color = Color.Red;
LineVertices[1].Position = new Vector3(graphics.GraphicsDevice.Viewport.Width / 2, 0, 0);
LineVertices[1].Color = Color.Red;
.
.
.
//Draw call
graphics.GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, Line2Vertices, 0, 1);

```

# Answer
> 3 votes
This is essentially simple trigonometry. Assuming the center of the screen is your origin (i.e. `(0, 0)`), then it's pretty straightforward:

```
x = length * sin(angle);
y = length * cos(angle);

```

Just insert the proper numbers and you end up with your vertex coordinates.

---
Tags: xna
---


title: HLSL SampleCmp compile error

text:
# Question
Title: HLSL SampleCmp compile error
When trying to compile the following HLSL:

```
Texture2DArray gShadowmap : register(TEXTURE_REGISTER_DEPTH);
SamplerState gShadowmapSampler : register(SAMPLER_REGISTER_DEPTH);

// ...

float3 projCoords = (float3)mul(gSplitVPMatrices[index], worldPos);
float viewDepth = projCoords.z - DEPTH_BIAS;
projCoords.z = float(index);
float visibilty = gShadowmap.SampleCmp(gShadowmapSampler, projCoords, viewDepth).r;

```

visual studio gives me:

```
error X3013: 'SampleCmp': no matching 3 parameter intrinsic method
error X3013: Possible intrinsic methods are:
error X3013: Texture2DArray<float4>.SampleCmp(SamplerComparisonState, float3|half3|min10float3|min16float3, float1|half1|min10float1|min16float1)
error X3013: Texture2DArray<float4>.SampleCmp(SamplerComparisonState, float3|half3|min10float3|min16float3, float1|half1|min10float1|min16float1, int2)
error X3013: Texture2DArray<float4>.SampleCmp(SamplerComparisonState, float3|half3|min10float3|min16float3, float1|half1|min10float1|min16float1, int2, float1|half1|min10float1|min16float1)
error X3013: Texture2DArray<float4>.SampleCmp(SamplerComparisonState, float3|half3|min10float3|min16float3, float1|half1|min10float1|min16float1, int2, float1|half1|min10float1|min16float1, out uint status)

```

I believe I match the first method, so why is this?

# Answer
> 0 votes
If we look at the documentation, we see that a `SamplerComparisonState` is not a regular `SamplerState`:

> \[in\] `SamplerComparisonState`: A sampler-comparison state, which is the sampler state plus a comparison state (a comparison function and a comparison filter).

Change your `SamplerState` creation code into a `SamplerComparisonState`. A good example (that seems to match your shadowing purposes) can be found on the Sampler Type bottom example:

```
SamplerComparisonState ShadowSampler
{
   // sampler state
   Filter = COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
   AddressU = MIRROR;
   AddressV = MIRROR;

   // sampler comparison state
   ComparisonFunc = LESS;
};

float3 vModProjUV;
  ...
float fShadow = g_ShadowMap.SampleCmpLevelZero( ShadowSampler, vModProjUV.xy, vModProjUV.z);

```

---
Tags: directx, hlsl
---


# Question
Title: How do I listen for an Admob interstitial ad load event?
I can show interstitial AdMob ads with the following code:

```
    if (GUI.Button(new Rect(10, 300, 150, 50), "Load Interstitials"))
    {
        interstitial.LoadAd(interstitialsRequest);
    }

    if (GUI.Button(new Rect(10, 400, 150, 50), "Show Interstitials"))
    {
        if (interstitial.IsLoaded())
        {
            interstitial.Show();
        }
    }

```

That's all working well.

Now I want to attach a listener for when the interstitial ad has loaded. I checked all the available source files, but can't find the right listener method.

```
void onAdLoaded()
{
    print("Interstitial Ad Loaded");
}

public void HandleAdLoaded(object sender)
{
    print("HandleAdLoaded event received.");
    // Handle the ad loaded event.
}

```

I use *googleads-mobile-plugins* for Admob ads.

What listener should I be using?

# Answer
There are several different events that can be called from the interstitial, `AdLoaded`, `AdOpened`, `AdClosing`, and `AdClosed`. Unfortunately it appears this is as much interaction as you can have with the interstitial *that google exposes*.

Digging deeper, if we look at the source of `InterstitialAd`, then we find it inherits from `IAdListener`, which only exposes the events

```
void FireAdLoaded();
void FireAdFailedToLoad(string message);
void FireAdOpened();
void FireAdClosing();
void FireAdClosed();
void FireAdLeftApplication();

```

At this point, you can add your own events. Then, simply reimplement them in `InterstitialAd`'s source.
> 3 votes

---
Tags: unity, admob
---


# Question
Title: How to initiate a TCP secure connection using LibGdx to a remote server?
Can anyone point to a link or share with me a piece of code which does: \- Base on LibGdx (Gdx.net package) \- Use a TCP secure connection to connect to a remote server

Many thanks

# Answer
From the documentation:

```
Socket socket = Gdx.net.newClientSocket(Protocol protocol, String host, int port, SocketHints hints);

```
> 1 votes

---
Tags: libgdx
---


title: How are entity systems cache-efficient?

text:
# Question
Title: How are entity systems cache-efficient?
Lately, I've been doing a lot of reading on entity systems to implement in my C++/OpenGL game engine. The two key benefits that I constantly hear lauded about entity systems are

1. the easy construction of new kinds of entities, due to not having to tangle with complex inheritance hierarchies, and
2. cache efficiency, which I'm having trouble understanding.

The theory is simple, of course; each component is stored contiguously in a block of memory, so the system that cares about that component can just iterate over the whole list, without having to jump around in memory and kill the cache. The problem is that I can't really think of a situation where this is actually practical.

---

First, let's look at how the components are stored, and how they reference each other. Systems need to be able to work with more than one component, i.e. both the rendering and physics system needs to access the transform component. I've seen a number of possible implementations that address this, and none of them do it well.

You can have components store pointers to other components, or pointers to entities that store pointers to components. However, as soon as you throw pointers into the mix, you're already killing cache efficiency. You can ensure that every component array is 'n' large, where 'n' is the number of entities alive in the system, but this approach is hideously wasteful of memory; this makes it very difficult to add new component types to the engine, but still throws away cache efficiency, because you're jumping from one array to the next. You could interleave your entity array, instead of keeping separate arrays, but you're still wasting memory; making it prohibitively expensive to add new components or systems, but now with the added benefit of invalidating all of your old levels and save files.

This is all assuming that entities are processed linearly in a list, every frame or tick. In reality, this is not often the case. Say you use a sector/portal renderer, or an octree, to perform occlusion culling. You might be able to store entities contiguously within a sector/node, but you're going to be jumping around, whether you like it or not. Then you have other systems, which might prefer entities stored in some other order. AI might be okay with storing entities in a big list, until you start working with AI LOD; then, you'll want to split that list up according to distance to the player, or some other LOD metric. Physics is going to want to use that octree. Scripts don't care, they need to run, no matter what.

I could see splitting components up between "logic" (e.g. ai, scripts, etc) and "world" (e.g. rendering, physics, audio, etc), and managing each list separately, but these lists still have to interact with each other. AI is pointless, if it can't affect the transform or animation state used for an entity's rendering.

---

How are entity systems "cache-efficient" in a real-world game engine? Perhaps there's a hybrid approach that everyone's using, but not talking about, like storing entities in an array globally and referencing it within the octree?

# Answer
> 56 votes
> The two key benefits that I constantly hear lauded about entity systems are 1) the easy construction of new kinds of entities due to not having to tangle with complex inheritance hierarchies, and 2) cache efficiency.

Note that (1) is a benefit of *component-based design*, not just ES/ECS. You can use components in many ways that do not have the "systems" part and they work just fine (and plenty of both indie and AAA games use such architectures).

The standard Unity object model (using `GameObject` and `MonoBehaviour` objects) is not an ECS, but is component-based design. The newer Unity ECS feature is an actual ECS, of course.

> Systems need to be able to work with more than one component, ie both the rendering and physics system need to access the transform component.

Some ECS sort their component containers by Entity ID, meaning that the corresponding components in each group will be in the same order.

This means that if you're linearly iterating over graphics component you're *also* linearly iterating over the corresponding transform components. You might be skipping some of the transforms (since you may have physics trigger volumes that you don't render or such) but since you're always *skipping forward* in memory (and by not particularly huge distances, usually) you're still going to have efficiency gains.

This is similar to how you have the Structure Of Arrays (SOA) being the recommended approach for HPC. The CPU and cache can deal with multiple linear arrays almost as well as it can deal with a single linear array, and far better than it can deal with random memory access.

Another strategy used in some ECS implementations - including Unity ECS - is to allocate Components based on the Archetype of their corresponding Entity. That is, all Entities with precisely the set of Components (`PhysicsBody`, `Transform`) will be allocated separately from the Entities with different Components (e.g. `PhysicsBody`, `Transform`, *and* `Renderable`).

Systems in such designs work by first finding all Archetypes that match their requirements (that have the required set of Components), iterating that list of Archetypes, and iterating the Components stored within each matching Archetype. This allows for completely linear and true O(1) component access within an Archetype and allows Systems to find compatible Entities with very low overhead (by searching a small list of Archetypes rather than searching potentially hundreds of thousands of Entities).

> You can have components store pointers to other components, or pointers to entities that store pointers to components.

Components referencing other components on the same entity don't need to store anything. To reference components on other entities, just store the entity ID.

If a component is allowed to exist more than once for a single entity and you need to reference a particular instance, store the other entity's ID and a component index for that entity. Many ECS implementations do not allow this case, however, specifically because it makes these operations less efficient.

> You can ensure that every component array is 'n' large, where 'n' is the number of entities alive in the system

Use handles (e.g. indices + generation markers) and not pointers and then you can resize the arrays without fear of breaking object references.

You can also use a "chunked array" approach (an array of arrays) similar to many common `std::deque` implementation (though without the pitifully-small chunk size of said implementations) if you want to allow pointers for some reason or if you have measured problems with array resize performance.

> Secondly, this is all assuming that entities are processed linearly in a list every frame/tick, but in reality this is not often the case

It depends on the entity. Yes, for many use cases, it's not true. Indeed, this is why I so strongly stress the difference between *component-based design* (good) and *entity-system* (a specific form of CBD).

Some of your components will certainly be easy to process linearly. Even in normally "tree heavy" use cases we have definitely seen performance increases from using tightly packed arrays (mostly in cases involving an N of a few hundred at most, like AI agents in a typical game).

Some developers have also found that the performance advantages of using data-oriented linearly-allocated data structures outweighs the performance advantage of using "smarter" tree-based structures. It all depends on the game and specific use cases, of course.

> Say you use a sector/portal renderer or an octree to perform occlusion culling. You might be able to store entities contiguously within a sector/node, but you're going to be jumping around whether you like it or not.

You'd be surprised how much the array still helps. You're jumping around in a much smaller region of memory than "anywhere" and even with all the jumping you're still much more likely to end up in something in cache. With a tree of a certain size or less, you might even be able to prefetch the whole thing into cache and not ever have a cache miss on that tree.

There are also tree structures that are built to live in tightly packed arrays. For instance, with your octree, you can use a heap-like structure (parents before children, siblings next to each other) and ensure that even when you "drill down" the tree you're always iterating forward in the array, which helps the CPU optimize the memory accesses / cache lookups.

Which is an important point to make. An x86 CPU is a complex beast. The CPU is effectively running a microcode optimizer on your machine code, breaking it into smaller microcode and reordering instructions, predicting memory access patterns, etc. Data access patterns matter more than may be readily apparent if all you have is a high-level understanding of how the CPU or cache work.

> Then you have other systems, which might prefer entities stored in some other order.

You could store them multiple times. Once you strip down your arrays to the bare minimum details, you might find you actually *save* memory (since you've removed your 64-bit pointers and can use smaller indices) with this approach.

> You could interleave your entity array instead of keeping separate arrays, but you're still wasting memory

This is antithetical to good cache usage. If all you care about are the transforms and graphics data, why make the machine spend time pulling in all that other data for physics and AI and input and debug and so on?

That's the point usually made in favor of ECS vs monolithic game objects (though not really applicable when comparing to other component-based architectures).

For what it's worth, most "production-grade" ECS implementations of which I'm aware use interleaved storage. The popular Archetype approach I mentioned earlier (used in Unity ECS, for example) is very explicitly build to use interleaved storage for Components associated with an Archetype.

> AI is pointless if it can't affect the transform or animation state used for an entity's rendering.

Just because AI can't efficiently access transform data linearly doesn't mean that no other system can use that data layout optimization effectively. You can use a packed array for transform data without stopping game logic systems from doing things the ad hoc way game logic systems usually do things.

You're also forgetting *code cache*. When you use the systems approach of ECS (unlike some more naive component architecture) you're guaranteeing that you're running the same small loop of code and not jumping back and forth through virtual function tables to an assortment of random `Update` functions strewn all over your binary. So in the AI case, you really want to keep all your different AI components (because certainly you have more than one so that you can compose behaviors!) in separate buckets and process each list separately in order to get the best code cache usage.

With a delayed event queue (where a system generates a list of events but doesn't dispatch them until the system finishes processing all entities) you can ensure that your code cache is used well while keeping events.

Using an approach where each system knows which event queues to read out of for the frame, you can even make *reading* events fast. Or faster than without, at least.

Remember, performance isn't absolute. You don't need to eliminate every last single cache miss to start seeing the performance benefits of good data-oriented design.

There is still active research into making many game systems work better with ECS architecture and data-oriented design patterns. Similarly to some of the amazing things we've seen done with SIMD in recent years (e.g. JSON parsers), we're seeing more and more things done with ECS architecture that doesn't seem intuitive to classical game architectures but offers a number of benefits (speed, multi-threading, testability, etc.).

> Or perhaps there's a hybrid approach that everyone's using but nobody's talking about

This is what I have advocated in the past, especially for folks who are skeptical of ECS architecture: use good data-oriented approaches to components where the performance is critical. Use simpler architecture where simplicity improves development time. Don't shoe-horn every single component into a strict over-definition of componentization like ECS proposes. Develop your component architecture in such a way that you can easily use ECS-like approaches where they make sense and use simpler component structure where ECS-like approach don't make sense (or make less sense than a tree structure, or so on).

I'm personally a relatively recent convert to the true power of ECS myself. Though for me, the deciding factor was something rarely mentioned about ECS: it makes writing tests for game systems and logic almost trivial compared to the tightly-coupled logic-laden component-based designs I've worked with in the past. Since ECS architectures put all logic in Systems, which just consume Components and produce Component updates, building a "mock" set of Components to test System behaviour is quite easy; because most game logic should live solely inside Systems, that effectively means that testing all your Systems will provide fairly high code coverage of your game logic. Systems can use mock dependencies (e.g. GPU interfaces) for tests with far less complexity or performance impact than you'd get if you had to inject those dependencies into thousands of interconnected logic-heavy Components.

As an aside, you might note that a *lot* of people talk about ECS without really understanding what it even is. I see classic Unity referred to as ECS with depressing frequency, illustrating that too many game developers equate "ECS" with "Components" and pretty much ignore the "Entity System" part entirely. You see a lot of love heaped on ECS on the Internet when a large portion of the people are really just advocating component-based design, not actual ECS. At this point it's almost pointless to argue it; ECS has been corrupted from its original meaning into a generic term and you might as well accept that "ECS" doesn't mean the same thing as "data-oriented ECS". :/

---
Tags: c++, entity-system, optimization
---


# Question
Title: Is lighting different from Immediate mode rendering to VBOs?
I recently got a textured cube to render as a VBO, and I've noticed some strange things as I have been trying to incorporate lighting.

Firstly, there is no difference if I comment out any lines involving the shaders. Does that mean I am using the default shaders? Do I need custom shaders for lighting to work correctly?

Second, the VBO cube has the same ambient lighting as the immediate mode cubes, but the VBO cube does not have the diffuse lighting. I've changed the color of the ambient lighting to blue to make this more obvious. There is one VBO cube next to two adjacent immediate mode cubes.

This is the front, with the light pointing at the cubes:

This is the back, when the other cubes have ambient lighting too:

So, with ambient light working, I am thinking it is possible to get diffuse too, is that true? Or, do I need to get the shaders working and implement lighting there?

For lighting, I set everything up by saying:

```
    // Enable lighting in GL.
    gl.glEnable(GL_LIGHT0);
    gl.glEnable(GL_LIGHTING);

    gl.glEnable(GL_DEPTH_TEST); // enables depth testing
    gl.glDepthFunc(GL_LEQUAL); // the type of depth test to do
    gl.glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // best
                                                            // perspective
                                                            // correction

    gl.glShadeModel(GL_SMOOTH); // blends colors nicely, and smoothes out
                                // lighting

    // Add colors to texture maps, so that glColor3f(r,g,b) takes effect.
    gl.glEnable(GL_COLOR_MATERIAL);
    gl.glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
    gl.glEnable(GL.GL_TEXTURE_2D);

```

And for each frame I also say:

```
    gl.glLightfv(GL_LIGHT0, GL_AMBIENT, lightColorAmbient, 0);
    gl.glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDif, 0);
    gl.glLightfv(GL_LIGHT0, GL_SPECULAR, lightColorSpecular, 0);
    gl.glLightfv(GL_LIGHT0, GL_POSITION, lightPos, 0);

```

Thanks so much!

# Answer
I didn't use normals (bind them, set them, etc) on my VBO, but they were already on my immediate mode cubes.
> 0 votes

---
Tags: shaders, lighting, vbo, jogl
---


# Question
Title: (Game Maker Studio) How do I make a high score system?
For my game, I want a way to make the game remember the top score. I know how to make the game save, I just need a way to save a high score.

This is my current system, that has not been working:

```
If next room exists >
If score is larger than health >
Set the health to score >
    highscore_add(global, score);
    highscore_value(health)

```

This has an output of nothing.

I would really appreciate some help!

# Answer
> 2 votes
According to the documentation, `highscore_value` takes different arguments from `highscore_add`.

> ## highscore\_value(place);
>
> **place**: The place on the table (1-10).
>
> With this function you can retrieve the score value that has been stored in the high score list at the given position.

> ## highscore\_add(str, numb);
>
> **str** The string (name) to attribute the score to
> **numb** The number (score) to add.
>
> With this function you can add a name and a score to the internal global high score list.

Your code

```
highscore_add(global, score);
highscore_value(health)

```

...attempts set and retrieve values using equal terms (`score` and `health`), which is a mis-use of the functions. You are also using the `global` variable when you should be using a string.

---
Tags: game-maker
---


title: OOP Question for Team System

text:
# Question
Title: OOP Question for Team System
I'm not quite sure right how I should create my "Team System". Lets say I have 2 teams with 4 players in there. The teams are Team Blue and Team Red. A team knows the amount of its members, the amount of its points (each team will have points which the players gain for the team) and maybe some details for the HUD.

My solution right know would be to create parent class Team with the childs TeamRed and TeamBlue and add the players to the teams. (it would be also great to get a player's team through the player -\> Example: `Player.GetTeam() == TeamBlue?`

But since Team red and blue are actually quit similiar and only have different HUD settings, I'm not quite sure about this design. Another possibility would be to just have a class Team and create the objects Team teamRed; & Team teamBlue;

what do you think guys? any better solutions?

# Answer
Take the following relations into account

* A team **has** players
* Team Red **is a** team
* A player **is associated** with a team

So, the following approach should give you a good hint.

Team Red and Team Blue are instances of a team, with the same attributes but they just differ in **values**. Unless you need to implement different behaviors (member functions) for each team, you just need one Team class with an array/list for storing players.

Each player could have its team assigned as an *enum*, *number*, or *pointer* variable. It's up to you.

---

Why do I suggest this approach? Imagine you have spells. Each one has probably different attribute values (and maybe they have different number of attributes), and they also behave completely different from each other (unless one derive from another). That way you could have parent abstract class Spell and then specific attributes and behaviors for each one (imagine a virtual member function called *cast*, for example).
> 4 votes

# Answer
You should not mix the view which defines how things look, like the teams' HUDs with the teams' model, their data structure or class instance.

Like @pctroll said, the teams could be instances of a `Team` class. In my opinion, the `Team` class should simply be a glorified array of players and some methods that tally up score. The player class should have a pointer to it's team.

Warning this is *pseudo* code:

```
//so the function of adding a player could be like this:

class Team
{
  .
  .
  .
  vector<Player> players;
  addMember(p : Player){
    p.team = this;
    players.push(p);
  }
}

```

The view styling could be an instance of class HUD that is handed to the Team constructor.
> 2 votes

---
Tags: c++, oop
---


title: Smooth radial collision

text:
# Question
Title: Smooth radial collision
I'm trying to make collisions smoother in my game. Currently, entities will stop completely when they collide with an obstacle. I saw the following article recently:

http://www.gamedev.net/page/resources/\_/technical/math-and-physics/simple-but-effective-collisions-part-1-radial-collision-handling-r3147

I gave it a try by writing a quick, small example. The commented out code in the function below is my attempt at getting it to work:

```
QPointF handleRadialCollisions() {
        QPointF deltaPos(0, 0);
        foreach (const QGraphicsItem *obstacle, mPlayer->scene()->collidingItems(mPlayer)) {
            const QPointF targetCentrePos = mPlayer->sceneBoundingRect().center();
            const QRectF playerBoundingRect = mPlayer->boundingRect();
            const qreal playerRadius = qMax(playerBoundingRect.width(), playerBoundingRect.height());
            const QRectF obstacleBoundingRect = obstacle->boundingRect();
            const QPointF obstacleCentrePos = obstacle->sceneBoundingRect().center();
            const qreal obstacleRadius = qMax(obstacleBoundingRect.width(), obstacleBoundingRect.height());
            const QPointF vectorToCentre(targetCentrePos.x() - obstacleCentrePos.x(), targetCentrePos.y() - obstacleCentrePos.y());
            if (vectorToCentre.manhattanLength() < obstacleRadius) {
                deltaPos += ((obstacleRadius / vectorToCentre.manhattanLength()) - 1) * vectorToCentre;
            }
//            if (vectorToCentre.manhattanLength() < obstacleRadius + playerRadius) {
//                deltaPos += (((obstacleRadius + playerRadius) / vectorToCentre.manhattanLength()) - 1) * vectorToCentre;
//            }
        }
        return deltaPos;
    }

```

It is used like so:

```
    void timerEvent(QTimerEvent *event) {
        // ... adjust velocity here depending on keys pressed.

        mPlayer->setVelocity(QPointF(xVelocity, yVelocity));

        mPlayer->setPos(mPlayer->pos() + mPlayer->velocity() + handleRadialCollisions());
    }

```

As mentioned in the comments of the article, the method presented doesn't account for the radius of the player. I attempted to fix this (commented out if statement in handleRadialCollisions()), but the player "bounces" off the obstacle instead of smoothly sliding off it. What am I doing wrong?

# Answer
I think your `playerRadius` is twice as big as it should be. Your `vectorToCentre` is measured from `targetCentrePos`, but you use the full `width()` or `height()` of `playerBoundingRect` to determine radius.

I suggest this change:

```
const qreal playerRadius = qMax(
  playerBoundingRect.width() / 2,
  playerBoundingRect.height() / 2);

```
> 1 votes

---
Tags: c++, collision-resolution, qt, bounding-spheres
---


# Question
Title: How can I generate isometric sprite sheets from 3D animations?
I want to generate sprite-sheets for an isometric projection of various 3d assets purchased from the Unity3D asset store. I'd preferably also render the normal maps. I am a programmer, but new to 3D modeling software (Blender, etc.)

I found two tools for this; *SpriteForge* and *SpriteWorks*, but neither supports enough formats to be worth their cost.

There must be an efficient way of isometrically rendering various animations of a 3d assets in Blender—but I don't know how. How can I do this?

# Answer
Blender is a good start.

To get "isometric" view you just need to configure the camera to orthographic projection and place it at the correct angle above and to the side of your model.

Then you need to animate the model as required. Here you need to ensure that the number of animation frames equals the desired sprite sheet.

Then you "film" the animation loop. You set the duration of the capture to equal your animation duration. Set the output to JPEG or PNG and the size to whatever you need.

Finally using something like ImageMagick and a small driver script you glue the images together into one big sheet.

Although the process could be a bit more automated, it should be feasible.

See also @API-Beasts's link for the isometric setup.
> 5 votes

# Answer
Fragmotion can create all the sprites you need and technically it's free... You load the FBX or BVH in and select *Create Sprite Sheet* from the menu. If you have the animations already pre-loaded into the character, it should be easy.
> 2 votes

# Answer
All credit to API-Beast for this, but since they didn't add it as an answer and this question remains technically unanswered...

Check out this link for a blender script to actually output the individual frames. That's doing just a rotation, but fundamentally it's the same process to iterate over multiple frames of animation and output a snapshot render taken of each frame.
> 0 votes

---
Tags: animation, sprites, isometric, 2.5d
---


# Question
Title: Sprite Kit - containsPoint for SKPhysicsBody?
I have a ball bouncing around the screen. I can pick it up and drag it onto a "bucket".

When my touches finish, I use the containsPoint function to check and see if I have dropped the ball onto the bucket.

This works fine, however, I actually want to check whether the ball is dropped onto the bucket node's physics body because my "bucket" is actually just an oval, and so I've applied a physics body which is the same shape as the oval, so that the white space around the oval isn't included in the physics simulation.

I can't seem to find a "containsPoint" function for physics bodies. Can anyone advise on how I'd check for this?

To summarise, I want to drop a node, onto a specific part of another node (or its physics body) and trigger an event.

Thanks in advance.

# Answer
> 1 votes
I had similar question and I did use this solution. Construct CGPathRef and then do check using CGPathContainsPoint in touchesBegan method.

# Answer
> 0 votes
The simplest means of determining if there is contact after your touches finish is to alter the category of the "ball" to a category that registers contacts with the "bucket".

That is to say, your ball would have a category that ignores the bucket until the ball is dragged and the touches end (*touchesEnd* method), at which point the category of the *SKPhysicsBody* of the ball will be changed to a category that no longer ignores the bucket. A simple *didBeginContact* method executes your desired behavior for the ball being dropped in the bucket.

---
Tags: collision-detection, ios, physics, spritekit
---


# Question
Title: How can I make my player move in the direction the camera faces?
I have a 3rd person camera which can rotate around the player. My problem is that wherever camera is facing, players forward is always the same direction.

For example when camera is facing the right side of the player, when I press button to move forward, I want player to turn to the left and make that the "new forward".

My camera script so far:

```
using UnityEngine;
using System.Collections;

public class PlayerScript : MonoBehaviour
{
    public float RotateSpeed = 150,
    MoveSpeed = 50;
    float DeltaTime;

    void Update()
    {
        DeltaTime = Time.deltaTime;
        transform.Rotate(0, Input.GetAxis("LeftX") * RotateSpeed * DeltaTime, 0);
        transform.Translate(0, 0, -Input.GetAxis("LeftY") * MoveSpeed * DeltaTime);
    }
}

public class CameraScript : MonoBehaviour
{
    public GameObject Target;
    public float RotateSpeed = 170,
    FollowDistance = 20,
    FollowHeight = 10;
    float RotateSpeedPerTime,
    DesiredRotationAngle,
    DesiredHeight,
    CurrentRotationAngle,
    CurrentHeight,
    Yaw,
    Pitch;
    Quaternion CurrentRotation;

    void LateUpdate()
    {
        RotateSpeedPerTime = RotateSpeed * Time.deltaTime;

        DesiredRotationAngle = Target.transform.eulerAngles.y;
        DesiredHeight = Target.transform.position.y + FollowHeight;
        CurrentRotationAngle = transform.eulerAngles.y;
        CurrentHeight = transform.position.y;

        CurrentRotationAngle = Mathf.LerpAngle(CurrentRotationAngle, DesiredRotationAngle, 0);
        CurrentHeight = Mathf.Lerp(CurrentHeight, DesiredHeight, 0);

        CurrentRotation = Quaternion.Euler(0, CurrentRotationAngle, 0);
        transform.position = Target.transform.position;
        transform.position -= CurrentRotation * Vector3.forward * FollowDistance;
        transform.position = new Vector3(transform.position.x, CurrentHeight, transform.position.z);

        Yaw = Input.GetAxis("Right Horizontal") * RotateSpeedPerTime;
        Pitch = Input.GetAxis("Right Vertical") * RotateSpeedPerTime;
        transform.Translate(new Vector3(Yaw, -Pitch, 0));
        transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);

        transform.LookAt(Target.transform);
    }
}

```

# Answer
(coincidentally I just wrote about this topic for my book. That chapter should be released next week; here's a brief summary)

There are two primary steps to what you're trying to do: 1) Determine which direction to face 2) Rotate the player to face that direction

The first task is handled via transforming the direction vector from camera-space to world-space. That is, take the "left" direction of the camera and transform that into a global direction, something like this in the player script:

```
Vector3 movement = new Vector3(Input.GetAxis("LeftX"), 0, 0);
movement = cameraTransform.TransformDirection(movement);

```

The second step is handled by turning the direction vector into a quaternion and then setting that as the player's rotation, something like:

```
transform.rotation = Quaternion.LookRotation(movement);

```

Although that will snap to the new direction instantly; if you want the player to smoothly rotate to the new direction then you should use Lerp:

```
Quaternion direction = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Lerp(transform.rotation,
                                     direction, rotSpeed * Time.deltaTime);

```
> 3 votes

---
Tags: c#, unity, camera, rotation, movement
---


title: Simulating Smartphones on PC with Unity

text:
# Question
Title: Simulating Smartphones on PC with Unity
I want to make a game that depends on the phone orientation (changing shoot direction with tilt), however I need to test this on PC. So is there any tool I can use to simulate the orientation of the phone with mouse or keyboard of my PC? Something like joysticks on the screen.

Thanks for any help!

## Edit :

Thanks to @jhocking for his suggestion of Unity Remote. I, however still can accept a solution with using only PC, since I'm afraid of shortening my phone's battery life, for some reason.

# Answer
> 3 votes
Unity Remote exists for this purpose. Quoting their description:

> Unity Remote is an application that allows you to use your target device as a remote control for your project in Unity editor. This is useful during development since it is much quicker to test your project in the editor with remote control than to build and deploy it to the device after each change.

However if you don't want to use that tool for some reason and absolutely have to have test controls done using a joystick or keyboard, just program alternate controls using GetAxis("Horizontal") and put this code inside a compiler directive #if UNITY\_EDITOR

---
Tags: unity, android, ios, iphone, simulations
---


title: Characters With Interchangeable Skills

text:
# Question
Title: Characters With Interchangeable Skills
I am using unity and I would like to create characters that have interchangeable spells. As an example it would be something like Pokemon that can attain different skills as they level up and the user can change out skills for new ones. Would this be a good place for inheritance? Should I make a parent class that inherited by all of the other characters? Would this be the best approach?

# Answer
> 10 votes
> Would this be a good place for inheritance?

No, this is a good place for composition, see the Strategy pattern for more details.

First of all, define an interface for your skills. Each character will have an instance of a class that implements that interface as a member. This ensures that you can switch between skills at runtime with ease. A simplistic example would look like this:

```
interface ISkill
{
      void Execute(Character character);
}

class HealingSkill : ISkill
{
      public void Execute(Character character)
      {
          character.Health += 10;
      }
}

class Character
{
       public int Health { get; set; }
       private ISkill _activeSkill;

       public void ChangeSkill(ISkill newSkill)
       {
           _activeSkill = newSkill;
       }

       public void UseSkill()
       {
           if (_activeSkill != null)
           {
               _activeSkill.Execute(this);
           }
       }
}

//In-game
var myChar = new Character();
myChar.ChangeSkill(new HealingSkill());
myChar.UseSkill();

```

---
Tags: c#, unity
---


title: Problem converting FBX file into XNB

text:
# Question
Title: Problem converting FBX file into XNB
I create a Monogame Content Project to convert assets into XNB. For FBX file without texture there is no problem: the file is correctly converted and when I load XNB into my project everything is ok. The problem occours when i have associated to fbx file a texture map: in this case both FBX and PNG files are converted to XNB but when i try to load these XNB files into my project the following problem occours:

"ContentLoadException: Could not load Models/maze1 asset as a non-content file!" Note: maze1 is the XNB file that was converted from FBX.

How can I solve this problem? Thank you in advance

# Answer
> 1 votes
According to the Wiki the Content Pipeline for Android requires different steps and it seems does not yet work with MonoGame's own content project.

However it seems parts are already working (a bit). So a possible work around is to import the FBX model without textures, but including texture coordinates (UV's) and load the texture separately. Then apply the texture to the model yourself during run time.

# Answer
> 0 votes
The Android file system is case sensitive.

Check that the filenames and paths match what the data is looking for. It's possible that the Models directory is lower-case on Android and therefore doesn't match the upper-case M in Model for example.

---
Tags: android, monogame, fbx, visual-studio
---


# Question
Title: Calculate velocity of a bullet ricocheting on a circle
I made a picture to demostrate what I need,basecaly I have a bullet with velocity and I want it to bounce with the correct angle after it hits a circle

**Solved**(look the accepted answer for explain):

```
Vector.vector.set(bullet.vel);    //->v
Vector.vector2.setDirection(pos, bullet.pos);     //->n normal from center of circle to bullet
float dot=Vector.vector.dot(Vector.vector2);    //->dot product
Vector.vector2.mul(dot).mul(2);
Vector.vector.sub(Vector.vector2);
Vector.vector.y=-Vector.vector.y;  //->for some reason i had to invert the y
Vector.vector.normalize();
bullet.vel.set(Vector.vector);

```

# Answer
> 1 votes
The formula for reflecting an incoming vector `v` across a unit normal `n` into an outgoing vector `v'` is

```
v' = v - 2*dot(v,n)*n

```

You can determine the normal `n` from normalizing the difference of the collision point and the center of the circle.

See the question on How to get a reflection vector? over on Math.SX for more elaborate derivations.

---
Tags: java, physics
---


# Question
Title: How to detect graphics API at runtime with SDL2?
Using SDL2, is there a way to determine at runtime whether the application is using OpenGL, OpenGLES, or DirectX?

EDIT: If there is a way to figure it out without using the SDL2 API, I'm willing to throw that code into my project.

# Answer
> 6 votes
In SDL2 the creation of the window is separate from the rendering environment used to draw into that window. So, while you might pass "SDL\_WINDOW\_OPENGL" to SDL\_CreateWindow(), this simply states that the window should support rendering from an OpenGL context later down the line and doesn't actually create an OpenGL context at that point. So, from SDL\_GetCurrentVideoDriver() I would expect only something like "windows", "x11" or "psp" due to the fact that this is the module used for handling just the window system and the final blitting of whatever the renderer draws to the screen.

Assuming that you're using a Renderer to draw 2D content to the screen - at the point you create a Renderer a DirectX or OpenGL context will actually be created for the renderer. After this point, you should be able to query the Renderer you have created for the actual driver being used. This is untested - so might need some tweaks, but I think it should give you more useful information than what you're currently getting.

```
/// ... Create Window ...

SDL_Renderer *renderer = SDL_CreateRenderer(sdlWindow, -1, 0);
SDL_RendererInfo rendererInfo;
SDL_GetRendererInfo(renderer, &rendererInfo);

std::cout << "Renderer: " << rendererInfo.name << std::endl;

```

You can request that SDL uses a given driver by setting SDL\_HINT\_RENDER\_DRIVER like so...

```
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "software");

```

But this is only a hint so it's not guaranteed. However, as the possible values for this hint are listed as 'direct3d, openGL, opengles2, opengles, software' I expect these to be the name values you would get back from the above SDL\_GetRendererInfo call.

Hope this helps. Apologies if I'm barking up the wrong tree or this doesn't work as expected. Just thought I would throw a suggestion out there before heading to bed!

# Answer
> 3 votes
Once upon a time there was Google.

Now this seems to be what you are looking for:

```
const char* SDL_GetCurrentVideoDriver(void)

```

> Returns the name of the current video driver or NULL if no driver has been initialized.

---
Tags: opengl, c++, directx, c, sdl2
---


title: Should I cap the frame rate in SDL?

text:
# Question
Title: Should I cap the frame rate in SDL?
I know this question has been asked a lot, but I never found an answer suitable for me. I have a game with a fairly big logic system and the movement system I am currently using is calling SDL\_GetTicks() and measuring the delta time between the frames. I multiply the delta with the speed and I get the pixel movement. The problem with this is that the CPU usage is quite high. I didn't really mind it until my friend started going on about how it was "the end of the world".

The question I really want an answer to is if I should cap the framerate, and if a high CPU usage is unwanted (or even dangerous!).

# Answer
> 5 votes
Should you cap the framerate: Yes

Is a high CPU usage unwanted: Yes

Or even dangerous!: Could be but if so not your problem

---

You want to cap the framerate because you are extremely unlikely to achieve any benefit (to your game) by calculating at a frequency higher than your ability to display the results. ie, if your monitor can only display at 60Hz then displaying at 200Hz achieves nothing because the display will a) ignore frames and only display at 60Hz anyway or b) display ugly tearing.

The high CPU usage is unwanted because you are drawing unnecessary current from the CPU and from the GPU, raising the temperature, fan speeds and your unsuspecting customers power bill :-)

Running at 100% CPU usage across all CPU's and flatlining the GPU simultaneously may possibly cause some system to overheat and even fail, but that would only be because that system is misconfigured (or improperly overclocked). So such a system failure would primarily be caused by the configuration error, you just triggered it. If you follow the above two guidelines this becomes a moot point.

---

Related to this is the internal logic & movement system which while not strictly tied to the framerate in theory, in practice it often is. The human eye *very* sensitive to tiny fractions of a second difference, particularly where it relates to input and game response to the input. So it's a really good idea to check player input only immediately before updating game characters, and also to put that part of the code as late in the game loop as is feasible.

The trick is doing all this as close as possible to your frame time slot without going over and missing your refresh.

For example at 60Hz you have 16ms per frame, and if your main loop takes 6ms, it's better to execute it at the 9ms mark rather than at the 0ms mark and lagging by 10ms.

Executing it as late as possible with a tiny leeway will make it feel just that touch more responsive, and gamers will notice.

Keep your loop timing tied to the vsync signal rather than some arbitrary random game start time. Also keep in mind that high res timers will derive over time so you'll need to watch it to keep it in sync. This way your 6ms main loop won't accidentally finish a millisecond after the screen refreshes so that you have a whole 15ms lag.

If you think it's ridiculous to say that a player would notice such a small interval, then go read this 2006 study to see just how quick the human eye is (this article includes a cognitive response to a massive amount of visual data in it's timing).

Also note player comments where they are adamant about noticing game responsiveness when the refresh rate is in fact beyond the ability of their monitors to display it.

It is because the very freshest data was used when drawing the frame they do see.

Also be careful as vsync synchronisation can make your program 'freeze' for a few ms while waiting for vblank. There is an excellent discussion of the vsync issues over at virtualdub.org as well as one at opengl.org on swap interval (now archived at the Wayback Machine) (read the talk page on opengl.org as well)

# Answer
> 0 votes
There are a couple of dangers with an unlimited framerate which I will try to explain

You already use delta time which means that a computer which would not reach 60 FPS should still be functional. But what if I have a monstrosity of a computer that is able to run the game at 600 FPS. Deltatime will become really small and in combination with floating point errors may cause unexpected behavior as there may be rounding errors.

So you would say that capping the game at 60 FPS might be a good idea. Only downside is that the person with the 120 Hertz monitor won't be able to play at 120 Hertz.

So you might want to cap the framerate at 60 or so and provide an option to run at 120 or 240 Hertz.

# Answer
> -1 votes
No, you should not cap the framerate. This is using unnecessary processing power to check and handle the framerate. It is not necessary to base timings on the framerate, eventually computer screens will be able to handle 120Hz, so allowing the computer to zip as fast as it can is better. It will not hurt your processor to run fast, because it only uses one core to the max, unless you have a multithreaded application. Everywhere I go I see people capping the frame rate, but I believe it is useless.

---
Tags: sdl, frame-rate
---


# Question
Title: HTML5 Canvas 2D lighting and normal maps
How using the HTML5 Canvas can I create a 2D game with light sources and also add an extra depth using normal maps. I have never really done lighting in 2D before and I'm not sure where to start.

Something like this:

or

<sub>(source: wholehog-games.com)</sub>

# Answer
This effect is likely done with blending modes. http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/

You would create a gradient light texture like:
and set the composition/blending mode to either additive or multiply (or some other mode for a different effect) and then draw it on top of the area you want lit up.

I'll see if i can include a demo
Edit: http://jsfiddle.net/6dzsbhpp/1/

As per normal mapping, this must be done by hand, see: http://29a.ch/2010/3/24/normal-mapping-with-javascript-and-canvas-tag
> 1 votes

---
Tags: 2d, html5, normal-mapping, lighting
---


# Question
Title: Libgdx 2D Game, Random generated World of random size, how to get mouse coordinates?
I'm a noob and English is not my mothertongue, so please bear with me!

I'm generating a map for a Sidescroller out of a 2D-array. That is, the array holds different values and I create blocks based on that value.

Now, my problem is to match mouse coordinates on screen with the actual block the mouse is pointing at.

```
public class GameScreen implements Screen
{
    private static final int WIDTH = 100;
    private static final int HEIGHT = 70;

    private OrthographicCamera camera;
    private Rectangle glViewport;

    private Spritebatch spriteBatch;

    private Map map;
    private Block block;

```

...

```
@Override
public void show()
{
    camera = new OrthographicCamera(WIDTH, HEIGHT);
    camera.position.set(WIDTH/2, HEIGHT/2, 0);

    glViewport = new Rectangle(0, 0, WIDTH, HEIGHT);

    map = new Map(16384, 256);
    map.printTileMap(); // Debugging only

    spriteBatch = new SpriteBatch();
}

@Override
public void render(float delta)
{
    // Clear previous frame
    Gdx.gl.glClearColor(1, 1, 1, 1 );
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    GL30 gl = Gdx.graphics.getGL30();
//    gl.glViewport((int) glViewport.x, (int) glViewport.y, (int) glViewport.width, (int) glViewport.height);

    spriteBatch.setProjectionMatrix(camera.combined);
    camera.update();

    spriteBatch.begin();

    // Draw Map
    this.drawMap();

//    spriteBatch.flush();
    spriteBatch.end();
}

private void drawMap()
{
    for(int a = 0; a < map.getHeight(); a++)
    {
        // Bounds check (y)
        if(camera.position.y + camera.viewportHeight < a)// || camera.position.y - camera.viewportHeight > a)
            break;

        for(int b = 0; b < map.getWidth(); b++)
        {
            // Bounds check (x)
            if(camera.position.x + camera.viewportWidth < b)// || camera.position.x > b)
                break;

            // Dynamic rendering via BlockManager
            int id = map.getTileMap()[a][b];
            Block block = BlockManager.map.get(id);

            if(block != null) // Check if Air
            {
                block.setPosition(b, a);
                spriteBatch.draw(block.getTexture(), b, a, 1 ,1);
            }
        }
    }
}

```

As you can see, I don't use the viewport anywhere. Not sure if I need it somewhere down the road.

So, the map is 16384 blocks wide. One block is 16 pixels in size.

One of my naive approaches was this:

```
if(Gdx.input.isButtonPressed(Input.Buttons.LEFT))
{
    Vector3 mousePos = new Vector3();
    mousePos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
    camera.unproject(mousePos);

    System.out.println(Math.round(mousePos.x)); // *16); // Debugging
    // TODO: round
 //   map.getTileMap()[mousePos.x][mousePos.y] = 2; // Draw at mouse position

 }

```

I confused myself somewhere down the road I fear. What I want to do is, update the "block" (or rather the information in the Map/2D-Array) so that in the next render() there is another block. Basically drawing on the spriteBatch *g*

So if anyone could point me in the right direction this would be highly appreciated. Thanks!

# Answer
Anko and ashes999 were both right. (See their comments to my initial question)

All my problems built upon my misunderstanding of spriteBatch.draw()-API. As soon as I got the right block size in place and adapted the camera to this new stuff all my problems were gone.
> 0 votes

---
Tags: 2d, libgdx, camera, coordinates, mouse
---


title: Orthographic Projection Issue

text:
# Question
Title: Orthographic Projection Issue
I have a problem with my Ortho Matrix. The engine uses the perspective projection fine but for some reason the Ortho matrix is messed up. (See screenshots below).

Can anyone understand what is happening here?

At the min I am taking the Projection matrix * Transform (Translate, rotate, scale) and passing to the Vertex shader to multiply the Vertices by it.

VIDEO Shows the same scene, rotating on the Y axis. http://youtu.be/2feiZAIM9Y0

```
 void Matrix4f::InitOrthoProjTransform(float left, float right, float top, float bottom, float zNear, float zFar)
{
    m[0][0] = 2 / (right - left);
    m[0][1] = 0;
    m[0][2] = 0;
    m[0][3] = 0;

    m[1][0] = 0;
    m[1][1] = 2 / (top - bottom);
    m[1][2] = 0;
    m[1][3] = 0;

    m[2][0] = 0;
    m[2][1] = 0;
    m[2][2] = -1 / (zFar - zNear);
    m[2][3] = 0;

    m[3][0] = -(right + left) / (right - left);
    m[3][1] = -(top + bottom) / (top - bottom);
    m[3][2] = -zNear / (zFar - zNear);
    m[3][3] = 1;
}

```

This is what happens with Ortho Matrix:

This is the Perspective Matrix:

# Answer
> 1 votes
Unless you just made a large number of typos posting this code, your indexing is sloppy; some of the array elements aren't initialized, some are overwritten and at one point you index out of bounds of the array. That looks like your problem.

```
m[0][0] = 2 / (right - left);
    m[0][1] = 0;
    m[0][2] = 0;
    m[0][3] = 0;

    m[1][0] = 0;
    m[1][2] = 2 / (top - bottom); // should probably be m[1][1]
    m[1][2] = 0;                  // immediately overwrites m[1][2]
    m[1][3] = 0;

    m[2][0] = 0;
    m[2][3] = 0;                  // should probably be m[2][1]
    m[2][2] = -1 / (zFar - zNear);
    m[2][3] = 0;                  // again overwrites m[2][3]

    m[3][0] = -(right + left) / (right - left);
    m[3][4] = -(top + bottom) / (top - bottom); // m[3][4] is out of bounds of the array
    m[3][2] = -zNear / (zFar - zNear);
    m[3][3] = 1;

```

---
Tags: opengl, graphics
---


# Question
Title: Algorithm to make entities closely follow one another?
I have a group of entities that I want to follow a leader very closely. A good example would be how the player's soldiers move in Cannon Fodder.

Any suggestions for achieving movement like this?

# Answer
I guess you want some ant like behavior (at least as far as comic ants are concerned)?

http://www.youtube.com/watch?v=HccgCeVo-4c

If so, I'd try the following:

* Pick the entity closest to the target as the "head" and mark it so it won't look for another entity to follow.
* For each remaining entity, find the next closest entity that doesn't have a follower yet.
* Once found, set the current entity as the follower of the other entity (which becomes the target).
* This can be optimized using strategies similar to path finding algorithms (if you're not happy with the results).

As an alternative, you could try something similar to what real ants do:

* Rather than path finding, let the "head" entity setup a vector field.
* Each vector points in the direction it should be going.
* Combine that with a simplified flocking algorithm (stay away from others, but follow the path) and you might end up with an even more natural movement.
> 1 votes

# Answer
The behavior I've seen in the video you attached could be mimicked like so:

When the characters are spawned, the current leader's position (2d point) is saved and is currently the only element in an array (or Vector) representing the **movement path coordinates** or `path-array`.

All `flowers` have a `goal` member that points to that element as the position they need to reach (but they are currently unable to move). They also have another `desired-distance` member that signifies how close they will be (in the line) to the leader which obviously differs between all followers (possibly something like `n` units for the closed one, `2*n`, `3*n` and so forth for the ones behind her).

When the player clicks a new target, the new position is pushed into the end of the vector. The distance between the current position of the leader and the new point is calculated. This distance is the amount the leader will move to reach the new target area. Assuming all soldiers were spawned with the correct distances between them, it is also the distance that each soldier is allowed to move (this is the easy way to implement it using integaral \[not floats\] units of distance).

So we begin to move the leader to the new point and at the same time, move the others to the leader's spawning point (the first element on the path array). Once each character reaches the leaders spawning point (first element in the `path-array`), that character's goals member is adjusted to point to the next element in the `path-array`. Each character is allowed to move exactly as much as the leader or alternatively, until the computed sum of distances from it's current position to it's current goal and from there through all other coordinates until the leader's current goal is equal to their `desired-distance`.

You could and probably should add a tiny delay from the moment the leader receives an order from the player or computer AI and until the followers begin moving. That delay should be small but you may want to increase it like the `desired-distance` so `t`, `2*t`, `3*t` and so forth as it will give a natural motion (like cars in traffic).

If the leader is redirected whilst she is moving, then her current goal coordinate in the path should be replaced with her current position and the new goal should be pushed as her target. The distance from the previous goal should be deducted from the allotted units of movement allowed to the followers and the distance to the new goal should be added.

As a data-structure, you could / should use a queue. Coordinates that all characters reached could be removed from the queue.
> 0 votes

---
Tags: algorithm, path-finding
---


# Question
Title: How can I load .obj files in the Soya3D engine?
I recently found Soya3D, and I want to import .obj files, but it seems to only accept .data files. How can I import .obj files into Soya3D?

Importing a .obj file named "house" produces this error:

> Traceback (most recent call last):
> File "introduction.py", line 7, in
> model = soya.Model.get("house")
> File "/usr/lib/pymodules/python2.6/soya/**init**.py", line 259, in get
> return klass.\_alls.get(filename) or klass.\_alls.setdefault(filename, klass.load(filename))
> File "/usr/lib/pymodules/python2.6/soya/**init**.py", line 268, in load
> dirname = klass.\_get\_directory\_for\_loading\_and\_check\_export(filename)
> File "/usr/lib/pymodules/python2.6/soya/**init**.py", line 194, in \_get\_directory\_for\_loading\_and\_check\_export
> dirname = klass.\_get\_directory\_for\_loading(filename, ext)
> File "/usr/lib/pymodules/python2.6/soya/**init**.py", line 171, in \_get\_directory\_for\_loading
> raise ValueError("Cannot find a %s named %s!" % (klass, filename))
> ValueError: Cannot find a named house!
> * Soya3D * Quit...

# Answer
> 2 votes
According to the (yet-in) complete guide to Soya 3D, the only supported model formats are .blend files or its own custom format. I've found a couple places that said you can import .obj files by placing them in a certain directory, but I'm not sure if it's true, and at least it's not in the documentation.

So to use your files, I recommend importing them with Blender, saving as a .blend file, then importing that with Soya. Either that, or use a separate .obj parser. This file may work, or I'm sure you can write your own, since .obj files are pretty easy to parse.

---
Tags: soya3d
---


# Question
Title: PCF shadow shader math causing artifacts
For a while now I used PCSS for my shadow technique of choice until I discovered a type of percentage closer filtering. This method creates really smooth shadows and with hopes of improving performance, with only a fraction of texture samples, I tried to implement PCF into my shader. This is the relevant code:

```
float c0, c1, c2, c3;
float f = blurFactor;
float2 coord = ProjectedTexCoords;
if (receiverDistance - tex2D(lightSampler, coord + float2(0, 0)).x > 0.0007)
    c0 = 1;
if (receiverDistance - tex2D(lightSampler, coord + float2(f, 0)).x > 0.0007)
    c1 = 1;
if (receiverDistance - tex2D(lightSampler, coord + float2(0, f)).x > 0.0007)
    c2 = 1;
if (receiverDistance - tex2D(lightSampler, coord + float2(f, f)).x > 0.0007)
    c3 = 1;

coord = (coord % f) / f;
return 1 - (c0 * (1 - coord.x) * (1 - coord.y) + c1 * coord.x * (1 - coord.y) + c2 * (1 - coord.x) * coord.y + c3 * coord.x * coord.y);

```

This is a very basic implementation. blurFactor is initialized with 1 / LightTextureSize. So the if statements fetch the occlusion values for the four adjacent texels. I now want to weight each value based on the actual position of the texture coordinate. If it's near the bottom-right pixel, that occlusion value should be preferred. The weighting itself is done with a simple bilinear interpolation function, however this function takes a 2d vector in the range \[0..1\] so I have to convert my texture coordinate to get the distance from my first pixel to the second one in range \[0..1\]. For that I used the mod operator to get it into \[0..f\] range and then divided by f. This code makes sense to me, and for specific blurFactors it works, producing really smooth one pixel wide shadows, but not for all blurFactors. Initially blurFactor is (1 / LightTextureSize) to sample the 4 adjacent texels. I now want to increase the blurFactor by factor x to get a smooth interpolation across maybe 4 or so pixels. But that is when weird artifacts show up. Here is an image: Using a 1x on blurFactor produces a good result, 0.5 is as expected not so smooth. 2x however doesn't work at all. I found that only a factor of 1/2^n produces an good result, every other factor produces artifacts. I'm pretty sure the error lies here: coord = (coord % f) / f; Maybe the modulo is not calculated correctly? I have no idea how to fix that. Is it even possible for pixel that are further than 1 pixel away?

# Answer
Your code is only sampling the corner texels, so is only valid for a 2x2 filter. Sample all the texels within your filter shape to achieve correct results.
> 2 votes

---
Tags: mathematics, shaders, hlsl, shadows, shadow-mapping
---


# Question
Title: How do I calculate distance between a point and an axis-aligned rectangle?
I have a 2D rectangle with x, y position, height and width, and a randomly positioned point nearby.

Is there a way to check if this point might collide with the rectangle if it is closer than a certain distance? Imagine an invisible radius outside of that point colliding with said rectangle. I have problems with this simply because it is not a square!

# Answer
If `(x,y)` is the centre of the rectangle, the squared distance from a point `(px,py)` to the rectangle's border can be computed this way:

```
dx = max(abs(px - x) - width / 2, 0);
dy = max(abs(py - y) - height / 2, 0);
return dx * dx + dy * dy;

```

If that squared distance is zero, it means the point touches or is inside the rectangle.
> 32 votes

# Answer
I assume your rectangle is Axis-Aligned.

You just have to "clamp" the point into the rectangle and then compute the distance from the clamped point.

Point = (px, py), Rectangle = (rx, ry, rwidth, rheight) // (top left corner, dimensions)

```
function pointRectDist (px, py, rx, ry, rwidth, rheight)
{
    var cx = Math.max(Math.min(px, rx+rwidth ), rx);
    var cy = Math.max(Math.min(py, ry+rheight), ry);
    return Math.sqrt( (px-cx)*(px-cx) + (py-cy)*(py-cy) );
}

```
> 12 votes

# Answer
You must use circle-rectangle collisions for this. There's a similar question on Stack Overflow.

Your circle's center would be the point in question, and the radius would be the distance you want to check.
> 3 votes

# Answer
If you're trying to figure out the distance from a point to a rectangle's edge, working with each of the nine regions created by the rectangle might be the fastest way:

```
function pointRectangleDistance(x, y, x1, y1, x2, y2) {
    var dx, dy;
    if (x < x1) {
        dx = x1 - x;
        if (y < y1) {
            dy = y1 - y;
            return Math.sqrt(dx * dx + dy * dy);
        }
        else if (y > y2) {
            dy = y - y2;
            return Math.sqrt(dx * dx + dy * dy);
        }
        else {
            return dx;
        }
    }
    else if (x > x2) {
        dx = x - x2;
        if (y < y1) {
            dy = y1 - y;
            return Math.sqrt(dx * dx + dy * dy);
        }
        else if (y > y2) {
            dy = y - y2;
            return Math.sqrt(dx * dx + dy * dy);
        }
        else {
            return dx;
        }
    }
    else {
        if (y < y1) {
            return y1 - y;
        }
        else if (y > y2) {
            return y - y2;
        }
        else {
            return 0.0; // inside the rectangle or on the edge
        }
    }
}

```
> 3 votes

# Answer
\[Modified answer based on comments\]

If you want to see if the point is within say 10 units if the grey rectangle in the image below, you check if the point is in any one of

1. red rectangle
2. Blue rectangle
3. any one of the green circles (radius 10)

```
inside=false;

bluerect.x=oldrect.x-10;
bluerect.y=oldrect.y;
bluerect.width=oldrect.width;
bluerect.height=oldrect.height+20;

if(  point.x >=bluerect && point.x <=redrect.x+bluerect.width &&
     point.y >=bluerect && point.y <=redrect.y+bluerect.height){
         //now point is side the blue rectangle
         inside=true;
}

redrect.x=oldrect.x;
redrect.y=oldrect.y-10;
redrect.width=oldrect.width+20;
redrect.height=oldrect.height;

if(  point.x >=redrect&& point.x <=redrect.x+redrect.width &&
     point.y >=redrect&& point.y <=redrect.y+redrect.height){
         //now point is side the redrectangle
         inside=true;
}

d1= distance(point, new point(oldrect.x, oldrect.y)) //calculate distance between point and (oldrect.x, oldrect.y)
d2= distance(point, new point(oldrect.x+10, oldrect.y))
d3= distance(point, new point(oldrect.x, oldrect.y+10))
d4= distance(point, new point(oldrect.x+10, oldrect.y+10))
if (d1 < 10 || d2 <10 || d3 < 10 || d4 <10){
    inside=true;
}

//inside is now true if the point is within 10 units of rectangle

```

This approach is a little inelegant. A similar method which avoids having to test all 4 corners by using rectangle symmetry is documented here on stackoverflow
> 2 votes

# Answer
You could use something like this:
> -2 votes

---
Tags: collision-detection, geometry
---


# Question
Title: Texturing a mesh generated from voxel data
I have implemented the Marching Cubes algorithm to display an isosurface based on voxel data. Currently, it is displayed with triplanar texturing. I'm working with unity, so I have a material with the triplanar shader attached. Now, the whole isosurface is rendered using this material. And thats my problem: I want the texture to represent the voxel data. I'm storing a material value for every point in the grid, and based on this value, I want the texture of the isosurface to change. Sadly, I have no clue how to do this. So if the voxel is sand, I want sand to be displayed; if it's stone, then there should be stone. Right now, everything is displayed as sand. Thanks in advance!

# Answer
> 2 votes
You need to combine texture atlas techniques with your existing triplanar shader so that you can easily switch the "textures" being used based on the terrain type in the voxel.

One technique if you are using shared vertices between voxels might be to use vertex color or UV coords to encode all the terrain types associated with a particular vertex, then you have all the data needed to blend between different terrain textures for a smooth transition between voxels with different terrain types.

If you are not using shared vertices, you can still encode the voxel type in the color or uv data, but you cannot blend textures between voxels.

# Answer
> 0 votes
You could try triplanar mapping. A variation I use is I iterate through vertices and look at the normal of the vertex, find the direction the normal faces most(component of normal vector with the largest absolute value) and use the position components of the vertex vector orthogonal to that direction. and example would be a vertex \[1, 2, 3\] with a normal \[1, 0, 0\], the UV vector would then be the y-z components of the vertex, or \[2, 3\].

---
Tags: textures, marching-cubes
---


# Question
Title: Unity Problem with colliding instances of same object
I want to check if object's instance is overlapping with another instance (any spawned object with another spawned object, not necessary the same object). I'm doing this by detecting collisions between bodies. But I have a problem. Spawned object (instances) are detecting collision with everything but other spawned objects. I've checked collision layers etc. All of spawned objects have rigidbodies and mesh colliders. Also when I attach my script to another body and I touch that body with an instanced object it detects collision. So problem is visible only in collision between spawned objects. And one more information I have script, rigid body and collider attached to child of main object.

```
    using UnityEngine;
using System.Collections;

public class CantPlace : MonoBehaviour {

    public bool collided = false;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        //Debug.Log (collided);
    }

    void OnTriggerEnter(Collider collider) {
                //if (true) {
                        //foreach (Transform child in this.transform) {
                        //              if (child.name == "Cylinder") {

                                //collided = true;
                                Color c;
                                c = this.renderer.material.color;
                                c.g = 0f;
                                c.b = 1f;
                                c.r = 0f;
                                this.renderer.material.color = c;
                                Debug.Log (collider.name);
                        //}
            //  }
                //}

        //foreach (ContactPoint contact in collision.contacts) {
    //      Debug.DrawRay(contact.point, contact.normal, Color.red,15f);
    //  }

    }
}

```

# Answer
> 1 votes
Turning on convex mesh fixed the problem. I have done it by script, because after importing object from blender there is no check box allownig to do this.

---
Tags: c#, unity, collision-detection
---


title: XNA: Rotating Bones

text:
# Question
Title: XNA: Rotating Bones
XNA 4.0

I am trying to learn how to rotate bones on a very simple tank model I made in Cinema 4D.

It is rigged by 3 bones, Root -\> Main -\> Turret -\> Barrel

I have binded all of the objects to the bones so that all translations/rotations work as planned in C4D. I exported it as .fbx

I based my test project after: http://create.msdn.com/en-US/education/catalog/sample/simple\_animation

I can build successfully with no errors but all the rotations I try to do to my bones have no effect. I can transform my Root successfully using below but the bone transforms have no effect:

```
myModel.Root.Transform = world;

Matrix turretRotation = Matrix.CreateRotationY(MathHelper.ToRadians(37));
Matrix barrelRotation = Matrix.CreateRotationX(barrelRotationValue);

MainBone.Transform = MainTransform;
TurretBone.Transform = turretRotation * TurretTransform;
BarrelBone.Transform = barrelRotation * BarrelTransform;

```

I am wondering if my model is just not right or something important I am missing in the code.

Here is my Game1.cs

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace ModelTesting
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        float aspectRatio;

        Tank myModel;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            myModel = new Tank();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            myModel.Load(Content);
            aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            float time = (float)gameTime.TotalGameTime.TotalSeconds;

            // Move the pieces
            /*
            myModel.TurretRotation = (float)Math.Sin(time * 0.333f) * 1.25f;
            myModel.BarrelRotation = (float)Math.Sin(time * 0.25f) * 0.333f - 0.333f;
            */

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // Calculate the camera matrices.
            float time = (float)gameTime.TotalGameTime.TotalSeconds;

            Matrix rotation = Matrix.CreateRotationY(MathHelper.ToRadians(45));

            Matrix view = Matrix.CreateLookAt(new Vector3(2000, 500, 0),
                                              new Vector3(0, 150, 0),
                                              Vector3.Up);

            Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                                    graphics.GraphicsDevice.Viewport.AspectRatio,
                                                                    10,
                                                                    10000);

            // TODO: Add your drawing code here
            myModel.Draw(rotation, view, projection);

            base.Draw(gameTime);
        }

    }
}

```

And here is my tank class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace ModelTesting
{

    public class Tank
    {
        Model myModel;

        // Array holding all the bone transform matrices for the entire model.
        // We could just allocate this locally inside the Draw method, but it
        // is more efficient to reuse a single array, as this avoids creating
        // unnecessary garbage.
        public Matrix[] boneTransforms;

        // Shortcut references to the bones that we are going to animate.
        // We could just look these up inside the Draw method, but it is more
        // efficient to do the lookups while loading and cache the results.
        ModelBone MainBone;
        ModelBone TurretBone;
        ModelBone BarrelBone;

        // Store the original transform matrix for each animating bone.
        Matrix MainTransform;
        Matrix TurretTransform;
        Matrix BarrelTransform;

        // current animation positions
        float turretRotationValue;
        float barrelRotationValue;

        /// <summary>
        /// Gets or sets the turret rotation amount.
        /// </summary>
        public float TurretRotation
        {
            get { return turretRotationValue; }
            set { turretRotationValue = value; }
        }

        /// <summary>
        /// Gets or sets the barrel rotation amount.
        /// </summary>
        public float BarrelRotation
        {
            get { return barrelRotationValue; }
            set { barrelRotationValue = value; }
        }

        /// <summary>
        /// Load the model
        /// </summary>
        public void Load(ContentManager Content)
        {
            // TODO: use this.Content to load your game content here
            myModel = Content.Load<Model>("Models\\simple_tank02");

            MainBone = myModel.Bones["Main"];
            TurretBone = myModel.Bones["Turret"];
            BarrelBone = myModel.Bones["Barrel"];

            MainTransform = MainBone.Transform;
            TurretTransform = TurretBone.Transform;
            BarrelTransform = BarrelBone.Transform;

            // Allocate the transform matrix array.
            boneTransforms = new Matrix[myModel.Bones.Count];
        }

        public void Draw(Matrix world, Matrix view, Matrix projection)
        {
            myModel.Root.Transform = world;

            Matrix turretRotation = Matrix.CreateRotationY(MathHelper.ToRadians(37));
            Matrix barrelRotation = Matrix.CreateRotationX(barrelRotationValue);

            MainBone.Transform = MainTransform;
            TurretBone.Transform = turretRotation * TurretTransform;
            BarrelBone.Transform = barrelRotation * BarrelTransform;

            myModel.CopyAbsoluteBoneTransformsTo(boneTransforms);

            // Draw the model, a model can have multiple meshes, so loop
            foreach (ModelMesh mesh in myModel.Meshes)
            {
                // This is where the mesh orientation is set
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = boneTransforms[mesh.ParentBone.Index];
                    effect.View = view;
                    effect.Projection = projection;

                    effect.EnableDefaultLighting();
                }

                // Draw the mesh, will use the effects set above
                mesh.Draw();
            }
        }

    }
}

```

# Answer
> 5 votes
Keep in mind I had this problem over 2 years ago and I have since moved onto Unity 3D. This is more of a conclusion than a solution.

The main problem was that moving the bones did not move the mesh. I used Cinema 4D to model and rig the model and exported as `fbx`. There are many fbx export options in C4D and I tried many variants with no success. Here are two topics I made on C4D Cafe about XNA and C4D but they do not have a solution.

**I was only ever able to rotate a mesh in XNA.** I was able to mimic the bone binding effect by structuring the different meshes in a hierarchy so that they affect each other appropriately (pictured below). The hierarchical method works for this simple tank model but a more complicated model would require a skeletons in many situations.

The final effect I ended up with in XNA is pictured below. You can download my project here. The code is essentially the same as the original code in the question but simplified to only do turret rotation instead of barrel and turret.

# Download the XNA Project

# Answer
> 0 votes
Draw each mesh apart(body,barrel,transform), applying transform directly do effect.world

```
effect.world = turretRotation * TurretTransform;

```

or you can create a Matrix\[\], where you would store rotation Matrices, and then

```
effect.world = RotationMatrices[mesh.ParentBone.Index] * boneTransforms[mesh.ParentBone.Index]

```

# Answer
> 0 votes
You need to draw each mesh separately, and with the appropriate bone transformations: (The below pulled from Reimer's tutorials as it's simple and clean):

```
private void DrawModel()
 {
     Matrix worldMatrix = Matrix.CreateScale(0.0005f, 0.0005f, 0.0005f) *
           Matrix.CreateRotationY(MathHelper.Pi) *
           Matrix.CreateTranslation(new Vector3(19, 12, -5));

     Matrix[] xwingTransforms = new Matrix[xwingModel.Bones.Count];
     xwingModel.CopyAbsoluteBoneTransformsTo(xwingTransforms);
     foreach (ModelMesh mesh in xwingModel.Meshes)
     {
         foreach (Effect currentEffect in mesh.Effects)
         {
             currentEffect.CurrentTechnique = currentEffect.Techniques["Colored"];
             currentEffect.Parameters["xWorld"].SetValue(xwingTransforms[mesh.ParentBone.Index] * worldMatrix);
             currentEffect.Parameters["xView"].SetValue(viewMatrix);
             currentEffect.Parameters["xProjection"].SetValue(projectionMatrix);
         }
         mesh.Draw();
     }
 }

```

Note the retrieval of the bone transforms from the model, then the world matrix being passed in to the effect becoming:

```
xwingTransforms[mesh.ParentBone.Index] * worldMatrix

```

(I.e. the model's original world matrix multipied by the bone transformation matrix).

---
Tags: xna, 3d, xna-4.0, skeletal-animation, rigging
---


# Question
Title: What kind of steering behaviour or logic can I use to get mobiles to surround another?
I'm using path finding in my game to lead a mob to another player (to pursue them). This works to get them overtop of the player, but I want them to stop slightly before their destination (so picking the penultimate node works fine).

However, when multiple mobs are pursuing the mobile they sometimes "stack on top of each other". What's the best way to avoid this? I don't want to treat the mobs as opaque and blocked (because they're not, you can walk through them) but I want the mobs to have some sense of structure.

**Example:**

Imagine that each snake guided itself to me and should surround "Setsuna". Notice how both snakes have chosen to prong me? This is not a strict requirement; even being slightly offset is okay. But they should "surround" Setsuna.

# Answer
> 15 votes
Give your agents a weak "electrostatic charge" to make them repel each other, along the lines of Coulomb's law.

Assuming for simplicity that mobs should push each other away with equivalent strength, it should be enough to apply a force between every pair of mobs with a magnitude `some_constant / distance^2`, where `some_constant` is a configurable repulsion strength and `distance` is the distance separating them.

The repulsion strengths then fall off with the square of the distance.

*Nature of Code* has a great example (with a live demo) here. It looks like this:

Matching every element against every other is a quadratic-time (`O(n^2)`) operation. If you have *really many* agents, you may wish to optimise the force calculations with a Barnes-Hut approximation, which takes it down to log-linear (`O(n log n)`) but requires a quadtree.

# Answer
> 1 votes
My approach is similar to @Anko's, but based on the work by Millington and Funge from Artificial Intelligence for Games.

This is what a Separation behavior would look like, but you need to take into consideration that this velocity should be computed with the agent's speed in its Update function.

```
public Vector3 GetSeparationVel (float threshold, float decayCoefficient)
{
    threshold = threshold * threshold;
    Vector3 separationVelocity = Vector3.Zero;
    for (int i = 0; i < enemies.Length; i++) {
        if (enemies[i] == this) {
            continue;
        }
        Vector3 direction = this.position - enemies[i].position;
        float distance = direction.LengthSquared();
        float strenght = 0.0f;
        if (distance < (threshold)) {
            strenght = Math.Min(decayCoefficient / distance, this.maxAccel);
            direction.Normalize();
            separationVelocity += strenght * direction;
        }
    }
}

```

---
Tags: c#, path-finding, steering-behaviors
---


title: Unity3d and Windows 8 run game in frame

text:
# Question
Title: Unity3d and Windows 8 run game in frame
How do I set Unity3D to run my game on Windows 8 in a fixed size frame (with a border around it) and not in fullscreen?

I tried setting this in the Unity script and in the final C# project, but nothings seems to work.

I have set the players resolution to 1366x786 (the desired size) and while this works fine with the webplayer the windows 8 solution seems really unimpressed by it. I also tinkered with the 'Default Is Full Screen' option

# Answer
I run Windows 8.1. Just check `Windowed` under the `Graphics` tab in the configuration when the game starts up:

---

If you don't have the startup config dialog. Go to `Edit->Project Settings->Player` and set `Display Resolution Dialog` to `Enabled`:

---

If you do not want to have the config dialog you can set the `Screen.fullScreen` property to `false` in code.
> 1 votes

# Answer
You have checked the player settings, right?

http://docs.unity3d.com/Documentation/Manual/class-PlayerSettings.html
> 0 votes

---
Tags: unity, windows-8, screen-management
---