# Question
Title: Will this method of hashing player positions be effective in defeating FPS wall-hacks?
For example using a class like below to Hold the player positions and only show the players to each other when their Distance is less than something, So the calculations are also used by the client's PC.

```
public struct SafeFloat {
private float offset;
private float value;

public SafeFloat (float value = 0) {
    offset = Random.Range(-1000, +1000);
    this.value = value + offset;
}

public float GetValue ()
{
    return value - offset;
}

public void Dispose ()
{
    offset = 0;
    value = 0;
}

public override string ToString()
{
    return GetValue().ToString();
}

public static SafeFloat operator +(SafeFloat f1, SafeFloat f2) {
    return new SafeFloat(f1.GetValue() + f2.GetValue());
}
// ...the same for the other operators
}

```

# Answer
This will *not* be effective.

Obfuscating the position of players does not help, because at some point the client must *un-obfuscate* them (or be given the un-obfuscated positions) in order to perform game logic or rendering or whatever. At that moment, a hacker can intercept the positions and do whatever they want. It's just as easy for a hacker to read the player positions post-obfuscation as they do pre-obfuscation, so this technique doesn't even introduce a speed bump.

Hashing, in particular, is a poor choice of obfuscation for this because it's not reversible in general. Your specific hashing method of adding a random number to the position is going to be particularly useless, since the only way to reverse the hash correctly is to cart around the random offset that was added with the "secret" number, which is basically like giving everybody who cares the keys to the castle.
> 3 votes

# Answer
To see how (perhaps even how *easily*) your implementation(s) can be defeated, compile a simple implementation in a skeleton game, then offer it as a reversing challenge for multiplayer game hackers in communities like MPGH, UnknownCheats, ElitePVPers, OwnedCore, etc.

If I understand your code correctly, then what you've demonstrated here is a way to obfuscate values that will really only defeat basic game hackers who know how to do exact value scans in a program like Cheat Engine.

Either way, here are a handful of considerations for you off the top of my head (as a game hacker):

* If coordinate data stays in the same memory address on the client, it doesn't matter how much you obfuscate it. All a hacker has to do is scan for changed/unchanged values and they'll find their way to the right value. You could create duplicate dummy data to mix it up a bit, but that's easy to weed through.
* If the local player structure is the same as the structure coming in from other player data (health, coordinates, etc. all at the same offset) via the server, then a hacker can glean quite a bit of information by hacking what they can for their local player.
* How good is your network protocol? If that isn't shored up, then a hacker can study inbound/outbound packets and make correlations to discover which bytes are related to coordinates. From there, it's just a matter of finding the sub-routine(s) that handle that data. If it's obfuscated data, then it's simply a matter of tracing code execution to find sub-routines related to de-obfuscation.
* Advanced reversers don't need to rely on dynamic analysis to find their way to what they need initially. Between custom tools, scripts, etc., they can find their way to code segments of interest--all without having to worry about dealing with your obfuscated value whatsoever.

Suffice it to say, there are multiple ways for game hackers to achieve success--many times the ways of which have absolutely nothing to do with your expectations as a forward-engineer of how your implementation(s) will be targeted.
> 0 votes

---
Tags: first-person-shooter, anti-cheat
---


# Question
Title: Why when adding a box collider to character i can still walk through the character?
Like the box collider is not active or exist. I added a box collider on the left soldier.

I'm using firstpersoncontroller and firstpersoncharacter as player but i can move through the soldier and when the mouse cursor is over the soldier it's not detecting it as "Interactable" object.

The only object that is detecting is the door behind the soldiers. Any other objects are not detecting using the ray cast. So i added a box collider to the soldier for testing but it's not working.

Can't figure out why only the door is detecting.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraRaycast : MonoBehaviour
{
    Ray ray;
    RaycastHit hit;

    void Update()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit, 1000))
        {
            if (hit.transform.tag == "Interactable")
            {
                print("Hitted on: " + hit.transform.name);
            }
        }
    }
}

```

# Answer
You'll need to add a rigid body to your game object as well. The physics implementation needs both the computer and the rigid body in order for it to work correctly.

https://docs.unity3d.com/Manual/class-Rigidbody.html
> 1 votes

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


# Question
Title: Populate triangles array when you already have sorted vertices array
Input is a `Vector3[]` of verticies. Length is unknown, it could be anything above 2 - so these vertices form all kinds of multifaceted shapes with 3 being a triangle and 6 hexagon-ish.

Poor example to visualize:

```
vertices = [Vector3(..), Vector3(..), Vector3(..), Vector3(..), Vector3(..)];

```

Coordinates in that array are **ordered counterclockwise**. I also have the coordinates of center point that these verticies form (look at illustration below) - it doesn't have to be used but if it helps..

Few examples of which shapes can occur and which cannot:

---

Now I need to build meshes out of them. For each shape I need:

* Vertices array (which I already have, nicely ordered)
* Triangles array - 3 indices (from vertices array) per triangle until all vertices are covered

How to populate triangles array with these relatively easy shapes where each vertex has "direct line of sight" to every other vertices? Number of vertices is unknown of course.

# Answer
> 3 votes
Unity meshes are indexed triangle lists. so one way is to construct the equivalent of a triangle fan:

```
int[] triangles new int[vertices.Length * 3 - 6];
for(int i=0; i<vertices.Length - 2; i++) {
    triangles[i * 3] = 0;
    triangles[i * 3 + 1] = i + 1;
    triangles[i * 3 + 2] = i + 2;
}

```

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


# Question
Title: Loading Collada Files Quickly (three.js, OpenGL, Javascript)
Okay, so I've created these sleek-looking spaceship models for an OpenGL game that I'm going to make. To make them look sleek and smooth, I used a Subdivision Surface modifier in Blender. Hmm... 100000+ triangles.

I've managed to get the files down to the 30 to 40 thousands range (EDIT: under ten thousand, but with loss of quality) in terms of triangles though. So the file size is usually around a few megabytes.

Soon I found out that this wasn't really a problem when rendering the spaceships. However, I did quickly notice that it takes forever for Firefox to load one spaceship. And I want to load three of them, possibly more.

Chances are if I create a game that starts up with a "Please wait five years whilst everything loads" loading bar, it's going to turn away a lot of users. And I still haven't even considered loading planets, images, and a bunch of other stuff.

So now, for my questions:

* Has anybody else run into this before? Is there a generally accepted solution for this type of problem?
* Speaking of libraries, is there one that could apply the subdivision surface modifier on the models at run time? Then I could just export the model frames, which are only somewhere around 1000 triangles.

Also, any other input would be very much appreciated.

Thanks! :)

EDIT: What I've tried so far:

So far, compression looks like a no-go but I'm not sure.

* method 1: zip folders: zipping the files drastically reduces filesize, but it requires a gigantic zip.js library to actually use the zip folders. So far I've been unable to get it to work, I guess the zip.js API is just way over my head.
* method 2: custom compression: I've managed to make my own sort of compression system, but it's not nearly as effective and only cuts away half of the file size. Oh and it also looks like it is broken ATM xD

EDIT: just realized that the bottleneck might not be my internet speed, but rather the Collada file loading script that I'm using. (ColladaLoader.js, it's from three.js) in this case compression is definitely out of the picture.

# Answer
> 1 votes
1. real-time models should have as few polygons as possible. 100k for a model is on the high end. 10k is more reasonable.
2. COLLADA is an interchange format designed for interoperability. You should open it in a program like Blender and export it as a format better suited for your needs. You may have to experiment with formats, but first try using Three.js's native JSON format -- JSON parsing is fast in javascript since it's built-in functionality. I don't remember if the exporter is bundled with Blender but you can get it at https://github.com/mrdoob/three.js/tree/master/utils/exporters/blender
3. Your browser should have a developer tools pane with a performance profiler -- you can use this to figure out where the delay is coming from.

# Answer
> 0 votes
To generate normal maps you'll have to have a version of your model uv-mapped and with low polygon density. You'll have to use a 3d software like maya, mudbox or blender to output a texture file your high resolution mesh onto your low poly-model. You can also use xNormal which is free and dedicated to this task.

# Answer
> 0 votes
I'm not sure if this technique is still used in modern games (I think it is, but I'm a gameplay programmer, not an artist or graphics programmer, so I haven't really kept up with modern techniques for creating art assets).

But a common technique for a long time was to create a high-res model and a low-res model, and project from the high-res model to the low-res model to generate a normal-map.

I think the technique is something like, for each vertex on the high-res model, raycast to the low-res model to figure out where the equivalent position is, then write the normal into the equivalent part of the normal map. Not a million miles away from lightmapping, I guess.

The normal map mimics the increased detail on the high-res model, but with a much lower polycount. I first heard of this technique being used on Doom 3, for the character models, but it's definitely been used on more modern games.

My understanding is that modern content creation tools support this, so you wouldn't need to go to the trouble of writing a tool to do this manually

---
Tags: models, three.js, compression
---


# Question
Title: How to create a non-inflationary player progress system (RPG)?
As an ambitious RPG gamer, I've often came to the conclusion that something's off. You're fighting your way through a dungeon, loot some chests, fullfill some side quests to get the rewards and start to get stronger and stronger equipments and therefore stats to challenge even harder enemies. However, at some point you want to revisit one of the first places just to chill there .. and all the enemies are just .. meh. Of course, that's how it is, but in my opinion not how it *should* be.

Let me explain it this way: I want to create a game where getting +20 Strength is a bonus, a real progression, not the requirement to have the chance to even challenge stronger enemies. When both you and the enemy have +5 Health compared to the last fight, you didn't made any real progress since then. That's something that bothers me alot about games like Diablo that takes it to its extreme. As a player, I'd feel cheated.

Moreover, there's a term called **mudflation**. To explain that here's an example: Back when you start your journey, you fight a monster and get loot worth of 10 gold. 2 hours later, you made some progress and can now fight stronger monster that drop loot worth 50 gold. Let's say you have to spend 2 minutes to fight each of them, it's obvious which one's worse efficient-wise. The progress you made at the beginning starts to get smaller and smaller the further you progress through the game. "Oh, you saved 100 gold from the first hour? Sweet, now you get double that amount within 2 minutes slaying this high end monster." Meaning it's not only an issue of increasing numbers, but also of spend effort and time that gets worth less and less.

I want to create a game with visible progress, so just removing all stats and only relying on the player getting better game skills by playing the game isn't an option for me. However, I can't think of a system without said mudflation - even Dark Souls that relies heavily on the player's skill had to add some stats that you can't just ignore as a player, otherwise you won't be able to kill the end bosses within reasonable time.

Does anyone know a solution for that? I want the players to actually know they've made some progress (so just cosmetics as rewards isn't a solution either), but they shouldn't feel cheated.

# Answer
> 14 votes
> However, at some point you want to revisit one of the first places just to chill there .. and all the enemies are just .. meh. Of course, that's how it is, but in my opinion not how it should be

There's a few ways games address the issue of "early levels become trivial when you return to them"

One is to have a few world-altering events that globally make the game harder at certain points in the player's progression. For example, at some point in your game "an enemy nation (demonic army) has taken over the country" and the new enemies roaming around the same old areas are harder than they were when you went there earlier. (an example of this approach is Terraria)

Another solution (although I suspect you ruled this out based on the "real progress" line) is to have all encounters somewhat scaled to the player's level. For example, in Elder Scrolls games at low levels you just encounter crabs and wolves but at high level in the exact same areas you'd encounter bears and more magical creatures (or the Draugr are training)

> When both you and the enemy have +5 Health compared to the last fight, you didn't made any real progress since then

If your stats go up over time, then the game becomes mechanically easier. Given that player skill improves over time as well, this means the difficulty curve is too hard at the beginning of the game and too easy at the end of the game unless you scale the encounters .... unless ..

maybe at the beginning of the game you can't fight everyone and you're avoiding most of the hard enemies in the area. Perhaps the game is structured that at early levels a lot of the challenge is in remaining undetected or escaping from bigger guys. This, however, can feel "un-fun" because part of the appeal of games is Rule of Cool and being able to feel Badass.

Another option is that enemy density increases over time in low-level areas. Fighting one zombie was easy when you just got out of the Academy, but the infestation is getting worse and worse -- can a more experienced you fight off 5 at once? An obligatory story from the DnD side: Tucker's Kobolds

> Oh, you saved 100 gold from the first hour? Sweet, now you get double that amount within 2 minutes slaying this high end monster."

There's no core concept that says you even have to increase the values over time. I think the reason many games have an exponential curve is that that exponentially increasing numbers are, in themselves, enjoyable. That's why an entire genre of clicker games are popular despite having close to zero interactive gameplay.

Therefore, avoiding this trope is just an exercise in adjusting the scale curve from exponential to something linear or sublinear. One issue with this is you have is to avoid incentivizing farming. If the hard creature gives you 5 gold and the easy creature gives you 4 gold but you've gained +20 Strength in the meantime, you may just decide the best use of your time is to stay in the easy level and farm easy creatures for more gold per minute.

> I want to create a game with visible progress, so just removing all stats and only relying on the player getting better game skills by playing the game isn't an option for me.

A common theme (especially in games falling into the Metroidvania category) is to keep the numerical buffs small and add skills and items that unlock new areas. Simultaneously many skills (wall-jumping, double-jumps, dashes) require higher player mechanics and increase character power in ways other than just hitting harder.

It's also a question of good interaction design. Can your core combat loop simply be *enjoyable* in its own right? When I was playing Assassin's Creed 2 at some point the "guards assaulting a merchant" random quests got repetitive, for sure, but at some level I just still enjoyed parrying a sword thrust and stabbing a guy in the face with a wristblade. When the player is otherwise having fun, you have greater leeway in the difficulty window.

Finally, you use some other numerical indicator of progress. You can give people toplists and best speedrun times. In many roguelikes, "how deep can you go before dying" is enough of an indication of progress. Diablo 3 borrows this idea in its Rift Runs, where how many levels deep can you survive is a way people measure their character's power. You could use the same idea without Diablo's inflationary economy. Many games can track visible progress with non-power metrics like "number of Pokemon collected" "Pieces of the Triforce retrieved" "Areas of the empire liberated" etc.

# Answer
> 5 votes
> However, at some point you want to revisit one of the first places just to chill there .. and all the enemies are just .. meh. Of course, that's how it is, but in my opinion not how it should be.

You either can scale the numbers of said monsters higher so that they're a threat, or you can replace those monsters with other monsters. You don't much like the former, which really leaves the latter as the only viable choice.

One important question I have with this scenario is this: why is the player *there*? Why has the player decided to go back to an old area? Are they looking for something? Did your gameplay require them to go there? Do they *believe* that the gameplay required them to go there (that is, are they unsure where they need to go and are just trying everything)? Or are they just "chilling"?

Well, if the player is just "chilling", then I would say that the player isn't interested in challenge. After all, your gameplay is (presumably) pointing them in the direction of where the challenge actually is. So if they've deliberately decided that they don't want to go there, maybe they don't want challenge.

So maybe you shouldn't *force* challenge upon them.

If the player is investigating old areas because they think something new may be there, then the presence of new monsters might give the player the impression that there really is something new there. If the game designer went through the effort to put new monsters there, they *must* be guarding something.

So if you do that, I would say that you have the responsibility as a game designer to actually *put* something there. Making the player believe that something will be somewhere when it isn't is a pretty large degree of mis-communication. And game design is all about communication.

At the same time, the lack of new monsters would also be indicative of a lack of new content. So if you want to put something in an old area, one gameplay mechanism to indicate this is to add new monsters.

> The progress you made at the beginning starts to get smaller and smaller the further you progress through the game. "Oh, you saved 100 gold from the first hour? Sweet, now you get double that amount within 2 minutes slaying this high end monster." Meaning it's not only an issue of increasing numbers, but also of spend effort and time that gets worth less and less.

I think you're measuring "progress" incorrectly here.

When I play such an RPG, "progress" to me reflects what I have. Gold is not really a thing I have. It is useful only to the extent that it can be converted into something that's actually useful. So gold in and of itself is not progress; gold *buys* progress.

As such, I feel progress when I get a new weapon or some new armor. I feel progress when I'm doing more damage or taking less damage. How much money I spent to get that progress is irrelevant; what matters is ultimately how much progress you make over a certain period of time.

And therefore, absolute flux of gold (gold-per-unit-of-time) is not particularly important. What matters is its flux relative to the actual cost of items. That is, it is the *item* flux that matters: items per minute.

So long as the cost of items increases proportionately with the flux of gold, then the player's item flux will be constant. Indeed, most RPGs will have lower item-per-minute numbers at the end of the game than at the beginning, despite the fact that monsters may be dropping several orders of magnitude more money than they did before.

So ultimately, what you need to look to is not how much gold in absolute numbers you're giving the player, but the gold relative to the desired level-appropriate items.

If the use of larger numbers truly irritates you though, there are ways to avoid dealing with ever increasing sums of money while still having control over items-per-minute.

One suggestion is to remove money from drops entirely. Make money a reward for doing things in the game, completing quests or whatever, not for killing random things. So it doesn't matter how many things you kill; you don't make money by killing stuff, so you don't have to give more money just for killing bigger stuff. And since you're in strict control over how much money you give out for each quest, you can decide exactly how much to charge for items. And therefore, you can maintain control over item flux.

Another suggestion is to make it so that money drops based on the relative difficulty of the fight. If you're level 10 and the enemy is level 1, decrease the amount of money you get for killing them proportionately.

Of course, this poses a problem: the player may level up faster than they get enough money to get what they want, which could leave them in a sticky spot. They might have to grind out lower-level mobs for crap rewards just to be able to afford the stuff needed to progress.

But in all of these cases, you need to re-evaluate the prices and availability for items. You're giving the player consistent purchasing power throughout the game; you need to make sure that powerful items are either outside of the players' price or are simply unavailable.

# Answer
> 2 votes
Adding to Jimmy's excellent answer, games can not only progress in terms of statistics but also in terms of complexity. You see this a lot in character action games which give you metroidvania-like abilities to access new areas but at the same time such abilities are usually also new fighting moves that are incorporated into your arsenal and can combo with your other moves, thereby increasing the complexity of the fighting system to a noticeable degree.

Thus, one thing you can do is decouple stat bonuses from complexity as the main source of difficulty in your game. Keep the statistical differences small, but increase the complexity of enemies with player progress. This way, late game enemies may have more complex movesets or, depending on the type of game, require combinations of different attacks or spells to defeat but have similar (although not equal) values of HP or strength compared to early game enemies. This is especially useful if you want to create a more grounded, realistic world - after all real people tend to differ much more in skill than in physical ability. This would also mean that a large buff in any given stat can make a difference for your character against every enemy in the game and never creep out of relevancy while you don't absolutely need to fight any enemy.

---
Tags: game-design, game-mechanics, rpg
---


# Question
Title: Testing a website in Steam overlay webbrowser
How do I test my website in Steam overlay webbrowser without running a game?

# Answer
> 2 votes
This doesn't quite address "without running a game", but a useful "placeholder game" for this kind of thing is Spacewar, which is the Steamworks API tutorial.

To install/launch it, run "steam://run/480" from the Run dialog (Windows-R)

# Answer
> 1 votes
Disclaimer: I'm not Steam dev, so I can't speak to this with much authority. I also suspect that the NDAs of SteamWorks may prevent those who do know from providing definitive, on the record answers. If you yourself are already a Steam dev, I'd recommend contacting them to see if there's some manner of pre launch support that might fit your needs.

That being said, I was able to do a little bit of work to make some educated guesses. Here's a sample dump of `GameOverlayUI.exe.log` when running a game:

```
Thu Nov 09 21:29:33 2017 UTC - GameOverlay process started: pid: 9504
Thu Nov 09 21:29:33 2017 UTC - GameOverlay process connecting to: pid: 11112
Thu Nov 09 21:29:34 2017 UTC - BuildID: 1509425745
Thu Nov 09 21:29:34 2017 UTC - Steam Path: C:\Program Files (x86)\Steam
Thu Nov 09 21:29:39 2017 UTC - SetScreenSize( 1253, 635 )
Thu Nov 09 21:29:39 2017 UTC - Changing resolutions from (1280, 1024) -> (1253, 635)
Thu Nov 09 21:29:40 2017 UTC - Generating new string page texture 2739: 256x256, total string texture memory is 262.14 KB
Thu Nov 09 21:29:40 2017 UTC - Generating new string page texture 2740: 128x256, total string texture memory is 393.22 KB
Thu Nov 09 21:29:41 2017 UTC - Overlay enable requested by game

```

Here's what happens if I attempt to manually launch the overlay:

```
Thu Nov 09 21:34:21 2017 UTC - GameOverlay process started: pid: 9128
Thu Nov 09 21:34:21 2017 UTC - GameOverlay exiting due to missing PID argument

```

I get the latter even when running a non-Steam game that I've added to my library. So it looks like GameOverlayUI won't launch if it can't handshake with an actual Steam app. Barring an official solution, I suspect the best you might be able to do is build a mock app of some kind that completes the handshake & go from there. Alternatively, there might be some command line switch that allows the overlay to function without the handshake - if such a thing exists, again you probably need to sign the NDA to know about it. Maybe you could fuzz it out, but that likely breaks their TOS.

# Answer
> 0 votes
The steam client uses a version of Chromium to display the websites. There shouldn't be too many differences between that and Chrome.

---
Tags: steam, browser
---


# Question
Title: How do I write a wave-spawning system for a shoot-em-up?
I recently played Knightmare Tower and was amazed by the way how different monsters are beign spawned.

I'm aware of time-based and count-based spawing systems in shoot-em-ups. Count-based systems allow a certain number of enemies on screen and spawn more as they die. Time-based ones spawn more at given intervals.

How are these spawning mechanism built? Is there some pattern or theory to it?

---

Additionally, such games typically have increasingly resilient enemies of increasing numbers of types. How are these balanced?

I'm looking for a general answer, independent of any particular game or technology.

# Answer
> 5 votes
From playing Knightmare Tower from beginning to end, it seemed like the enemies were mostly predefined as opposed to being procedurally generated. There was some randomization, but from what I can remember it was very minor variance.

But to achieve something similar, I would do something along the lines of:

* Have several collections of enemies to pull from, for each "floor", and replace the collection every time the player reaches a new floor.
* Then have weights associated with the enemies based on difficulty to control how often they show up, and possibly have a maximum for each type of unit, so there is no way to get, say five of the wizard type mobs, that would be quite difficult for the floor to deal with.
* Then to place them, you can just check and see where other enemies are, and place them decently far from the others.
* As for timing, I would say pick a base enemy density, which increases as the player reaches new floors.

Spawning systems are so specific to a game, I'm not sure how applicable any general theorycrafting would be. I would just recommend hammering out a basic system for spawning, start playing the game, and refining it from there. For example, you could implement moving weights for enemy chance, say every time it spawns the weight goes down by 5%, to make it self correcting for some of the randomness, etc.

# Answer
> 6 votes
You want to slowly improve the strength, speed, and AI of these types of units. I'll provide a list of what exactly I would do in your situation:

* You can add where they do new moves once they hit a specific level. For example, they may shoot fireballs at level 10.
* Increase their reaction speed to your attacks. For example, they may have AI to predict when you attack, make the gap smaller.
* Increase the amount of monsters that can spawn at once.
* Increase their health.
* Increase their damage.

# Answer
> 0 votes
Since you have asked multiple questions at once I will try to shed some light on the whole topic.

## Composing waves of different enemy types

Similar to David M's answer I would suggest assigning an *cost* to each enemy type reflecting it's strength or difficulty. Then for each wave you have an *budget* which you can spend on different enemies which make up the current wave. By increasing the *budget* each level you can increase the difficulty of this level.

The strategy for distributing enemy types is up to you. You can spread them out evenly so each wave is essentially the same just with more and stronger enemies. I would instead suggest to have different wave distributions to make the waves more distinct. Each level you choose one distribution type at random which will prefer e.g. mostly ranged enemies, mostly mages and some melees to protect them or an balanced distribution among all types. This way you can give each wave an distinct character and force the player to come up with different tactics for each wave type.

This way you avoid having the same enemies in every wave which will result in the same tactic and same gameplay every time, just with more enemies.

If you have wave types with only strong enemies you should only enable them if you have reached a high enough *budget* so you wont have a wave with only one very strong enemy early on in the game.

## Balancing difficulty

You can adjust or increase the difficulty for each level/wave with several methods:

1. Increase number of enemies or choose stronger enemy types (increase *budget*)
2. Make enemies smarter or give them new attacks
3. Increase per enemy strength (e.g. more health, more damage)

In my personal opinion increasing the number of enemies and switching to more stronger enemy types should be your main method to increase the difficulty of a wave. Boosting their AI or giving them new attacks, skills or abilities is very good but often difficult to archive. Increasing the per enemy strength often feels weird and results in 'bullet sponges' (enemies with seemingly endless health) or enemies which can one-hit you, both behaviors which, in my opinion, are signs of bad game design.

## Adjusting difficulty

This heavily depends on what type of game you want to create.

* If you want to have some sort of highscore or generally want to make the game competitive in some way you need a **fixed difficulty**. You just increase the difficulty (e.g. by increasing the *budget*) each level/wave by some amount and wait for the player to die after level X because he isn't able too keep up with the increasing difficulty anymore. This allows the player to feel good after beating wave X because it's an archivement requiring some level of skill. The downside it that this can result in a player failing too often and feel weak, eventually give up after dying too often.
* If you want the player to feel strong but always give them a challenge without overtaxing his abilities you may want to go for a **dynamic difficulty**. You slowly increase the difficulty and measure the players performance each level. If he performs well you increase the difficulty, if he fails or struggles you step down a bit and give him easier enemies. This will result in an more 'fun' gameplay but now you cant really assign some sort of highscore anymore because he only beat his own personal difficulty which is not comparable to want some other player has archived.

On this last topic of adjusting the difficulty I can recommend these sources:

1. Vales AI-Director from Left for Dead (starting at page 51) http://www.valvesoftware.com/publications/2009/ai\_systems\_of\_l4d\_mike\_booth.pdf
2. This YouTube video on dynamic difficulty in general https://www.youtube.com/watch?v=zFv6KAdQ5SE

---
Tags: architecture, game-mechanics, shoot-em-up, spawning
---


# Question
Title: Procedurally splitting and merging paths
I'm making a text-based adventure which sends the player along different paths depending on their choices. Each scene is like a node in a directed graph. Each node has a time step which is equal to the number of nodes prior + 1. There is a maximum of Tn nodes per time step, say 5, and so you can visualise this in this way:

I want to generate paths like these.

Where a node points to more than one other, that could be called a fork and where two point to one, that could be called a merge.

At any particular timestep there will tend to be Tn / 2 paths, only rarely going down to one or up to Tn.

Does anyone have ideas or know of any similar work?

(One small issue - paths never cross - that is, those on the left stay on the left until merging to the right. And there's no wrapping from far left to far right. Because of this, it seems like nodes on the far left or far right of a timestep will have a smaller probability of merging. Is this avoidable?)

# Answer
> 2 votes
Base requirements:

* Input n, totalTime
* Max n nodes at time T
* Minimum 1 node at time T
* Average n/2 nodes at time T
* T is an int in the range of \[0, totalTime)

There are three different options for each node at each time step

* Continue
* Split
* Merge

For each time T, every node should have a chance to do one of the options, with different weights depending on how full the tree structure is

* Having 1 node should reduce merge chance to 0
* Having n nodes should reduce split chance to 0
* To keep it around n/2 nodes, a somewhat normal distribution should be used

---

It may be useful to put all related scene data together

```
class Scene
{
    Scene[] nextScenes; //a list of the next scenes in the graph
    //your other data here, setting/plot/things
}

```

Creation steps:

1. Initialize root of tree to build from
2. Iterate until the tree is depth totalTime
    * Each node picks if it wants to attempt to grow or shrink the tree
    * The next layer is built based on the last layers actions to grow/shrink
3. Return the built tree

This will be the only method that needs to be called by the game to request/build a tree

```
Scene generateTree(int n, int totalTime)
{
    //initialize the root
    Scene root = new Scene();

    //iterate until tree is deep enough
    Scene[] lastLayer = {root}; //helper data structure
    for(int i = 1; i < totalTime; i++)
    {
        int[] actions = new int[lastLayer.length];
        int nextSize = getActions(actions, n);
        lastLayer = addLayer(lastLayer, actions, nextSize);
    }

    //return the tree
    return root;
}

```

Node grow/shrink choice logic:

1. Each node picks a desired layer size
2. Grow if the next layer is estimated to be too small
3. Shrink if the next layer is too big
4. Otherwise maintain size

This can be put into a function that takes the current estimate for the next layer's size, and the max nodes possible

```
Random rand = new Random();
int getAction(int nextSize, int n) //action of a single node, < 0 shrink, > 0 grow
{
    return rand.nextInt(n) + 1 - nextSize; //[0, n) + 1 - (0, n]
    //can get a bit fancier if you want more nodes to continue instead of grow/shrink
    //int range = 1; //total bonus chances at choosing continue (could use n * 0.1)
    //int r = rand.nextInt(n + range) + 1;
    //return (r < nextSize ? -1 : (r > nextSize + range ? 1 : 0));
}

```

Choosing actions of the nodes:

* If the selected node already is marked as merging left/right, it can't shrink further, but can grow with a split
* To shrink, a node must have an adjacent node to merge into (node must be continue or split)
    + When merging, the node being merged into should be marked as well
* Nodes default to continue

The code for choosing merging actions gets a bit lengthy from all of the different conditions

```
private static final int CONTINUE = 0;
private static final int SPLIT = 1;
private static final int MERGEL = 2;
private static final int MERGER = 3;
int getActions(int[] actions, int n)
{
    int nextSize = actions.length; //estimated next layer size
    boolean[] processed = new boolean[actions.length];

    for(int i = actions.length; i > 0; i--) //loop through each node of the last layer
    {
        int selection = rand.nextInt(i); //randomly choose from [0, i) to process, first loop iteration can select any index, last iteration can only select the 1 remaining unprocessed node
        for(int j = 0; j < actions.length; j++) //figure out the actual index selected (skip processed nodes)
            if(!processed[j] && selection-- == 0)
            {
                selection = j; //set selection to the actual index
                processed[j] = true; //mark selection as being processed
                break;
            }

        //process the selected node
        int choice = getAction(nextSize, n); //goal size for this node to work toward (will average to n/2)
        boolean grow = choice > 0;
        boolean shrink = choice < 0;
        if(selection == 0) //on the left edge
            if(actions[selection] == CONTINUE) //doesn't have an action
            {
                if(grow)
                {
                    actions[selection] = SPLIT;
                    nextSize++;
                }
                else
                    if(shrink && actions[selection + 1] != MERGER)
                    {
                        actions[selection] = MERGER;
                        if(actions[selection + 1] == CONTINUE) //mark it as merging a direction
                            actions[selection + 1] = MERGEL;
                        nextSize--;
                    }
            }
            else //has an action already (MERGER)
                if(grow)
                {
                    actions[selection] = SPLIT;
                    nextSize--;
                }
        else
            if(selection == lastLayerCount - 1) //on the right edge
            {
                if(actions[selection] == CONTINUE) //doesn't have an action
                {
                    if(grow)
                    {
                        actions[selection] = SPLIT;
                        nextSize++;
                    }
                    else
                        if(shrink && actions[selection - 1] != MERGEL)
                        {
                            actions[selection] = MERGEL;
                            if(actions[selection - 1] == CONTINUE) //mark it as merging a direction
                                actions[selection - 1] = MERGER;
                            nextSize--;
                        }
                }
                else //has an action already (MERGEL)
                    if(grow)
                    {
                        actions[selection] = SPLIT;
                        nextSize++;
                    }
            }
            else //in the middle, has two neighbors
            {
                if(actions[selection] == CONTINUE) //doesn't have an action
                {
                    if(grow)
                    {
                        actions[selection] = SPLIT;
                        nextSize++;
                    }
                    else
                        if(shrink)
                            if(actions[selection - 1] != MERGEL)
                                if(actions[selection + 1] != MERGER) //can go left or right
                                {
                                    if(rand.nextBoolean()) //merge left
                                    {
                                        actions[selection] = MERGEL;
                                        if(actions[selection - 1] == CONTINUE)
                                            actions[selection - 1] = MERGER;
                                    }
                                    else //merge right
                                    {
                                        actions[selection] = MERGER;
                                        if(actions[selection + 1] == CONTINUE)
                                            actions[selection + 1] = MERGEL;
                                    }
                                    nextSize--;
                                }
                                else //can only go left
                                {
                                    actions[selection] = MERGEL;
                                    if(actions[selection - 1] == CONTINUE)
                                        actions[selection - 1] = MERGER;
                                    nextSize--;
                                }
                            else
                                if(action[selection + 1] != MERGER) //can only go right
                                {
                                    actions[selection] = MERGER;
                                    if(actions[selection + 1] == CONTINUE)
                                        actions[selection + 1] = MERGEL;
                                    nextSize--;
                                }
                }
            }
    }

    return nextSize;
}

```

Merging the actions of the nodes:

* Variables `i` and `index` show the position in `lastLayer` and `nextLayer` respectively
* `CONTINUE` connects `lastLayer[i]` to `nextLayer[index]`, incrementing `i` and `index`
* `SPLIT` connects `lastLayer[i]` to `nextLayer[index]` and `nextLayer[index+1]`, incrementing `i` by 1 and `index` by 2
* `MERGEL` connects `lastLayer[i]` to `nextLayer[index-1]`, only incrementing `i`
* `MERGER` connects `lastLayer[i]` to `nextLayer[index]`, only incrementing `i`
    + If `MERGEL` comes right after, it processes that action too
        - `lastLayer[i+1]` is connected to `nextLayer[index]`, incrementing `i` and `index`

The last step is putting the actions together and adding a layer

```
Scene[] addLayer(Scene[] lastLayer, int[] actions, int nextSize)
{
    Scene[] nextLayer = new Scene[nextSize];
    int index = 0;
    for(int i = 0; i < lastLayer.length; i++)
        switch(actions[i])
        {
            case CONTINUE:
                lastLayer[i].nextScenes = {nextLayer[index++]};
                break;
            case SPLIT:
                lastLayer[i].nextScenes = {nextLayer[index++], nextLayer[index++]};
                break;
            case MERGER:
                lastLayer[i].nextScenes = {nextLayer[index]};
                if(actions[i + 1] == MERGEL) //handle the next too
                    lastLayer[++i].nextScenes = {nextLayer[index++]};
                break;
            case MERGEL:
                actions[i] = {nextLayer[index - 1]};
                break;
        }

    return nextLayer;
}

```

# Answer
> 1 votes
Here is my code dump after a few days of work using a functional language, F#. I'm hesitant to mark it as an answer because that would be a snub to the time that @phflack also spent doing it in an imperative way which more people will understand. Also his pseudo code was closer to the actual requirements I described.

This problem is unexpectedly difficult to code given even simple specifications. I wanted to allow forks and merges in the same timestep, like this:

I tackled this by first performing the fork operation, then storing the results in a sequence of "partial links". Here there are three marked in grey (this diagram is equivalent to the above):

The merge is then performed by considering random pairs of partial links.

Fork probability and merge probability are constants, respectively 1/4 and 1/3. The higher merge probability acts as a soft limit on the number of nodes per timestep and acts as a replacement for the hard limit of N nodes per timestep.

Here is an example of part of a graph generated by this code:

Using this approach, sometimes the number of paths reaches 20, and other times it stays on 1 for a long time - so it's not perfect. This will be tweakable to an extent by changing the fork and merge probabilities.

```
open System

type Scene (text : string, links : int array) =
    member this.Text = text
    member this.Links = links

type StoryGenState = { timestepNum: uint32; currentTimestepWidth: uint32 }
type FullLink = { fromIndex: int; toIndex: int }

let forkProbability = 1.0 / 4.0
let mergeProbability = 1.0 / 3.0

let random = new Random()

let GetForkDecision() =
    if random.NextDouble() < forkProbability
    then true
    else false
let GetForkDecisions n =
    seq { for i in 1u .. n do yield GetForkDecision() } |> Seq.toArray
let GetPartialLinks (toFork : bool array) =
    seq {
            for i in 0 .. toFork.Length - 1 do
                if toFork.[i] then
                    yield i
                yield i
        }
    |> Seq.toArray
let GetMergablePairs (toFork : bool array) =
    seq {
            for i in 0 .. toFork.Length - 1 do
                if toFork.[i] then
                    yield false
                if i < toFork.Length - 1 then
                    yield true
        }
    |> Seq.toArray
let GetMergeDecision() =
    if random.NextDouble() < mergeProbability then true else false

let rec PerformMergeStep (toMerge : bool array) (isMergable : bool array) numberOfMergesToDo =
    if numberOfMergesToDo = 0 || (isMergable |> Array.contains(true) |> not)
    then
        toMerge
    else
        let mergableIndices = seq {for i in 0 .. isMergable.Length - 1 do if isMergable.[i] then yield i} |> Seq.toArray
        let indexOfIndexToMerge = random.Next(0, mergableIndices.Length)
        let indexToMerge = mergableIndices.[indexOfIndexToMerge]
        let nextToMerge = toMerge |> Array.copy
        do Array.set nextToMerge indexToMerge true
        let toFlagFirstIndex = max (indexToMerge - 1) 0
        let toFlagLastIndex = min (indexToMerge + 1) (isMergable.Length - 1)
        let toFlagCount = toFlagLastIndex - toFlagFirstIndex + 1
        let nextIsMergable = isMergable |> Array.copy
        do Array.fill nextIsMergable toFlagFirstIndex toFlagCount false
        PerformMergeStep nextToMerge nextIsMergable (numberOfMergesToDo - 1)

let GetMergeDecisions (isMergable : bool array) =
    let numberOfMergesToDo = isMergable |> Array.map(fun b -> if b then GetMergeDecision() else false) |> Array.where (fun b -> b) |> Array.length
    PerformMergeStep (Array.create isMergable.Length false) isMergable numberOfMergesToDo

let rec BuildFullLinksStep (fullLinks : FullLink list) (partialLinks : int array) (toMerge : bool array) (partialLinkIndex : int) (currentToIndex : int) =

    let nextFullLinks = fullLinks @ [{ fromIndex = partialLinks.[partialLinkIndex]; toIndex = currentToIndex }]

    if (partialLinkIndex = partialLinks.Length - 1)
    then
        nextFullLinks
    else
        let nextToIndex = currentToIndex + (if toMerge.[partialLinkIndex] = true then 0 else 1)
        BuildFullLinksStep nextFullLinks partialLinks toMerge (partialLinkIndex + 1) nextToIndex
let BuildFullLinks (partialLinks : int array) (toMerge : bool array) =
    BuildFullLinksStep [] partialLinks toMerge 0 0
let CreateScenes (fullLinks : FullLink list) =
    seq {
            for i in 0 .. fullLinks.Length - 1 do
                Console.WriteLine("FullLink: {0},{1}", fullLinks.[i].fromIndex, fullLinks.[i].toIndex)
                if i = fullLinks.Length - 1 || fullLinks.[i + 1].fromIndex <> fullLinks.[i].fromIndex
                then
                    let tempList =
                        if i = 0 || fullLinks.[i - 1].fromIndex <> fullLinks.[i].fromIndex
                        then
                            [fullLinks.[i].toIndex]
                        else
                            [fullLinks.[i - 1].toIndex] @ [fullLinks.[i].toIndex]

                    let (links : int array) = tempList |> List.toArray

                    yield Scene("", links)
        }
    |> Seq.toArray
let GetNumUniqueOutputScenes (links : FullLink list) =
    links |> List.map(fun l -> l.toIndex) |> List.distinct |> List.length

let StoryGen(maxTimesteps : uint32) =
    Seq.unfold
        (
            fun (state : StoryGenState) ->
                Console.WriteLine("current step of unfold has timestep {0} and width {1}", state.timestepNum, state.currentTimestepWidth)
                Console.ReadLine() |> ignore
                if (state.timestepNum >= maxTimesteps) then
                    None
                else
                    let toFork = GetForkDecisions state.currentTimestepWidth
                    let toMerge = toFork |> GetMergablePairs |> GetMergeDecisions
                    let fullLinks : (FullLink list) = BuildFullLinks (toFork |> GetPartialLinks) toMerge
                    let scenes : (Scene array) = CreateScenes fullLinks

                    Some(scenes, { timestepNum = state.timestepNum + 1u; currentTimestepWidth = (GetNumUniqueOutputScenes fullLinks) |> uint32 })
        ) {timestepNum = 0u; currentTimestepWidth = 1u}
    |> Seq.toArray

[<EntryPoint>]
let main argv =
    let story = StoryGen(240u)
    Console.ReadLine() |> ignore
    0

```

---
Tags: game-design, procedural-generation
---


# Question
Title: Using collision.contacts to determine if on a floor
I'm trying to make my own first-person character (because I get lost in the sea that is Unity's FP character script), and am trying to make it so it detects when it is standing on a floor. I tried using a playerController, but I've found rigidbody is just more malleable.

Anyways, so I think how you'd do it is finding the direction of the contact, and if it isn't straight down, then to keep onGround as false. I'm just not entirely sure the scripting behind this, and several searches have turned up nothing.

Several offered using mutliple colliders, but I would prefer to keep the number of objects, colliders or otherwise, at a minimum, considering there will be a large number of them in the scene as is. I also want something that's easily manipulable so that I can add extra features like climbing up a wall or the like, and I think that measuring the angle to the center is about as simple and easily manipulated as it gets.

# Answer
> 1 votes
I'm assuming you're referring to the player being detected as touching the ground, and not every object? Regardless; simply place a collider on your floor.

Then add the following script to your floor.

**C#**

```
OnCollisionEnter(Collision col){
    if(col.gameObject.tag == "Player") {
        col.getComponent<myCharacterScript>().isOnFloor = true;
    }
}

OnCollisionExit(Collision col){
    if(col.gameObject.tag == "Player"){
        col.getComponent<myCharacterScript>().isOnFloor = false;
    }
}

```

(You can equally use OnCollisionStay to have only one of these, however, it means the script has to check every fraction of a second as opposed to only when the event is called, so it ends up being less efficient.)

Also, the script I am referring to as "myCharacterScript" is simply whatever script you have on your player which is meant to hold whether he/she is touching the floor or not. That script (regardless of whatever else it holds) must have a boolean value "isOnFloor".

Then you can do whatever you want with detecting it. E.g.

```
if (isOnFloor == true) {
    //Can Jump
}
else {
    //Can't Jump
}

```

# Answer
> 1 votes
Let's assume your player is using an upright capsule as a collider, or otherwise has a sphere shape at the bottom of their collision representation (this can help avoid little snags from small ridges in the level geometry, and has a more intuitive behaviour when going up ramps, rather than cantilevering off them as a box collider would.

Let `radius` be the radius of this spherical/capsule end, and assume it's centered on the player's vertical axis (collider's local `x` & `z = 0`)

```
// Maximum angle in degrees that should still count as a floor/"underfoot".
public float maxIncline = 45.0f;

bool IsContactUnderneath(ContactPoint contact) {
   // Ignore collisions with ceilings/walls
   if(contact.normal.y <= 0f)
     return;

   // Take the contact point into our local space.
   Vector3 local = transform.InverseTransformPoint(contact.point);

   // Flatten & ignore the vertical component.
   // We'll just look at the footprint.
   local.y = 0.0f;

   // Cache this to a variable somewhere
   // to avoid repeating the trig for every check.
   float threshold = radius * Mathf.Sin(maxIncline * Mathf.Deg2Rad);
   threshold *= threshold;

   return local.sqrMagnitude <= threshold;
}

```

This uses the fact that the steeper a flat surface is, the further out on the collider it will make contact - from directly in the center for a perfectly horizontal surface, to all the way out at the perimeter for surfaces approaching vertical.

If you only have the one collider, you can instead check that `contact.normal.y >= Math.Cos(maxIncline * Mathf.Deg2Rad)`. Here I'm doing a position-based check just in case you might hit an object with multiple colliders - like a gun barrel or an object you're carrying - so even if the normal is upright it's not mis-detected as a floor you're standing on.

---
Tags: unity, collision-detection, physics, rigidbody
---


# Question
Title: Rendering into every material preview windown. How is this possible?
So starting up unity today has presented me with a extremly wierd bug. The animated material that is rendered by the NVidia HairWorks Integrationg seems to be rendering into every material preview window. I have not done anything special to "achieve" this. Restarting Unity does not help( I tried all the usual stuff). The fur even simulates inside the material preview window if I hit the little play button. Any ideas ?

# Answer
Updating to Unity 2017.2.0p1 seems to have resolved the issue.
> 1 votes

---
Tags: unity, materials
---


title: Unity A* Pathfinding Move backwards

text:
# Question
Title: Unity A* Pathfinding Move backwards
I am using the A\* Pathfinding project to move my character. More specifically i am using the `RichAI` component.

If you take a look at the below picture:

What you can see here is the NPC and a pivot point that shows that my character has to move to this location.

The way the character does so is by turning 180 degrees and then move towards the point.

However, this isn't really desirable for me as the NPC should be facing my player and then walk backward.

My question is how dI i tell A\* not to turn around but instead walk backward?

# Answer
> 1 votes
A\* is an algorithm for finding a path.

The problem you pose does not appear to be about finding paths: it's about controlling the details about how an object traverses a path.

I do not know the libraries you're using, but I imagine you're looking in the wrong place for a solution; you want to look at whatever controls how objects actually travel along a chosen path.

---
Tags: unity, path-finding
---


# Question
Title: What would encourage a player to play the both the combat and building aspects of my game?
I have been planning all of the features for my game idea. It is an RPG fantasy free roam game, in which the main focus of the game is on combat and adventure, though I also want to add in the ability to be a carpenter, shop keeper, brick mason, and/or cook.

Though this is all well thought out, another thought has cane to mind: *Why* would anyone actually follow through with the average life-style or even begin to think of living a normal life? I thought of how an experienced adventurer might "retire" and go into business for themselves, but what could be some other things that might make a player go for the worker's lifestyle?

# Answer
> 2 votes
**Why not both?**

Not all adventurers have to be nomads. Going out for adventures and coming home again is a good cycle of excitement and newness with comfort and familiarity. Of course this is difficult if the economics of the craft are such that you have to do it full time or not at all, but that's something you as the designer can decide. Furthermore, adventuring can feed into homesteading and vice versa. You can go out on an adventure to collect rare materials (ores, animal pieces, plants, dyes etc.) to make cool things out of in your home workshop (or to sell) and you can make equipment for yourself with some crafting skills or earn money to buy it with others.

**Completionism**

Some people just like to have done everything a game offers and don't want to miss anything. If there's a house to be built, they'll put on all add-ons there can be, if there's a brick-laying skill they'll max it. This is one of the situations where the job of the designer is to either make it fun/engaging or not include it at all, because some of us will grind it out no matter how much we hate it and curse you all the way.

**It's fun!**

Games based on a peaceful activity can be fun in and of themselves. There are games about shop keeping in fantasy worlds like Recettear, Holy Potatoes A Weapon Shop! or... Shop Heroes it may have been called? There are also several cooking games. Now, obviously you don't want to spend the development time to make a whole game for each and every job you offer, but minigames that are simple can still be engaging as long as they have good rhythm of play, a decent reward and engagement curve and a cute presentation. Just look at how much time people spend in Euro Truck Simulator or Elite: Dangerous just hauling goods from place to place - an activity usually described as boring, but it's peaceful and if you do it for fun it's engaging in a relaxing way. Or look at the play stats of incremental games. Of course you can also tie quests into your job activities.

# Answer
> 2 votes
One of the options is to kind of make it a second game. If you make the "normal job" aspect as complex, complete and balanced as your "adventurer" part (so that it is fun), it will appeal to players. Have a leveling system, upgrade the buildings, buy more land, buy the competitors, make deals with the Crown or with other towns, go shady and kill the competitors without being noticed, start advertisement campaigns!

Another option is to keep them poor during their "adventurer" life: make the adventurer money faucets and money sinks nearly equivalent. And show them that there is a bit more money to be made by having a "normal job": have the shop-keeper, bartender, blacksmith, etc. introduce them to their trade!

You could accompany that with the body ability to fight battles decaying over time, making the adventurer life less and less appealing. You could even throw a "Fountain of youth potion" that costs a lot and could only be obtained through a "normal job" if they want to continue that life.

This second option may not please every player because it could feel like they'll always be running to get money, reducing the fun they'll get out of the game.

# Answer
> 1 votes
Consider this: most players play videogames to escape reality and experience the thrill of adventure. That said, it's safe to assume many, if not most of your players would opt for combat over normal life because that's what they came for: *an adventure*.

Think of it this way: the "normal lifestyle" in your game should be as exciting as combat to capture the interest of your players. Adding quest lines specific to the chosen line of work and character interactions will both assist greatly in that. Besides, nobody said that a person living a normal life should forget using their weapons and combat skills: you may include situations in your quests which may require use of some, like stealing, or fist fights.

So really, your main problem to solve is how to make the player experience as interesting when they retire as it was during their adventures.

EDIT: Someone has mentioned *Skyrim: Hearthfire DLC* as an example. While it indeed contains some additional building and crafting gameplay elements, it doesn't offer a choice to fully *retire*. However, it does serve as a good example of how to make a potentially boring gaming experience a thrilling one. I.e. in the following scenario, a player can build a house and populate it with their adopted children, spouse and other NPCs. Even though the player may grow attached to their own home, they also grow bored since there is no other thing to do with it. This changes when the game generates an event in which a band of vampires raids the house, adding some excitement and entertaining the player.

# Answer
> 1 votes
Don't think players will neglect building aspects in favor of combat. Wealth building and customization can actually be a super fun game mechanic, and if balanced right, you could get just as many players willing to focus on it as you would have players focused on combat. Some good examples of this are Rune Factory and Stardew Valley. A couple things I noticed these games do that might help:

1. Each focus gives an advantage to the other. Sure, you might be able to neglect your farm and just storm through the dungeons, but it would be really hard. Also, if you ignore the combat and just work on your farm, some resources are going to be hard to find, limiting what you can actually do. The combat loot gives you materials for building your farm (or in you case, whatever you do at home), and the things you build at home give you a fighting edge in the dungeons, such as weapons or potions.
2. Each focus has its own story and mysteries. A story motivates us to press through a dungeon, since we want to discover what it contains and possibly trigger some new cut-scene. The dungeons, though, aren't the only things that can have story. You can create the same motivation by revealing more to players as they befriend townsfolk or successfully craft rare items.

Since the two focuses are interdependent, most players will choose to do a little of both unless the game is multiplayer. If it is, they would be able to focus more on one part, since they can trade with other players. If this is the route you want players to take, it may be wise to add skill levels. Then, it may be more advantageous for players to specialize, become the best at a particular skill, and then trade for the other things they may need.

---
Tags: game-design, planning
---


# Question
Title: Per pixel normal mapping resulting in static on normals starting on Z axis
For the past week I've been trying to implement bump mapping in DirectX 11 using the Frank Luna's '*3D Game Programming with DirectX 11*' book. I got it working until I tried to add a flat 2D plane facing in the -Z axis and the texture appeared distorted. After a while I found out it was the bumped normals that were causing it.

I've used Terathon to calculate tangents after generating a mesh.

My code is as follows:

```
void AddTangentToVertexArray(const UINT vertexCount, const UINT indexCount, PackedVertex* vertices, const WORD* indices)
    {
        const UINT triangleCount = indexCount/ 3;

        XMVECTOR* tan1 = new XMVECTOR[indexCount* 2];
        XMVECTOR* tan2 = tan1 + indexCount;
        ZeroMemory(tan1, indexCount* sizeof(XMVECTOR) * 2);

        for (UINT a = 0; a < indexCount; a++)
        {
            WORD i1 = indices[(a * 3)];
            WORD i2 = indices[(a * 3)+1];
            WORD i3 = indices[(a * 3)+2];

            const XMFLOAT3& v1 = vertices[i1].vertex;
            const XMFLOAT3& v2 = vertices[i2].vertex;
            const XMFLOAT3& v3 = vertices[i3].vertex;

            const XMFLOAT2& w1 = vertices[i1].uv;
            const XMFLOAT2& w2 = vertices[i2].uv;
            const XMFLOAT2& w3 = vertices[i3].uv;

            FLOAT x1 = v2.x - v1.x;
            FLOAT x2 = v3.x - v1.x;
            FLOAT y1 = v2.y - v1.y;
            FLOAT y2 = v3.y - v1.y;
            FLOAT z1 = v2.z - v1.z;
            FLOAT z2 = v3.z - v1.z;

            FLOAT s1 = w2.x - w1.x;
            FLOAT s2 = w3.x - w1.x;
            FLOAT t1 = w2.y - w1.y;
            FLOAT t2 = w3.y - w1.y;

            FLOAT r = 1.0f / (s1 * t2 - s2 * t1);
            XMVECTOR sdir{ (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
                (t2 * z1 - t1 * z2) * r };
            XMVECTOR tdir{ (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) *r,
                (s1 * z2 - s2 * z1) * r };

            tan1[i1] += sdir;
            tan1[i2] += sdir;
            tan1[i3] += sdir;

            tan2[i1] += tdir;
            tan2[i2] += tdir;
            tan2[i3] += tdir;
        }

        for (UINT a = 0; a < vertexCount; a++)
        {
            const XMVECTOR& n = XMLoadFloat3(&vertices[a].normal);
            const XMVECTOR& t = tan1[a];

            XMStoreFloat4(&vertices[a].tangent, XMVector3Normalize((t - n * XMVector3Dot(n, t))));

            vertices[a].tangent.w = (XMVector3Less(XMVector3Dot(XMVector3Cross(n, t), tan2[a]), XMVECTOR{ 0.0f, 0.0f, 0.0f, 0.0f })) ? -1.0f : 1.0f;
        }

        delete[] tan1;
    }

```

And I used Frank Luna's implementation to use those tangents to calculate the bitangent but in the the newer version of directX 11

```
float3 NormalSampleToWorldSpace(float3 normalMapSample, float3 NormalW, float4 TangentW)
{
    float3 NormalT = 2.0f*normalMapSample - 1.0f;
    float3 N = normalize(NormalW);
    float3 T = normalize(TangentW - dot(TangentW, N)*N);
    float3 B = cross(N, T) *TangentW.w;

    float3x3 TBN = float3x3(T, B, N);

    float3 bumpedNormalW = mul(NormalT, TBN);

    return normalize(bumpedNormalW);
}

```

EDIT: After a couple hours of debugging I've found that changing the T calculation to `float3 T = normalize(TangentW - dot(TangentW, N));// *N);` seems to have stopped any distortions. If someone can confirm that this isn't going to cause later issues I'm willing to say it's solved.

All surfaces are using the same normal map in the following gifs.

A visual example of what happens to normals facing down and up the Z axis Here is the same plane but rotated 90 degrees

A visual example of a sphere that isn't affected by the distortion due to what i can only assume is having no normals along the Z axis

My guess is that something is wrong within the tangent calculator as the error persists when the plane is rotated, but I cannot seem to find anything different to the version on Terathon.

If there's anything else that you need to tackle the problem just let me know and I can supply it.

# Answer
Well, I solved it, turns out I had the incorrect byte offset declared in my Input Layout. My tangent's are now the right value and the bump mapping is looking spectacular.

Just a quick breakdown of how I worked it out for anyone else who needs to debug their shaders.

I started off by identifying that my problem was within the pixel shader tangent calculation. I then realised that the dot product was returning odd values for the tangent and normal values I'd output to console. I then decided to output my tangents and realised "These are all blue, that's not right!". So finally I had a quick look at my vertex structure and input layout to find out I'd overextended the byte width by 4 bits.
> 0 votes

---
Tags: c++, shaders, directx11, hlsl, normal-mapping
---


# Question
Title: Why wouldn't games be published with Map Editors included?
15 years ago, in 2002, **Warcraft 3** was released. Aside from being a great RTS game, it had lived for years past its release mostly due its World Editor - a fully-functional industrial-grade Map Editor that gave players all the tools the devs had during the development process. It has lead to creation of millions of custom maps, cinematics, campaigns, and first MobAs.

Very few companies have released their own Editors with their games since then. Even Blizzard didn't do it again with the new Starcraft release (the version which was eventually released wasn't nearly as powerful as the Warcraft's one). As we see from the history, something as seemingly trivial as this may tremendously prolong the game's lifetime. So why wouldn't developers release World Editors they used alongside with their games?

# Answer
> 58 votes
Because it is expensive, and the return on that cost is usually zero.

Building tools to create games is hard and expensive already. It becomes harder and more expensive when those tools need to be brought up to the level of polish required to ship them to (potentially very non-technical) end-users. Once you ship those tools, you also have customer expectations that you will support them: provide documentation, create examples, fix bugs, add new features over time.

In the past, building games was somewhat simpler and building the tools similarly so. Customer expectations about how much support they should get around official mod tools and the like were lower. Games have become more complex, the related toolchains have increased in complexity in lockstep. It's become harder and harder to justify the business expense of what is essentially building and shipping an *entire separate product* at the same time a game. Especially since almost never bring in revenue on their own (and attempts to monetize them have been met with consumer backlash; recall the Skyrim paid mods fiasco).

Further, in many cases there isn't a single "map editor" but rather a complex pipeline of smaller bespoke tools. Or the "map editor" is an existing, commercial product that cannot be redistributed by the developer *anyway*.

# Answer
> 11 votes
There could be a lot of factors but the ones that come to my mind first are ease of use and compatibility.

1. An AAA office environment would most likely have company-provided computers, meaning there would be very little variety in the OS and hardware that the program would need to support. This would mean fewer bugs, and it would also mean that if released to the public they would need frequent bugfixes and patches to make it available to a large variety of systems.
2. Second, (the most probable reason) is ease of use. The small team of people making the mapping engine aren't going to waste time making it look fancy. It takes time and money to do so. They know that the people using the software are "experts" and thus they will give them the minimum graphical interface needed to make the program work. However, if it was released to the public many people with no skill in mapping would want to pick it up, and a minimal or ugly interface is daunting to newbs and generally looked down upon compared to simple, easy to use map editors like Portal 2's test chamber builder.

# Answer
> 10 votes
What money can you make from such a map editor?

Prolonging the lifetime of a game is great for the customer, but for the studio? Blizzard had to keep the original Battle.Net servers online much longer, and with much greater capacity. That costs money. at the same time, sales of new copies of the game are almost non-existent.

Users expect patches for new OS versions, compatibility with new hardware etc. The more lifetime your game has and the more users, the higher the demand will be and the higher the backlash for not doing so.

So, you drastically increase maintenance costs without getting much in return.

Moreover, microtransactions and DLC are becoming increasingly popular. A map editor eats away at that lucrative market.

Finally, making a releasable map editor is a tremendous amount of work. Having a buggy, hard-to-use map editor for in-house production is something you might be able to live with. But releasing it to non-technical customers? That's a recipe for disaster. When making such an editor, you have the initial cost of polishing it enough to actually release it, and then have to maintain and support it. You are basically building two products at the same time.

You have to undertake quite some financial efforts to make that possible, for a questionable gain. It's a simple business decision, does having an editor and custom maps drives sales of your game really enough to justify the costs of providing the editor? In the modern gaming industry, the question is increasingly "no".

Furthermore, companies are reluctant to play the long game. take AoE 2 for example, as said in a comment by inappropriateCode:

> Consider Age of Empires 2. The scenario editor created a community of mappers and modders, and part of them went on to create the unofficial expansion: The Forgotten Empires. That was successful, and the product owners decided given AoE2's lingering popularity, there was money in reviving it with Age of Empires 2 HD, and subsequent expansions. It's the most popular paid RTS on Steam by a mile, with over 4 million owners last I checked. Sure the developers at the time didn't benefit from that, but the product owner certainly did later. Producers/developers?

While this is true, its a risk. At release time, you cannot foresee the future. You can either have lower costs and thus more profits *now*, or gamble on some sales 10 years in the future that may or may not happen at all. Its a *huge* risk, and AoE2 is one of the *extremely few* examples where this *did* work out that way. Since companies are usually risk-averse, this is not a strategy that would deliberately be chosen.

While WC3 and AoE are good examples for games where it worked, Settlers V, which included a *very* powerful map editor with its own scripting language, receved very mixed critics and is generally considered a failure, despite being part of a very popular and strong series of games (granted, they probably peaked at Settlers II/III and then went downhill) and having such an editor.

# Answer
> 3 votes
To complement the already existing answers I want to add two points:

1. Often newer games have more complex geometry, effects or design (I'm not speaking of level layout here, only the complexity of the objects/buildings placed in one level). In old games you could just create a new map my placing different already existing terrain or structures in a new way, in newer games you often need new assets to create new levels.
2. This is a bit sad but I think developers don't gain much from having a long lasting community for one game if it is part of an annually releasing series like Call of Duty or Assassins Creed. Improving the long term playability of those games by giving the community the ability to create new content could reduce the sales of the newer releases. But keep in mind that this is only a thought of mine, I can't back this up with evidence or facts.

# Answer
> 0 votes
Dota2 introduced modding tools and it's not doing so well. I have a top game in the dota 2 mod community so I'm well aware of the current situation. Truthfully it seems the cost of developing the modding API vs the reward is simply not there.

The tools not only have to be polished enough to get people to use them, but they have to be kept up to date with the constantly evolving base game. The games created by modders generally aren't entertaining enough to attract or keep players' attention. Games that have 12-24 months of dev time die in just under a month.

# Answer
> -2 votes
Starcraft 2 (which i assume you mean by "new" Starcraft as the original was well prior to warcraft 3) has had the Galaxy editor available since the early beta as of April 2010 even well before the full release in July. It is far more powerful including its own scripting language on top of the warcraft similar style GUI; granted a little too powerful to the extent it wasn't as accessible to newer mapmakers.

MOBA games like Dota 2 have the hammer level editor. Starwars Empire at war rts also has an editor although produced by a different company. Roller Coaster Typhoon is essential an editor as a game similar to Mario maker. You could even call a 'sandbox' game like Minecraft to be an in-game editor. https://en.wikipedia.org/wiki/List\_of\_level\_editors is a list of over 250+ games and their matching editor's, many of which are build it.

Perhaps its as simple as people these days rarely have an interest to dive further into the programs directory past the initial 'launch game' app; and with that current trend why go further to release something that is less and less likely to be used by the public.

---
Tags: game-industry, map-editor
---


# Question
Title: Still i can't make the cross hair to be in the middle of the screen, What am i missing?
In the editor i did:

GameObject \> UI \> Image

On the Canvas i changed the Render Mode to Screen Space - Camera.

It created a Canvas and a child Image in the Hierarchy. Then i changed the Image source to UISprite changed the color to red also added to it a material in red.

I can't changed the Canvas anchors not sure why.

The Image rect transform anchors is set to the center.

I don't have a Main Camera the only camera i have is on the FirstPersonController (The FirstPersonController is a child of a FPSController).

But still the red dot/circle is a bit to the left not in center.

Screenshot of the Canvas:

And two screenshots of the Image:

And

# Answer
OnGUI is *deprecated*. And it has been for a long time. Make sure your Unity is updated at least to a fairly recent version.

**Use the Unity Canvas.**

On the Unity Main Screen, go to GameObject in the menu bar at the top, scroll down to UI, and select image. It will automatically create a new Canvas for you (assuming you don't have one). It will also create a new image. Click on the Canvas, and set it's "Render Mode" to "Screen Space - Camera". Then set the Camera to your Main Camera/The Camera for your game.

By default, the anchor points of the image you created should be set to center, so simply set the x, and y transform to 0. Your image will be centered. If the anchor points are not automatically set to Center, simply click on the transform of the image, and at the top should be it's anchor point. Set it to center and follow the same steps listed in this paragraph.

Make the created image your crosshair circle/hit marker by selecting the sprite and setting it to whatever you need.
> 1 votes

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


# Question
Title: UDK: Playing two audio tracks simultaneously
I have some environmental music playing in the background, but when I try to play another track (door opening sound effect) at the same time the background music stops playing.

**How can I play two audio tracks simultaneously?**

# Answer
> 0 votes
The UDK site says you can use the SoundCue editor to combine sounds, maybe you could fade these two musics in and out quickly so it sounds like they're playing at the same time.

You could use Volume Ducking to lower these background sounds when the door opens.

https://docs.unrealengine.com/latest/INT/Engine/Audio/Overview/index.html

\[BELOW\] This person used an AudioComponent class to use music and sound on a loop, and got two musics to play at the same time:

http://romerounrealscript.blogspot.com/2011/11/playing-sounds-in-unrealscript.html

Hope this helps. :)

# Answer
> 0 votes
You haven't displayed any code, making it difficult to help you.

**REMEMBER:** To have two sounds playing at one time, you must require two audio sources. By guessing (without seeing code or your scenes) you will have a single audio source, and you've set it to change dependent on what is happening.

E.g. door not opening = background music, door opening = door sound. However, instead, have two separate audio sources. One on the door, and one on an empty game object named "game audio".

This way two sounds can play at once.

Equally, remember you DO NOT need multiple audio listeners. Only audio sources.

---
Tags: udk, audio
---


# Question
Title: Unity - Instantiate 2 copies at same time?? (Asteroids clone) C#
I haven't been at my computer learning code or game dev in a few months and am just starting again. I am trying to make a game very similar to Asteroids. In 3d but fixed camera from above so basically disregarding the Y Axis at the moment.

I have everything working fine so far such as the rocket stays in middle and can rotate, and fire weapon. The Asteroids for now all come from the top side of the screen, and have some code to randomise the X location and speeds.

When the laser hits the Asteroid I want it to destroy that Asteroid and create two more that are half the size and with a Rotation added of 45/-45 degrees.

I have the code that I thought would work but it is only creating one more and not two. (note: as you'll see I have tried making tempAsteroid2 and even asteroidPrefab2, before this I just had the one which I tried to instantiate twice).

What am I missing? why does this code not make two more appear upon laser collision??

Any help massively appreciated as always. Many thanks:

```
public class Asteroid : MonoBehaviour {
float speed;
public GameObject asteroidPrefab, asteroidPrefab2;
public int sizeKey = 2;
// Use this for initialization
void Start () {
    if (sizeKey < 1)
    {
        Destroy(this.gameObject);
    }
    transform.position.Set(transform.position.x, 0f, transform.position.y);
    speed = Random.Range(0.5f, 2f);
}

// Update is called once per frame
void Update () {
    GetComponent<Rigidbody>().transform.Translate(Vector3.forward * speed * Time.deltaTime);
}

private void OnTriggerEnter(Collider other)
{
    if (other.tag == "Laser")
    {
        BreakAsteroidInHalf();
        Destroy(other.gameObject);
    }
}

void BreakAsteroidInHalf()
{
    GameObject tempAsteroid = asteroidPrefab;
    tempAsteroid.transform.position = transform.position;
    tempAsteroid.transform.Rotate(0, -45, 0);
    tempAsteroid.transform.localScale *= 0.5f;
    tempAsteroid.GetComponent<Asteroid>().sizeKey -= 1;
    Instantiate(tempAsteroid);
    GameObject tempAsteroid2 = asteroidPrefab2;
    tempAsteroid2.transform.position = transform.position;
    tempAsteroid2.transform.Rotate(0, 45, 0);
    tempAsteroid2.transform.localScale *= 0.5f;
    tempAsteroid2.GetComponent<Asteroid>().sizeKey -= 1;
    Instantiate(tempAsteroid2);
    Destroy(this.gameObject);
    Debug.Log("Asteroid destroyed and replaced by 2 more");

}

```

# Answer
It's important to remember that **C#** is an **Object Oriented Programming language**. As such, this is a bad example of how to use it.

Instead of the current solution, try using:

```
void BreakAsteroidsInHalf() {
float rot = 45;
for(int i = 0; i < 2; i++){
GameObject asteroid = Instantiate(asteroid, transform.position, transform.rotation) as GameObject;
asteroid.transform.localScale(0.5,0.5,1);
asteroid.transform.Rotate(0, rot,0);
asteroid.GetComponent<Asteroid>().sizeKey -= 1;
rot -= 90; // If you increase you "i" limit, this will allow you asteroids
rotate at different degrees.
     }
Destroy(gameObject);
}

```

This keeps your code succinct, readable, and most importantly, object oriented.
> 2 votes

# Answer
```
void BreakAsteroidInHalf()
{
    GameObject tempAsteroid = Instantiate(asteroidPrefab);
    tempAsteroid.transform.position = transform.position;
    tempAsteroid.transform.Rotate(0, -45, 0);
    tempAsteroid.transform.localScale *= 0.5f;
    tempAsteroid.GetComponent<Asteroid>().sizeKey -= 1;

    GameObject tempAsteroid2 = Instantiate(asteroidPrefab2);
    tempAsteroid2.transform.position = transform.position;
    tempAsteroid2.transform.Rotate(0, 45, 0);
    tempAsteroid2.transform.localScale *= 0.5f;
    tempAsteroid2.GetComponent<Asteroid>().sizeKey -= 1;

    Destroy(this.gameObject);
    Debug.Log("Asteroid destroyed and replaced by 2 more");
}

```

---

**Explanation:**

Actually, you still have 2 copies, but they have identical transforms.

In your code, you are modifying the prefab here:

```
GameObject tempAsteroid = asteroidPrefab;             //tempAsteroid is the prefab right now, not an instance in the scene
tempAsteroid.transform.position = transform.position; //modifying prefab
tempAsteroid.transform.Rotate(0, -45, 0);             //modifying prefab
tempAsteroid.transform.localScale *= 0.5f;            //modifying prefab
tempAsteroid.GetComponent<Asteroid>().sizeKey -= 1;   //modifying prefab
Instantiate(tempAsteroid);                            //creating an instance

```

The problem with this approach is, when you are using a prefab as the original object, `Instantiate` function will wipe the transform values of the top transform in the hierarchy of prefab, right after the creation of a new instance. So all of your previous modifications to prefab will be replaced by some other values on the new instance.

So instead, we first need to instantiate and then modify the instance on the scene.
> 2 votes

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


# Question
Title: How to dispose in Newest Java/LibGDX ApplicationListener?
**What I'm wondering:**

How do you dispose of textures / spritebatches and the things you normally need to dispose of now?

**Why I'm asking:**

Because theirs no automatic dispose() function upon creation of the Main libGDX class. I don't remember details but there used to of been an @override dispose

**I don't want a memory leak or whatever it's called when you don't dispose.**

# Answer
> 1 votes
Make sure that you implement `ApplicationListener` in your main class in order to override `dispose()`.

For example if `MyGame` is my main class then:

```
public class MyGame implements ApplicationListener {
    // put your Logic
}

```

Also libGDX provides the `Game` class that already implements `ApplicationListener`, so you can extend the `Game` class as follows:

```
public class MyGame extends Game {
    // Logic
}

```

Once you follow one of the above approaches you are able to override `dispose()`.

# Answer
> 0 votes
Some resources are not cleaned by the garbage collector. You need to dispose them manually, in order to save memory. You just need to call `.dispose()` You can find more information about libGDX memory management here. There is also a list with all resources that implement a disposable interface.

For example, you can dispose a Polygon Shape after using it to create your Fixture:

```
public void create() {
    FixtureDef fDef = new FixtureDef();
    Fixture fixture;
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(w, h, position, angle);
    fDef.isSensor = true;
    fDef.shape = shape;
    fixture = body.createFixture(fDef);
    shape.dispose(); //You can dispose the shape.No longer needed.
}

```

However, you have to pay attention before disposing something that is still needed in your code:

```
public void setWalkLeftAnimation() {
    assetManager.load("walk_left.pack", TextureAtlas.class);
    assetManager.finishLoading();
    atlas = assetManager.get("walk_left.pack");
    walkingLeft =  new Animation(1/12f, atlas.getRegions());
    // Don't dispose it,you won't be able to render the animation.
    //assetManager.dispose();
    //atlas.dispose();
}

```

Dispose the Asset Manager and Atlas in the proper dispose method:

```
@Override
public void dispose(){
    assetManager.dispose();
    atlas.dispose();

    //Dispose it here with other resources.
}

```

---
Tags: java, libgdx, graphics
---


# Question
Title: How to Structure my Database for a HTML turn-based strategy game?
I'm making simple HTML socket game that I want to record over time.

It's a "risk" type game where individual tiles can be conquered, and the team with the most tiles is winning.

As of right now, I've finished most of the game, but the problem is that every time the server restarts all the server data is lost.

I want to use the database to store all the different teams and also of all the tiles that have been conquered, but I am also thinking of storing all the tile conquerings with timestamps so I can see the progression of how the map was conquered. (so I can theoretically play it back in time and see how the map began to evolve).

I also want it so on the event that the server crashes, the server can retrieve data from the database and go back to a previous world state (with which tile has been conquered by whom, etc.)

I'm very new to databases, and have only learned SQL in school because I had to. I was considering using MongoDB (noSQL) for this, and seeing that I will only write at most every few seconds to the board, is this the right approach?

# Answer
It really doesn't matter which database you use for this. You can use pretty much any.

The sql-by-the-book solution for storing the current state of all games would be to create a table with these fields:

* game\_id (primary\_key)
* tile\_id (primary\_key)
* owner

The game history would look like this:

* game\_id (primary\_key)
* move\_id (primary\_key)
* timestamp
* tile\_id
* new\_owner

Actually, the first table with the current state could be redundant, because you can construct the current gamestate by simply reconstructing the whole game from its history. But that might be quite performance-intense for such a common operation (you will want to suspend any games to the database where nobody made a move for a while in order to save memory on your gameserver).

But if retrieving the whole game is your primary use-case, then you might decide to deviate from SQL-by-the-book for the current state table and store the gamestate serialized to binary and store it as a BLOB:

* game\_id (primary\_key)
* gamestate

You then can no longer do queries for individual tiles, but saving and restoring the complete gamestate will be a much faster operation, because it's just a single row.

---

The question also mentioned MongoDB. How would this look there? MongoDB emphasizes nested documents over relations. Anything which has a relation should by default be stored in the same document (there are exceptions, see later). The default game document would look like this:

```
{
    _id: ObjectId(),
    player1: <player identifier>,
    player2: <player identifier>,
    tiles: [
       // array representing the states of all tiles
    ],
    history: [
        {
            timestamp: Date(),
            tile_id: <index in the tile-array above>,
            new_owner: <player identifier>
        },
        /*...and more such objects...*/
    ]
}

```

However, MongoDB has a problem: It doesn't like documents which grow, because when a document grows beyond its initial size it sometimes needs to be relocated to a different hard drive location. This harms write performance. So when you notice that updating the game history becomes a bottleneck, you might want to move it to a different collection where each game event is one document:

```
{
     _id: ObjectId,
     game: <ObjectId of the game where the event happened>
     timestamp: Date(),
     tile_id: <index in the tile-array above>,
     new_owner: <player identifier>
}

```
> 1 votes

# Answer
Usually you can achieve the same thing by different approaches. It all depends on what you want to do and what you choose of: programming language, server, database, etc.

Anyway, if you're using websockets, consider using a real-time database, like RethinkDB (NoSQL) or Firebase Realtime Database.

AFAIK Mongodb doesn't support realtime, and I didn't use Firebase myself, but I have experience with RethinkDB and is definitely cutting-edge. Note: the syntax of RethinkDB is ugly (IMHO) and because it's relatively new in the market you might not find much of help in stackoverflow (you're on your own).

**TL;DR:**

IMHO, in your case, if you can avoid using any database, just don't use any. Because if the server crashes or some players got discounted, they will easily restart the game and play again.
> 0 votes

---
Tags: javascript, html5, databases, sql, mongodb
---


title: Problem using glm::lookat

text:
# Question
Title: Problem using glm::lookat
I am trying to rotate a sprite so it is always facing a 3D camera.

Object

```
GLfloat vertexData[] = {
    //  X     Y     Z       U     V
    0.0f, 0.8f, 0.0f,   0.5f, 1.0f,
    -0.8f,-0.8f, 0.0f,   0.0f, 0.0f,
     0.8f,-0.8f, 0.0f,   1.0f, 0.0f,
};

```

Per frame transform

```
glm::mat4 newTransform = glm::lookAt(glm::vec3(0), gCamera.position(), gCamera.up());
shaders->setUniform("camera", gCamera.matrix());
shaders->setUniform("model", newTransform);

```

In the vertex shader:

```
gl_Position = camera * model * vec4(vert, 1);

```

The object will track the camera if I move the camera up or down, but if I move the camera left/right (spin the camera around the object's y axis), it will rotate in the other direction so I end up seeing its front twice and its back twice as I rotate around it 360.

If I use -gCamera.up() instead, it would track the camera side to side, but spin the opposite direction when I move the camera up/down.

What am I doing wrong?

# Answer
> 1 votes
glm::lookat was not what I wanted after all. Found the answer here

For completeness sake, the code is reproduced below (I changed the translate line to vec4(position, 1), otherwise it doesn't translate):

```
mat4 billboard(vec3 position, vec3 cameraPos, vec3 cameraUp) {
vec3 look = normalize(cameraPos - position);
vec3 right = cross(cameraUp, look);
vec3 up2 = cross(look, right);
mat4 transform;
transform[0] = vec4(right, 0);
transform[1] = vec4(up2, 0);
transform[2] = vec4(look, 0);
// Uncomment this line to translate the position as well
// (without it, it's just a rotation)
//transform[3] = vec4(position, 1);
return transform;
}

```

The reason why I don't want to manipulate each vertex of the billboard is because I plan on using more complicated 2d geometry in the future.

# Answer
> 4 votes
I'd like to share an alternative solution based on the assumption that you have access to the view matrix. It has the advantage to make the billboard stay exactly perpendicular to the view vector instead of just orienting the billboard towards the camera. See it neatly explained here: https://swiftcoder.wordpress.com/2008/11/25/constructing-a-billboard-matrix/

You don't have to compute anything, just use the transpose of the top 3x3 section of the view matrix and the billboard position vector:

```
                     V11 V21 V31 P.x
billboardTransform = V12 V22 V32 P.y
                     V13 V23 V33 P.z
                      0   0   0   1

```

Where P is the world position of the billboard object and V is the view matrix defined as:

```
|V11 V12 V13 V14|
|V21 V22 V23 V24|
|V31 V32 V33 V34|
|V41 V42 V43 V44|

```

**Note:** Indexing is done using mathematical notation. Therefore, don't forget to take into consideration the memory layout of your data (row-major / column-major).

---
Tags: opengl, camera, rotation
---


# Question
Title: Why am I hitting a small character limit when rendering with SDL_TTF?
I'm making a text based game using SDL2 and SDL\_TTF. I just started working with TTF, and I've noticed there is some kind of character limit regarding how much text you can render at a time! I can only render about 15 characters, after that, (16 characters or higher) the screen is just blank.

I really want to render large bodies of text (multiple sentences at a time) so how do I overcome this issue? For rendering text, I have this function:

```
void drawDialog(const char* content) {
    //Draws a dialog box with set text

    TTF_Font* font = TTF_OpenFont("assets/times.ttf", 900);
    SDL_Color textColor = { 255, 255, 255 };
    SDL_Surface* message = TTF_RenderText_Solid(font, content, textColor);
    SDL_Texture* tex;

    SDL_Rect destRect;

    destRect.x = 50;
    destRect.y = 730;

    destRect.w = 200;
    destRect.h = 30;

    tex = SDL_CreateTextureFromSurface(renderer, message);
    SDL_FreeSurface(message);
    SDL_RenderCopy(renderer, tex, NULL, &destRect);
    SDL_RenderPresent(renderer);
}

```

So, any advice for overcoming this limit? Any help would be greatly appreciated!

# Answer
You're probably running into surface/texture size issues, since you're loading the font in a massive size (900). I'd suggest using a much smaller point size, and that should look just as good as you don't necessarily need to downscale it at all.

I render fonts with sizes around 30 for smaller text, and around 50 for larger menu text.
> 2 votes

---
Tags: c++, rendering, sdl, text, ttf
---


title: How to custom UI Slider with Unity UGUI

text:
# Question
Title: How to custom UI Slider with Unity UGUI
I want to use Unity UGUI to custom a slider and the final looking show be like this:

And the images I use are:

But I found it hard to accomplish:

The handle will be screeched and the fill will not be fully filled with the handle

Can somebody tell me how I could accomplish this?

# Answer
Note that you are stretching the handle by setting these values. For the fill issue I would have to see a image to tell why it is not filling properly.

set those to 0,0 that way they will also scale properly with bigger screens. then select the rect transform and in the anchor preset use Ctrl Alt Click Left. and keep the other on stretch. You can also adjust the pivot X to something around -1 to bring the handle over to better match with the fill but the fill itself may still need adjustment if that doesn't solve the filling issue.
> 1 votes

---
Tags: unity, ui-design
---