This is the second part of the assorted tricks, hacks and interesting mechanics I remembered while writing the article about “coyote time”, but back there it seemed like such a small and almost innocent trick, one that lives somewhere on the edge of a platform and never shows up anywhere else. In reality it is only the most visible bit of a fairly big game-dev kitchen, because in randomness, in enemy behaviour, in hitboxes and even in exactly where a character’s feet are standing you have to make all sorts of allowances, not out of spite, but simply because an honest simulation feels worse than a tweaked one. The player doesn’t see the formulas, but he does see the consequences, and the consequences often look unfair, and no amount of explaining about a correct random number generator will talk the player out of the idea that the game is cheating.
The funnier part is when the complaints land precisely on the honest systems, and if you have ever read the forums of any game with loot drops, you have certainly seen threads along the lines of “the 10% chance is a lie, I killed the boss forty times and got nothing”. And then the author of that thread starts review-bombing with his feelings about how things ought to work, but his conclusions are wrong, because with an honest 10% forty misses in a row happen to roughly one player in seventy, and you have, say, a hundred thousand players, and so there he sits, miserable, among his seventy comrades in “random”, feeling sad.
Sid Meier once told the story of how Civilization players refused to accept honest combat odds, and a loss at 3 to 1 in their favour was perceived as cheating, because the player believes that if it’s 3 to 1, then every other battle will go his way. Just accept it, when people see numbers in games, they always read them in their own favour. And in the end Civ had to tweak the odds so that they matched not the math but people’s expectations.
Lying about randomness
People are very bad at understanding what randomness is, and this is not the people’s problem but the game developers’, and it is a long-known fact from psychology. We expect a random sequence to be “shuffled in our favour”, with no long streaks, no clumps, no repeats. Except real randomness works the exact opposite way, and “honestly” produces streaks, clumps and repeats simply because it doesn’t care what came before, which is why almost any random generator in a game that is supposed to feel fair is actually tweaked in the player’s favour. Why? Because people want to win.
The simplest and most common trick is when an item says it has a 10% drop chance, and the “correct” implementation looks like this:
bool RollDrop(float chance) {
return Random01() < chance;
}
But such a roll has no memory, and it doesn’t know that the player has already missed thirty times in a row, and on the thirty-first try he again gets the same 10%, while the probability of a streak of N misses in a row falls exponentially but never reaches zero. If you run a hundred thousand rolls, the worst miss streak will be somewhere around 70–80, and for the player who got that streak your game will forever remain “broken”.
A pity timer solves this by counting misses, so that after a certain threshold the chance starts to grow, and at some point the drop becomes guaranteed. Gacha games turned this into a system with soft pity, where the chance shoots up after a few dozen attempts, and hard pity, where the item is guaranteed to drop on the 90th attempt if it hasn’t dropped earlier. The 90 didn’t come out of thin air either, it is the limit of “human expectation”, taken from analysing the slot machines that bring casinos the most income. Here is roughly how it looks:
float PityChance(int misses) {
if (misses + 1 >= hardPity) return 1.0f;
if (misses < softPityStart) return baseChance;
float t = float(misses - softPityStart + 1) / float(hardPity - 1 - softPityStart);
return baseChance + (1.0f - baseChance) * t;
}
Pity lies to the player by making wins more frequent, and the real drop rate under such a rule is higher than the one written in the item description. In the example with 10% on screen, the chance growing after the eighth miss and a guarantee on the eighteenth attempt, the real chance comes out at about 14%, and the worst miss streak over a hundred thousand rolls is cut down to 16 instead of the honest die’s 78.
There are smarter variants too, like the one invented for Warcraft III that is still alive and well in Dota 2. This gacha is called pseudo-random distribution, PRD, and the chance on the N-th attempt after the last success equals C × N (the blue column), where C is chosen so that the average matches the stated chance. So for an item with 10% (the constant is roughly 0.01475), the first hit after a crit has only a one and a half percent chance to crit again, while the tenth is already at almost 15%, and players consider it one of the fairest random systems around.
float PrdChance(int misses) {
return min(1.0f, C * float(misses + 1)); // C = 0.01475 for 10%
}
PRD is good because it is “humanly honest” on average, and if you count over a long distance you get those very same 10%. But it produces almost no long streaks in either direction, neither streaks of failures nor streaks of successes, and a hundred thousand rolls give a worst miss streak of about 30, which is why players consider it truthful.
Try it yourself: three players roll the same die, and with Pity and PRD the chance grows with every miss.
Damage dice and true hit
The second source of the feeling that randomness is unfair is the shape of the distribution itself. Take, for example, weapon damage (1–12) and make it honest, with a single d12 roll, then the average damage will be 6.5 and every value from 1 to 12 will come up equally often, meaning a hit for one point will happen on every twelfth swing. But a 1 is a fail, and the player will definitely remember it and say the game is unfair, so we roll 2d6 instead, getting almost the same range, but now the average is 7 and the distribution turns into a triangle where a one never comes up and a two comes up once in thirty-six, that is, three times less often than a 1 on a d12. Is that fair? Go ask the D&D crowd which is fairer, 2d6 or 1d12.
But this isn’t lying yet, we simply picked the right formula and explained it to the player properly, and the lying starts in Fire Emblem, where starting with Binding Blade the game shows a hit chance of, say, 70%, but under the hood rolls not one random number from 0 to 99 but two, and takes their average:
The average of two uniform numbers gravitates toward the middle, so high chances get even higher and low ones even lower, which is why at 70% on screen the real chance to hit is about 82%. The game’s community calls this true hit, and the developers never wrote about it publicly, because the player intuitively overestimates high chances and underestimates low ones anyway, and the system simply plays along with your expectations, which is probably why winning there is so much fun, and a miss at 90% still happens, but so rarely that the player forgives it.
Why honest randomness looks broken
Now about the space you pick your random numbers in. Say you need to scatter trees, chests or enemy spawn points across a map, and you do it the obvious way and simply take a random x and a random y.
Except the result almost always looks bad, somewhere three trees have stuck together into a single bush, and right next to them there’s a huge empty clearing, and if you show such a map to a player he will say the generator is broken. Meanwhile the generator is absolutely, crystal-clear honest, this is what real uniform randomness is, it just doesn’t look the way we imagine it.
This exact story happened to Spotify, when users started complaining that shuffle wasn’t random because songs by the same artist played back to back, so the engineers had to make the shuffle less random so that it would feel more random.
In space this problem is solved with Poisson disc sampling, and we still throw points at random but discard the ones that land closer than a given distance to the ones already placed. In the most naive version this is just “keep throwing until you hit a free spot”, and the fast version with a grid and an active list was described by Robert Bridson in 2007.
In the example with 60 trees, honest randomness gives on average twelve stuck-together pairs and Poisson gives zero, and yet almost everyone calls the second forest “more random”, and if you ask a person to place the trees “any old way” themselves, they will almost always draw something very similar to Poisson, because nobody puts trees on top of each other when depicting randomness.
Storyteller and the director
The last and biggest trick in this group concerns not individual rolls but when anything happens at all. Any game with enemy waves, raids, events or disasters has a scheduling question, and the “honest” answer to it looks like a Poisson process, where every second something happens with some probability, regardless of what happened before.
void Tick() {
if (Random01() < wavesPerSecond)
SpawnWave();
}
But the problem with an “honest” Poisson process is the same as with a memoryless die, it doesn’t know that the player has just fought off a big wave and has twenty percent health left, so sometimes two big waves arrive back to back, and sometimes the player stands around for a minute and a half and nothing happens. Within a single match the player manages to complain both that “the game is unfair” and that “it’s boring”.
Left 4 Dead solved this with the AI Director, which tracks the players’ “intensity”, how much damage they took, how many enemies are around them, how close someone came to dying, and hands out events in phases: build-up, peak, fade and respite. RimWorld turned the same idea into a whole feature where you choose a storyteller, and Classic hands out events along a rising curve with pauses, while Randy does almost honest randomness, yet players are convinced that with Randy it almost always hurts.
void DirectorTick() {
float tension = aliveEnemies * kAlive + recentDamage * kDamage;
if (now < relaxUntil) return; // respite
if (tension >= peakTension) { // peak, ease off
relaxUntil = now + relaxTime;
return;
}
if (now - lastWaveTime > maxCalmTime) { // too quiet
SpawnWave();
return;
}
float headroom = 1.0f - tension / peakTension;
if (Random01() < wavesPerSecond * boost * headroom)
SpawnWave();
}
The director doesn’t make the game easier in terms of enemy count and even hands out more waves than the honest stream, but with the same weak bot player the honest stream loses the base in every seventh run and the director in just one, removing the moments when four or more enemies break through to the base at once. The director doesn’t reduce the load, it changes its schedule, and a player who has played with the director is sure that everything was random. Again, all of this came from the management theory of casinos and poker tables, when they noticed that people who were given a breather after a loss left, on the whole, one and a half times more money than those who lost several games in a row, and so the dealers were told to deal stronger cards to the “weak” players.
Attack tokens and Lanchester’s law
Now imagine any third-person action game where the player fights a crowd of melee enemies. If you make everything honest, each enemy walks up and hits as soon as it can, and the player facing eight enemies doesn’t survive a couple of seconds and hurls his mouse at the monitor, complaining about a balancing bug, but alas, math is a harsh mistress.
In 1916 Frederick Lanchester showed that in a battle where everyone shoots at everyone, an army’s strength grows as the square of its size, so eight enemies against one hero are not eight but sixty-four times stronger. Eight enemies dealing 7 damage per 1.4-second attack cycle make about 40 damage per second against a hero with 100 health, so an honest fight is over in two and a half seconds... math is harsh.
That’s why all games with crowds of enemies use attack tokens, or the “kung-fu circle”, where there is a limited number of attack tokens and only an enemy holding a token may strike, while the rest circle around, growl, wind up and generally act menacing, but don’t attack. After striking, the enemy gives the token back, and it goes to whoever has waited the longest, which is what Batman Arkham, Assassin’s Creed and many other games do, where a fight with a crowd looks spectacular and still stays beatable.
void AssignTokens() {
int holders = CountEnemiesWithToken();
auto waiting = EnemiesWithoutToken();
SortByWaitTimeDescending(waiting);
for (Enemy* e : waiting) {
if (holders >= maxTokens) break;
e->hasToken = true;
e->waitTime = 0;
++holders;
}
}
void EnemyAfterAttack(Enemy* e) {
e->hasToken = false; // give up our turn
e->ReturnToRing();
}
The enemies are the same, the damage is the same, the speed is the same, only the queue has changed, and with two tokens the damage ceiling drops from forty to ten per second, but the player doesn’t see the queue, he sees eight enemies around him and feels that he is fighting a crowd and... heroically winning.
The guard who honestly doesn’t know
With enemies in stealth games the situation is the reverse, and if a guard loses sight of the player, the developer has two solutions (both bad). The first is that the guard goes to the last place he saw the player, looks around and forgets about him, which looks dumb, because the player slips around a corner and feels like a ninja. The second is that the guard simply knows where the player is, since the game knows it, and walks straight to him through every turn, which looks like blatant cheating, and the player notices that too.
So a good solution (not the best, just good) makes it look as if the guard is reasoning (this is called a possibility map or occupancy map), where we keep on a grid the probability that the player is in each cell. At the moment the player disappears from view, all the probability is concentrated at the last known point, and then every tick it “spreads” to the neighbouring walkable cells, because the player could have taken a step, while all the cells the guard can currently see are zeroed out, since if the player were there the guard would have seen him.
void DiffuseBelief(Grid& belief, const VisibleSet& seen) {
Grid next = Zero();
for (Cell c : belief.Cells()) {
auto ns = OpenNeighbours(c);
float share = belief[c] / (ns.size() + 1);
next[c] += share;
for (Cell n : ns) next[n] += share;
}
for (Cell c : seen) next[c] = 0.0f; // you're not there, or I'd have seen you
Normalize(next);
belief = next;
}
After that the guard heads to where the probability is highest, adjusted for distance, and crosses out everything he sees along the way, which looks like a very believable search, as he peeks into the corridors you could have gone down, checks the rooms one by one, and sometimes guesses right, but guesses honestly.
Alien: Isolation took a third path and built a two-level system where the director knows where the player is and every now and then hints the direction to the Alien, while the Alien itself searches with its own senses, so there is lying there, but it is dosed and hidden.
DDA, or the opponent who lets you win
The next trick is more interesting and is once again built on knowing psychology, and people turn out to be very predictable, far more predictable than they think, especially when they try to act randomly, alternating, avoiding repeats, and still falling for the same patterns.
The classic way to exploit this is described in Ian Millington’s book on game AI and is called an N-gram predictor, where we remember the player’s last N (usually no more than 8) actions and count what he usually does after such a sequence.
int PredictNext(const History& h) {
for (int len = order; len >= 0; --len) {
auto ctx = h.Last(len);
if (auto counts = table.Find(ctx); counts && counts->Total() > 0)
return ArgMax(*counts); // the most frequent next move
}
return RandomMove();
}
In the example with three lanes, where a shooter tries to hit the player, a third-order n-gram very quickly starts guessing the moves, and the shooter at “full power” becomes unbearable. This is where dynamic difficulty adjustment, DDA, comes into play, which knows the same thing the predictor knows but deliberately shoots wide to keep the hit rate around a target value.
void AfterRound(bool playerWasHit) {
float error = RecentHitRate() - targetHitRate;
mercy = Clamp(mercy + error * gain, 0.0f, 1.0f);
}
int ChooseShot() {
int predicted = PredictNext(history);
if (Random01() < mercy)
return AnyLaneExcept(predicted); // I know where you're going, and I miss
return predicted;
}
Similar systems were hidden in a great many games, starting with the early Resident Evil games (quietly changing enemy damage, accuracy and aggression) depending on how you play, or Crash Bandicoot, which after several deaths in a row started cutting you some slack at the start of a level, or Mario Kart, which hands the players at the tail of the race better items than the leaders. Nobody tells the player about it, because the game would immediately be branded a cheat, and the very idea that “the game is letting you win” ruins the joy of victory. But beating an opponent who misses feels exactly the same as beating a sniper.
Spawning out of sight
This trick is really simple, but without it the sense of a coherent world falls apart, so when the game needs to create a new enemy and the honest implementation picks a random free point on the map, sometimes that point turns out to be right in front of the player’s eyes. Then the enemy simply appears out of thin air, and instead of a living world the player suddenly sees stage scenery assembling itself around him.
For this the game computes the player’s visibility polygon, that is, the area he can see taking walls into account, and places enemies only outside it, and it works the other way round too, if there are too many enemies and one has to go, you remove one the player can’t see, otherwise you get an unpleasant vanishing act. Left 4 Dead, by the way, does exactly this, and the special infected appear where the survivors aren’t looking, so it feels like they’ve just come round a corner.
Hitboxes
A hitbox is the shape with which a character collides with the world, and it almost never matches reality, and the most vivid example here is a bullet hell like Touhou, where the player’s ship is drawn the size of a decent coin while its hitbox is a few pixels in the centre, and the game even shows you that dot when you slow down. If you make the hitbox match the sprite, the player will keep dying from bullets that brushed the edge of a wing, and every such death will feel unfair, because “it didn’t even touch me”.
bool PlayerHit(const Bullet& b) {
return Distance(b.pos, player.pos) < coreRadius + b.radius; // not spriteRadius
}
bool Collect(const Pickup& p) {
return Distance(p.pos, player.pos) < spriteRadius + magnetBonus;
}
The damage hitbox is smaller than the sprite, while the pickup radius for coins and power-ups is bigger, and a player who flew a pixel away from a bullet and grabbed a coin he never actually reached feels like a dodging genius. Touhou even turned this into the graze mechanic, where bullets that whizz past by a hair earn you points.
Hit stop
Hit stop, also known as hitlag, is freezing the game for a few frames at the moment of impact. Say a sword hits an enemy, and for 50–100 milliseconds both the sword and the enemy stop, and then the animation carries on, and if you look frame by frame it seems as if the game “hung” for a second, but in motion this effect reads as resistance, as if the sword bit into something, and the blow feels heavier. Fighting games have used this trick for decades, and Masahiro Sakurai has talked a lot about how hitlag was turned into a mechanic of its own that grows with the strength of the hit.
void OnHit(Attacker& a, Target& t, float damage) {
t.hp -= damage;
float freeze = BaseHitStop + damage * HitStopPerDamage;
a.localTimeFrozen = freeze; // freeze only those involved in the hit
t.localTimeFrozen = freeze;
camera.Shake(0.15f);
t.Flash(Color::White, 0.06f);
}
void Update(Entity& e, float dt) {
if (e.localTimeFrozen > 0) { e.localTimeFrozen -= dt; return; }
e.Animate(dt);
}
On its own, hit stop changes neither the damage nor the length of a fight to any noticeable degree, and if a strike lasts eighteen frames, a four-or-five-frame freeze adds next to nothing to the time. But if you put two identical strikes side by side, one with the freeze and one without, most people will confidently say the first one is stronger, and on top of that people usually add camera shake, a white flash, knockback and particles, and the industry calls all of this together “juice”, even though it has no effect on damage whatsoever.
Feet and IK
And the last trick concerns something the player looks at more often than he thinks, the character’s feet. Physically almost any character in a game is a capsule, a vertical cylinder with rounded ends that slides through the world and never tilts. The walk animation was made by an animator on a flat floor, and as long as the character walks on a flat surface nobody cares, since everything works anyway, but the moment he steps onto stairs or a slope it turns out that one leg is hanging in the air and the other is sinking into the ground, because the capsule rests on the highest point beneath it and the animation has no idea that the floor has suddenly tilted.
Foot IK fixes this not by changing the physics but simply by swapping what the player sees. For each leg we find a point on the real ground, put the foot there and solve two-bone inverse kinematics, thigh and shin, with the law of cosines to get the knee position. And so that the lower foot can actually reach the ground, the pelvis drops a little.
void SolveLeg(Vec2 hip, Vec2 target, float l1, float l2, Vec2& knee) {
float d = min(Length(target - hip), l1 + l2 - eps);
float base = Angle(target - hip);
float off = acos((l1 * l1 + d * d - l2 * l2) / (2.0f * l1 * d));
knee = hip + FromAngle(base + off * bendSign) * l1; // knee forward
}
void UpdateFeet() {
for (Foot& f : feet) {
if (f.planted && DistanceBehindHip(f) > stride * 0.5f && !OtherFootStepping(f))
f.StepTo(GroundAt(hip.x + dir * stride * 0.5f)); // step only when needed
}
hip.y = LowestHipThatReaches(feet, idleHipHeight);
}
A separate point is that a foot standing on the ground must not slide, and until the character needs to take the next step (which is exactly why legs in a good implementation behave like legs and not like an animation) it stays pinned to a point. The capsule meanwhile keeps gliding forward, we have simply lied to the player about where the foot should really be right now.
Where the line is
If you put all these tricks together, you can see that they share one property, none of them makes the game unfair to the player, quite the opposite, almost all of them make it feel “more natural” from the player’s point of view. But the line is crossed where the lie starts working against the player, or when the player notices it, and the all-knowing guard gives himself away instantly, breaks the illusion of the world and cheapens the victory. Good lying in games is always invisible and always on the human’s side, we are used to thinking that a game is a system of rules and the player is the one who carries them out, but if you make everything honest and correct, the player will keep losing and complain that the game was unfair. As the immortal Lord Gaben used to say, if you want kitten pies... you’ll have to catch the ingredients yourself.
All articles