# Question
Title: What kinds of conflict-resolution can be fun beyond combat in an RPG?
As someone who grew up on the single-digit Final Fantasy games and AD&D, there are few ways of solving an rpg problem as fun as a fight. Different streams of accomplishment (object acquisition/crafting, skill trees, puzzles, player strategies, team combination/synergies, etc) all go into a few minutes of frenetic action, allowing for the feeling of accomplishment and progress via stat increases as the game progresses.

That said, we tend to characterize rpg players as murderhobos for good reason. When you incentivize killing things, it's not long before all problems start looking like something to hit with your sword. And when you're able to steal anything not nailed down, why not do it?

While other kinds of conflict-resolution can be fun when in their element (farm/ Civ/Sim games for the sense of building something, spy/ninja/assassin games for deftness and exploiting situations, social games for roleplaying a character or out-thinking the other guy), they're often not fun outside their very narrow venue. And because we're limited to conversation with a computer (at least in single-player games), social games can't even explore the whole of their venue.

I'm racking my brain trying to figure out how to properly gamify the societal ideals of don't-kill, don't-steal in such a way that attacking or stealing becomes a conscious choice, not just a default means of action...but at the same time keep the same diversity of fun-inputs that fighting/stealing games have. Most games just code in consequences: the town guards are sent after you and/or some faction is less willing to deal with you. But this feels unnatural, and only invites further gaming of the system, producing better murderhobos at the end.

My reason for doing so? The main theme of my game is a heavily philosophical one(think a halfway-understandable Xenosaga) on how morality might play out in the post-post apocalypse. While killing and stealing would be a part of that, I feel that our natural tendency as gamers wouldn't allow this question to play out 'fairly'.

Any idea on how to put killing and stealing on a truly equal playing field with other forms of conflict resolution?

# Answer
> 16 votes
Why don't we constantly steal and murder in the real world?

1. We have empathy with other people and don't want them to feel bad.
2. We are afraid of getting caught and punished.

Why do games often fail to convey these hinderances to committing crimes?

## Creating empathy

There are actually quite a lot of games which manage to create empathy for NPCs, but usually only for a sub-class of the NPCs in the game. Most games clearly separate the world population into those NPCs you can murder and steal from and those you can not.

In the Elder Scrolls series, for example, the player will get punished if they commit crimes against NPCs in a city (and get caught). This punishment might be a game mechanic (like guards hunting down the player) or a meta-mechanic (quests become unavailable when the player kills key NPCs). So most players will only do this when they want to experience the fantasy of playing an immoral thief and/or assassin (which isn't wrong per-se as long as the game handles this well).

But there are no repercussions whatsoever for going to a bandit camp, killing everyone there and stealing all their possessions. Even players trying to roleplay a "good" character will do this, because the game communicates to them that this is something they are supposed to do. Is this a moral thing to do? No, most societies would prefer to catch those bandits alive and put them on trial for their crimes. And even if they approve this kind of vigilante justice, they would at least expect that the things they have stolen get returned to the rightful owners. But most games do not care about this. Bandits are just moving targets to hit and their loot is the reward for doing this well.

If you want to avoid this, do not have such a class hierarchy of humanized NPCs and dehumanized NPCs. Make sure that criminals are people too. Give them names, backstories, friends and families. Also give the player some other meaningful ways to interact with them besides fighting them.

## Fear of punishment

Your conscience is the voice in your head constantly whispering to you that someone might find out what you have done.

In order to invoke this feeling in your game, you need to make sure that committing crimes against people is handled in a plausible way. Many games will give you an immediate feedback if you get caught. But that's not how crime works in the real world. If I steal something from a friend's house, they might not catch me immediately. But over time they might notice that their stuff goes missing everytime I was at their place. They might call me out on this, but I will deny. Then they see their stuff in my possession and won't want to be my friends anymore. Then they murder me. It might take years until the police finds my body and locks up the murderers. This delayed form of punishment is one important reason why we are afraid of committing crimes in the real world.

Also remember the last section: Criminals are people, too. When you harm a criminal, then lawful people might forgive you or even approve. But criminals also have friends and families... and mob bosses who dislike people who interfere with their business. The punishment for harming a criminal might be even harsher than anything you might expect from a court of law.

Most games do not simulate this because it can become quite complex.

One problem is that it is very difficult to communicate to the player which acts exactly lead to bad consequences at a later point in the game. When a game punishes the player but they have no idea what they did wrong, then the player can't learn from this experience. So you should invest quite a lot of resources into communicating this well. One way I could think of would be to replay a flashback of the player committing the crime to remind them of what exactly they did wrong.

This whole mechanic goes against the usual expectations of the player. So you need to teach the player early that their actions have delayed consequences. Tempting the player to commit a petty crime and then calling them out for it a few minutes later should be part of your tutorial.

Another problem is that when you allow the player to antagonize every single NPC in the game, then they might break the plot of your game. This is why I would rather recommend to experiment with this in a game where the plot isn't pre-written but rather created through emergent gameplay.

# Answer
> 9 votes
The core of most RPGs tend to be around their combat system, items increase your ability to fight, progress depends on winning fight, classes and levels focus on combat ability.

But the mechanics of turns and use of items and abilities don't need to be only useful in a system to represent an abstraction of combat, similar mechanics could be used to apply to dealing with characters in other ways,

Rather then dialog trees, use the mechanics of combat in RPGs.

Example :

A guard blocks the entrance to the castle, the party engages the guard, in conversation, he has high resistance to intimidation and medium resistance to persuasion and deception

The party members can have turns to use abilities that can affect different 'health' bars representing how close they are to being persuaded/intimidated/deceived/cheered up;

Abilities could be depend on non combat classes a \[Deceptive\] character could use 'Confusing' to do deceptive damage and make the guard miss have next turn encourage your party rather then its intended result.

The guard could have 'Threaten' which intimidates your party, and could result in losing the encounter. Special abilities could include calling in more guards.

There could be healers ('Reassure') buffers, and equipment and stats that buff your characters, a large strong character might have high intimidate, and stacking it with gear like could be used to increase. (Could be easily confused by deceptive characters)

Collecting items, giving gifts that have high persuasion (or 'knowledge items' that work on specific characters') like finding out a characters secret and using it in a fight as +X intimidate).. or using gold to bribe

All of this would allow non combat situations to have the addictive elements of an RPG (leveling, progression, strategy, collecting)

Also unlike combat there is a bit more room for different outcomes,

If you're party loses to a guard by intimidating it could lead to them being imprisoned and having to escape;

If they intimidate the guard they might be able to get in the main gate, but have to deal with different encounters then a persuasion might (an escort to another npc) and the story branches are determined by mechanical results

# Answer
> 8 votes
### Rewards

One approach might be to make the NPCs themselves, and their support, resources worth acquiring. Design the incentives and core resources around things that only other characters in the game world can provide. Focus on mechanics that require the NPC to *remain* alive and friendly towards the player.

* Perhaps the player has an agenda they need to push, a religion or philosophy they promote, or they're just looking to become famous. Every friend or follower gained increases their influence, which is tied to the main objective(s) and/or character progression.
* If the game allows for it, let most NPCs be recruited as followers, temporarily or permanently. Balance the difficulty around the player having followers.
* Let friendly NPCs provide resources or items that are otherwise scarce, and need to be "refilled". Depending on your settings that might be necessities like food and shelter, healing potions, ammunition etc. Make reputation a resource the player can spend on this *or* resrict access to a *positive* reputation (as opposed to "they didn't hurt me yet so I guess they're alright.")
* Tie experience or skill upgrades to bits of information obtained (primarily) from NPCs. Maybe a lot of knowledge has been lost in the apocalypse and most people only know fragments. For example, each NPC could have 2-3 skills they could increase by one point, or a single magic spell they know. If you want to master a skill, you'll have to persuade a lot of people to teach you.

### Creative interaction

Some open world RPGs allow you to invest in NPCs to improve their services or make them stronger followers, but that's usually reserved for e.g. store owners or designated party members. You could allow the player to shape most NPCs or factions by "giving back". Allow them to build or name things, give equipment to NPCs, claim areas for them. Most players will care more about a town they helped design than one they're just passing through, and later on, when the villain convinces everyone they're a criminal, they might be more inclined to persuade the guards to let them speak to the council and prove their innocence than to burn it all to the ground.

### It's not necessarily either-or

Many games allow for social encounters to progress into combat ("The bandits seem unimpressed, they draw their weapons") but not the other way around. Allow the bandit leader to negotiate their surrender after the player kicked a few asses, and give a substantial reward for capturing criminals. Give the player the same option if they end up in a tough spot. Make the difficulty of a fight something that's hard to assess at a glance, but give hints in conversations.

### Tweaks for "social combat" systems

Physical combat in most games has a few aspects, for example terrain and positioning, that are easy to intuitively understand and can be used without much effort to add depth to a combat system. These aspects are lost if you just copy and "reskin" the same system for social encounters, and technology isn't yet at the level where we can randomly generate compelling dialog (while generating a tilemap is easy). Most (video) games that use this kind of mechanic handle it in a very abstract and often repetitive way.

I'd recommend looking at **card games** for elements that add a degree of guessing and puzzle solving to your system, or even base the system entirely on a card game (with or without actually rendering/refering to any cards).

Classical card games combine a tweakable randomness with the ability to "out-think" your opponent and can be complex enough to be engaging to play against an AI.

TCG style systems allow the player to collect "cards" (secrets, skills, information, a specific reputation) and use them in combination for synergy effects. Perhaps executing the thief, bringing her to the authorities or letting her go will each give you a different, unique card that can be played later when you encounter the thieves' guild?

# Answer
> 3 votes
I'll go into a few details to supplement the other answers.

**Don't let NPCs be dehumanised**

Games aren't made in a vacuum. Through our experience with the medium we have been trained to expect certain things, one of them being that certain NPCs are important while others are nameless background characters. We assume that a named NPC has a role in the story or a quest while someone just called "guard" or "merchant" is simply a hull for their function and can otherwise be treated with impunity (Philipp said as much).

If you want the player to treat NPCs more like people, one possibility is to subvert this expectation - either by giving every NPC a name, regardless of how irrelevant they are or - possibly more powerfully - naming every NPC after their appearance until the player character learns their name, thus suggesting that behind everyone's apparent meaninglessness is a person.

**Let actions have consequences not just for the player**

Everyone knows that when you're caught committing a crime the guards will be after you, but little consideration is often given to the victim. If you break into someone's house unnoticed and rob them blind, they'll now be poor, they may become homeless and starve along with their families. If you kill someone and nobody catches you, their family will grieve and if that person was their breadwinner, they will fall into poverty again. This can have mechanical consequences (the merchant is bankrupt and there's no trader for you to sell to now), but the surprise of a player returning to the city and finding the house empty and the family begging in the streets may have the greater emotional impact.

Keep in mind that this requires a significant investment in terms of development. I would suggest simplifying the reaction as much as possible by creating a few trigger conditions (death of X, net value below Y) and a few consequences (grieving dialogue, possibly just with the names adjusted, new NPC locations with begging dialogue) and try to apply them as broadly as possible. A player who tries to play around with the system may notice that the depth is limited, but the reaction you strive for is for the player to be shocked, feel sorry and not do it again, so the majority shouldn't have this experience.

One game to maybe have a look at for this is This War of Mine.

**Create fitting mechanics for the philosophical underpinnings of conflict resolution methods**

That's a mouthful, but anyway: the others have already made the point that every method of conflict resolution needs to be mechanically interesting in order to be worth using. Games that have a deep and visceral combat system encourage the player to use it. I would go a step further: try to design the mechanics of each method to make the player feel a certain way according to your message.

For example: If you want your players to try and understand the NPCs in order to convince them in dialogue, take a look at the social bossfights in Deus Ex: Human Revolution. You have a few character types/traits that influence how characters react to certain approaches. A proud character will react positively to flattery, while a fearful one will dismiss it, but can easily be pressured. Essentially what you're creating here is a system similar to turn-based combat with elemental weaknesses and resistances, but you need to actually listen to the characters in order to find out what they're susceptible to, humanising the characters in the process. Take care to give most characters more than one trait, otherwise it becomes formulaic.

If you want to expand on such a system you can introduce more complexity for important NPCs by giving them hobbies ("Did you paint that waterfall in the dining hall? That's pretty amazing!"), relationships ("I know this is a lot to ask Mr. Bert, but Ernie told me I could trust you with this.") and desires ("I know it's a risky proposition, but if you want to win Princess Buttercup's hand in marriage you'll need to convince her father and I'm told he's a big fan of pirate novels"). This further encourages not just talking to the person in question but to explore their social environment.

Similarly, if you want to communicate that solving problems with violence is barbaric and cruel, design your combat system accordingly. Have combat itself be frantic and stressful through high speed and high lethality. Let weak enemies try to run away and miserably beg for mercy. Have injured opponents bleed to death in whimpering agony or even beg for a finishing blow to not lie dying for hours and days (I think there were a few FPS games about the world wars that tried to depict how horrifying these injuries can be). Then reference the point about consequences above for further fallout.

This can still lead to a kind of power fantasy for the player, but one that is stained and dirty. The player may enjoy it in the moment, but they should feel guilty afterwards as if coming from an eating binge and feeling the nausea or having masturbated to some really effed up porn and wondering where their life went (no kink-shaming intended).

**Offering options takes lots of work**

An unfortunate reality of game development is that resources are limited. If you want your player to be able to talk their way through every quest, fight their way through every quest, have a few solutions for stealth and crafting as well and maybe magic on top you'll quickly run out of time and money. Not every method will work for every quest (some people just won't listen), but even then you should probably decide on a few main methods (e.g. combat and conversation) and use the others as supplements (e.g. stealth to find information to use in conversation). In the end a game is supposed to induce a certain experience in the player and that experience should determine the core concepts and mechanics and the corners that can't be cut.

# Answer
> 2 votes
## Objectives.

If what you have is a mission you have to accomplish then defeating enemies might not be an advantage, it might even be a cost of resources.

Combat encounters can be about suppressing the enemy enough to buy time for your objective.

In Mordheim: City of the Damned the whole game is built around getting resources, you lose the game if you don't get them. It's less about defeating the enemy team and more about achieving your objective as efficiently as possible.

I am thinking along the lines of a game like Silent Storm where you can infiltrate bases stealthily, cause distractions with your team as well as investigate clues and deal with NPCs.

You can also have levels of hostility and access restriction as well as neutral hubs you can work with like in a Deus Ex game. This will give you exploration and NPC dialog alternatives to your mission objectives you can use.

NPCs are poorly underused in most games but in a game like this it can have an essential role in reaching your objectives. It can serve as functions from which you can manipulate the game world and open new paths and add new variables to give rise to new opportunities to exploit.

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


# Question
Title: How can procedural generation be used to support exploration mechanics?
It would seem that procedural generation would be a great tool for open adventure games, since it would provide an almost limitless world. However, I notice most successful procedural generation games are of a totally different genre. The only game I can think of that uses procedural generation for exploration specifically is No Man's Sky, but it failed to meet expectations, probably in part because the procedural content, while vast, did not necessarily add as much value to the exploration game mechanics as people thought it would.

From attempts making procedural generation games and from what I see in other games, I see three problems hindering procedural generation in adventure games, and I cannot see any solutions:

1. **Procedural terrain may be straightforward, but procedural storytelling is not**. I tried both. A few simple rules can make something that resembles a mountain or a city, but it is hard to make a game around it unless you have some sort of quest. It is hard to design a quest, though, unless you have a map to work with. How can you make a quest to find a place that might not exist?
2. **Procedural terrain provides scale without density**. Sure, a procedural mountain might have all the textures and ridges to give it the complexity of a real mountain, but where's the fun it that unless there are lots of things to do on that mountain? Much of the strength of procedural generation is that it is easy to make something massive. If you make a world too massive without putting enough new things to experience in that world, it will just feel empty.
3. **The experience is not consistent**. Much of the enjoyment from adventure games is reaching "that one part." Walkthroughs, tutorials, and wikis usually rely on the fact that players are all playing the same game, taking place in the same world. It is more difficult sharing your excitement for a game with others if the experience is so personalized. Imagine sharing a meme about the game if no other player in the world played a game with the same locations, characters, or creatures.

Keeping these problems, and perhaps others you can think of in mind, is there still a way to incorporate procedural generation into a game without ruining exploration? Maybe some certain limited procedural techniques that an adventure game could benefit from but not get in the way of a story?

# Answer
Procedural generation of *environment* is something which game designers experiment with for decades. There were some great steps forward in this area. Our toolbox of stock techniques grew a lot in the past.

But not so with procedural *storytelling*. This is an area which is still in a quite basic stage.

One approach of procedural storytelling is having a list of prescripted quest templates and spread them all over the procedurally generated world. Those templates usually have a number of variables which are filled in randomly from predefined lists or appropriate objects in the environment. Usually the player will soon notice these recurring patterns. At that moment the illusion of a living world breaks apart and all immersion is gone.

Another approach is to rely on emergent gameplay. Instead of pre-scripting stories, you design AI actors driven entirely by behavior rules. Those rules control all interactions with the environment, with other AI actors and with the player. They hope that this will lead to plausible social behavior which results in interesting stories emerging on their own. The main problem with this approach is that it is very hard to control and balance. The most interesting stories might take place in ways that the player does not even notice them. It can be very hard to get these AI actors to perform these interactions in the way that it makes for the most interesting gameplay experience for the player.

One game which does this a lot is Dwarf Fortress. Does it have interesting memes for the community to talk about? You bet it has! Interestingly, most of these were born from glitches and quirks of the emergent gameplay systems. Among these are the horror of killer-carps (AI-controlled fish which were far too aggressive and overpowered in early versions), Catplosions (population explosion of cats which was hard to prevent due to dwarfs being very attached to them) or the mantra "Losing is Fun!" (a way to cope with the frustration which can result from the emergent gameplay generating unwinnable situations). So your fear that players won't have anything to talk about when everyone's experience is different is quite unjustified. To the contrary: Emergent gameplay gives the players even more to talk about, because they want to share the unique and interesting stories they experienced.
> 3 votes

# Answer
I think a good example of a procedural "adventure" game (by some definition), one where the procedural content promotes exploration, is Terraria. I think it handles many of the pain points that you outline quite effectively:

> Procedural terrain may be straightforward, but procedural storytelling is not.

"Storytelling"? Terraria doesn't really do that. But it does have progression and de-facto quests (I'm not talking about fishing quests). It accomplishes this through a combination of factors.

Progression is not usually based on getting to a single, specific location. Terraria is a game about stuff, so progression is based on *getting stuff*: harvesting resources, opening chests, killing monsters for loot. Of course, resources, chests and monsters are all based on locations, but this is done in a very broad way. There are *large* biomes, and throughout these biomes, you'll find whatever resources are specific to them, randomly placed throughout.

There are elements of progression that are based on specific locations. But those are always generated in "specific" locations. Floating islands are always floating in the sky. The Dungeon is accessible from the surface on one side of the world, and the Jungle is on the other. Corruption/Crimson areas are many and it's pretty much impossible to miss them (unless the RNG was especially bad to you).

The least consistent place in Terraria that is important for progression is probably the Jungle Temple. And even that is not something you're likely to miss.

> Procedural terrain provides scale without density.

That all depends on what you generate. Earlier versions of Terraria had problems with this. The underground areas could become very "samey".

Terraria, especially 1.2 and 1.3, solved this problem, making them incredibly dense with stuff. There's always something new to stumble across: ruined houses with chests, icy caverns, abandoned railroad tracks, underground lakes, underground desert, marble caverns, etc.

Density is created in Terraria through *diversity*. Instead of repeating the same content over and over, you repeat *new* contents. You have enough variations of content that the player doesn't get too bored.

What Terraria in particular does is that it builds the basic terrain of the world. Then the world engine goes in and randomly puts things in various places. A marble cavern here, a ruined house there, a shrine over there. The icy caverns go over there, a big desert sits here. The system is designed to be able to slot these features in *anywhere* in the world. That ensures that there is enough density of them that you won't get bored.

Now, the world engine isn't stupid. It biases certain features based on depth or distance from the center of the world (where you first spawn). But the main goal is to make sure that the game is filled with lots and lots of new stuff.

It may not make much sense why there's a ruined house perched above a lake of lava, but the player will appreciate that it's not just another cave.

However, diversity can only be achieved if the experience of play allows it. Terraria is an open-world game in which you can build lots of stuff. But it also has an action-oriented combat system that offers many dimensions of possible play. There are four "classes" (defined by what bonuses the armor you're currently wearing gives you): melee, ranged, magic, and summon. And within most of these classes, there is a large diversity of play options.

Ranged characters have a number of weapon types, but they also need to deal with the fact that they can't take a lot of hits, so they need mobility items. Melee characters need items that improve their ability to take hits. Magic characters need items that deal with mana regeneration. And so forth.

There are two important elements here: the diversity of play experience, and the *lack* of an enforced class system. The latter is really important, since it means that if you find a good melee weapon or a good ranged weapon, you can still use it even if you're not in ranged or melee armor. You may not be as effective as a dedicated build, but it's not *useless* to you. You can always try it out and see if you like it.

Plus, this means a "class" change is just an armor-switch away. If you get a good melee weapon, you can probably craft some melee armor and try out a melee build. If it doesn't work out, switch back to your ranger.

In this way, Terraria creates a game system where the diversity of exploration encourages a diversity of play, since there are a lot of options in the play experience. And vice-versa: diversity of play is what makes the diversity of exploration possible, since it allows the creation of a multitude of items.

> The experience is not consistent.

This is where diversity and scale meet. Terraria achieves a surprising level of consistency in its overall play experience. While each individual world is different, the scale and scope of play means that you're unlikely to come up short on something important.

You're going to find enough Gold to make Gold Armor, if that's what you're interested in. You're going to find enough cobwebs to make spellcaster robes, if that's what you're interested in. Etc. All of the essential stuff is available in sufficient quantity. And thanks to the diversity of stuff, if you don't find one particular kind of thing, you probably ran across something similar to it.

Furthermore, there are a number of checkpoints you have to cross in order to move to another sequence of progressions. Surviving the Underworld is extremely difficult to do unless you have access to the Jungle/Dungeon/EoW/BoC-teir of equipment. You cannot shift your world to Hardmode unless you fight a boss in the Underworld. You cannot harvest Chlorophyte from the Jungle until you've killed all three of the Mechanical Bosses. And so forth.

Because of these checkpoints, you're encouraged to gather more resources until you can pass them. Which ensures that you have the chance to run across lots of various loot, thus ensuring a relatively consistent power level.

Now, that doesn't mean that inconsistency doesn't happen. Bad world creation can put you in a tight spot sometimes, or maybe you find yourself in a boring patch of world. But this is quite rare, thanks to Terraria's massive diversity.

The worst the world creator will do to you is feed you lots of the *same* resource.
> 5 votes

# Answer
As you said, procedual generation is a good tool to create open world's with a lot of possibilities. The obvious downside is, that it is hard to balance in many regards: either it feels to empty or to cramped, to "over the top" or dull...

Good adventure games live by the atmosphere, especially those with a big open world. My favorites in this regard are Gothic 1 and 2. You could never recreate this atmosphere with just procedual generated environment, I guess.

The only way to work on your points is somehow circumvent them.

> Procedural terrain may be straightforward, but procedural storytelling is not.

You could go the Minecraft way of creating biome. Maybe a city biome, a hill biome, a desert biome. Then fill the city biome with a "pre-designed" city structure, add important places, then add quests and bind them to a hill biome nearby, connect those via streets and add the needed dungeon structures to the hill biome. This way you can add other random structures around the biome, maybe with possible loot, to encourage more exploration. Technically it's still procedually generated, but you need a lot of work for the structures, quests and the assertion that all needed structures in every needed biome is generated. Starbound does something similar, where you have to gather resources from other planets, or it creates an instance of a dungeon to explore.

> Procedural terrain provides scale without density.

Imo Skyrim got a lot of "empty" places. Just walking around from town to town took a long time, but you always had something to do or look at. Beautiful flowers, mountains or epic buildings, then gathering stuff along the road, kill the wildlife or discover another empty hut. Yes, Skyrims world was designed, but with enough content you can encourage players to walk of the tracks, just with randomly placed structures, enemies and just stuff. Again, I think it's hard to balance, but I would prefer cramped world's over empty world's, at least partially.

This is actually what I think No Man's Sky did wrong. I have not played it, but watching it was boring. Walking around on the planet, everything seems lifeless. You had goofy animals walking around, maybe 4 of the same kind, some resources, rarely some technology or alien words. That was it. No really big structures, big groups of animals and no interactions between them.

> The experience is not consistent.

Yes, and that is most likely unfixable. As I said, atmosphere is what carries an adventure game. On the other hand, players love to enjoy things that are unique to them. Maybe one player has to fight a boss in a room with a complicated layout or other enemies from a nearby dungeon can rush in, while another player was able to cheese the shit out of this exact same boss. These might be things players want to share or brag about. It might also encourage creativity.
> 2 votes

# Answer
You misunderstood procedural generation. It's not about slapping together a noise and a mesh generator. Most successful procedurally generated games used some sort of pre-designed architecture.

Let's look at some examples. First of all, Spelunky. It's praised by almost everyone and it used procedural generation. It worked with a 4\*4 map, it chose a path first from top to bottom, then filled them with premade rooms and made small changes to them. This made the game feel fresh and fair every time, but it was always completeable.

Another example is Cube World. It mainly used a (low frequency) noise generator, but it also added pre-defined features to the world, such as huge monolith like cliffs and variois buildings.

If you want a game with a story that used procedural generation, then just look at the first four Elder Scrolls games, especially the first two, Arena and Daggerfall. The designers created every important dungeon by hand, but the other dungeons were randomly generated.

Yes, the experience won't be consistent, but it isn't consistent in other games either. Most games will have better and worse moments.
> 0 votes

# Answer
The complexity of managing procedural world generation and play-balancing can outweigh the benefits. The major early benefit to proc gen was to save developer time over the long haul; only in recent years has it come to be lauded for attributes outside of that (though Elite and Captive were great early examples of achievable playability, even they were not purely procedural).

The best way to manage complexity is to build tools to do that for you. We currently spend a lot of time manually fine-tuning parameters to allow us to build the procedural worlds we want. New biome, new parameters. New quest/story type, new parameters. What becomes clear only after a much longer time of building procedural worlds, are the patterns behind these processes which then allow us to build tools to amplify our work rate. (This is true of any area of development.)

Since we all develop differently... I'd encourage you to try it the manual way enough times that those patterns start emerging for you, for the problems *you* often have to solve. Once they do, you'll be on the road to building tools to support that work. Really, it's fairly bleeding edge knowledge generation.

Those parameters you mention, scale without density, inconsistent experience, can all be addressed by proper (runtime or compile time) automated tuners. The complexities of story management can be handled by a combination of a sound knowledge of graph theory and narrative theory.
> 0 votes

# Answer
> Procedural terrain may be straightforward, but procedural storytelling is not.

Procedural terrain obviously gives you terrain to work with. This is not bad and it's not the only thing you can generate. You can generate dungeons ala Roguelikes and you can generate Cities if you use rules similar to City Building games like Anno or Impressions Games.

But terrain is not gameplay, so you need to add the proper games.

It's actually not that hard to generate a dynamic living world.

X3 Albion/Terran is the best example of this. It has trading gameplay with even building stations to get resources and create products, it has a space combat game where the player pew pews with pirates and it has a bit of a Strategy 4X flair with faction conflicts and bigger fleet battles that works pretty well with its economy.

> How can you make a quest to find a place that might not exist?

Procedural generation can give categorized data that you can use. When it creates a cave or a mountain it can tag that area as such. This could be used in a quest to populate that area with a monster. This is how Dwarf Fortress Adventure mode generates its quests I believe. In a Minecraft like jungle biome you can generate a special herb used in a quest. In an ancient ruin dungeon you can have a special artifact for a quest.

> Procedural terrain provides scale without density.

If you want to go beyond procedural generation then you are looking at **user generation**.

Imagine a world where players can create their own personal empire with Factorio style in depth development and logistics as well as 4X style research.

Now imagine all players uploading their empires onto a shared world that they can explore.

People can explore the ruins of player empires and their technology.

People can even fight with their empire against a AI controlled uploaded player empire.

### A True Exploration Game is User Generated.
> 0 votes

---
Tags: game-mechanics, procedural-generation, adventure-games
---


# Question
Title: What are common methods for organizing game objects?
I'm in the early stages of developing a game in C++.

As of currently, I've defined a base GameObject class that is the base class for any interactive item in my map (e.g. enemies, loot, projectiles, etc.). When these items are created, I want to give them to an ObjectManager class. The ObjectManager class is responsible for iterating over each object and calling abstract methods like "update" or "render".

Originally, I planned on storing all objects (or references to the objects) in a single container. I would then iterate over this container.

However, I'm starting to have second thoughts about whether or not this is a good idea. I've come up with two reasons why this might be a bad idea:

1.) Regarding object collision, it makes sense to only perform calculations between certain objects on whether or not they've collided. For example, I would want to determine if the main character has collided with a loot item. However, I would never to want to calculate if a loot item has collided with another loot item (at least in my case).

2.) Object pools. Referencing this article, it has come to my attention that continuously allocating/de-allocating memory is expensive. Because of this, it is a common technique to use object pools that request memory upfront and then manage that memory without actually deleting it. One of the comments made in the article is that the objects that exist within the pool must all be the same size (or each pool slot must be big enough to accommodate the largest object).

Both of these examples make me think having a single container that houses all GameObject is a bad idea.

Instead, it seems like it would make more sense to have different containers for each type GameObject type. For example, it would make sense to have a container for enemies, loot, projectiles, etc. This way I would have more control in iterating/comparing only on objects that make sense for certain object types (e.g. don't try to calculate collisions between two loot items).

The problem I'm facing however is that I don't know how to break up these containers. Should all projectiles go in a single container? However, what if I later decide to create a "fire projectile" that performs some kind of "burn" logic. Would this require a new container to then to iterate over all fire projectiles? Essentially, I don't know how granular my containers should be.

I haven't come across any reference material on this topic. Any advice would be appreciated.

# Answer
> The problem I'm facing however is that I don't know how to break up these containers. Should all projectiles go in a single container? However, what if I later decide to create a "fire projectile" that performs some kind of "burn" logic. Would this require a new container to then to iterate over all fire projectiles? Essentially, I don't know how granular my containers should be.

You don't know yet because you are still in the early stage of developing your game. What you are doing right now is "premature optimization". You are trying to guess where the performance bottlenecks of your game could be and fix them before they become a problem. But you can not know yet if those guesses are correct. You might currently spend hours on overengineering a solution which will make further development much more complicated and could in the end just save you \<1% of CPU time. Or even none at all because after playtesting you realize that fire projectiles don't really fit into your game and you remove the whole game mechanic.

It is usually a far better strategy to start with a simple solution first, measure the FPS, use a profiler to find the *true* performance eaters in your code and fix those.

That being said, it can be a good performance optimization to have an object pool in form of an array which keeps the actual data and then a bunch of secondary data structures which keep pointers to that data. If you notice that you spend a lot of CPU time filtering objects by a specific property, create another vector of pointers to game objects which have that property. If you spend a lot of CPU time looking for objects in a specific area, create a spatial hash, Quadtree or similar data structure organized by location.

The cost for this is that all these secondary data structures need to be kept up to date. Not only does this require CPU cycles. You can also encounter a lot of weird bugs when you forget to do that.

Other architectural pattern you might want to look into are the entity - component - system pattern and data oriented design. The idea is that you don't have an object pool for all game objects but in fact a separate object pool for each *component* of a game object, while complete game objects are composites of different components. But this would be a very different approach than your current object-oriented design.

I am looking forward to playing your game.
> 2 votes

# Answer
The simplest is a std::vector for each type:

```
std::vector<Projectile> bullets;
std::vector<ItemEntity> loot;
std::vector<CharEntity> mobs;
//...

```

If you reserve the upper limit up front then you won't have to worry about reallocations mid frame. If you replace the allocator you can make it assert should it attempt to anyway.

You can remove an object from the vector quickly by swap-with-back-and-pop\_back or add an `alive` flag and reuse a pointer-sized chunk for a free list. Projectiles would use the swap method while smarter objects that need referential stability (the enemies) would use the freelist.

You can often avoid creating a new object type by adding a variable or flag to mark it as one. For example for the fire projectile you would add an effect enum that can be set to NONE, BURN, POISON, MIND\_CONTROL, etc. and on collision you would then apply the correct effect with a switch statement.
> 0 votes

---
Tags: gameobject
---


title: Designing a trade / market system

text:
# Question
Title: Designing a trade / market system
I'm working on an idea for a trading game. Players would be traders buying in place A and selling in place B, hopefully for a profit.

I want prices to be dynamic, based on demand and supply. So if place A produces less food than it consumes, prices for food would he high and getting higher the closer they get to running out, while in place B, which has much more production than supply, prices would be near the production cost (minimum price). But if someone buys up a lot of the supply in B, prices would rise, and if someone sells a lot in place A, prices would drop.

Obviously, there are many ways to game such a system if it's not well-designed. The most easy is to empty the market, wait for the price to adjust, then sell everything back.

How could I design this system? I mean the actual math and functions, not philosophical musings. I searched a lot and haven't found anything specific.

I found this question but it and its answers are a lot more specific to the specific formula the guy uses in his game. I'm looking for a more generic approach (I want different price elasticity for different goods, maybe non-linear price curves, etc.)

# Answer
A far simpler, easier to implement and easier to balance solution than the other one I proposed before (although with less gameplay depth):

* Have a function `NpcSellPrice(stock)` for each commodity where `stock` represents how many units the NPC currently owns. Any implementation would do as long as more stock means that the NPC sells at a lower price. It doesn't need to be realistic. Design it so it fits your overall gameplay balance.
* Implement the formula `NpcBuyPrice(stock)` as `NpcSellPrice(stock + 1)` so the NPC will always buy for the price it would sell for if it had one more unit of stock.
* Only allow the player to trade in increments of one unit at a time and recalculate the price after each traded unit (UI-wise you can implement this with a button which trades as long as the user holds it).

That way prices will increase and decrease when the player buys and sells commodities, but when they trade it back they will end up with exactly the same amount of money they had before. The only way for the player to make a profit is if the stock decreases for some other reason than player trading while the player is holding on to commodities. For example, by traveling to a different NPC with a smaller stock.

When the player is the only active force on the market, the player can only make money by evening out the stocks of all NPC traders in the game. After all traders have the same amount of stock, there is no profit to be made anymore. To allow the player to constantly make profit, you need to introduce some entropy into the market.

An easy way to do that is by making some NPC's "producers" whose stock constantly increases over time (up to a cap) and other NPC's "consumers" whose stock constantly decreases. The player could then make money by buying at producers and selling at consumers. For example, a farmer would be a producer of grain while the nearby bakery would be a consumer. The player could make profit by buying at the farmer and selling at the bakery.
> 8 votes

# Answer
> The most easy is to empty the market, wait for the price to adjust, then sell everything back.

This implies that if the price for a unit of `coal` while there is 100 units left in stock is at 50 gold, and you purchase the whole lot of 100 units, you'll pay `100 * 50 = 5000`.

That's not the correct way to look at it.

Games such as *Port Royale 3* have this as a core mechanic: the price is adjusted *per unit*, not as a whole.

This means that the first unit you'll buy when there are 100 left in stock will be 50, but then, it will reduce the amount of what there is left in stock to 49. The price will increase to 51 for that next unit, and so on, until it reaches the maximum price.

Here is an example written in pseudocode.

With these input variables:

```
maxStockThreshold      // Amount of unit in stock equal to and above which the trade price
                       // remains constant, no matter how many units there are.
maxStockThresholdPrice // Price of the items when there are maxStockThreshold or more in
                       // trade station. The price should be discouraginly low. Incentive
                       // to buy from station.
minStockThreshold      // Same for the maxStockThreshold, but for the minimum
minStockThresholdPrice // Prices should be high: incentive to sell to the trade station.
amountInStock          // Amount currently in stock in the trade station.

```

In these methods:

```
getTradePriceForOne( amountInStock, maxStockThreshold, maxStockThresholdPrice,
                                    minStockThreshold, minStockThresholdPrice )
  if amountInStock >= maxStockThreshold
    return maxStockThresholdPrice
  if amountInStock <= minStockThreshold
    return minStockThresholdPrice

  // Otherwise, lerp, kiss
  stockThresholdRatio = amountInStock / (maxStockThreshold - minStockThreshold)
  return minStockThresholdPrice
         + stockThresholdRatio * (maxStockThresholdPrice - minStockThresholdPrice)

// amountDesired: positive -> buying from stock in trade station
//                negative -> selling to trade station
// return: positive -> the cost to buy the items
//         negative -> the amount offered when selling to trade station
getTradePriceForMany( amountDesired, amountInStock,
                      maxStockThreshold, maxStockThresholdPrice,
                      minStockThreshold, minStockThresholdPrice )
  amountDesiredLeft = amountDesired
  amountInStockLeft = amountInStock
  cost = 0
  while( amountDesiredLeft != )
    thisUnitPrice = getTradePriceForOne( amountInStockLeft,
      maxStockThreshold, maxStockThresholdPrice,
      minStockThreshold, minStockThresholdPrice )
    if amountDesiredLeft > 0
      cost += thisUnitPrice
      amountInStockLeft--
      amountDesiredLeft--
    else
      cost -= thisUnitPrice
      amountInStockLeft++
      amountDesiredLeft++

```

With that, the player can't buy everything and wait for the price to adjust because the market adjusts *while he buys/sells*.

Sometimes, while making a game, you have to abstract a bit of realism and twist it a bit to make it fun and expected. These rules are very stiff, but it makes the expectations predictable for the players, which is what you want.
> 6 votes

# Answer
You could model your ingame market to work in the same way real-world stock and commodity exchanges work: With actors placing orders.

* Consumers place buy-orders, reading "I buy X units of food for Y credits each"
* Suppliers place sell-orders, reading "I sell X units of food for Y credits each"
* The system automatically joins orders with each other where buy-price \>= sell-price and resolves them.

These consumers and suppliers can be either AI actors or players. The published "market price" is the current average at which orders get resolved. But it is no guarantee that the player can actually buy or sell at that price, because their orders have to go through the same system. AI actors should experiment by first placing orders slightly worse than market price, and if their orders don't get resolved, make better offers. That makes sure that the market prices stay dynamic.

The quantities at which AI consumers place their orders should be influenced by price elasticity of demand. That means that the higher the market price, the less goods they will order. Different goods should have different elasticity values. For example, when there is a famine, people will still buy almost as much food as they used to, even at outrageous prices. But when the prices for jewelry explode, people will order far less because they can certainly live without a gold bracelet when it costs their whole life savings.

On the side of the AI actors which produce goods, you should also simulate elasticity of supply. A high market price means a higher profit margin for producers. This will motivate AI suppliers to invest into increasing their production, which results in more sell offers being posted, which again stabilizes the market.

This makes it hard for the player to corner the market, because even when they achieve a total monopoly on a good, they still can't sell more than people are willing to buy. So it will take time for them to make money, and in that time additional AI suppliers will appear who will undercut the player.

However, if the AI suppliers are physical entities in your game world, then it might be a viable strategy for the player to drive up the prices by getting rid of them. Likewise, they could reduce prices for commodities they want by getting rid of AI consumers.
> 1 votes

# Answer
The trading system is not that interesting compared to what you do. The basics is always buy low where there is supply, sell high where there is demand.

It's more important how you place your local resources and production specialities as well as how you setup the mechanics of demand.

Patrician 3 is a brilliantly designed trading game and I recommend to everyone to at least look at the resource map.

Supply and production is pretty straightforward, but demand is more complex and can make or break your game. Patrician 3 is also great here with 3 population types with their own demand. It is also good if you can tie demand with city growth and development like in Anno 1404.

In a trading game it's all about the **fight** against the **players optimum**. There is couple of ways trading games solve this. The last thing you want is something that is **too reliable** that the player can do **over and over again**. Investments can work to reap bigger profits reliably but in that case the economy has to scale to play with the bigger boys and higher stakes.

Some examples:

Have multiple ships all over the world tackling multiple locations.

Have danger along the way that might make you reevaluate your plans like Storms or Super Strong enemy fleets that can kick your ass. It's also good to have this information beforehand otherwise the player will push his way on regardless.

In Patrician selling is incremental(or averaged out) so the more you sell the more you satisfy demand so its efficient to not sell in just one place leading to the creation of trade runs.

In Patrician it takes some time to "digest" what you sold so you have to do runs with other products.

In Patrician your competition is also selling stuff so information is important, you can setup information networks and you want to have backup plans by going on a route where you can sell in multiple places along the way.

An information network can really break your trade game so its best to balance it with recurring costs, like crew costs and taxes if you expand too much.

Supply/production and demand is generally known in one location but the current state might not be, you can make some informed choices based on time, previous information, your surroundings and predicting your competition.

In Starsector "economic disruptions" I think are a mistake since they tell you too bluntly what your opportunities are. But that is circumvented somewhat by the encounters while traveling there and having an awesome combat. Thus efficiency comes in the form of **how good you are in combat**.

In Starsector it does well the **economy of scale** well since you can invest in large ships that move cheaper product in larger volumes.

In X3 Albion/Terran the economy has "holes" that you can fill up investing in the relevant station/factory.

In X3 equipment can be directly used for outfitting your fleet so the economy is not useful only for monetary reason but also for your combat potential.

In The Guild 2 the items you make you can sell on the market, they also have functions that the competition can use. If you buy all the antidotes and then poison your competition then they cannot heal themselves.

In The Guild 2 business also have simple input output system for their product. If you can monopolize and control the input, like buying the input resources on the market, taking over the farms that generate the input and controlling the harvest points with thugs you can starve a business.

In Battle Brothers enemy forces can raid towns and target traders on the road that affect the economy of the surrounding towns. Similarly in Starsector you can target traders and blockade a planet or sector by blockading the wormholes.

In a more complex game you can do this also with the output where you can use the desirability of your output that you have cornered the market in for political advantage. In other words in a game with factions and useful equipment like in X3 you can sell to a particular faction to equip them and give them an advantage(note:this does not happen in X3 itself).

Offworld Trading Company also does this type of manipulations.

Interesting economic games: Patrician 3, X3 Terran/Albion, Starsector, Factorio, Imperialism Series, Battle Brothers, The Guild 2, Anno 1404, Cultures/Northland, Tropico, Offworld Trading Company, Space Run, Galaxy Trucker, Food Chain Magnate(not necessarily a good game).
> 0 votes

---
Tags: economy
---


# Question
Title: Inspector does not appear to match actual value
A text object is where the inspector says, but not where I expected it, and not where Debug.Logerror says it is. What I read as my "strengthTextObj.transform.position.x" is -213 in the inspector but transform.position.x is logged as 111. Why might these be different?

# Answer
> 1 votes
From the Unity Rect Transform documentation :

> Pos (X, Y, Z) Position of the rectangle’s pivot point relative to the anchor

From your image we can see that the anchor is the center of the Canvas, so relatively to this anchor, your text position is correct (x = -200). What your are debugging is "strengthTextObj.transform.position.x". From the Transform documentation :

> transform.position : The position of the transform in world space.

The origin of the world is at the bottom left corner of your canvas, so relatively to this point, your debugging position is correct (x = 111).

---
Tags: unity, transformation, text
---


title: Enemy AI in Unity2D

text:
# Question
Title: Enemy AI in Unity2D
How to make a enemy AI follow in Unity2D so that it can recognize paths, example jumping and ladder usage?

I want an enemy AI like Keystone Kapers game in Unity2D. If there is tutorial links please tell me.

# Answer
A good approach as always would be the A\* Algorithm. Here are a few links that will help you (I advise you to read them in order) :

* Wikipedia : Basic understanding ;
* Red Blob : A really nice introduction that goes more in depth, using pseudo-code ;
* J.Gallant : A Unity 2D approach, that generates a grid using raycast. He gives you the code. I re-implemented it so ask me if you need technical help.

You will need to tweek a little bit this algorithm to include ladders and jumps, maybe using different kinds of nodes : "Ladder", "JumpPossibility", "WalkingPath" etc. As the J.Gallant solution is based on Raycasts, it can be achieved using appropriate Colliders and Layers for the Ladders and other interaction objects.
> 1 votes

---
Tags: unity, 2d
---


title: How to update a dynamic texture

text:
# Question
Title: How to update a dynamic texture
I'm using Ogre 1.10, I have a dynamic texture assigned to a material that I need to update its buffer with a new image every few seconds. How can I transfer pixel data from an image to my dynamic texture?

I've created a manual texture like:

```
         // Create the texture
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(
            "dyn_texture", // name
            Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
            Ogre::TEX_TYPE_2D,      // type
            256, 256,         // width & height
            0,                // number of mipmaps
            Ogre::PF_BYTE_BGRA,     // pixel format
            Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);

```

And on my update function I have the image that I want to transfer:

```
Ogre::Image img;
img.load(basename.toStdString(), "resources");
//Copy pixels from img to texture
//??

```

I've already tried doing:

```
Ogre::HardwarePixelBufferSharedPtr pixelBuffer = texture->getBuffer();
pixelBuffer->blitFromMemory(img.getPixelBox());

```

works but it's quite slow, gui freezes when updating like that.

# Answer
Answering my own question, I did the following:

```
//Using Qt to load an image, Ogre::Image can be used as well
QImage qimg = QImage("someTexture.jpg");

//Get texture ptr
Ogre::TexturePtr texture = Ogre::TextureManager::getSingletonPtr()->getByName("myTexture");
Ogre::HardwarePixelBufferSharedPtr buffer = texture->getBuffer();
/// Lock the buffer so we can write to it
buffer->lock(_box, Ogre::HardwareBuffer::HBL_DISCARD); //Fast!!
const Ogre::PixelBox &pb = buffer->getCurrentLock();

/// Update the contents of pb here
/// Image data starts at pb.data and has format pb.format
/// Here we assume data.format is PF_X8R8G8B8 so we can address pixels as uint32.
uint32_T *data = static_cast<uint32_T*>(pb.data);
const uint32_T *data_img = reinterpret_cast<const uint32_T*>(qimg.constBits());
int height = qimg.height();
int width = qimg.width();;
size_t pitch = pb.rowPitch;
for(int y=0; y<height; ++y)
{
    for(int x=0; x<width; ++x)
    {
        data[pitch*y + x] = data_img[pitch*y + x];
    }
}

/// Unlock the buffer again (frees it for use by the GPU)
buffer->unlock();

```

I did a short benchmark and this technique is faster than using `HardwarePixelBufferSharedPtr::blitFromMemory()` (jpeg, 256x256px)
> 1 votes

---
Tags: textures, ogre
---


title: Player area in navmesh?

text:
# Question
Title: Player area in navmesh?
In my game, If i click on terrain my soldier goes there. In my terrain there is no place without a navmesh. So, I want to make area where player moves his soldiers on it. If he clicks outside this area, soldier will not move there or moves to closest point inside the area to this outside. Could invisible wall do this ? Image.Image2. update: To solve this, make any object fit your area. then, use mouse to detect that object.

# Answer
To solve this, make any object fit your area. then, use mouse to detect that object.
> 0 votes

---
Tags: unity, navmesh
---


# Question
Title: (unity3d) Raycast Tags: Object reference not set to an instance of an object not working!
Here is the code I have written for an AI:

```
public Transform player;
public NavMeshAgent Enemy;
public CharacterPowers CharPow;
public GameObject me;

// Update is called once per frame
void Update () {
    Vector3 targetDir = player.position - transform.position;
    float angleToPlayer = (Vector3.Angle(targetDir, transform.forward));

    if (angleToPlayer >= -90 && angleToPlayer <= 90)
    {
        RaycastHit hit;
        Physics.Raycast(me.transform.position, player.position, out hit);

        if(hit.transform.tag == "MainChar")
        {

            if(CharPow.IsCloaked == false)
            {
                Debug.Log("Player in sight!");
                Enemy.destination = player.position;
            }

        }

    }

}

```

However, according to the error message, the line

if(hit.transform.tag == "MainChar")

is missing a reference to an object. I have checked, and yes, the player character does have the tag. Everything else used to work, such as the cloaking mechanic. However, now nothing about the AI works at all.

# Answer
> 1 votes
Raycasting methods take a start point and a *direction*, but you're passing two points: a start and an end. The second point will not be interpreted the way you expect.

Instead, your second argument should be:

```
player.position - me.transform.position

```

to get a vector pointing toward the player from the start point at "me".

You should still check whether you've hit anything at all before you try to access the members of the resulting `RaycastHit`, so you don't hit NullReferenceExceptions even when unusual situations arise (like `me` being inside the player's collider)

You'll also want to use the CompareTag method instead of `.tag ==` for efficiency.

# Answer
> 0 votes
I think that instead of `if(hit.transform.tag == "MainChar")` you should use `if(hit.gameObject.tag == "MacinChar")`. Did you try this?

---
Tags: unity, collision-detection, ai, navmesh
---


# Question
Title: Make a place or city feel crowded in procedural generated worlds
I have thought about this while thinking about a game concept, but it should be applicable to many game types.

Imagine an RPG or something else with an open-world. Normally you would want to populate your world to make it feel alive and allow for interaction with NPCs in any form (talk, steal from, kill.. whatever).

Now, what if you don't have the option to fill it with NPCs or similar. My example would be a procedural generated RPG world where you want to enter a house filled with people or even a city. It would be strange for none of the NPCs to talk to you.

Another example might be a space station your ship is docking to. There might be only one or two NPCs you are able to talk to, but the space station could be steaming with other people, but you might not acces them somehow.

Sure, one possibility would be to have procedural generate NPCs with random messages as well, but depending on the size of the city and/or the amount of NPCs you would need a lot of NPCs with different messages. And then it would be easily possible to have to NPCs with identical messages. The other problem would be that you would end up with to many NPCs, that make the place feel overfilled instead of just crowded. I image that a hard number or relation for space to NPCs is impossible to pinpoint, but you surely get my point.

So, my question is, what other possibilities are there to make a city / place feel crowded? Maybe with NPCs, or maybe even without?

# Answer
> 6 votes
If you don't have people in your city it's going to feel deserted. I don't think there's anything else which will substitute for having NPCs but games have used the types of NPC behaviours you've excluded so I don't think those are things you should worry about too much.

In GTA there is no option for the player to talk to 'unnamed' NPCs. In Elder Scrolls games NPCs have a few lines which are picked randomly. Both these allow for relatively simple NPCs to populate the world and make it feel more alive than not having them would.

# Answer
> 5 votes
If you want a city's population to exist, but not talk to you: Have them speak a different language. Granted, it would still be weird to not speak the language, but it would be better than a town/city/station without NPCs. The language would have to fit in to the story. Another option would be to use actions. NPCs smile, frown, growl, etc.

# Answer
> 4 votes
A place doesn't feel crowded from everyone just standing around. **Places feel busier when there is more movement and interaction.** Rather than focusing on generating lots of NPCs all with unique messages, maybe focus more on creating a handful of NPCs with uniques stats that affect behavior. A few examples of traits that could be randomized:

* *A regular path.* This could be some footpath loop that the NPC would default to when there are no factors affecting it. Giving them somewhere to go, even if it is a circle, creates the illusion of purpose.
* *Level of friendliness.* Friendly NPCs are more likely to stop other nearby NPCs to talk to them. Unfriendly NPCs are more likely to distance themselves from other NPCs, adjusting their paths to avoid others.
* *Walking speed.* Having different speeds for different NPCs makes them seem less robotic and more likely to interact with each other as they pass each other up.

These factors, when they vary from one NPC to another, give the impression that these are people, each with different personalities and goals. It adds just enough chaos to create a crowd without requiring any real story.

# Answer
> 1 votes
You could stay by generating "areas" such as a market, brothel, trading post, etc. Each area could contain specific building blocks. For example the market may have stalls with vendors while the brothel or tavern could have rooms. When you first create a town/city you could have a variety of sizes defined. Outpost, town, city, etc.

Next i would define a range for the population of an area. For example: 3-7 stalls in a market for a city.

Then i would generate the vendors for the stalls from a predefined list of vendor types.

You could expand on this concept to cover a wide variety of points of interest in a town.

# Answer
> 1 votes
If a NPC just impedes the player's movement that is enough for the player to acknowledge their existence. Something on the level of GTA is enough.

Bonus points if the crowds are useful for the player like blending in in Assassin's Creed.

We don't really think about strangers too deeply in the real world either, they are just background and obstacles to us.

# Answer
> 0 votes
Maybe you could try to make a more visual indication whether npc's have dialogue or not. You could try blending their colours more to fit the direct enviroment, while npc's with dialogue have more vibrant colours that pop out more. This helps making npc's stand out, and also trains the players to disregard more blended characters.

Also, it could also be an option to have npc's in unreachable places for players. Just having some npc's sitting on a balcony, talking on the other side of a river or looking for stuff on a supply cart can add life to your city where natural borders will prevent players from accessing certain npc's without dialogue

---
Tags: game-design, rpg, procedural
---


title: Composition Based Spell System

text:
# Question
Title: Composition Based Spell System
I was wondering if anyone would mind explaining a little about how a composition based spell system should work.

I've been working on this for a few days now, I think I understand the composite pattern enough for what I want to do as my entity's follow the same pattern. (Everything has a single purpose)

But I am really having trouble connecting everything together.

For example my `Entity` has a `Entity Caster Component` and `Entity SpellList Component` and I believe following a pattern like this the `Entity Caster Component` shoudn't need to know anything about the spell other than it's just been asked to cast the one given, correct?

Which leads me to the problem of actually casting the spell as each spell is currently an empty object with 4 SpellComponents on it one of each type (`SpellTargeting`, `SpellEffect`, `SpellLocomotion`, `SpellModifier`) which all extend from `SpellComp` so I should in theory be able to treat them all the same.

But in practice I can't as targeting, modifier and effect mostly only need to run once where as locomotion needs to be called every frame.

I haven't figured out how to still call one inherited base method but have 1 component fire a coroutine and the others work as normal while still treating them the same.

Currently when I "cast" a spell I spawn an empty gameobject with the comps and enable the first component which does it's job and fires an event to start the next component until the last.

`TargetComp` \> `EffectComp` (VFX) \> `LocomotionComp` \> `ModifierComp` (Heal/Hurt etc)

which has the obvious effect of leaving a empty object in my scene that responds to target input even after the spell is over.

I feel like at some point I've started mixing two separate systems together and made an unholy mess I no longer understand.

Every other part of the project has gone and is going fine but just thinking about taking another look at the spell system makes me lose a few brain cells.

I linked an empty project I created purely for testing this with my "oh god its so awful but it sort of works" implementation attempt.

I would add the code for each file but there is over 10 and most of them are just extending from a base abstract class so I can treat them the same and this post is already very long.

https://www.dropbox.com/s/ft6awn4v36a0pu0/Modular%20Spell%20Test.zip?dl=0

**Any help appreciated, thanks!**

Note: Also I use "Entity" as a base class for anything that moves and would have health, I am not trying to implement ECS, I think.. it was just the easiest way to categorize it in my head.

# Answer
> 1 votes
Component-based architecture can be a nice solution, but they are not the right solution for every architecture problem. When a component doesn't actually *do* anything but is just holding a piece of information required exactly once then it shouldn't really be a component.

But note that an Entity with a list of Components is not the only form of composition. The classic Composite object, which is an object with other objects in its attributes, is also an option.

In your case, `Spell` could be such a composite class, with `SpellTargeting`, `SpellEffect`, `SpellLocomotion` and `SpellModifier` all being attributes or lists of attributes. The types might be full-fledged objects (not MonoBehaviours - plain old C# classes), or they could just be a delegate method or even just a value.

Example:

```
class Spell: MonoBehaviour {

     private SpellEffect[] effects; // an array of effects which happen to whatever gets hit
     private Action<Transform> locomotionFunction; // a delegate-method manipulating a transform
     private SpellTargeting targetMode; // might be an enum
     private SpellModifier modifier;

     void Start() {
         targetMode.doWhateverThisDoes();
     }

     void Update() {
         // move the spell using the locomotion function
         locomotionFunction(transform);
     }

     void OnCollision(other) {
          foreach(SpellEffect effect in effects) {
              effect.applyOn(other, modifier);
          }
     }
}

```

# Answer
> 1 votes
Beware of thinking of a solution, then making that the new problem. You're basically asking "how do I use the Composite pattern to make flexible spells?" when you could also be asking "how do I build flexible spells?".

A pattern that's well-worth looking into is Bytecode/Interpreter and Gameprogrammingpatterns has a page exactly for this.

You'd basically be creating a tiny language inside your game for wildly expansive flexibility when building new behaviour, such as "select nearest enemy, damage by 10, knockback by 20, select player, heal by 10".

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


title: Ray-box intersection problem

text:
# Question
Title: Ray-box intersection problem
I try to implement ray-box intersection algorithm given by the following code. However, I'm not really understand for two cases as shown in the following figures. Firstly, when the box is located in front of the ray, why the code give intersection even though the end point of the ray doesn't intersect with the box. A similar observation can be seen from the second case when the ray origin is located inside the box. Is this nature of the algorithm? How can solve this problem?

```
// r.dir is unit direction vector of ray
dirfrac.x = 1.0f / r.dir.x;
dirfrac.y = 1.0f / r.dir.y;

// lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
// r.org is origin of ray
float t1 = (lb.x - r.org.x)*dirfrac.x;
float t2 = (rt.x - r.org.x)*dirfrac.x;
float t3 = (lb.y - r.org.y)*dirfrac.y;
float t4 = (rt.y - r.org.y)*dirfrac.y;

float tmin = max(max(min(t1, t2), min(t3, t4)));
float tmax = min(min(max(t1, t2), max(t3, t4)));

// if tmax < 0, ray (line) is intersecting AABB, but the whole AABB is behind us
if (tmax < 0)
{
    t = tmax;
    return false;
}

// if tmin > tmax, ray doesn't intersect AABB
if (tmin > tmax)
{
    t = tmax;
    return false;
}

// if tmin < 0 then the ray origin is inside of the AABB and tmin is behind the start of the ray so tmax is the first intersection
if(tmin < 0) {
  t = tmax;
} else {
  t = tmin;
}
return true;

```

# Answer
Rays are infinite, the start and endpoint only define them. What you're looking for is a line segment based intersection.

It's very easy to convert a ray-box intersection to a line segment-box one since we know the point has to lie on the line that goes through the ray, we only need to check whether the bounding box of the line segment contains it. So convert the line segment to an AABB and test the resulting point against it.

Alternatively, get the length of the vector going from the ray origin to the resulting point and if it's longer, than the line segment, then it falls outside.
> 0 votes

---
Tags: collision-detection, collision-avoidance
---


# Question
Title: AdMob Rewarded Video Ads always shows same ad
I have integrated **AdMob rewarded video ads** in my iOS game. Currently, the game is in development stage and not released on the store. Currently, the **fill rate** is around **30%-40%** and I always see the same rewarded video ad. I have following questions:

1. Why the fill rate is such low? I am testing the game in India and the US.
2. Why the game is receiving the same ad from AdMob? Are there any settings that can allow different ads from the network?

I would appreciate any suggestions and thoughts on this topic. Thank you

**More information:**

The **test ads** gives 95%-98% fill rate. Hence, I think there is no problem with the AdMob SDK configuration. Previously, I tried using **AdMob mediation** and the ads were coming other ads networks (**NO ADS FROM ADMOB**).

Is there a AdMob policy where they don't provide enough ads to "under development" game/application?

# Answer
Whatever ad is being served is irrelevant to you as the app developer. You get paid just the same. However, you should generally be seeing a higher fill rate than that. While in development you should be using test ads anyway, though. This involves either using a test ad point or registering specific devices as test devices.

See here:

https://developers.google.com/admob/ios/test-ads

If you get the same fill rate with test ads, there is likely an issue with communication to the AdMob servers. If, on the other hand, you get a much higher fill rate with test ads, AdMob may simply not have sufficient inventory for your app. Your best bet in this case is to use AdMob mediation to allow other ad networks to pick up the slack to get you that high fill rate.

https://developers.google.com/admob/ios/mediation/
> 1 votes

---
Tags: ios, advertisements, admob
---


# Question
Title: Unity3d physics stability with low fixed timestep
I'm developing a vehicle simulator game for mobile platforms. This vehicle has some hydraulic arms. I use hinge joints and configurable joints. There can be collisions to walls etc.

When I set a low Fixed Timestep (more fixed updates, less performance) like 0.001 it runs smoothly on editor and it handles the collisions well. But on the target mobile device, the performance drops to 2-3 FPS! So 0.001 (1000 fixed updates per second) is not an option.

When I change the Fixed Timestep to its default 0.02 value or 0.01, performance becomes acceptable on mobile. But when collisions occur, the vehicle is torn apart and everything flies away at a high velocity as if there was an explosion.

How can I achieve stable physics with 0.02 Fixed Timestep?

Note: I don't set the velocity or transform position. I move the vehicle by applying torque to the wheels.

Update 1 : The problem happens when the vehicle hits an obstacle that has a collider but doesn't have a rigidbody.

# Answer
> 2 votes
I solved it, "Enable Preprocessing" option should be disabled in the joints as described below:

"Uncheck the Joint’s Enable Preprocessing property. Disabling preprocessing can help prevent Joints from separating or moving erratically if they are forced into situations where there is no possible way to satisfy the Joint constraints. This can occur if Rigidbody components connected by Joints are pulled apart by static collision geometry (for example, spawning a Ragdoll partially inside a wall)."

From Unity docs

---
Tags: unity, physics, collision-resolution, mobile, fixed-timestep
---


# Question
Title: Is "Check your surroundings" warning on splash screen really needed for geolocation games?
I'm currently building an Android game as a solo dev. It follows the trend of geolocation-based games (like Niantic), but with more unique aspects.

Anyway, I noticed that in Niantic games - Ingress, Pokemon Go - there's always a "check your surroundings" or "don't drive and play" kind of warning to the player in the splash screen. I'm afraid that it might have something to do with legal implications regarding people being trampled or fall to their death while playing.

While I'm definitely not a fan of losing my player base / cause pain and sorrow to their families, I still see no reason to add this to my game. Because let's face it, people promptly ignore warnings like that and play the way the want in the end.

My case is somehow different from most geolocation games, in the sense that one of its unique features is that you don't need to keep looking at the screen to play. In case it helps to clarify how it works here is the play store's link: https://play.google.com/store/apps/details?id=com.arvere.theforage (I'm not sure if this is compliant with SE's rules, if it isn't, I ask to some mod to remove it, please)

So, would there be any reason (besides legal security) to do this in a game like mine?

# Answer
Some geolocation games like Pokemon Go had quite a lot of bad press due to people getting injured while playing them. There were also cases of people trespassing on private property or entering restricted areas because the game they played encouraged them to do so.

When a company needs to defend itself against allegations that they put their players in danger, then being able to say "We told people to be careful, it's not our fault when they ignore our warnings" is certainly a good defense.

But what's in my opinion more important than trying to find some magic words to protect ourselves from bad PR is that we as game designers take responsibility. We have to make sure we design our games in ways which don't encourage reckless behavior. For example, when we reward players for moving quickly from A to B in urban environments, we encourage them to jaywalk or dash through crowds. And when we place objectives at randomly chosen geo-coordinates, we risk sending people into private or even dangerous areas.

As game designers, we usually encourage players to be bold, take risks and explore the limits of their abilities, because it makes for exciting and memorable gameplay. As long as the game takes place in a virtual space, there is nothing wrong with that. The only thing the player really puts at risk is their game progress. But if we apply the same risk - reward mechanics to games which take place in a physical environment, then we need to be far more responsible. That means that we need to work against our usual habits and instincts.

Games can be really powerful motivators. A player who is fully immersed in a good game will do whatever it takes to win. So we need to make sure that we do not reward people for putting themselves into physical or legal danger.
> 8 votes

---
Tags: mobile, geolocation
---


# Question
Title: Helicopter controller, spherical world with faux gravity
I followed this tutorial to create a planet with faux gravity that attracts objects.

Further I'm trying to create a helicopter-like controller that could move vertically and horizontally and that when the player presses control buttons this would compensate the faux gravity applied with `AddForce` to `Rigidbody` and the helicopter could fly. I implemented that in a way that when player presses buttons faux gravity with `AddForce` is not applied, but still the control feels very awkward.

What would be the best way to compensate the faux gravity to move the helicopter?

Edit: I only need it to move in XY plane (so only up/down/left/right). The camera looks on helicopter from its right side. The attractor script works in 3 axis and this is ok for now.

Player controller (assigned to the helicopter):

```
public class PlayerController : MonoBehaviour {
    public float moveSpeed = 15;

    private Rigidbody rb;

    private Vector3 moveDir;
    private float h;
    private float v;

    void Awake() {
        rb = GetComponent<Rigidbody>();

        if(!rb) throw new Exception("Game Object must have Rigidbody!");
    }

    void Update () {
        GetControls();
        moveDir = new Vector3(h, v, 0).normalized;
    }

    void GetControls() {
        h = Input.GetAxis("Horizontal");
        v = Input.GetAxis("Vertical");
    }

    void FixedUpdate() {
        rb.MovePosition(rb.position + transform.TransformDirection(moveDir) * moveSpeed * Time.deltaTime);
    }
}

```

Faux Gravity Attractor (assigned to the planet):

```
public class FauxGravityAttractor : MonoBehaviour {
    public float gravity = -10;

    public void Attract(Transform body) {
        Vector3 gravityUp = (body.position - transform.position).normalized;

        Vector3 bodyUp = body.up;

        Rigidbody bodyRb = body.GetComponent<Rigidbody>();

        bodyRb.AddForce(gravityUp * gravity);

        Quaternion targetRotation = Quaternion.FromToRotation(bodyUp, gravityUp) * body.rotation;
        body.rotation = Quaternion.Slerp(body.rotation, targetRotation, 50 * Time.deltaTime);
    }
}

```

Faux Gravity Body (assigned to the helicopter):

```
public class FauxGravityBody : MonoBehaviour {
    [SerializeField]
    float gravity = -10;

    public FauxGravityAttractor attractor;
    private Transform myTransform;

    void Start () {
        Rigidbody rb = GetComponent<Rigidbody>();
        rb.constraints = RigidbodyConstraints.FreezeRotation;
        rb.useGravity = false;
        myTransform = transform;
    }

    void Update () {
        attractor.Attract(myTransform);
    }
}

```

# Answer
Since the tutorial also rotates the character based on it's relation to the planet, you can use AddRelativeForce to move the helicopter up.

If you didn't fully understand the tutorial, I would recommend reading these articles. Linear algebra is a very useful skill in game development and, since Unity does all the difficult stuff for you, it's pretty simple.
> 0 votes

---
Tags: unity
---


title: Adding hotbar to inventory?

text:
# Question
Title: Adding hotbar to inventory?
I have a inventory and I need to add a hotbar to access certain items.

What this hotbar needs to do is when in the inventory "Menu" you add items to it and when you close the menu the hotbar moves to the bottom of the screen and you select and item, weapon, food ect, and can use it (like in Minecraft).

My problem is I don't know whether I should:

1. Keep track of which items are in hotbar "spaces" of the inventory and use them accordingly, or
2. Make a separate list for hotbar items and move them between the inventory and hotbar lists when needed

or a third way I did not even think of.

My inventory works by having items in a list. The item class has values such as dmg, uses, name, etc. I have an item data class I put on GameObjects that has a public `item` variable. I have an inventory UI class that takes the inventory list and displays them.

# Answer
I went with number 2 and made methods to move items around like inventory to hotbar and hotbar to inventory. This post helped to make the swaping methods
> 0 votes

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


# Question
Title: How can I take ingame images and videos?
I’m using MonoGame and Visual Studio Community on my Mac to develop a game for iOS. I want to take ingame images and videos of the gameplay while the game is running on an iPhone/iPad. Afterwards, I want to use these images and videos for promotional reasons on my website or on facebook.

Is it necessary to install third party software or can I take images and videos in Visual Studio Community without installing additional software?

# Answer
> 0 votes
On Mac, you can use Shift-Command (⌘)-3 to take a screenshot, and QuickTime to record the current screen or a portion of it. You're not installing additional software, since they're included in the OS, and you aren't adding unnecessary libraries for screen recording to your game.

# Answer
> 0 votes
Or use **ReplayKit**

Overview Using the ReplayKit framework, users can record video from the screen, and audio from the app and microphone. They can then share their recordings with other users through email, messages, and social media

https://developer.apple.com/documentation/replaykit

---
Tags: c#, monogame, ios, visual-studio, macos
---


title: Collision not smooth in unity3d

text:
# Question
Title: Collision not smooth in unity3d
I am working on a project(Racing car). When it hit an object the object should be destroyed. The Object is being destroyed when it is hit, but the car stops for a moment after hitting like an obstacle. How can I make this smooth, like the object is there and it is destroyed on collision but the car moves with the same speed?

Script attached to the object:

```
void OnCollisionEnter(Collision col){

    Destroy (gameObject);

}

```

---

Nothing needs to stop or slow down. It doesn't need to exert any physical force.

Thanks.

# Answer
On the objects that are to be destroyed on collisions, set `isTrigger` to `true` on the collider component. Then use `OnTriggerEnter(Collider other)` instead of `OnCollisionEnter()`.

Triggers still detect collisions, but allow rigidbodies to move through them freely.

The one downside I've run into with this method is it's more difficult to figure out exactly where the point of collision was (since now you're only given a `Collider` instead of a `Collision`, but it looks like this won't matter for your situation.
> 1 votes

---
Tags: unity, collision-detection, 3d
---


# Question
Title: Setting up a low res viewport to stretch in Unity
I am working on porting a low-res game over to Unity. In my previous engine, I had the option to set a native resolution (say, 160 x 144), and it would automatically stretch when the player entered fullscreen (with options for whether you wanted to keep the same aspect ratio, or stretch).

I am having trouble figuring out how to set up something similar in Unity. I see that you can play around with resolution settings from **Edit \> Project Settings \> Player**. I tried various combinations of `Default Is Fullscreen`, `Default Is Native Resolution`, and `Default Screen Width` and `Default Screen Height`, but I haven't been able to get it to work.

When I play the scene in the editor, the viewport is still much larger than my desired resolution. And when I `Maximize On Play`, the FOV is even larger.

I Googled around, but couldn't find an answer that helped.

**Any advice?**

# Answer
> 1 votes
1. Set up a RenderTexture of your desired resolution. You can create this as an asset in your project folder, or via code at the start of the game.
2. Set this RenderTexture as the target texture for your main camera(s). This will ensure the scene is rendered at the desired resolution.
3. Display the contents of this RenderTexture to the whole window. You can do this in a few ways, eg. as a RawImage component in a screenspace overlay canvas, or as an unlit textured quad positioned in front of a second camera (configure the camera's depth to render after the main camera(s), and its layers so that it sees only the quad).

---
Tags: unity, 2d, resolution, viewport
---


# Question
Title: How to Create a Perfect Dash (Quick Movement) in Pygame
I am trying to create 2d side scrolling platform similar to Megaman. Here is the progress so far: Red box is the spriteholder while blue box is the hitbox of the character. The sprite I use is random idle sprite I found on the internet.

My question will revolve around the quick movement, where the character will accelerate faster than their usual speed for certain distance / time / sprite index. This is my take currently on the problem:

```
def dash_left(self):
    self.sprite.index = 0
    self.sprite.rect.midbottom = self.rect.midbottom
    if self.dash_current_use > 0:
        self.vx = -1.5 * self.speed
        self.ax = (self.speed * 0.5)
        self.status = -3
        self.dash_current_use -= 1

```

on the def main():

```
if event.type == g.KEYDOWN:
    if event.key == g.K_q:
        player.dash_left()

if event.type == g.KEYUP:
    if event.key == g.K_q and player.vx < 0:
        player.stop_left()

```

The problem is that in my take, the dash will go continuously as long as the player pressed Q, or upon collision. My aim is for the dash to be able to stop itself, preferred when a certain distance has been passed or when ax (velocity variable from outside force) is greater or lesser - depending on the direction - than the vx (velocity variable from input.)

# Answer
> 1 votes
I think it would be a good idea to implement the dashing with a finite state machine, because that will make the transitions between the different states cleaner and the program will be easier to extend. There's a great chapter about state machines in Game Programming Patterns and I highly recommend that you read it before or while you're checking out my example.

Here's the explanation of the example:

I define some states (the MoveState, DashState, IdleState classes) and assign the current state instance to the `self.state` attribute of the `Player` class. The player object (its state machine) can only be in one state.

These states have their own methods for event handling and updating and are able to switch the state of the player object. To switch the state, I create a new state instance in the `handle_event` method when a specific key gets pressed and return it to the player, otherwise if `None` gets returned the state will not be changed.

The player object is responisble for passing the events to the current state and for calling its update method.

Also, in the `DashState` I don't return the new state from the `handle_event` method but change the player's state in the `update` method, because we need to wait for the timer which is updated there.

For the dash timer you need to pass the delta time (`dt` = time difference since last clock.tick call) to the update method where it is used to decrement the `self.dash_timer` attribute. When the timer is done the next state will be assigned to the `player.state` attribute.

```
import pygame as pg
from pygame.math import Vector2

PLAYER_IMAGE = pg.Surface((30, 50))
PLAYER_IMAGE.fill(pg.Color('dodgerblue1'))

# Classes for the three states (dash, idle, and move).

class DashState:

    def __init__(self, velocity_x, next_state):
        self.dash_timer = .5  # The dash will last .5 seconds.
        self.velocity_x = velocity_x
        self.next_state = next_state

    def handle_event(self, player, event):
        # Can queue the Move- or IdleState as the
        # next state after the dashing.
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_a:
                self.next_state = MoveState(-4)
            elif event.key == pg.K_d:
                self.next_state = MoveState(4)
        elif event.type == pg.KEYUP:
            if event.key == pg.K_a:
                self.next_state = IdleState()
            elif event.key == pg.K_d:
                self.next_state = IdleState()

    def update(self, player, dt):
        # Decrement the timer each frame.
        self.dash_timer -= dt
        # Update the position of the player.
        player.pos.x += self.velocity_x
        player.rect.center = player.pos

        if self.dash_timer <= 0:  # Once the timer is done...
            # switch to the queued state.
            player.state = self.next_state

class MoveState:

    def __init__(self, velocity_x):
        self.velocity_x = velocity_x

    def handle_event(self, player, event):
        # Can switch to Dash or Idle or change the direction.
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_q:
                return DashState(-8, player.state)
            elif event.key == pg.K_e:
                return DashState(8, player.state)
            elif event.key == pg.K_a:
                self.velocity_x = -4
            elif event.key == pg.K_d:
                self.velocity_x = 4
        elif event.type == pg.KEYUP:
            if event.key == pg.K_a and self.velocity_x < 0:
                return IdleState()
            elif event.key == pg.K_d and self.velocity_x > 0:
                return IdleState()

    def update(self, player, dt):
        player.pos.x += self.velocity_x
        player.rect.center = player.pos

class IdleState:

    def handle_event(self, player, event):
        # Can switch to Move or Dash.
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_a:
                return MoveState(-4)
            elif event.key == pg.K_d:
                return MoveState(4)
            elif event.key == pg.K_q:
                return DashState(-8, player.state)
            elif event.key == pg.K_e:
                return DashState(8, player.state)

    def update(self, player, dt):
        pass

class Player(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = PLAYER_IMAGE
        self.rect = self.image.get_rect(center=pos)
        self.vel = Vector2(0, 0)
        self.pos = Vector2(pos)
        # Start in the IdleState.
        self.state = IdleState()

    def handle_event(self, event):
        new_state = self.state.handle_event(self, event)
        # Check if the state's handle_event method returned a new
        # state object, if yes, assign it to self.state.
        self.state = new_state if new_state is not None else self.state

    def update(self, dt):
        # Update the current state.
        self.state.update(self, dt)

def main():
    pg.init()
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    player = Player((600, 300), all_sprites)
    dt = 0
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            player.handle_event(event)

        all_sprites.update(dt)

        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        dt = clock.tick(30) / 1000  # delta time in milliseconds.

if __name__ == '__main__':
    main()
    pg.quit()

```

---
Tags: pygame
---