# Question
Title: Is it unethical to make a game AI that is secretly non-competitive?
In several games the AI is designed to give the player an easy time without their knowledge. This can be having a 0% chance to hit the first time you appear, enemy letting you sneak up on them by not turning around, or the lowering of difficulty when the player is hurt or has restarted several times.

I would be offended if at the end of a board game or sport I was told that a human had not tried their hardest.

Does the same ethics exist for an AI?

edit As in the title, my main concern was **keeping the handicap hidden** from the player, for example, when playing a shooter it is reasonable to expect the player knows the AI has an artificial reaction time and poor aim but my question was about games that hide things such as enemies not using the best weapon or lowering their difficulty when the player is inured.

# Answer
> 44 votes
What do you want to accomplish with your AI?

If your game is trying to tell a *story*, then it is reasonable to have the AI adjust so that you get the story you want to tell.

If you want the player to have a *sense of accomplishment* from overcoming an obstacle or beating an opponent, making the controlling AI throw the game takes away from that — you need the AI to actually be the threat it's presented as.

# Answer
> 241 votes
Game AIs are almost always non-competitive, because if the AI would really try its hardest to win, it would often be unbeatable. An AI is not bound to human limitations like reflexes, accuracy, perception, fatigue or computational ability. So when it is seriously playing to win, no human would ever stand a chance.

Let's take the first person shooter genre as an example. Most of this answer should be applicable to most other genres. There are exceptions. AIs have difficulties beating humans at very complex strategy games, for example. Many real time and turn-based 4X strategy games cheat a lot in order to make the AI players challenging. But covering every single game genre would make the scope of this answer too large. So let's focus on the FPS genre.

A perfect playing AI would shoot you with perfect accuracy in the first frame where a single pixel of your character is visible to them. You sometimes encounter this in multiplayer when you play against cheaters. They are called aimbots, and nobody likes playing against them, because it's extremely frustrating.

But such a perfect aiming AI is in fact the easiest one to program:

```
if (lineIsUnobstructed (this.position, player.position)) {
     rotateTowards (player.position);
     shoot();
}

```

So perfect play is the default behavior. Human weaknesses like inattentiveness, limited perception, delayed reaction and inaccurate aiming are things you as a game developer need to program intentionally. And you usually take a long time to tweak these aspects until the enemy behavior is both plausible and provides the right amount of challenge to the player. How much challenge is "the right amount of challenge"? Very interesting question, but not within the scope of this question.

Also keep in mind that most single-player games are inherently asymmetrical for narrative reasons. Player and AI opponents usually do not have the same goals, have different tools available and are often not even subject to the same game mechanics. It's not uncommon for the sole player-character to face dozens or hundreds of opponents in a single level. When every opponent would be as good as the player, this would be impossible to do. But most games are selling power fantasies. The player is supposed to be a badass action hero who can single-handedly defeat a small army. That's usually the experience the player expects when they buy a first person shooter. That means in order to give the player a "fair" challenge, you need to make the single enemy relatively weak and stupid.

Now regarding the question **"Should I make the game easier when the player is losing?"**. Maybe, maybe not. Lots of players do indeed feel condescended when they repeatedly fail at a challenge and then suddenly the challenge gets taken away by becoming a lot easier. So you might want to avoid that, at least without asking the player if they want help.

But what many games do very successfully is a technique called *rubber banding*. Adjust the difficulty of future encounters depending on the player's success in past encounters. Sometimes you can even do that naturally within the fiction of the game.

# Answer
> 47 votes
A game's AI is a part of a game's overall design. At the end of the day, the AI you create needs to complement the game design.

If your game is designed around creating a challenging, competitive environment, then a "perfect" AI might be a good thing. At the same time, you have to consider something very important:

Humans *aren't computers*.

Even without cheating, it's not at all difficult in many competitive games to craft an AI that can beat any human without effort. AIs don't have to read player inputs to have faster reaction times than any human. If the player takes an action that has any visual hint, the AI has the right under your "play as best as it can" rule to use even slight visual differences to perfectly react to what is happening.

To make this work, you have to change the nature of the game itself. For human-to-human play, you might have all of the wind-up animations for fast attacks look very different, since human reaction time is being taken into account. But for computers, such a game is trivially easy; they can react instantaneously and perfectly.

So in fighting games, if a perfect computer has a fast move, and you attack with *anything* that takes more frames than their move, the computer *will hit you*. What was an intricate guessing game where players have to predict each others' movements turns into the human losing to the computer.

If you want to have a perfect AI, you need to build a game where the AI can play perfectly *and still lose*. That's not an easy thing, and it wouldn't work in a lot of genres. It could only happen if there are things that the AI has to react to but without enough time to do so. This would be like RTS games where there is hidden information. Truly perfect play would require perfect knowledge, but that is unattainable. Therefore, the computer will have to settle for "perfect, as far as I know, play". And thus, it can be fooled.

But even in such games, the speed of computers gives them an advantage in any situation where there is well-understood information. They can micro perfectly, positioning each unit for maximum effect. And so forth.

Basically, most games made for humans are *made for humans*, not for computers.

This is not a question of "ethics". It's a question of who the game is made for and what the purpose of the AI opponent is.

# Answer
> 26 votes
As a preface, I'm going to correlate ethics with cheating. If you feel cheated, you feel something unethical has happened to you.

In a nutshell, to make your AI's behavior acceptable, make the behavior it mimics believable. People don't feel cheated by believable behavior, they do feel cheated by unbelievable/unrealistic behavior. So be believable, and you won't have the ethics question.

Also, look at what AI stands for when considering your question: it's Artificial **IntelliGENCE**, not Artificial **IntelliGENT**. Intelligence is the ability to acquire and apply knowledge and skills. Intelligent is something that has typically has high intelligence. In other words, just because something has intelligence doesn't mean it's smart. A squirrel has intelligence, but it is not (by human standards) intelligent.

Lastly, separate decisions the AI makes from actual game mechanics, and don't let the AI break the rules. That last point is maybe a bit harder to explain, so here is an example...

**An Example with Guns and AI**

Your AI is not simulating a gun and how it fires, it's simulating a thinking being (or maybe machine) behind that gun.

The gun itself is managed by code that calculates whether a shot hits by taking into account range, weapon accuracy, pattern spread over distance, stance of shooter, whether shooter is moving, skill of shooter, etc. You should never mess with that code as it's simulating mechanical and physical reality. If you do this, you break believability.

But the thing holding the gun? That's managed by AI. It should have **no** influence on how the gun actually works. Only how the gun is used.

So given the gun's known behavior, ask yourself *why* the AI might miss on the first shot. Then make your AI behavior reflect what would make that first shot miss. Is it because it's simulating a low-skill opponent who fires from the hip and doesn't aim? Is it because the AI fires the first shot out of panic while moving? Is it because the opponent has a low quality weapon? Is it because the opponent is a long ways away?

If your AI simulates these kinds of "why" things, you've created an AI that behaves believably when it shoots and misses. And nobody will feel cheated by that kind of AI.

**A Scenario for Guns and AI Example**

Consider a scenario where you sneak up and surprise an AI opponent. They jump up and fire at you wildly while running backwards - and your shot code basically is going to give them a very low chance of hitting on the first shot because of this. And assuming the player knows what makes shots inaccurate, they will find this miss highly believable and acceptable.

But if you want, the AI could say, "OK I need to increase my odds of hitting. What can I do... OK I can stop moving. I can crouch down. I can aim my weapon using sights instead of firing from the hip." And the AI then starts to change how it fires, and the opponent starts getting better. That is intelligence moving towards intelligent.

Of course a very smart version of that opponent won't panic, and will immediately go towards the most effective action. They might quickly drop down on a knee and aim at you with sights, and greatly increase their chance of hitting.

**Guns and AI Example Summary/Conclusion**

Basically what this says is for AI that involves shooting at something, the "skill level" of the AI centers around how fast can it move towards doing all it can to optimize its accuracy. SUPER dumb AI never figures it out, always shooting from the hip while running and moving. Smarter AI does more and more to optimize accuracy. REALLY smart AI just immediately does everything it can to optimize accuracy.

# Answer
> 18 votes
Yes. An AI should stay at the level that it was set to.

A chess AI will beat all of us every time, and it's up to us to tune it to something we find enjoyable. I would never want the AI to dumb itself down when it sees that it's going to win, or have a pop-up saying "mate in 25, do you want me to be worse at chess?". Just beat me until I get tired of playing at a level that's beyond me.

Let's not think that giving the opponent all queens has anything to do with AI.

# Answer
> 12 votes
I would say no. You see for me games are first and foremost entertainment products. They want to deliver an experience to a specific audience. So it all depends on what experience and to what audience you want to make a experience for. Take a new game for example like Cuphead. This game is made for people who want the game to be hard and unforgiving and so on. That type of player would feel bad if the game dumbed down after they die X times( so far I've died 255). Then again automaticly lowering the difficulty for a more casual audience might help them progress in the game and generally have a better time. So in conclusion: "Know your audience".

# Answer
> 11 votes
Try to be competitive at a sport with your date, or with your kids. In both cases, you may end up playing that sport alone because you have not made it fun for them.

The term *Artificial Intelligence* is a bit misleading. By default, the AI is run by the computer which has a complete knowledge of the rules and the state of the game, thus the AI would know exactly what to do and when to do it to beat the player.

This is not fun.

The *Intelligence* part of the AI has to be turned into dumbness, just enough to give a challenge to the players and keep them playing.

That's a challenge and that's why game designers exist.

# Answer
> 9 votes
Ultimately, the role of AI is to help produce a note-worthy, rewarding experience. Dr. Ian Lane Davis talks about this in some of his interviews, that the role of an AI is to lose convincingly. PCAuthority Interview (The mechanics that you mention are examples of the game not being convincing, instead opting for a cheap and easy way to provide victory for the player.)

From the same interview:

> Your AI opponents are tools for drama and tension as much as they are intelligent agents.

In movies, books, tv shows, what we want as viewers is for the odds to mount against the protagonist, but only up until a point. Then we want the good guys to win. The closer the enemy came to winning, the greater the payoff.

The goal is always entertainment.

# Answer
> 9 votes
The goal of your AI should not be to win, it should be to provide an enjoyable game. Part of that enjoyment is in being challenged. My approach to this in Scrabble has been two-fold: Firstly, aim for plays that match the vocabulary level of the human. The level matching will improve over several games but you can also make quite a good estimate on the fly in the early games. In Scrabble you would need a lexicon that is classified by reading age, though as a fallback, using a large corpus to determine word frequency in use is a reasonable approximation. Secondly, use playing constructs that initially mimic the human's - for example a computer would generally make far more parallel plays than an occasional human player (I assume we're not playing world class experts). However as experience against a specific opponent increases, *then* you start using a few tricks against them that they don't use themselves - but sporadically, with the intention of providing an example for the human to emulate and improve their own play.

The success of your AI will be measured by how often the human comes back for a return match. Your satisfaction with the code should come from how well it manages to play like a human rather than a machine. This is something that can be tested by setting up online competitions where humans do not know if they are playing other humans or machines. (A limited Turing test)

I've always referred to this style of coding as "Artificial Stupidity" rather than AI :)

I don't consider this at all unethical. In contrast, I think that using the full resources of a computer algorithm to beat a human is unethical - just as much so as someone playing Scrabble online using a computer to find the highest-scoring plays.

Another way of 'dumbing down' an algorithm is to place genuine human-level limitations on your AI player's capabilities - again, using Scrabble as an example, instead of providing a fixed vocabulary, you could have your AI player learn its vocabulary from reading internet articles and you could limit its memory capacity so that it would have to make deliberate choices which words were worth remembering. There is absolutely nothing unethical in this and it achieves the goal of making play more human-like - for example, in removing the computer's advantage of perfect knowledge of which words are valid dictionary words and which words should be challenged when played by the human opponent.

# Answer
> 5 votes
There are several reasons why computer opponents need to be dumbed down.

Philipp has mentioned the part of keeping it fun already, but another worth mentioning is balancing for computer opponents‘ unfair advantages.

We are not able to make a true AI that plays like a player. The computer opponents we face today (even when called AI) are not analyzing the rendered game image to find what to shoot, like a human. Neither do they have to move a physical object over a desk surface to indicate they need to turn.

In fact, most computer opponents have the deck stacked in their favor. They know the exact location of every player, how tall they are, where the ideal headshot point is for this enemy type/character model, have a gun they can just tell „shoot at this coordinate“ and it‘s an exact hit, etc. So to make the game fair, you now have to approximate the limitations of a human.

So a big part of this „dumbing down“ is necessary simply to create a fair game for opponents that play by different rules.

If you’re already doing that, it is a small step from there to applying a few more modifications for storytelling effect and to make things more entertaining.

Another aspect is the accelerated timeline on which most games run. There are four-hour games where you are a sniper. It takes much longer to learn how to precisely shoot a gun. It takes longer than that to track an animal through a forest. A good game finds the right balance between making the game trivial to beat and having to attend years of police academy.

So it depends on who and what a game is for, whether these choices are good. For example, many big games really aren‘t a single game. They are more several games merged into one, to appeal to the broadest possible audience and make enough money to recover the huge up-front costs for a professionally acted/mition-captured, voiced, scored and textured game.

So you‘ll have players who want to compete with other players, who only care about the battle mechanics. You have others who only want to experience an interactive story, and find the battles between them a chore, and again others who are mainly looking for a crafting game or a resource management- or trade-simulation.

To find the sweet spot here, you have to provide a challenge for each type of player, but you also have to keep it simple enough that the other player types can either ignore those undesirable (for them) mechanics, or complete the game while doing badly in them.

In single-player games, this is often achieved by allowing to prop up deficits in one mechanic with exceptional skill in another (i.e. craft an awesome armor and the fighting becomes easier), or by having difficulty settings that let you turn on/off the parts that irk you.

In multiplayer, that‘s not really possible, so you match up players with similar rank/gear and adjust difficulty for the whole match.

However, these are all fairly "above the table" tricks. Every player gets the "secret double-damage last bullet" and can take advantage of it. Most peoples' intuitive understanding of how likely a "50% hit chance" really is is wrong, and they will be helped by telling them the percentages "translated" into their "language". What, as you say, about "secret" tricks?

Well, if a game was like chess, and you were told one set of rules, but really those were a lie, that would be cheating.

But none of the games in recent articles I've read on game developers' tricks to make you feel better were actually like that. Most were story-heavy games, or games that are famous for invoking a certain mood or feeling. And in that context, displaying 100% mathematically correct health bars makes the game much less exciting.

It's like a magic trick: Players go in *expecting* to be served an illusion, so I think it's fair to give it to them. It's also like a magic trick in that some people will still want to believe there is actual magic and will be disappointed when they find out about the trick.

# Answer
> 4 votes
When a human opponent doesn't try their hardest, you're offended because it's condescending. The AI can't be condescending, but you might think that the developer of the AI can. There are two differences here though:

1. The developer and the player can never be evenly matched, unless it's some NP-hard game that the developer would need deep learning for an AI to match a human, and in that case, the AI is always trying its hardest.
2. Unless the developer made the game just for you, they're catering to many players (usually certain kinds of players), and therefore can't make assumptions about your individual skill level.

This applies to level design too. You might think it's condescending if the developer babies you with obvious prompts, but that just makes the game boring. Equally, if it's so hard that you need millisecond reflexes, then it can be so frustrating that it's boring.

It reduces to the same problem that is always between humans. If you played a sport called "baby soccer", you don't get offended at the game's inventor, because they're not being condescending to you in particular. Equally "artillery soccer" is just the same in the opposite direction.

There would have to be a human involved, e.g. a multiplayer opponent that lets you win, for the offence to be equivalent IMO.

# Answer
> 4 votes
When creating a game, you want to aim to create an *experience*, not an AI that is technically/mechanically "fair".

In some games, players are able to take a few more hits than normal when they're very low on health. This mechanic is purposefully implemented to create the experience of narrowly surviving a fight. The game designers want you to have that adrenaline rush, even if you took a hit or two more than you should have. There is absolutely nothing unethical about implementing something similar in your game.

The same concept applies to AI in general. You get to design the rules of your game, but more importantly, you are in full control of the experience. If making AI oblivious to your nearby movement or causing them to miss their first few shots improves the gaming experience, then by all means implement them guilt-free.

If the premise/design of your game revolves around unforgiving AI, you'll want to make sure it's a fun and positive experience for the player. If it's not, you can adjust other mechanics to make it more engaging. Some examples I can think of would be to give the player other advantages over AI, such as more health, speed, damage, or better weaponry. These would offset the skill gap between an unforgiving AI and the player.

# Answer
> 4 votes
You need to step back and ask for **purpose**

In a competition, the purpose is to find out who is better. That is why not trying your best is the same kind of cheating as performance-enhancing drugs: It spoils the purpose.

The purpose of AI in computer games is to entertain and challenge the player. A perfect AI will make the player feel like he truly accomplished something, so it should **feel** difficult. This can be done either by tuning the difficulty level so that it is *just right* \- not too easy, not too hard. Or by cheating, by making the AI adaptive, or through some of the many, many tricks we know that players don't notice.

There is no moral question here. The player is no more cheated than he is when he watches a movie with CGI or a stage magician. He **expects** the game will entertain him, and as long as it delivers, nobody was cheated, even if some of the details are not entirely honest. But neither is the magician, or the movie.

# Answer
> 4 votes
## No, it is neither unethical nor necessary

In fact, there are no "ethics" involved here, just fun.

That said, it should not be *necessary* to make it uncompetitive at all, in the ideal world. Give the AI exactly the same tools that you, as the player have. This means a clear separation in the game code. For example, it should not know anything about its items/actors that you, as a human cannot know.

Then go and code your AI so it can deduce everything it needs to know about the current situation by witnessing it like you as human player would. The AI should make its own internal world representation about what it sees. Obiously, at some point you have to make ammends, i.e. it would be nonsensical for the AI to have to do OCR on some textual representation in a simulated UI. But it should be straightforward to allow it to "see" only those facts about entities in the game that you, as a human, can see through the user interface as well.

Obviously the AI can only give the same commands to its entities as you can, and is, in any other aspect, also bound to the same rules. Ideally you would run it through the same net code that your game client also uses (with the added restriction that you make sure that it does not get to "know" about things that your (human-targetted) client had delivered over the network but not just yet displayed through the UI.

I guarantee you that this will make the AI complicated enough to implement that *dumbing it down* is your least problem. And if you manage to program it so it can play in a meaningful way, it *will* probably feel awesome.

That will also give you all the tools to tune the AI to a level that is fun for the player. Give it an artificial reaction time, make it so it forgets stuff, or misremembers information (e.g., a slight obfuscation or random jittering of its "remembered" entitie values). Playing against an AI that makes *realistic* errors would solve your problem as the AI can be very competitive, and through its errors still be beatable.

I saw such an approach once, in the game Angband (descnedant of Moria, in the Nethack genre), many *many* years ago. Since that game is single-player, it was not an AI playing against a human, but one that *simulated* human play. The maintainer back then ("Ben" soandso, if I recall correctly) actually did what I described; he simulated the whole data structures of the actual game in a second dataset for the AI. The AI only "knew" things that it had actually witnessed (including monster attributes and such). Very impressive.

And needless to say, I have never seen such an approach ever again, at least not so that I could recognize it - all "AI" in any computer game whatsoever was always stupenduously stupid and unintelligent, predictable, the rules very obvious, with enforced cheating to give it a chance against players, and worse.

**TL;DR:** in the ideal world, the question should not occur; in the real world getting a fun AI to work is challenge enough (for the programmer).

# Answer
> 2 votes
There are more ways an enemy AI makes it easier for you.

Taunting animation after it scores a hit. This lets the player finish the stun animation and get ready for an attack of her own. It would be very easy to turn off taunting and then stun lock the player.

Repeatedly using attacks that can be countered (or dodged and leaving the enemy open for damage). In crappy cover-based shooters this is the enemy coming out of cover to let you hit them. A competitive ai will not select those kinds of attacks. Granted this can be fixed with *plot*.

Telegraphing moves (the windup) so the player has a chance to react. This windup animation is a very important part of difficulty scaling especially in reaction based combat.

It's very easy to make an enemy difficult to play against. But it's very hard to make it a challenging yet fun enemy. Part of that is making the enemy do dumb stuff and let the player have a winning move at all.

# Answer
> 2 votes
In essence, the absolute quality of AI as an opponent really depends on the type of game, the amount of time spent on developing the in-game AI and the CPU power/allotted cycles behind the AI.

On a simple board game, like Chess, home computer powered AI would always win because it can crunch the moves better than a human ever can and the algorithms to do so are very well known.

Respectively, on arcade shooters (most FPS games), an AI can have perfect aim (assuming things like projectile speed \>\>\> player speed) and perfect "vision" in which case you can also end up with a situation where AI will just wipe the player out of the game, assuming the in-game resources are even between AI & the player. On the other hand, for example, plug vision recognition into an FPS AI and you'll soon run into real processing problems and the player suddenly is the favourite (for now!).

On RTS, AI running on a normal PC can be superior or inferior regardless of whether it follows the rules or not. The complexities of the game decide whether balancing the AI requires handicapping or whether it has to "cheat" to provide a decent challenge. Same goes for 'complex board games' (turn based strategy games such as Civilizations, but also Go \[for a while on home PC\]) and certain other genres, such as flight & racing simulators, where the superiorities of AI – near instant reaction times, superior number crunching, perfect memory and full knowledge of surrounding environment – can be overshadowed by the complexities of the game mechanics.

The fact of the matter is that fair playing *Standard-Game-AI* running on a home computer with similar to human limitations (e.g. AI sees/hears what you would see/hear) will almost always lose to player beyond simple board games (for now!). On the other hand, make the rules simpler, add extra in-game knowledge (e.g. AI knows the environment, including where you are, all the time), crunching power and AI development time and the human might end up losing the game.

Overall, the question of ethics is in my opinion quite irrelevant and misleading. The point of playing a computer game vs AI is not to win or lose, but to enjoy the experience. And to this end, on terms of balancing, adding AI/player handicaps/bonuses is usually much easier to do than making different level AIs.

# Answer
> 2 votes
from Wiktionary:

> to err is human

For me, one of the most desirable (and most difficult to achieve) traits of a proper game-AI is the ability to make errors like we (humans) do.

Because we do err, by default. AIs do not, by default. Imbuing game-AIs with this inherently human "quality" would go a long way towards obviating that feeling of being “cheated” (either way, by winning or losing).

This would also be a trait an apt AI would need to master to be able to pass the Turing test: one would not believe an intelligence to be of human origin if it was unable to show the “ability” to make “human” (or human-like) mistakes.

# Answer
> 2 votes
No, in general it's not - as a game developer, you are crafting an interactive experience, and how your AI should behave is determined by the kind of experience you are trying to create. As a counterexample, consider a situation where you are able to implement an AI that would be *unbeatable* by *any* human on the planet. Should you do it? Would it be unethical to "dumb down" the AI so that the game is actually playable? An unethical thing would be to take advantage of your players; but this - this is just the usual gameplay design.
Let me open a can of worms for you: please visit this twitter thread.

P.S. Note, though, that some gamers will not see things this way. They might even get angry. But this stems from their misunderstanding of how game development and AI work. This doesn't make the practice unethical.

# Answer
> 1 votes
I would say it rather depends on the player.

Personally I'm used to bots being significantly stupider or unfairly skillful (sometimes even both). It's hard for me to remember a game where bots were at "fair" difficulty and I don't expect them to be such, because I know how limited they are.

Also many such "tweaks" would be noticed in the end if the game gets popular enough.

I'd say it's still better to inform players about "changes to difficulty" and I know games that do so.

# Answer
> 0 votes
Alternate answer that's more about design, motivated by your question edit.

You stated in your edit...

> ...my main concern was keeping the handicap hidden from the player, for example, when playing a shooter it is reasonable to expect the player knows the AI has an artificial reaction time and poor aim but my question was about games that hide things such as enemies not using the best weapon or lowering their difficulty when the player is inured.

**What the real problem is here**

The real question here is about design, not ethics. Bad design is what's making something seem "unethical". You're trying to solve here is balancing player skill against opponent challenge of the game.

A game that purposely has "handicapped" the challenge to balance with the player's skill taking an overly simplistic design approach towards trying to balance player skill and opponent challenge. So it's not per se unethical to do this, it's just bad design.

Say the player runs into a big strong opponent who is too difficult for them. That means either the player has gone way deep into the game to an area that's too much for them (think Casadores if you head north out of Goodsprings in Fallout: NV), or the designer has put the player up against challenging opponents when they know the player is not ready.

How do you solve this from the design perspective? Simple. You don't put the player up against an opponent that's too hard for them. And you design clear differentiation between opponents, and part of that differentiation is the opponent's skill. And you make your game progress such that it's harder (but not impossible) for a player to get in over their head too fast.

This is basically what the idea of Flow is all about in game design.

**An example with three ogres**

Imagine you have 3 kinds of ogres in your game: a little weak ogre who swings at you with a stick, a middle level ogre with a bigger branch, and a huge ogre who with a big log.

If you are a new player who hasn't gained new health, armor, etc., the little ogre would have to hit you 4-5 times to kill you. But once you are higher level, he can't hardly do a thing to you.

The middle level ogre can kill you as a beginner in 1-2 hits, but if you're higher level, it takes 4-5.

The huge ogre can kill you as a beginner in 1 hit, or 4-5 hits if you're higher level.

All the ogres always determine if they hit the same way. How they determine if they hit never changes. There is no artificially low (or high) reaction time, no artificially low (or high) damage. They just are what they are.

**The solution**

If the player is low level, put them up against only little ogres. Maybe give them a medium level ogre now and then as a challenge. Or several little ogres together. Never put them up against a huge bunch of little ogres, multiple mediums, or a giant, as they will die.

If they are middle level, put them up against middle level ogres with a few low level ogres just for "fun". Maybe have a swarm of little ones to make it more interesting. Never put them up against a bunch of middle level ogres or a giant ogre, as they will die.

Only high level go up against the giant ogre. Maybe give them some medium level ogres now and then, or a giant ogre with a swarm of little ones, or something else to boost the challenge. Never put them up against a bunch of giant ogres, as they will die.

With this approach, uyou never have to "handicap" anything, because the player will never see things that might need to be weakened.

And if a low level player truly is willing to go so deep into the game where they run into giant ogres, let them die - they deserve it.

---
Tags: game-design, ai, balance
---


# Question
Title: set zfar/znear in openGL using shaders (QT env)
I have a QT canvas and I'm using shaders to build my scence. I've set the camera image plane at some position, and would like to view object from the image plane to infinity. How do I set the zfar and znear values?

# Answer
> 1 votes
You can't make OpenGL render to infinity. The depth buffer usually uses floats (it can use other types, but none of them can represent an infinite number of values), meaning it has a set precision. If you set the zFar value to 100,000 for instance (not even close to infinity), then you'll have problems with z fighting between objects, that are hundreds of units apart from each other.

---
Tags: opengl, projection-matrix, qt
---


title: C++ SDL Bullet shooting problems

text:
# Question
Title: C++ SDL Bullet shooting problems
I'm coding a C++ SDL game and now I got a problem with my bullets. If I shoot, bullets should fly away in a straight line according to the player's angle. That's ok but how can I copy multiple bullets to the screen at the same time? For example, if I had an uzi or a machine gun and wanted to copy up to 30 bullets at the same time.

Currently I'm only getting one bullet on the screen at a time and when I hit space, it just deletes my first bullet and copies the second bullet.

Notice that the variable `bulletFire` is set to '2' when I hit space (fire), so its main object is to keep bullets on the screen when space is up.

In the class `Shooting` I have following lines of code:

```
class Shooting
{
public:
const Shooting()
{
    if (selectedWeapon == 4 && fire || selectedWeapon == 4 && bulletFire == 2 || selectedWeapon == 6 && fire || selectedWeapon == 6 && bulletFire == 2)
    {
        BulletMovement();
    }
    else BulletStart();
}

```

In `BulletMovement()`:

```
    if (current == 1)
    {
        bullet[0].x = 1893;
        bullet[0].y = 673;
        bullet[0].w = 3;
        bullet[0].h = 4;
        ClipBullet[0].x += BulletSpeed * (cos((currentAngle) * 3.14159 / 180));
        ClipBullet[0].y += BulletSpeed * (sin((currentAngle) * 3.14159 / 180));
        ClipBullet[0].w = bullet[0].w;
        ClipBullet[0].h = bullet[0].h;
    }
....
if (current == 30)
    {
        bullet[29].x = 1893;
        bullet[29].y = 673;
        bullet[29].w = 3;
        bullet[29].h = 4;
        ClipBullet[29].x += BulletSpeed * (cos((currentAngle) * 3.14159 / 180));
        ClipBullet[29].y += BulletSpeed * (sin((currentAngle) * 3.14159 / 180));
        ClipBullet[29].w = bullet[29].w;
        ClipBullet[29].h = bullet[29].h;
    }

```

In `BulletStart()` I keep moving my bullets' startpoint next to the pistol if I haven't shot it yet:

```
static void BulletStart()
{
        if (currentBulletUpdate[1] == '0')
        {
            ClipBullet[0].x = (clipPlayer.x + 50 /*51*/) + 60 * cos((playerAngle) * 0.0174532925);
            ClipBullet[0].y = (clipPlayer.y + 24.5 /*51*/) + 60 * sin((playerAngle) * 0.0174532925);
        }
....
        if (currentBulletUpdate[30] == '0')
        {
            ClipBullet[29].x = (clipPlayer.x + 50 /*51*/) + 60 * cos((playerAngle) * 0.0174532925);
            ClipBullet[29].y = (clipPlayer.y + 24.5 /*51*/) + 60 * sin((playerAngle) * 0.0174532925);
        }

```

Then I have `BulletCycle()` which increases the variable `current` when I shoot:

```
static void BulletCycle()
{
    if (selectedWeapon == 4 && bulletFire == 2 || selectedWeapon == 6 && bulletFire == 2)
    {
        if (fire) current = 1;

        if (current == 1)
        {
            currentBulletUpdate[1] = { 1 };
            CopyBullets();
            if (ClipBullet[0].x <= WINDOW_WIDTH + 1000 || ClipBullet[0].y <= WINDOW_HEIGHT + 1000) CopyBullets();
            if (fire) current = 2;
            else if (ClipBullet[0].x >= WINDOW_WIDTH || ClipBullet[0].y >= WINDOW_HEIGHT) currentBulletUpdate[1] = { 1 };
        }

        if (current == 2)
        {
            currentBulletUpdate[2] = { 1 };
            if (fire) current = 3;
            if (ClipBullet[1].x <= WINDOW_WIDTH + 1000 || ClipBullet[1].y <= WINDOW_HEIGHT + 1000) CopyBullets();
            if (ClipBullet[1].x >= WINDOW_WIDTH || ClipBullet[1].y >= WINDOW_HEIGHT) currentBulletUpdate[2] = { 1 };;
        }
....
            if (current == 30)
        {
            currentBulletUpdate[30] = { 1 };
            if (fire) current = current = 1;
            if (ClipBullet[29].x <= WINDOW_WIDTH + 1000 || ClipBullet[29].y <= WINDOW_HEIGHT + 1000) CopyBullets();
            if (ClipBullet[29].x >= WINDOW_WIDTH || ClipBullet[29].y >= WINDOW_HEIGHT) currentBulletUpdate[30] = { 0 };;
        }

```

And finally I copy my bullets in `CopyBullets()`:

```
static void CopyBullets()
{
    if (fire)
    {
        currentBulletAngle = bulletAngle;
        if (left) currentBulletAngle -= 0;
        if (right) currentBulletAngle += 0;
    }

    if (currentBulletUpdate[1] == '1')
    {
        SDL_RenderCopyEx(rend, texture, &bullet[0], &ClipBullet[0], currentBulletAngle, NULL, SDL_FLIP_NONE);
    }
    if (currentBulletUpdate[2] == '1')
    {
        SDL_RenderCopyEx(rend, texture, &bullet[1], &ClipBullet[1], currentBulletAngle, NULL, SDL_FLIP_NONE);
    }
....

    if (currentBulletUpdate[30] == '1')
    {
        SDL_RenderCopyEx(rend, texture, &bullet[29], &ClipBullet[29], currentBulletAngle, NULL, SDL_FLIP_NONE);
    }

```

And notice all this code is in the while loop in `int main()`; I just cannot find any possible errors, so please help me.

# Answer
> 1 votes
I'm not sure I can find your problem in the current code, but you could clean it up.

A lot of places you have 30 times exactly the same code with just different bullet id's. You should make a subroutine with the id as parameter for those places. A few places only 29 repeats, this is probably the most likely place for the error.

```
if (currentBulletUpdate[1] == '0') {
    ClipBullet[0].x = (clipPlayer.x + 50 /*51*/) + 60 * cos((playerAngle) * 0.0174532925);
    ClipBullet[0].y = (clipPlayer.y + 24.5 /*51*/) + 60 * sin((playerAngle) * 0.0174532925);
}
...

```

to

```
ClipIt(0);
ClipIt(1);
...
ClipIt(30);

```

When you have done that refactoring, you will realise that there might be a way to update the bullets individually in a loop instead.

```
for (int cnt = 0; cnt < 30; cnt++)
  ClipIt(cnt);

```

Now you have reduced your problem from 4 lines * 30 = 120 lines to just 2 lines of code making the program easier to reason about.

Treating each bullet individually instead of coping them to a new position not only saves you the copying but also makes it easier to identify which one is wrong.

Though you will in this design have to keep check on which bullets are active so you know where to place new bullet in the array.

---
Tags: c++, textures, sdl
---


# Question
Title: Approaches on detecting if a car should steer left or right considering a next direction
I'm developing the A.I. of my racing game, and I'm having an unforeseen problem. I manage to get the bot to drive by itself by accelerating in the direction of an angle that is returned using the atan2 trig function considering the position of previously-defined waypoints on the track data structure. Here's the code for `ai.py`:

```
import math
import pygame

class Bot:

    def __init__(self, player, track):
        self.player = player
        self.track = track
        self.current_waypoint = 1
        self.player.states[0] = True
        self.track.choose_waypoint_path()
        self.number_of_waypoints = len(self.track.waypoint_positions.keys())
        self.get_waypoint_angle()

    def get_waypoint_angle(self):
        self.dx = self.track.waypoint_positions[self.current_waypoint][0] - self.player.car.pos[0]
        self.dy = self.track.waypoint_positions[self.current_waypoint][1] - self.player.car.pos[1]
        self.ratio = math.atan2(self.dy, self.dx)
        self.angle = -self.ratio * (180/math.pi)

    def think(self):
        if pygame.Rect(self.player.car.pos, self.player.car.dimensions).collidepoint(
            self.track.waypoint_positions[self.current_waypoint][0],
            self.track.waypoint_positions[self.current_waypoint][1]
        ):
            self.track.choose_waypoint_path()
            self.number_of_waypoints = len(self.track.waypoint_positions.keys())
            if self.current_waypoint == self.number_of_waypoints:
                self.current_waypoint = 0
            self.current_waypoint += 1
        self.get_waypoint_angle()
        self.player.car.angle = self.angle
        self.player.car.rotate()
        self.player.move()

```

The thing is, when I set the car angle based on the return of the atan2 function, `self.player.car.angle = self.angle`, the car rotates/turns in an extremely unrealistic fashion. It works, but it means that I have to gradually steer the car, and then I face this problem. I don't know when to steer left or right, because the angle can be negative. If I do this, for example:

```
        if self.player.car.angle > self.new_angle:
            self.player.car.angle -= self.player.car.steering_speed
        else:
            self.player.car.angle += self.player.car.steering_speed

```

The bot drives to the next waypoint destination by weirdly driving in circles.

So, I know the direction in which the bot should drive, but based on its previous angle, I don't know whether it should steer left or right to reach that direction.

# Answer
I'd skip the trigonometry outright and use a 2D vector trick that lets us check the left/right direction with simple addition & multiplication.

Here you'd have your car store its forward direction as a 2D unit vector, `car.forward` (which you might already be using to compute its velocity anyway), then:

```
// Compute the offset from the car to the waypoint, as you have now.
self.dx = self.track.waypoint_positions[self.current_waypoint][0]
          - self.player.car.pos[0]
self.dy = self.track.waypoint_positions[self.current_waypoint][1]
          - self.player.car.pos[1]

// Form the dot product of this offset with the perpendicular
// to the forward vector: (forward.y, -forward.x)
self.side = self.dx * self.car.forward[1] - self.dy * self.car.forward[0]

// If this dot product is negative, the destination is on one side...
if self.side < 0:
    self.player.car.angle -= self.player.car.steering_speed
// ...otherwise it's on the other (or dead ahead if the value is close to 0)
else:
    self.player.car.angle += self.player.car.steering_speed

```

The signs might flip depending on the conventions of your coordinate system (y up vs y down / angles measured clockwise or counter-clockwise)
> 1 votes

# Answer
I suspect the problematic logic is here:

```
   if self.player.car.angle > self.new_angle:
        self.player.car.angle -= self.player.car.steering_speed
    else:
        self.player.car.angle += self.player.car.steering_speed

```

You can't tell whether to steer left or right simply due to ordinal comparison (`<` or `>`) because the angles could be close to pi, and the discontinuity there messes you up (for example, if you're currently heading 3, and the target angle is -3, this code tells you to steer clockwise (negative angle delta), whereas really you just want to steer towards 3.28 \[which is equivalent to -3\])

You want something more like

```
# angle_to_steer is now our angle difference, chosen so that it's between -pi and pi
angle_to_steer = (self.new_angle - self.player.car.angle + pi) % (2 * pi) - pi
if angle_to_steer < 0:
   self.player.car.angle -= self.player.car.steering_speed
else:
   self.player.car.angle += self.player.car.steering_speed

```
> 0 votes

---
Tags: mathematics, ai, python, steering-behaviors, racing
---


# Question
Title: How could I remove part of a Terrain Collider?
After reading through this site, I began to think on how could I remove the colliders of vertexes with a transparent texture on it? I had read a suggestion (forgot where it was) to disable the whole terrain collider, but I also have NPC's, so having them plumet through the map wouldn't go over well.

# Answer
> 1 votes
You can't remove a part of it, but you can get it out of your way.

One approach to doing this would be to set the terrain heights in the hole region absurdly low, allowing objects to fall into the hole. But that might have unpleasant visual artifacts at the edges of your terrain (especially as it drops to lower LODs, which might cause the hole to erode its surroundings) and only allows you to make pits, not caves/tunnels that travel laterally.

The other thing you can do is to leave the collider where it is, but ignore it.

Set up a trigger collider (or more than one) to completely encompass the aperture of your hole. Then add this script to the GameObject containing these triggers.

```
public class TerrainHole : MonoBehaviour {

    // Assign the collider you want to tunnel through.
    public Collider terrain;

    // This lets us keep track of objects
    // in one of our (possibly many) colliders.
    Dictionary<Rigidbody, int> _containment
                      = new Dictionary<Rigidbody, int>();

    // When a new body enters one of our triggers,
    // make it start ignoring the terrain's collision.
    private void OnTriggerEnter(Collider other) {
        Rigidbody body = other.GetComponent<Rigidbody>();

        if (_containment.ContainsKey(body)) {
            // The body is in the intersection of more than one
            // of our triggers. Keep a count so we know
            // when it's exited completely.
            _containment[body]++;
        } else {
            _containment.Add(body, 1);
            Physics.IgnoreCollision(other, terrain);
        }
    }

    // Once a body has exited all of our triggers,
    // tell it to pay attention to the terrain again.
    private void OnTriggerExit(Collider other) {
        Rigidbody body = other.GetComponent<Rigidbody>();

        int depth;
        if(_containment.TryGetValue(body, out depth)) {
            depth--;
            if (depth <= 0) {
                // The body has left the hole's vicinity.
                // Re-enable collisions and forget about it.
                Physics.IgnoreCollision(other, terrain, false);
                _containment.Remove(body);
            } else {
                _containment[body] = depth;
            }
        }
    }
}

```

This isn't guaranteed to give sensible results if an object enters/exits the hole while in close contact with / intersecting the terrain. Usually you'll want to have some other geometry skirting around the hole, both visually and in its collision, to keep the player from seeing or interacting with the raw edge, so this should keep us out of those cases.

---
Tags: unity, terrain
---


title: Pathfinding with lock and key?

text:
# Question
Title: Pathfinding with lock and key?
I'm working on a game with maps that resemble lock and key puzzles. The AI needs to navigate to a goal that may be behind a locked red door, but the red key may be behind a locked blue door, and so on...

This puzzle is similar to a Zelda-style dungeon, like this picture:

> To get to the Goal, you must defeat the Boss, which requires going over the pit, which requires collecting the Feather, which requires collecting the Key

Zelda dungeons tend to be linear. However, I need to solve the problem in the general case. So:

* The goal could require one of a set of keys. So maybe you need to get either the red key or the blue key. Or there could be an unlocked door the long way around!
* There could be multiple doors and keys of a kind. E.g. there could be multiple red keys in the map, and collecting one will grant access to all the red doors.
* The goal may be inaccessible because the right keys are behind locked doors

How would I perform pathfinding on such a map? What would the search graph look like?

Note: the last point about detecting inaccessible goals is important; A\*, for example, is extremely inefficient if the goal is inaccessible. I would like to deal with this efficiently.

Assume that the AI knows where everything is on the map.

# Answer
**Standard pathfinding is Good Enough** -- your states are your current location + your current inventory. "moving" is either changing rooms or changing inventory. Not covered in this answer, but not too much additional effort, is writing a good heuristic for A\* -- it can really speed up the search by preferring to pick up things over moving away from it, preferring to unlock a door near the target over searching for a long way around, etc.

This answer has gotten a lot of upvotes since it came first and has a demo, but for a much more optimized and specialized solution, you should also read the "Doing it backwards is much faster" answer https://gamedev.stackexchange.com/a/150155/2624

---

Fully operational Javascript proof of concept below. Sorry for the answer as a code dump -- I had actually implement this before I was convinced it was a good answer, but it seems pretty flexible to me.

To start off when thinking about pathfinding, remember that the heirarchy of simple pathfinding algorithms is :

* Breadth First Search is about as simple as you can get.
* Djikstra's Algorithm is like Breadth First Search but with varying "distances" between states
* A\* is Djikstras where you have a 'general sense of the right direction' available as a heuristic.

In our case, just encoding a "state" as a "location + inventory" and "distances" as a "movement or item usage" allows us to use Djikstra or A\* to solve our problem.

Here is some actual code demonstrating your example level. The first snippet is just for comparison -- jump to the second part if you want to see the final solution. We start off with a Djikstra's implementation that finds the correct path, but we've ignored all the obstacles and keys. (Try it out, You can see it just beelines for the finish, from room 0 -\> 2 -\> 3-\>4-\>6-\>5)

```
function Transition(cost, state) { this.cost = cost, this.state = state; }
// given a current room, return a room of next rooms we can go to. it costs
// 1 action to move to another room.
function next(n) {
    var moves = []
    // simulate moving to a room
    var move = room => new Transition(1, room)
    if (n == 0) moves.push(move(2))
    else if ( n == 1) moves.push(move(2))
    else if ( n == 2) moves.push(move(0), move(1), move(3))
    else if ( n == 3) moves.push(move(2), move(4), move(6))
    else if ( n == 4) moves.push(move(3))
    else if ( n == 5) moves.push(move(6))
    else if ( n == 6) moves.push(move(5), move(3))
    return moves
}

// Standard Djikstra's algorithm. keep a list of visited and unvisited nodes
// and iteratively find the "cheapest" next node to visit.
function calc_Djikstra(cost, goal, history, nextStates, visited) {

    if (!nextStates.length) return ['did not find goal', history]

    var action = nextStates.pop()
    cost += action.cost
    var cur = action.state

    if (cur == goal) return ['found!', history.concat([cur])]
    if (history.length > 15) return ['we got lost', history]

    var notVisited = (visit) => {
        return visited.filter(v => JSON.stringify(v) == JSON.stringify(visit.state)).length === 0;
    };
    nextStates = nextStates.concat(next(cur).filter(notVisited))
    nextStates.sort()

    visited.push(cur)
    return calc_Djikstra(cost, goal, history.concat([cur]), nextStates, visited)
}

console.log(calc_Djikstra(0, 5, [], [new Transition(0, 0)], []))
```

So, how do we add items and keys to this code? Simple! instead of every "state" begin just the room number, it's now a tuple of the room and our inventory state:

```
 // Now, each state is a [room, haskey, hasfeather, killedboss] tuple
function State(room, k, f, b) { this.room = room; this.k = k; this.f = f; this.b = b }

```

Transitions now change from being a (cost, room) tuple to a (cost, state) tuple, so then can encode both "moving to another room" and "picking up an item"

```
// move(3) keeps inventory but sets the room to 3
var move = room => new Transition(1, new State(room, cur.k, cur.f, cur.b))
// pickup("k") keeps room number but increments the key count
var pickup = (cost, item) => {
    var n = Object.assign({}, cur)
    n[item]++;
    return new Transition(cost, new State(cur.room, n.k, n.f, n.b));
};

```

finally, we make some minor type-related changes to the Djikstra function (for example, it still is just matching on a goal room number instead of a full state), and we get our full answer! Note the printed result first goes to room 4 to pick up the key, then goes to room 1 to pick up the feather, then goes to room 6, kills the boss, then goes to room 5)

```
// Now, each state is a [room, haskey, hasfeather, killedboss] tuple
function State(room, k, f, b) { this.room = room; this.k = k; this.f = f; this.b = b }
function Transition(cost, state, msg) { this.cost = cost, this.state = state; this.msg = msg; }

function next(cur) {
var moves = []
// simulate moving to a room
var n = cur.room
var move = room => new Transition(1, new State(room, cur.k, cur.f, cur.b), "move to " + room)
var pickup = (cost, item) => {
 var n = Object.assign({}, cur)
 n[item]++;
 return new Transition(cost, new State(cur.room, n.k, n.f, n.b), {
  "k": "pick up key",
  "f": "pick up feather",
  "b": "SLAY BOSS!!!!"}[item]);
};

if (n == 0) moves.push(move(2))
else if ( n == 1) { }
else if ( n == 2) moves.push(move(0), move(3))
else if ( n == 3) moves.push(move(2), move(4))
else if ( n == 4) moves.push(move(3))
else if ( n == 5) { }
else if ( n == 6) { }

// if we have a key, then we can move between rooms 1 and 2
if (cur.k && n == 1) moves.push(move(2));
if (cur.k && n == 2) moves.push(move(1));

// if we have a feather, then we can move between rooms 3 and 6
if (cur.f && n == 3) moves.push(move(6));
if (cur.f && n == 6) moves.push(move(3));

// if killed the boss, then we can move between rooms 5 and 6
if (cur.b && n == 5) moves.push(move(6));
if (cur.b && n == 6) moves.push(move(5));

if (n == 4 && !cur.k) moves.push(pickup(0, 'k'))
if (n == 1 && !cur.f) moves.push(pickup(0, 'f'))
if (n == 6 && !cur.b) moves.push(pickup(100, 'b'))
return moves
}

var notVisited = (visitedList) => (visit) => {
return visitedList.filter(v => JSON.stringify(v) == JSON.stringify(visit.state)).length === 0;
};

// Standard Djikstra's algorithm. keep a list of visited and unvisited nodes
// and iteratively find the "cheapest" next node to visit.
function calc_Djikstra(cost, goal, history, nextStates, visited) {

if (!nextStates.length) return ['No path exists', history]

var action = nextStates.pop()
cost += action.cost
var cur = action.state

if (cur.room == goal) return history.concat([action.msg])
if (history.length > 15) return ['we got lost', history]

nextStates = nextStates.concat(next(cur).filter(notVisited(visited)))
nextStates.sort()

visited.push(cur)
return calc_Djikstra(cost, goal, history.concat([action.msg]), nextStates, visited)
o}

console.log(calc_Djikstra(0, 5, [], [new Transition(0, new State(0, 0, 0, 0), 'start')], []))
```

In theory, this works even with BFS and we didn't need the cost function for Djikstra's, but having the cost allows us to say "picking up a key is effortless, but fighting a boss is really hard, and we'd rather backtrack 100 steps rather than fight the boss, if we had the choice":

```
if (n == 4 && !cur.k) moves.push(pickup(0, 'k'))
if (n == 1 && !cur.f) moves.push(pickup(0, 'f'))
if (n == 6 && !cur.b) moves.push(pickup(100, 'b'))

```
> 22 votes

# Answer
**Backwards A\* will do the trick**

As discussed in this answer to a question about forward vs backward pathfinding, pathfinding backwards is a relatively simple solution to this problem. This works very similarly to GOAP (Goal Oriented Action Planning), planning efficient solutions while minimising aimless wondering.

At the bottom of this answer I have a break-down of how it handles the example you gave.

**In Detail**

Pathfind from the destination to the start. If, in your pathfinding, you come across a locked door, you have a new branch to your pathfinding that continues through the door as if it is unlocked, with the main branch continuing to look around for another path. The branch that continues through the door as if it's unlocked is no longer looking for the AI agent -- it's now looking for a key it can use to pass through the door. With A\*, its new heuristic is distance to key + distance to AI agent, instead of just distance to AI agent.

If the unlocked-door branch finds the key, then it continues looking for the AI agent.

This solution is made a little more complicated when there are multiple viable keys available, but you can branch accordingly. Because the branches have a fixed destination, it still lets you use a heuristic to optimise the path-finding (A\*), and impossible paths will hopefully be cut off quickly -- if there's no way around the locked door, the branch that doesn't pass through the door runs out of options quickly and the branch that goes through the door and looks for the key continues on its own.

Of course, where there are a variety of viable options available (multiple keys, other items to circumvent the door, long path around the door), many branches will be maintained, affecting performance. But you'll also find the fastest option, and be able to use that.

---

**In Action**

In your specific example, pathfinding from the Goal to the Start:

1. We quickly encounter a boss door. Branch A continues through the door, now looking for a boss to fight. Branch B stays stuck in the room, and will soon expire when it finds there's no way out.
2. Branch A finds the boss and is now looking for the Start, but encounters a pit.
3. Branch A continues over the pit, but now it's looking for the feather, and will make a bee-line towards the feather accordingly. Branch C is created which tries to find a way around the pit, but expires soon as it's unable to. That, or it gets ignored for a while, if your A\* heuristic finds that Branch A is still looking most promising.
4. Branch A encounters the locked door, and continues through the locked door as if it's unlocked, but now it's looking for the key. Branch D continues through the locked door as well, still looking for the feather, but then it will look for the key. This is because we don't know if we need to find the key or the feather first, and as far as the pathfinding is concerned, the Start could be on the other side of this door. Branch E tries to find a way around the locked door, and fails.
5. Branch D quickly finds the feather and continues looking for the key. It's allowed to pass through the locked door again, since it's still looking for the key (and it's working its way backwards in time). But once it has the key, it won't be able to pass through the locked door (since it couldn't pass through the locked door before it found the key).
6. Branch A and D continue to compete, but when Branch A reaches the key, it's looking for the feather, and it will fail to reach the feather because it has to pass through the locked door again. Branch D, on the other hand, upon reaching the key, turns its attention to the Start, and finds it without complication.
7. Branch D wins. It has found the reverse path. The final path is: Start -\> Key -\> Feather -\> Boss -\> Goal.
> 13 votes

# Answer
**Edit**: This is written from the point of view of an AI that is out to explore and discover a goal, and does not know the location of keys, locks, or destinations ahead of time.

First, assume that the AI has some kind of overall goal. E.g,, "Find the boss" in your example. Yea you want to beat it, but really it's about finding it. Assume it has no idea how to get to the goal, just that it exists. And it will know it when it finds it. Once the goal is met, the AI can stop working to solve the problem.

Also, I'm going to use the generic term "lock" and "key" here, even if it might be a chasm and a feather. I.e., feather "unlocks" the chasm "lock".

**Solution Approach**

It seems like you'd start first with just an AI that was basically a maze explorer (if you think of your map as a maze). Exploring and mapping out all the places it can go would be the primarily focus of the AI. It could be based purely on something simple like, "Always go to the closest path I have seen but not yet visited."

However, a few rules would kick in while exploring that might change the priority...

* It would take any key it found, unless it already had the same key
* If it found a lock it had never seen before, it would try every key it had found on that lock
* If a key worked on a new type of lock, it would remember the key type and the lock type
* If it found a lock it had seen before and had the key, it would use the remembered key type (e.g, second red lock found, red key worked before on red lock, so just use red key)
* It would remember the location of any lock it could not unlock
* It would not need to remember the location of locks it had unlocked
* Any time it found a key and knew of any previously unlockable locks, it would immediately visit each of those locked locks, and try to unlock them with the new found key
* When ever it unlocked a path, it would simply revert back to the exploration and mapping goal, prioritizing stepping into the new area

A note on that last point. If it has to choose between going to check out an unexplored area it's seen before (but not visited) versus an unexplored area behind a newly unlocked path, it should make the newly unlocked path the priority. That's probably where there are new keys (or locks) that will be useful. This assumes a locked path probably won't be a pointless dead end.

**Expanding the Idea with "Lockable" Keys**

You could potentially have keys that can't be taken without another key. Or locked keys as it were. If you know your old Colossal Caves, you need to have the bird cage to catch the bird - which you need later for a snake. So you "unlock" the bird with the cage (which doesn't block path but can't be picked up without the cage), and then "unlock" the snake (which blocks your path) with the bird.

So adding some rules...

* If a key can't be taken (it's locked), try every key you already have on it
* If you find a key you can't unlock, remember it for later
* If you find a new key, go try it on every known locked key as well as locked path

I won't even get into the whole thing about how carrying a certain key might negate the effect of another key (Colossal Caves, rod scares bird and must be dropped before bird can be picked up, but is needed later to create magical bridge).
> 6 votes

---
Tags: path-finding
---


# Question
Title: Do I need to "use" the shader program when buffering and defining VBO data?
I'm trying to wrap my head around the relation between a GL "program", and the VAOs, buffers, textures, etc. I don't quite understand when I need to "use" my shader program, and when (if ever) I need to "un-use" it?

So when do I **need** to use the shader program (i.e. invoke `glUseProgram`), exactly? Does my shader program need to be in "use" when:

1. Creating and binding VAOs?
2. Creating and binding VBOs?
3. Buffering data to VBOs?
4. Defining vertex attributes (i.e. invoking `glVertexAttribPointer`)?

# Answer
> 3 votes
Your shader is only used during rendering, so it only needs to be enabled before you render the objects.

You also don't need to disable it, there won't be any problems if a shader stays enabled.

# Answer
> 3 votes
Programs have *nothing to do* with vertex array state. Yes, really.

VAOs and their associated functions govern vertex array state. Those are the objects which decide how to interpret vertex data from buffer objects. VAOs are the objects that govern how this vertex data is packaged into a vertex for use by the vertex shader.

But the VAO and the vertex shader have no direct relationship. The VAO describes how data is fed to vertex attribute indices, and the vertex shader *reads* data from those attribute indices. But the two objects never directly communicate. They communicate indirectly though the list of attribute indices.

As such, a particular VAO can feed many distinct vertex shaders. So long as the VS's take the same attributes that the VAOs generate, everything is fine. Similarly, the same VS can be fed from multiple distinct VAOs, so long as they're providing the same attributes.

The only things in OpenGL that care about which programs are in use are:

1. Vertex rendering commands, which use the currently bound program for rendering operations.
2. `glUniform*` commands, which modify the uniform data in the currently bound program. But you should be using `glProgramUniform*` whenever possible, as those don't require the program to be bound to work.

> What about compiling/linking the vertex and fragment shaders?

What about it? `glCompileShader` takes the shader object *as a parameter*; it doesn't care about what program is bound through `glUseProgram`. Same goes for `glLinkProgram`.

> Also, some quick testing now reveals that when defining vertex attributes with the wrong program in use makes the vertex attributes incorrect...

That is a bug in your code. You're probably querying attribute indices from the program with `glGetAttribLocation`, rather than developing an index convention.

# Answer
> 2 votes
You need to enable your shader before rendering and disable it when you don't need it anymore. If you are going to want to change uniforms in your shader at runtime for example, you are going to want to enable your shader in the main game loop, and then change the uniforms.

Disabling the shader is not required, but it would be better if you do it.

---
Tags: opengl, shaders
---


# Question
Title: Would an unbeatable opponent ethical for a game?
Would it be unethical to create an A.I. bot that has full advantage of **ALL** of the game mechanics? Would it be better if it was optional and gave full disclosure before it let you face this opponent?

# Answer
> 0 votes
Starting of with if it was not optional and the player did know: If I was playing through a game and in the final level the opponent was humanly unbeatable I would feel cheated in the same way I would if I bought a jigsaw with a piece left out by design.

If it was not optional and the player didn't know: This is similar to above, but the player will in some ways waste their time trying to achieve the impossible.

If it was optional and the player didn't know, then it's really a time waster.

If it was optional and the player did know then I don't know what it would do for the game other than an Easter egg or for narrative.

Some games have arguably unbeatable elements:

* any endless mode, here there will be a truly unbeatable stage however only a perfect player will be able to reach a level where perfect play will still be defeated. All other levels you see can be beaten.
* in the game splunky a ghost will appear and chase the player if they take too long to finish a level, this is unbeatable in the sense that it can't be stopped or defended against but it is beatable in that you can outrun it.
* in many games you will see your final opponent at an early stage and after being killed you will progress to the next level. But it is always the case that you win in the end.

# Answer
> 0 votes
> Would it be unethical to create an A.I. bot that has full advantage of ALL of the game mechanics?

Probably. (I would say Yes, considering you make a perfect A.I.)

Just like the comments say; If your A.I. takes full advantage of every mechanic in the perfect way, you can never beat it.

Have you seen this answer / post? It is about building in a handicap into an A.I. but the answers also describe why a perfect A.I would be unbeatable.

I think this post will also answer your second question.

---
Tags: ai, game-mechanics
---


title: How can I make huge terrains in Unity?

text:
# Question
Title: How can I make huge terrains in Unity?
How can I make **extremely** huge terrains in Unity? It seems like I can set width and length to large values. But the Heightmap resolution only goes up to 4097 and the Detail resolution only goes up to 4048.

Any ideas?

# Answer
Split the terrain into square "chunks", load those you care about (mostly: Those near the currently active camera) in Update() and - if you are strapped for space (you likely will be), unload the not needed ones far away.

Use pre-calculated low-poly models for far-away terrain LoD, unless you don't mind having a low view distance. Also, if you need the terrain heightmap of far away terrain for anything (like NPC movement or some other simulation), create a low-resolution or variable resolution variant of your terrain to keep in memory; don't use the full terrain data for it. This can be done automatically on game load, but generally it's a better idea to make a tool which creates this pre-generated data during the build or package.

Finally: To avoid floating point precision problems, you'll have to reposition the whole scene every time your main camera moves far away from (0.0f, 0.0f, 0.0f).

Possibly relevant question on Unity Answers http://answers.unity3d.com/questions/17225/dynamic-terrain-loading.html
> 26 votes

# Answer
You'll need to break up the terrains in chunks, ie. several smaller terrains. Yo'll need to 'seam' those agains eachother (with a script) so there won't be 'holes' between them but otherwise you can just start doing them right away.

You might want to know too that since Unity3D ~3.0 you can't move items (read terrains and items) too far away (like +/-100000 steps IIRC) so this will influence the maximum size of your world.

I'm using this in my online RPG game anyway (with the exception that I only use Unity3D for level design, not for the actual game).

Just because I'm curious, would you like to share some info about your game (like advancement, type, graphics, style etc.)?
> 4 votes

# Answer
We did implement huge terrains in Unity5 by processing SRTM data for the whole earth into height-maps for `TerrainData` objects with different Levels of Details\[1\]. There are a couple of things to consider:

1. The very edges of the height maps need to overlap by at least one sample and you need to position your terrains accordingly. `Terrain.SetNeighbors` will not connect the mesh, only account for different levels of detail done by Unity.
2. You, necessarily, need 2^n + 1 height samples per `TerrainData` object, otherwise Unity will just assign a height of 0 to the unset parts.
3. If you have less than 2GB of `TerrainData`, you can get away with having them as Assets in a Resource folder and `Resource.Load` them at runtime. If you have more than 2GB this approach will no longer work as there cannot be more then 2GB of resources with Unity builds. In this case you will need to build AssetBundles and asynchronously load them with the `WWW` object. This has the unwelcomed side-effect of calling `Shader.Parse` for each with an overhead of approximately 500ms. I did report this on the forums\[2\] and are still waiting for a reply. I will submit a bug report eventually.
4. Don't think about using `AssetDatabase.LoadAssetAtPath`, it is only available in the editor and not in Unity builds.

\[1\] https://www.youtube.com/watch?v=2UsyVuWoFbQ
\[2\] http://forum.unity3d.com/threads/shader-parse-delays-loading-of-assetbundle-containing-no-shader.358235/
> 2 votes

# Answer
There are third party solutions.

this code can make terrains of 99,999 meters width, the mountains are any noise formulas, but you can mix 100 noise formulas into one map if you want. for example, in this terrain, the total number of triangles available in a map is between 66million, low resolution, and 200million medium resolution. here is a 66million triangle map, where 0.7mn triangles are updated around the camera. unityplayer giant terrain, WASD and Space
> 0 votes

# Answer
I would recommend loading your terrain in chunks. By using smaller terrains, and perhaps your script could check if you are in a certain proximity to your terrain by using transform.position - terrain.transform.position. I actually wrote a blog post on how to optimize your game as a whole, and I talked about chunk loading. Hope this helps.
> 0 votes

---
Tags: unity, optimization, terrain-rendering, terrain, heightmap
---


# Question
Title: lookAt with orthographic camera (gl-matrix)
Technically this is a webgl question though I think it's generic enough to get some opengl, erm, perspective on it too...

If I setup an orthographic camera (**perspective** matrix) like this:

`mat4.ortho(output, 0, screenWidth, 0, screenHeight, 0, 1)`

And compose it with an identity matrix as the **view**, and then compose my **model** matrix with that - everything is fine and I see the items at the correct size on the screen. However, if instead of using an identity matrix as the *view* I use `lookAt` via:

`mat4.lookAt(output, [0,0,0], [0,0,1], [0,1,0])`

I do not see anything. I've tried some other variations like moving the `eye` parameter from `[0,0,0]` to `[0,0,-1]` and increasing the `far` value of `ortho()` but nothing worked.

What exactly *is* the relationship between `lookAt` and `ortho` \- are they compatible for `perspective`x`view`, if so what settings can I use for `lookAt` such that it works correctly here?

# Answer
> 9 votes
> When I use the identity view matrix, I can see my model, but when I use `LookAt`, it is not visible. How can I see my model using `LookAt`?

The `LookAt` function takes three parameters:

* `eye`, which is where your camera is. in the identity matrix, your camera is at `0, 0, 0`
* `target`, which is where your camera is pointed at. you can think of the camera's direction vector as `target - eye`. In the identity matrix, the camera is facing in the direction of the negative Z axis.
* `up`, which is which way your camera is rotated. `0, 1, 0` is the default `up` in the usual coordinate system.

In order to replicate your identity view matrix, just use `mat4.lookat(.., [0, 0, 0], [0, 0, -1], [0, 1, 0])`.

If the above works, now you can experiment with changing the `eye` parameter to move the camera around.

> If I set up an ortho camera like this: `mat4.ortho(output, 0, screenWidth, 0, screenHeight, 0, 1)`, things go wrong.

Those parameters dont' look right to me. it should be `mat4.ortho(output, -scaleX, scaleX, -scaleY, scaleY, 0, farZ)` . Depending on your coordinates and aspect ratio, the values of `scaleX` and `scaleY` are roughly half the distance between your camera and target to get a similar scale of view to the perspective camera. If you have no ideal, start scaleX and scaleY off at 1. additionally, farZ = 1 is a very short range, you may want to raise it up much higher, especially if you're moving the camera around.

### Playground

I've included a basic "rotating camera around a triangle" demo here, the left side is a perspective projection, the right side is an ortho projection. Feel free to play with the `distance` variable and see how the scale for the ortho changes in proportion to the perspective shrinking as the camera is further away.

```
cv.width = window.innerWidth;
cv.height = window.innerHeight;
var gl = cv.getContext('webgl');
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);

function Mesh(arr) {
  var buf = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(arr), gl.STATIC_DRAW);
  return buf;
}
var mesh = Mesh([0.0, 1.0, -0,-1.0, -1.0, -0,1.0, -1.0, -0 ])

function shader(type, src) {
  var s = gl.createShader(type);
  gl.shaderSource(s, src);
  gl.compileShader(s);
  return s
}
var program = gl.createProgram();
gl.attachShader(program, shader(gl.VERTEX_SHADER, `
attribute vec3 pos;
uniform mat4 view;
uniform mat4 projection;
void main() { gl_Position = projection * view * vec4(pos, 1); }
`));
gl.attachShader(program, shader(gl.FRAGMENT_SHADER, "void main() { gl_FragColor = vec4(1); }"));
gl.linkProgram(program);
gl.validateProgram(program);
gl.useProgram(program)
gl.bindBuffer(gl.ARRAY_BUFFER, mesh);
gl.enableVertexAttribArray(program, 0);
function render(viewport, proj_mat, view_mat) {
    gl.viewport.apply(gl, viewport);
    gl.uniformMatrix4fv(
      gl.getUniformLocation(program, 'projection'), false, proj_mat)
    gl.uniformMatrix4fv(gl.getUniformLocation(program, 'view'), false, view_mat)
    gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
    gl.drawArrays(gl.TRIANGLES, 0, 3);
}
var view = mat4.create();
var ortho_proj = mat4.create();
var perspective_proj = mat4.create();
var fov = 0.7, distance = 4;
var scale = Math.tan(fov / 2) * distance; // since ortho is distance invariant, scale by (distance from camera to some reference point)

function loop(t) {
t /= 1000;
mat4.perspective(perspective_proj, fov, 1, 0.1, 1000.0);
mat4.ortho(ortho_proj, -scale, scale, -scale, scale, 0.1, 100);
mat4.lookAt(view, [distance * Math.sin(t),0, distance * Math.cos(t)],[0,0,0],[0,1,0]);

render([0, 0, cv.width / 2, cv.height], perspective_proj, view);
render([cv.width / 2, 0, cv.width / 2, cv.height], ortho_proj, view);
  requestAnimationFrame(loop);
}
loop();
```

```
body, html { margin:0px; padding:0px; }
canvas { background: #39e; position:absolute; top:0px; }
h2, h3 { position:absolute; top:0px; z-index: 20; }
.r { right:0px; }
```

```
<h2>Perspective</h2>
<h2 class=r>Ortho</h2>
<canvas id=cv> </canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.4.0/gl-matrix.js"></script>
```

---

## Obsolete Answer

This first answer to a supposed question "what, in the general sense, is the relationship between an ortho and a lookAt matrix?".

There's 3 kinds of matrices that combine to form a full transformation:

the **model** matrix, which describes the transformation applied to the vertices of your model to get them into world-space,

the **view** matrix, which describes the transformation to get from your world-space into a camera-relative space (eye coordinates),

the **perspective** matrix to describe how to transform the camera-space positions into how it appears on your screen (clip-space / screen-space after the perspective correction).

In your case, `ortho` and `perspective` are ways to create the perspective matrix, and `lookAt` creates a view matrix (you could also manually create a view matrix by combining a bunch of mat4.translate/rotate/scales to re-create the camera position).

Your final transform must multiply the perspective * view * model matrices.

---
Tags: opengl, camera, matrix, webgl
---


# Question
Title: How to add multi-core features to a game engine that was created to run on a single core?
I'd like to turn old game engines (such as *Doom engine*/*id Tech 1*) that were designed to run on a single core computer into multi-core game engines.

How can I do that?

# Answer
You cannot just edit the binary or configuration files of some already-compiled game written under single-threaded assumptions to turn it into a game that effectively utilizes more than one thread. Unless the code has some existing multithreaded features that were just shipped disabled, making this kind of change requires access to the source code. The switch to a multi-threaded computation model from a single-threaded computation model is non-trivial, which is part of why it continues to be so difficult.

If you have access to the source code of the game in question, making this transition is done exactly the same way as you would in building a game to leverage multi-threading in the first place. It will probably be harder because you will first need to learn the existing code base *and* work around a lot of fundamental design challenges stemming from the fact that the original code probably did not bother to consider concurrency.

The basic process will involve identifying portions of the code that can be rewritten to execute in parallel, and then performing that refactoring. The specifics of the tasks will vary based on the specifics of the code and problems you're dealing with; entire books can be written on the general topic of effective design under concurrency scenarios.
> 5 votes

---
Tags: c++
---


title: Raycast can't hit my player

text:
# Question
Title: Raycast can't hit my player
I have been trying for the past 5 hours to get this to work.

So i have an enemy that has the following script:

```
        private bool Look(StateController controller)
    {
        Debug.DrawRay(controller.transform.TransformPoint(controller.mCombatant._CombatOffset),  controller.transform.TransformDirection(Vector3.forward) * 800,
            Color.green);
        RaycastHit hit;

        if (Physics.SphereCast(controller.transform.TransformPoint(controller.mCombatant._CombatOffset), 360,
                controller.transform.TransformDirection(Vector3.forward), out hit, 800)
            && hit.collider.CompareTag("Player"))
        {
            controller.mCombatant.Target = hit.transform;
            controller.chaseTarget = hit.transform;
            return true;
        }
        else
        {
            return false;
        }

        return false;
    }

```

Now both my enemy (the one this script is attached to) and my player are on the `default` layer

Here are some images that shows the gameview:

As you can see from the above picture The "Ray" should hit the player:

My Player prefab looks like this:

So my question is what have i done wrong?

**EDIT**

So after alot of time i managed to make the following code work (however its a normal raycast :( )

```
    RaycastHit hit;

    if (Physics.Raycast(controller.transform.position, controller.transform.forward, out hit) &&
        hit.collider.CompareTag("Player"))
    {
        var g = 0;
    }

```

This is good but not good enough since i want the vision of my enemy to be more than a straight line :(

# Answer
> 1 votes
I think a spherecast radius of 360 is much too big.

Quickly eyeballing your other colliders, it looks like your characters are about 0.4 units in radius themselves, and only a few units apart.

That means when the physics sphere starts its cast, it's already encompassing all of the colliders nearby. Since spherecasts and raycasts detect only stuff they *hit* as they travel, these already-embedded colliders get ignored.

Try reducing your sphere radius to be more on par with the sizes of your characters & scale of their interactions.

---
Tags: unity, physics, raycasting
---


title: DirectX poor Sprite Performance

text:
# Question
Title: DirectX poor Sprite Performance
I render an animation with 100+ frames. (Direct X9,Sprites / Pngs) I load them all in an array and render them.

How i do it: Load all frames in an array of bytes. When i need the frame x, i create the sprite from the specific buffer with "D3DXCreateTextureFromFileInMemoryEx & D3DXCreateSprite". I do that, bec loading them at the start& at device lost etc takes ages.

My question now: What can i do? Creating the sprite takes very long but why? I googled that including all frames into 1 png and rendering regions from it is faster but isnt that like crazy ? I would get files sizes of 100k x 1080px.

The scenario looks the following: \- Consumes about 100 mb ram (i am okay with that bec its only displaying 1 animation, so about 100 mb total ram for the program) \- Consumes a lot of cpu (not okay, its just rendering 1 sprite at a frame, why does it have way more consume than my 3d rendering)

# Answer
> 3 votes
Sprites in Direct3D are just textured triangles (or rather two triangles forming a quadrilateral). As such, the performance hit is because each time you *change* the source texture it has to flush the sprite batch and submit it as a `Draw`. The key to Direct3D performance is to get as much work into each `Draw` as possible. You are basically drawing two triangles per `Draw` which is always going to perform slowly. If you were drawing the same texture a few thousand times in a row, it would take about the same time as drawing a single sprite.

The general solution to this kind of issue is to use a texture atlas (or specifically for sprites, a 'sprite sheet') where you pack the individual sprites into the same texture. The main challenge is that you are limited to the hardware support for maximum texture sizes. With Direct3D 9 Shader Model 3 hardware, the best you can do is 4096 x 4096. With Direct3D 11, it depends on your target Direct3D hardware feature level but it can range from 4096 x 4096 up to 16384 x 16384. With Direct3D 11 and Feature Level 10.0 or better, you can even get tricky and pack sprites into a 8192 x 8192 textures in an 2D texture array of up to 512.

I have an example Sprite Sheet implementation using DirectX Tool Kit for DirectX 11's `SpriteBatch` class.

---
Tags: c++, 2d, animation, sprites, directx9
---


# Question
Title: How to improve my input handling in GLFW?
Currently I'm busy working on a game engine. I have my own window class with GLFW functionalities. Currently, I have a very primitive way to handle input in my class:

It is not fast, and not "extendable" enough. I'm essentially using something along the lines of

```
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_E && action == GLFW_PRESS)
        //do something
}

```

I would like to call something like the following:

```
// Create a window object
Window window("title",800,600);
//the parameters specify the key pressed and what the window has to do when the event occurs.
window.getKeyPressed(KEY,ACTION);

```

How would I go about implementing a more flexible input handling system?

# Answer
If if-statements won't do it for you, I'd suggest a map-based approach, where your Window (or a separate InputManager) class stores a map of function callbacks, that get invoked when a key is pressed.

```
class Window
{
public:
    using Callback = std::function<void()>;

    void addBinding(int key, const Callback& callback)
    {
        m_Callbacks[key].push_back(callback);
    }

    void onKeyPress(int key)
    {
        for (Callback& callback : m_Callbacks[key])
        {
            callback();
        }
    }
private:
    std::map<int, std::vector<Callback>> m_Callbacks;
};

```

This way you can create `std::function`s and pass those to the class, and then once you get a keypress event from GLFW, all you have to do is call `onKeyPress` with the correct key, and the callbacks will get invoked.

Just be careful with object lifetime if you end up creating `std::function`s for class methods. Adding a `removeBinding` method to the Window class might not be a bad idea.

Also, supporting other events (like key releases for an example) isn't tricky at all with this solution: either add a specific method (like `addReleaseCallback`) or introduce another layer to the map, so that the first layer fetches the correct bindings for an event type, and the second layer is the key lookup.
> 5 votes

# Answer
Similar to Tyyppi\_77's answer, I also normally opt for a map-based approach. However, I prefer to use a map similar to the one shown below:

```
struct KeyPress {
    bool current, previous;
}

std::map<int, KeyPress> mKeyPresses;

```

This way, you can track whether the key has just been pressed, released, or is being held down, based on combinations of bools. You can also easily specify which keys are used, without having to track all of the keys or rely on complicated callbacks. It also, in my opinion, makes conditional events easier to control over callbacks, because you can use if/switch statements to handle whether a key is in a certain state or not.
> 2 votes

# Answer
There is another option, which is more object orientated.

Generate an engine input event for each GLFW input and send it to a central event queue. Then you can have a bunch of behaviours elsewhere in your engine that will handle respond to these events via hard coded behaviour, or scripts:

```
class KeyEvent : public GameEvent {
    public:
        int key;
        int keystate;
};

handleInput(GLFWwindow* window, int scancode, int keystate, Engine& engine) {
    auto event = std::make_shared<KeyEvent>();
    event->key = scancode;
    event->keystate = keystate;
    engine.enqueueEvent(event);
}

Your handler would look something like:

class Controlhandler {
    //game state stuff here
    public:
        void handleEvent(std::shared_ptr<GameEvent> event) {
            auto e = std::dynamic_ptr_cast<KeyEvent>(event);
            if(e){
            // check event, update state, and respond.
            }
        }
};

```

In this way, you can write control handlers which do a bunch of different stuff with the same events.
> 1 votes

---
Tags: c++, input, glfw
---


# Question
Title: Unity3d - AudioSource is not playing if gameObject is removed after play was started
I am not able to play my audio source if I deactivate the panel where the AudioSource is attached to AFTER it.

```
    _audioBtnEnter = tmpBtnGeneral.GetComponent<AudioSource>();
    _audioBtnEnter.Play();
    tmpBtnGeneral.SetActive(false);

```

I would totaly understand if this would not be possible:

```
    tmpBtnGeneral.SetActive(false);
    _audioBtnEnter.Play();

```

But why does the first code not trigger the audio play?

Is this a race condition problem?

# Answer
> 3 votes
When disabling a gameobject, all the attached components are disabled too.

Documentation states the following :

> Making a GameObject inactive will disable every component, turning off any attached renderers, colliders, rigidbodies, scripts, etc... Any scripts that you have attached to the GameObject will no longer have Update() called, for example."

Since your audio source is attached to your gameobject, disabling the gameobject (and thus, the component) will stop the audiosource from playing your audio.

If you need to hide the gameobject, you could disable the `Renderer` instead of the gameobject itself. Otherwise, create an empty gameobject holding your audiosource and disable the gameobject.

# Answer
> 0 votes
I solved it by adding an `AudioSource` Component to the gameObject where my script is attached to and adding a reference to my audio file in the script. Then I play it like this.

```
public AudioClip audioBtnEnter; //Reference to Audio Clip

...

this.gameObject.GetComponent<AudioSource>().PlayOneShot(_audioBtnEnter);
tmpBtnGeneral.SetActive(false);

```

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


title: Weird streching of a texture in OpenGL

text:
# Question
Title: Weird streching of a texture in OpenGL
Here is the problem: I'm rendering a red triangle in an offscreen Frame Buffer Object. I have a texture of that Buffer, and i'm applying this texture to a Simple rectangle(at runtime).

I get This result:

This is exactly what i wanted. the problem is that when i strech my window the texture gets a little weird:

Just for curiosity i tried to render the rectangle without the texture.

And then I stretched the window once again:

I believe this is happening because in my default FBO I am setting glViewport to glViewport(0,0,m\_Width,m\_Height); (m\_Width and m\_Height are the dimensions of the Window)

# Answer
Your guess is correct. Every time you resize your window, make sure both of your `glViewport()` and projection matrix are up to date. In SFML it would be something like this:

```
while (running) {
    sf::Event e;
    while (wind.pollEvent(e)) {
        switch (e.type) {
        // ...
        case sf::Event::Resized:
            glViewport(0, 0, e.size.width, e.size.height);

            // Set your projection matrix here
            // Will be different from one library to the other

            break;
        // ...
    }
    // ...
}

```
> 0 votes

---
Tags: opengl, textures, rendering, rendertexture
---