# Question
Title: Why do some games persistently have mostly one viable strategy, while others can have many?
The interesting thing in *League of Legends* is the existence of the "meta", which, for the purpose of this question, can be defined as the One Strategy That Rules Them All. The meta shifts between patches; but soon after a patch is released, a new variation of the meta emerges and everyone agrees that this particular strategy is, in most cases, objectively best.

It's not that Riot Games doesn't try to migitate this. For instance, they introduced Runes that were supposed to allow personal preferences to be a bigger factor in gameplay – that is, allow a bigger diversity of viable strategies. But most such attempts backfire: there soon emerges the One Correct Rune Page For A Champ anyway.

Oddly, I am told and I read on Internet, this is not the case in *Dota 2*. (I don't know; I don't play *Dota*.) According to information I was able to gather, in *Dota* "nothing is slated in stone" and many heroes can be legitimately played in many roles, there exist multiple viable lane distributions and multiple viable strategies.

This seems counter-intuitive because of another difference between the two games that is frequently pointed out – that is, *Dota* embraces the concept of hard counters (i.e. if you pick a wrong hero pre-game and are hardly able to be relevant in-game then tough luck, you should've picked another hero), while *LoL* considers such mechanics broken and instead strives to provide soft counters mostly. Superficially, hard counters would seem to make a game lean towards "slated in stone" strategy (the correct pick is entailed by previous own team and enemy team picks), while soft-counters would seem to allow more diverse strategies thanks to allowing a greater variation of champs to pick in any given situation.

Might I ask, what exactly makes a game have One Strategy To Rule Them All, and what exactly makes a game have multiple viable strategies instead? I provided the examples of *LoL* and *Dota* because I think the difference is most striking given the similarity between the two games, but I believe the question easily applies to almost any competitive multiplayer game.

# Answer
> 76 votes
In the end it all boils down to one axiom: Game design is hard!

And multiplayer game design is even harder. After years of development, you think you came up with a perfectly balanced game design which allows for multiple viable playing strategies. You did extensive playtesting with a dozen or so full-time inhouse testers and a hundred external spare-time beta testers. They all tried different strategies and they can't tell which one is the optimal one.

But the moment you publish your game, thousands of people (millions if you are one of the lucky few who land a hit like Dota2 or LoL) will jump on it and look for ways to optimize their gameplay. They will scrutinize your game mechanics in ways you never considered possible. And when it is a multiplayer game, knowledge will spread quickly. When one player figured out some new trick, everyone playing with them will learn that trick from them.That knowledge will then be used by all the players to build upon and do even deeper analysis of the game. They will write forum posts and wiki articles to share their research. This thorough overanalyzing will result in someone finding the one strategy which is just a tiny bit more optimal than the others. That knowledge will spread, and soon everyone will play that strategy.

But there is one game mechanic you can not optimize for, and that's human psychology. So if you still want to allow multiple viable strategies, then allow the players to play mind games.

1. Create a rock-paper-scissors system with different strategies. Strategy A beats strategy B and strategy B beats strategy C, but strategy C beats strategy A. A more complex game might have more than three strategies, and they might not necessarily be perfectly balanced against each other. It is OK when one strategy beats more strategies than the others or is much easier to play. All that matters is that you have at least one viable hard-counter for every possible strategy.
2. Design your match progression in a way that players need to commit to one of these strategies early on. You should still allow to change strategies mid-game. Otherwise the match is decided before it even started, which can be pretty frustrating. But changing strategy should be a costly and risky move.
3. Give the players the ability to hide from their opponent which strategy they pursue until the opponent fully committed to theirs. Also add ways for players to mislead the opponent about which strategy they actually pursue, so they can trick the opponent into wasting time and resources on preparing a counter for a strategy they won't use.

Now every strategy is viable as long as the player can bluff their opponent into assuming they pursue a different one.

# Answer
> 16 votes
You said it: Dota has a mixture of RPS balance and fixed, hidden character selection.

The characters that the enemy team chooses to play are hidden information, and thus you must evaluate your own choice of character against a probabilistic model of what the enemy is going to play. Because outcomes in Dota are more dependant on hero selection than in Lol, it is very important to both select heroes that are strong against the heroes that the enemy is likely to play and you want to avoid heroes that are likely to be countered by your enemy doing the exact same thing.

This means that if a hero becomes very popular, then people will choose to play its counters more often, even if such counters are not as strong in general as the popular hero. In other words, the dominant meta heroes in Dota are dependent on a priori expectations about enemy heroes. So hero usage fluctuates chaotically even in absence of balance patches, and at any moment even the theoretically strongest team composition will be beaten by a purpose-made counter team.

It's a cheap way to force diverse hero usage in my opinion. Matches that are decided before players even begin to play are not particularly engaging, but Dota's popularity is surely not entirely illegitimate (I don't play either Dota or Lol btw).

Note that if you remove one of the two components then the whole thing doesn't work anymore: in Lol hero choice is hidden but because counters aren't as strong, the theoretical meta team tends to not have a proper counter with enough of an advantage. In Overwatch you can switch heroes midgame and so even though some heroes are hard countered, you can just switch if you do get countered and generally you can recover from the loss of momentum. Interestingly, it means that in Overwatch some heroes don't get play time even when their counter is not on the field. This is merely because of the threat of potential switching of the enemy to that hard counter.

# Answer
> 13 votes
Player of both here. DOTA has a set amount of damage for most attributes. A Lina ultimate will always deal X amount of damage unless the enemy has a debuff on them that increases the damage they take. This means that Mage damage output from skills remains relatively the same throughout the game.

However, this is offset but each character having a "main" stat like strength, agility, intellect. which adds the the base auto attack damage. The scaling is a little more gradual with utility items and activation items making most of the changes.

This allows for just about any character to be viable as you can almost always defeat the enemy by changing your utility itemization. Get the BKB (Anti-Magic damage) to deal with a pesky mage. Get a Force Staff to give yourself the mobility to escape a jungler. These item changes can effectively shift the strategy unlike LoL.

LoL's take on the MOBA genre is that there will be a rotating list of strong characters to prevent burnout on playing a singular strong META list. This is accentuated by the itemizations and AP/AD affecting the damage of abilities and at different ratios.

To delve deeper into "Why do some games persistently have mostly one viable strategy, while others can have many?". It is the design philosophy. LoL as mentioned above, intentionally has a Flavor of the Month META list. While DOTA as mentioned above, intentionally goes for such a wide variety of counters in combination with slowly increasing attributes to keep the play more like Spy Vs. Spy where gathering knowledge and implementing it becomes more important than individual picks (usually).

Balancing is hard. Thus, changing which characters are stronger at certain patches leads to variety and is easier in terms of design. DOTA's approach is much more fragile but much more rewarding in terms of what characters you can play. Occasionally, certain skillsets have become meta and dominated it but, can always be countered with a certain playstyle or item set.

# Answer
> 7 votes
What other posts have described from a gaming perspective is simply called a stable mixed strategy equilibrium in game theory. Here are some requirements for this:

You generally want to have a game of imperfect information or simultaneous moves. Game theoretically, simultaneous moves are a special case of imperfect information. Without imperfect information, each choice by a player becomes an optimization problem with little flexibility for a player. If one choice is just slightly better than another, one should make that choice. With imperfect information, a player can make a choice that has value because it is unexpected, even if under perfect information there would be a strategy for the other player to make this choice suboptimal.

What is also helpful is to have a game with incomplete information about the other players. Not knowing the goals or ability of another player means that different strategies can be optimal depending on the beliefs the player has about the other player's goal or ability.

The question is what makes the mixed strategy stable? Suppose that a small deviation from the mixed strategy equilibrium (increasing the probability of one action by a small amount) incentivizes others to respond in such a way that the player wants to deviate even further from the mixed strategy equilibrium. Then this equilibrium is unstable and unlikely to be observed in reality. What makes an equilibrium stable is that the other player has an optimal response to my deviation, such that I want to move back towards the equilibrium. Hard counters provide such a mechanism. If a player takes a particular action with greater likelihood, the other players will respond by playing the hard counter to that action with greater likelihood, incentivizing the player to decrease the probability of that action.

Here is how some games achieve strategic diversity. Rock paper scissors is a simultaneous move game with hard counters. Thus, it has a stable mixed strategy with maximal diversity given the number of strategies. Chess is a game of perfect information in sequential moves. This is bad for strategic diversity in principle. However, given our limited computational abilities, it is actually a game of imperfect information as neither player can compute the optimal strategy to the end. Moreover, at the highest level it is a game of incomplete information because the players do not know which openings the opponent has prepared.

# Answer
> 4 votes
I'm not initmately familiar with LoL or Dota, and a definitive or comprehensive answer will be hard to come by in any case, but allow me to share some mechanisms I have observed.

### Choice

From a naive viewpoint, the more unique options you offer to players, the greater the risk that one of them will turn out overpowered and/or break some core mechanic. In Dota/LOL, the number of playable characters, each with their own unique abilities, is quite high, so if only one of them turned out too powerful, that will shape the metagame. To make matters worse, many players tend to more or less blindly latch on to whatever strategy's deemed the most powerful, exaggerating the imbalance.

A common approach to mitigating this is to introduce specialization via classes or roles (e.g. tank, spank, healer in most MMOs). The idea is that if different options compete in different categories, there has to be at least some diversity (e.g. at minimium, one optimal tank, damage dealer and healer instead of just one optimal character).

In practice, this approach carries the danger of pigeonholing both individual options (a damage dealer might now be measured *only* by their dps, making it easier to find the "best" choice) and overall composition (a party *needs* to have a tank and a healer).

The above is a pretty typical attempt to "pre-empt" a specific metagame by, effectively, codifying a different one, thus limiting (viable) choice. This may well be intentional, as it can make a game more accessible and easier to balance towards the chosen playstyle (Blizzard likes to do this a lot), but whether desired or not, it will lead to a "stale" meta that swings heavily with balance patches. LoL would probably fall into that category.

### On counters

I would argue that where an option falls on the "hard vs soft counter" spectrum matters far less than how options are chosen and what mechanisms a player has to react to an opponent's choice.

Consider Starcraft 2, for example. As a rule of thumb, you have to pick a build before even scouting the enemy. Once you know what they're up to, you can of course react, but that takes time. Philipp has outlined that mind game aspect pretty well.

Say you went for Roaches and your opponent went Phoenix. That's (at reasonable numbers) a hard counter, the Roaches can't ever shoot up. However, it doesn't mean you lost the game, you're just at a disadvantage until you transition into something else, say, Ling/Bane/Hydra.

Now, in LoL/Dota, you can't switch champions mid game, but you can pick items and change up your tactics to adapt to a limited degree. The relative influence of these mid-match decisions compared to your initial champion pick determines the "wiggle room" you have for making a strategy viable, affecting the range and diversity of viable strategies.

### Synergy and interaction

As a rule of thumb, options that compete, but do not (meaningfully) interact lead to one superior option emerging and the rest being phased out.

Spellcasters in D&D 3.5 had, among many other tricks, two very similar methods of defeating a monster: reducing their hitpoints to zero, or reducing one of their ability scores (strength, intelligence etc.) to zero. The latter turned out to be slightly easier, so that's what character-optimizing players would pick.

In this case, changing the numbers will usually just lead to a few days of chaos until players have determined the best option again.

In the interest of a diverse and malleable metagame, options need to interact. Whether this is in the form of counters ("rock-paper-scissors"), synergies or something else entirely, the idea is that the presence of one element changes the strategic role or value of another, shifting in turn the value of the inciting element (the principle behind "perfect imbalance").

Again, there is a risk of severely limiting your metagame if you don't provide a wide range of interactions. If fire damage is unusually common or powerful, and Ice Armor is the only counter to that, guess which spell everyone will pack?

Now, if I were to hazard a guess, based on PSquall's description, it sounds like LoL with its rigid role and lane structure might have hit this nail as well.

# Answer
> 2 votes
> What exactly makes a game having One Strategy To Rule Them All, and what exactly makes a game having multiple viable strategies instead?

* The total number of interacting game mechanics which offer the player **a variety of options** which might lead to one or more victory conditions.
* The total number of simultaneous victory conditions, AND how loose tight or loose the constraints on achieving each victory condition are, at every step through play.
* Designers ability to recognise different strategies, and impose different pros and cons thereon.

More mature mods, and more recent games, tend to have more attention applied by the designer to (dynamic) balancing, as collective human knowledge of what makes good game design, grows.

Any early game prototype, in the absence of attempts to balance it, *will be horribly unbalanced*. The more dynamics we introduce, the more potential paths we give the player, which *may offer opportunities* to balance better; however this still doesn't imply the game *is* more balanced, just that there are now more choices through which the player *might* succeed over other strategies.

**DoTA is the elder of the two games (second only to AoS) in the MOBA genre, and I would say that this is why it retains the more primitive "pick before you start" design.**

As seen in AoE, Warlords Battlecry III, Rise of Nations, Total Annhilation and indeed many in the RTS genre, it's fairly essential to give players a range of different outcomes that can lead to victory. Any game that doesn't do this is, in the first place, narrowing its player base to those with a skillset optimal to achieving that One Metric of Success, for example, twitch-based first-person shooters.

Crucially, designers (should) want to support different play styles. This means allow something like the X-beats-Y-beats-Z-beats-X type cycles already mentioned here, although that graph can be a lot more complex than just a three part XYZ ring. Alternatives are the hallmark of good gameplay.

But it all depends on the designers' target market. If DoTA's target is older players who have been playing MOBAs for 15+ years happy, then they wouldn't change the dynamics, would they? The key for them might be (and probably is) keeping the older, loyal fanbase happy.

# Answer
> 2 votes
Given a non trivial game **it takes time/work to find a winning strategy**.

Once a winning strategy has been found other strategies can be **adapted to counter it**.

If adaptations are found the strategy is considered weak. **If no adaptations are found the strategy is strong**.

Eventually strategies will be "stronger" as they have shown to be able to overcome "weaker" strategies. The meta consist of every current winning strategy considered strong, but as time progresses more and more will be considered weak.

The meta can then become a single strategy that is strong vs everything or it becomes a set of weaker strategies that counter each other but are strong against all other known strategies.

The meta is just the players thinking there is a stable set of viable strategies. It has no correlation to the possible strategies that could be.

In a **"overbalanced"** game new winning strategies are likely to be strong vs old strategies, because **lack of time or choices to adapt after the strategy is deployed**.

In a **"underbalanced"** game new strategies are likely to be weak vs old strategies, because **time is given to adapt and overcome after the strategy is used**.

**Dota is "overbalanced"** (compared to Lol), everything has a counter, and that counter has a counter etc. This is largely because the game is hard, unforgiving, unpredictable and unintuitive. **Once you are taken by surprise it is too late to recover**. Unknown beats known.

**Lol is "underbalanced"** (compared to Dota) because the game is more intuitive, that is **easy to reason about and apply once figured out**. Riot has long removed the design guidelines that makes explicitly it under balanced but it lives on in the game. Notably (in the past) **Lol enforced that it is never wrong to use skills**, just not optimal. Not wrong means that the gap between minimum and optimal skill usage smal. Failing to apply a strategy has less impact in Lol over Dota because of this **skill floor**.

# Answer
> 2 votes
There two steps to creating a game with many viable strategies: 1. Create a game where winning depends on both players choices 2. Cultivate a community that encourages creative approaches to playing the game

The first part by itself is not a huge issue, Rock Paper Scissors being a simple example, but the trick comes in how it interacts with the second part. For there to be a community that explores the game there needs to be something to explore. In the case of Dota or Starcraft this means lots of moving parts and continuous choices rather than discreet. For example, consider how positioning units in Starcraft can affect the outcome and how that might change if things snapped into a grid. (Not that grid based games can't have depth). All these factors give players a lot of points of control to manipulate.

However, it is also important to give community things that can be communicated in concrete terms. Items to buy in a MOBA or build times in Starcraft are good examples of that. This gives the community a shared language, but can also lead to rigidity if everything can be decided on ahead of time.

The most important thing to realize in all this is that balance in these types of games is mostly a social construct. If you let the community decided that there is only one way to win the game it doesn't matter if that is actually true or not.

This leads into the second step, cultivating a community.

Why is a community important for having many strategies? Because the community is who is actually using the strategies. Using League of Legends patches as an example, the meta changes at that point not solely because of the actual balance changes, but more because the community *expects* things to change. Suddenly, new ideas are allowed and the meta adapts. You can tell that this occurs when a community behaves as if a balance change was made when it was actually a mistake in the patch notes.

Different communities have different expectations around how the Meta should change, who can change it, how much to adhere to it, and how it should be enforced. The League community has, at times, enforced Meta adherence through toxic behavior, such as afking or verbal harassment, which leads to a very rigid Meta. If you can cultivate a community that doesn't self police so effectively than you can avoid this.

You need to make sure that the unique, the strange, and crazy strategies aren't squashed before they are discovered. Reducing cost of failure, encouraging positive player interactions, and proving places for players (new, old, skilled, unskilled) to practice and experiment can all be tools used to accomplish this. There are a bunch of ways to get players to feel free to explore the game space.

Even in games with ridged metas you can often see what the game could be in the Pro scene. Pro players have the social standing, by way of there skill to be afforded space to break the meta and often do.

So, I think the secret sauce to a shifting meta is a community that shifts the meta, the game just provides the space for it.

# Answer
> 1 votes
League player here, so everything i say about Dota has to be taken with a grain of salt.

League is designed to support several distinct roles/lanes in mind: Support, Carry, Mid, Jungle, Top. While in the recent past the game changed alot and the meta reflected that (No Marksman as carry, funneling a hyper carry etc.), those roles are pretty much consistens and Riot changes seem to aim to keep it this way (e. g. make funneling impossible, so no "jungle support" in mid). But most likely, you dont see support champs in toplane, or mages in jungle etc. That said, everytime there are changes, that targets a specific type of champ, e.g. tank buffs or an assassin item gets nerfed, you feel those changes mostly in the roles, those type of champs get picked. For example Tanks in Top, Jungle and Support, assassins in mid, maybe top and recently in Support role, thus creating a swing in Meta.

The changes in Dota 2 are mostly soft, trying to balance out the meta, thus creating a plain field, where everything is possible, but because real hard counters exist, hero select is way more important and more strategic. You can't compensate that much with skill (Dota has way less skillshots than League for example), and you have to rely on, that everyone knows, what every other champ does.

This makes it very hard for a meta to establish, as the meta can get countered with maybe 2 or 3 champs. So Valves is interested in keeping champs as balanced as possible.

Riot keep those changes heavy handed, maybe in interest of strong meta swings and thus creating counter-meta and so on. And most likely, its their interest to keep this "Perfect Imbalance". Extra Credit had a great video about this.

# Answer
> 1 votes
You mention hard counter and soft counters. What distinguishes them? The only difference between them is if a counter can be overcome or not.

For example, Rock-Paper-Scissors is a hard-counter-game. Meaning that one option **definitively** counters another. To matter how much Paper tries, it will **always** lose to Sciccors.

As another example, if you play an ineffective Pokémon type against a Pokémon of a stronger type, you will be at a disadvantage, but that doesn't mean you can't win. Therefore, it is a soft counter.

Where do we draw the line between a hard counter and a soft counter? That's a really good question. I don't think we can create a definition that everyone agrees with.

Technically speaking, taking +100% damage from an enemy which counters you, and only doing 1% damage to that enemy is a *soft* counter. If the enemy never hits you and you consistently hit the enemy, you can technically still win.
But this may not be true in context (healers, potions, mana restrictions, health regen, ...)

The question is what is **reasonably** possible, and that mean you need to define what's reasonable, which is inherently subjective. How impossible must something be for it to actually be considered impossible?

---

> Might I ask, what exactly makes a game having One Strategy To Rule Them All, and what exactly makes a game having multiple viable strategies instead?

Limiting myself to multiplayer versus games, there are two main game incentivizes:

* Getting the best result
* Beating the opponent

While they often coincide, changing the prioritization between the two options will often lead to different gameplay.

**Getting the best result** is like playing a racing game. It's all about who get across the finish first.

Contrast that to a racing game where the winner is decided by score, which can be increased in several ways (doing tricks, wrecking opponents, a high finish ranking).
Suddenly, there are **multiple** ways to win the game. You might hang back and therefore not try to cross the finish first, but instead have a clear shot at the opponents in front of you. You might go off-track completely in order to do tricks around the map to score points.
As long as your playstyle gives you a chance at getting a higher score than the others, you are using a valid strategy.

The key to having a varied-strategy-game is to allow for different win conditions (or different ways to achieve a single win condition).

---

The generalized approach to gameplay is a series of questions that the player asks themselves:

* How can I win the game?
* How can I prevent the others from making me lose the game?
* How can I positively impact my chance of victory?
* How can I negatively impact the opponent's chance of victory?

*You may think that the first two questions are the same, but that is not always true. Taking the example of racing games, compare a race where you cannot bump into each other (you can only win by driving fast) and a race where you can bump into each other (you can win by driving fast, or you can make others lose by ramming them).*

This is how a strategy is formed. It works in all types of games:

**RPG-like games (DOTA, LoL)**

* How can I win the game? =\> Get to the end objective.
* How can I prevent the others from making me lose the game? =\> Prevent them from getting to the end objective.
* How can I positively impact my chance of victory? =\> Get better stats, buff yourself. Avoid being temporarily disabled.
* How can I negatively impact the opponent's chance of victory? =\> Debuff the enemy or temporarily remove them from the board.

**Sports games (Rocket League)**

* How can I win the game? =\> Score goals.
* How can I prevent the others from making me lose the game? =\> Defend your own goal.
* How can I positively impact my chance of victory? =\> Learn to handle your car better, improve your teamwork, learn tactics.
* How can I negatively impact the opponent's chance of victory? =\> Run interference on the enemy's team work. Ram them, demolish them, read and counter their tactics.

Part of a strategy is to choose how to tip the odds in your favor. For example, in soccer/football, it's not uncommon for a team that's leading to start playing more defensively. The first strategy (scoring even more goals) is irrelevant as long as they can ensure the second strategy (preventing the opponent from scoring any goals).

If your team is better at defense than it is at offense, it makes sense to play defensively **once you have the lead** (not before). If you're better at offense instead of defense, it may make sense for you to play aggressively and assume to gain a bigger lead on your opponent that they cannot recover from.

This effectively boils down to a "when they zig, we zag" approach, which is the essence of multi-strategy games.

# Answer
> 0 votes
(Only just realised this is quite similar to @Arcane Engineer's answer, but I'll leave it up as it provides some examples form a different genre)

It's CCG rather than videogame based, but somewhat relevant: I read an interesting comment yesterday from Richard Garfield (who created Magic: the Gathering).

Context: he has a new game coming out in which every deck is unique, generated by an algorithm, so no two players will have the same deck.

Obviously, a lot of people are curious about how this is going to work. People are wondering how you can be sure an algorithmically generated deck will maintain balance between players.

He has a couple of anecdotes including one from an earlier competitive CCG, in which a particular deck building strategy emerged that was deemed to be unbeatable. There were repeated calls for elements of the game to be nerfed, since in competitive games anyone able to implement this strategy was guaranteed to win. They decided to leave it as it was. Then at the world championships some players suddenly unveiled a tactic which successfully countered the 'unbeatable' strategy.

Even the game designers didn't know whether a counter was possible. But they chose not to reduce the complexity of the game , and to leave it up to the players to find a solution.

# Answer
> 0 votes
To add to the discussion above as someone who plays both, league items and dota items are designed very differently. In leagues most items are bought for their passive stats while in dota items are bought for their active abilities.

In league this leads to less variation as the optimal item build can be built before hand while in dota it requires player execution and decision making to be effective. This allows the game designers to design differently. In league the designers have to plan the game around the items due to how static they are. In dota they can focus on designing around periods of action where item abilities are used.

Thus in league player decisions are set in stone from the get go if they execute the draft as they should but in dota the draft can be turned around by player decisions.

This is counterintuitive in that making the items more complex makes game balancing simpler, and that in general giving the players more hard decisions to make makes the game more fun ( in a game that isn't hyper casual)

# Answer
> 0 votes
Seems pretty simple...

Different game companies cater to different gamer demographics. Some like the grind, some like the strategy, and a newer thing is for some to get submersed in the game as part of their daily lives.

I also suspect it's easier to make money in a pay to win model in a more linear game with less options, but if all games were like that there would be an uncatered to demographic of gamers who want a bit more than to provide a credit card to win.

# Answer
> 0 votes
Something that might interest you is "Open Ai" for DotA2. Basically it's machine learning for bots. These bots managed to win against the best Human teams (except when they picked a bad hero lineup). So it isn't too unrealistic that even something this complex might be practically solved. Like chess.

Now, there are some concessions made for the bots (they have superhuman reflexes, map awareness and coordination. It's also not played with the full hero pool), but we already see players using some of the bots strategies that might seem unintuitive at first. Like suicidal strategies that generate more value then they cost, because the enemy has to respond and you buy time/space for the rest of the team. Or focusing more on buying regeneration while in lane.

Now we can say the exact opposite. While theoretically bots could solve the game, for players there's always more they could do. So there is a better strategy players just haven't found it yet.

So in theory there always is a perfect strategy, but in practise what matters is how fast your players find it, and how often they change their opinion. I think at the highest level this is increased by more complexity. Everyone can solve 3-wins after 20 minutes. Dota needs millions of ay hours.

Dota so has a interesting patch-strategy. There are some small patches every month, but really there are around 2 big patches per year. These patches shake up the very basics of the game. In the new environment other heroes and strategys shine, and you have to start solving again.

Obviously this has its own problems.

---
Tags: game-design, multiplayer, balance
---


title: Cocos2d JS - Getting vector reflection

text:
# Question
Title: Cocos2d JS - Getting vector reflection
I'm working on a small Breakout clone using Cocos2D-JS, without the use of a physics engine.

One of the things that baffles me was how the ball bounces. My friend came up with this:

> inputVector - 2(normalVector * inputVector)

I have no idea how to translate that in code. So I tried with this:

```
g_Ball.position = this.velocityComputer(cc.p(g_Ball.x, g_Ball.y), cc.p(this.x, this.y));

velocityComputer: function(inVector, thisNVector) {
    var prodVec = cc.pDot(inVector, thisNVector);
    var retVec = inVector - (2 * (prodVec * inVector));
    cc.log(retVec);
    // cc.log(blockNVec);
    return retVec;
},

```

But `g_Ball` doesn't change directions, and `retVec` simply logs `NaN`.

Any suggestions?

Thanks.

# Answer
Kevin ven der Velden's answer is close, but gets the types wrong.

The dot product of two vectors returns a scalar (float)

```
var prodVec = cc.pDot(inVector, thisNVector);

```

So this isn't eligible as an argument for the componentwise multiplication function `pCompMult` because it's not a vector.

In the case where your second input is a normal vector (pointing in the direction the surface is facing) of unit length, the dot product gives the projection of your input vector onto this normal's direction.

Scaling the normal by this projection gives us the vector component of our input vector in the direction away from the surface. Subtracting this from our input once gives a vector parallel to the surface. Subtracting it twice gives us our reflected vector: moving away from the surface by the same amount, in the opposite direction.

```
pReflect: function(inVector, normalVector) {
    var projection = cc.pDot(inVector, thisNVector);
    var retVec = cc.pSub(inVector, cc.pMult(2 * projection, normalVector));
    return retVec;
},

```
> 1 votes

# Answer
Javascript does not support operator overloading (i.e. specifying how "-" on something that isn't a number should work), you should call whatever functions your vectors provide for that (I can't find any documentation that cocos2d-js provides that API).

The NaN is because javascript is going "I don't know how to multiply these 2 things that aren't numbers, so that's Not A Number (NaN)"

```
velocityComputer: function(inVector, thisNVector) {
    var prodVec = cc.pDot(inVector, thisNVector);
    var retVec = cc.pSub( inVector, cc.pMult( cc.pCompMult( prodVec, inVector ), 2 ) );
    cc.log(retVec);
    // cc.log(blockNVec);
    return retVec;
},

```
> 0 votes

---
Tags: javascript, cocos2d
---


# Question
Title: how to use glm::rotate with a eulerangle?
I have a `vec3` to represent my object's orientation/rotation but the `glm::rotate` method expects a quaternion. If I just convert it to a quaternion like this:

```
glm::quat rot = rotation;

```

The W value will just be zero, right? And then there won't be any changes in rotation.

In my code I just want to be able to do `rotation.x += 5.0f;` in the update method of an object.

This is the method I'm using for my transformations:

```
glm::mat4 GameObject::Transform(glm::mat4 model, glm::vec3 position, glm::vec3 scale, glm::quat angleAxis)
{
    model = glm::translate(model, position);
    if (angleAxis.w > 360.0f)
    {
         angleAxis.w -= 360.0f;
    }
    else if (angleAxis.w < 0.0f)
    {
         angleAxis.w += 360.0f;
    }
    model = glm::rotate(model, angleAxis.w * toRadians, glm::vec3(angleAxis.x, angleAxis.y, angleAxis.z));
    model = glm::scale(model, scale);
    return model;
}

```

Currently I'm just passing on that rotation `vec3` to that `angleAxis` quaternion parameter but that obviously doesn't work.

This is how i currently calculate my front, up, and right vectors:

```
void GameObject::calculateCameraView()
{
    front.x = cos(glm::radians(rotation.x)) * cos(glm::radians(rotation.y));
    front.y = sin(glm::radians(rotation.y));
    front.z = sin(glm::radians(rotation.x)) * cos(glm::radians(rotation.y));
    front = glm::normalize(front);

    right = glm::normalize(glm::cross(front, worldUp));
    up = glm::normalize(glm::cross(right, front));

    front.y = invertMouse ? front.y * -1 : front.y;
}

```

# Answer
> 2 votes
> in my code i just want to be able to do rotation.x += 5.0f; in the update method of an obj

A quaternion representing a rotation of `angle` radians in the x axis is:

```
q.x = sin(angle / 2f);
q.y = 0;
q.z = 0;
q.w = cos(angle / 2f);

```

Or in general for any `angle`-`axis` rotation:

```
q.xyz = axis.xyz * sin(angle / 2f);
q.w = cos(angle / 2f);

```

---
Tags: opengl, rotation, glm
---


# Question
Title: Access violation executing location 0x00000000
When I try to debug my program, this Exception is being thrown in a call to `glGenBuffers`. I'm using OpenGL and SDL. Here is my code:

It consists of two classes: m and sprite

s is var of sprite class

class m is like this:

```
void run()
{
    init();
    s.init(-1.0f,-1.0f,1.0f,1.0f);
    loop();
}

void  init()
{
    SDL_Init(SDL_INIT_EVERYTHING);
    glewExperimental = GL_TRUE;
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    window = SDL_CreateWindow("mine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 768, SDL_WINDOW_OPENGL);
    if (window == nullptr) {

        fatalerror("cant create (open) window");
    }

    SDL_GLContext context = SDL_GL_CreateContext(window);
    if (context == nullptr) {

        fatalerror("context cant be created ");

    }
    GLenum cerror = glewInit();
    if (cerror != GLEW_OK)
    {
        fatalerror("cant init glew:(");
    }
    std::cout << "ok";

    glClearColor(1.0f, 0.0f, 0.0f, 1.0f);

}

void looploop()
{
    while (state != gamestate::exit)
    {

        input();
        draw();
    }

}
void M::input()
{
    while (SDL_PollEvent(&events)) {

        switch (events.type)
        {
        case SDL_QUIT:
            state = gamestate::exit;
            SDL_DestroyWindow(window);
            break;
        case SDL_MOUSEMOTION:
            std::cout << events.motion.x << ',' << events.motion.y << "\n";
            break;
        }

    }

}

void draw()
{
    glClearDepth(1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnableClientState(GL_COLOR_ARRAY);
    s.draw();

    SDL_GL_SwapWindow(window);

}

```

class sprite:

```
void init(float x, float y, float w, float h)
{
    _x = x;
    _y = y;
    _w = w;
    _h = h;

    if (vboid == 0) {

        glGenBuffers(1, &vboid);
    }

    float vertexdata[12];
    //first triangle
    vertexdata[0] = x + w;
    vertexdata[1] = y + w;
    vertexdata[2] = x;
    vertexdata[3] = y + h;
    vertexdata[4] = x;
    vertexdata[5] = y;
    //second triangle
    vertexdata[6] = x;
    vertexdata[7] = y ;
    vertexdata[8] = x+h;
    vertexdata[9] =  y;
    vertexdata[10] = x+w;
    vertexdata[11] = y+h;
    glBindBuffer(GL_ARRAY_BUFFER,vboid);
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertexdata),vertexdata,GL_STATIC_DRAW)
        ;

}

void draw()
{

    glBindBuffer(GL_ARRAY_BUFFER,vboid);
    glEnableVertexAttribArray(0);
    glVertexAttribLPointer(0,2,GL_FLOAT,GL_FALSE,0);
    glDrawArrays(GL_TRIANGLES,0,6);
    glDisableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vboid);

}

```

# Answer
Let me guess, you're on ms windows?

You need to "wrangle the OpenGL extension" using GLEW. Personally, I use OpenGL Core Profile, and use GL3W to do this for me on the windows platform.

Without doing glewInit() or gl3wInit() first, your extension function pointers are all nil, hence the crash.

On all other platforms (Linux, MacOS, etc) this is not necessary. Root cause for this is Microsoft's Installable Client Driver model.
> 1 votes

---
Tags: c++
---


title: Creating random path in grid

text:
# Question
Title: Creating random path in grid
I need to find a path with required length in the ***N****x**N*** matrix without loops and deadlocks. For example:

1. We Have a grid ***7****x**7*** (49 blocks in total) with **START** (orange) point.
2. We need to build random path length of 25 cells.
etc

My problem is I don't know how to create the path with required length fast and avoid loops and deadlocks.

# Answer
Edit: I just noticed you don't have a fixed endpoint to steer towards.

In this case, we can solve this with recursive backtracking:

```
Path FindPathOfLength(int length, Point startPoint) {
    // Track visited state so we don't touch/cross.
    MarkVisited(startPoint, true);

    foreach(cardinal direction in random order) {
        // Check if there's a path of the desired length in this direction.
        path = Extend(length, startPoint, direction);
        if(path == null)
           continue;

        // Finish & return the path.
        path.Add(startPoint);
        return path;
    }

    // Search failed. No such path exists!
    return null;
}

Path Extend(int remainingLength, Point startPoint, Direction currentDirection) {

    // Proceed in the given direction to find our next point.
    point = startPoint + currentDirection;

    if(point is out of bounds OR point is already visited)
        return null;

    // Avoid touching/crossing path so far.
    foreach(neighbour in 2x3 rectangle forward, left, and right of point)
        if(neighbour is within bounds AND already visited)
            return null;

    MarkVisited(point, true);

    // Endpoint! Time to bubble back up.
    if(remainingLength == 0)
        return new Path(point);

    foreach (turnDirection forward, left, or right of currentDirection, in random order ) {
        // Search for a feasible solution to a smaller sub-problem.
        path = Extend(remainingLength - 1, startPoint, turnDirection);
        if(path == null)
             continue;

        // Extend that path to include this point.
        path.Add(point);
        return path;
    }

    // No such path through this point panned out. Undo our choice to try it.
    MarkVisited(point, false);
    return null;
}

```

---

Or, assuming a fixed endpoint (that's feasible to reach in the desired path length. ie. `desiredPathLength - ManhattanDistance(start, end)` is even), one way we could do this is using a force-directed graph.

We pick n points with floating point coordinates in our grid to start with, with point 0 being our start and point 1 being our end. Place the rest roughly along a line between these two, with small random displacements (this seeds our randomness)

Now we have our initial constraint of a non-self-intersecting line of points with the desired number of intermediate sites, but it might not yet be a "path" since sequential points might not be in adjacent cells.

Then we loop over the points from i = 1 to i = n - 1; in each iteration:

* We apply an attractive force to pull point I toward the closest of four points: point i - 1's position plus or minus one or the x or y. Then the same, relative to point i + 1.
* We apply a repulsion force to nudge point i away from any other points less than 2 grid cells away.
* Also apply a repulsion force to any points that try to stray outside the bounds of the grid.
* If point i lies in a valid grid cell adjacent to the cells of points i - 1 and i + 1, and has no other points in its cell or adjacent cells, then we call it "satisfied"

Once all points are satisfied, we round their positions to grid cells and we have our final path.
> 3 votes

---
Tags: algorithm, random, grid, tower-defense, path
---


title: How do I draw text using DirectX 12?

text:
# Question
Title: How do I draw text using DirectX 12?
I'm currently tasked with porting a control from Direct 11 to DirectX 12.

How do I draw text on the screen?

How do I draw any 2D on a DirectX 12 device?

Current Text rendering code is below:

`using (var textFormat = new TextFormat(device2DManager.DirectWriteFactory, string.IsNullOrEmpty(text.FontName) ? FontName : text.FontName, text.FontSize == 0 ? FontSize : text.FontSize))
 {
renderTarget.DrawText(text.Text, textFormat,
 new RawRectangleF(autoPosition.HasValue ? autoPoint.X : text.Location.X, autoPosition.HasValue ? autoPoint.Y : text.Location.Y,
 renderTarget.Size.Width, renderTarget.Size.Height),
 foreColor);
}`

# Answer
How did you draw your text with DirectX 11?

> `D3DX9`, `D3DX10`, `D3DX11` and in fact the entire legacy DirectX SDK are deprecated per MSDN. You don't actually need it for DirectX 11, and it doesn't support anything to do with DirectX 12. See Living without D3DX

For drawing text on Direct3D 11 or Direct3D 12, you have two basic choices:

1. You can use Direct2D/DirectWrite to render the text. With DirectX 11.1 or later, the device sharing makes this fairly straight-forward but it is a fair bit of code. This is the best option if you want to support complex layout, very large character sets, and highly scalable resolution output.
2. Alternative you can either implement or use the same 'spritesheet' based approach that was implemented in the legacy `D3DX` library font system. For C++, see `SpriteFont` in the *DirectX Tool Kit* for DX11 and DX12.

For C# using SharpDX, option (1) might be your best bet.
> 1 votes

---
Tags: c#, directx, sharpdx, directx12
---


# Question
Title: How to create a skybox in an infinite world like minecraft?
I'm making a minecraft-clone game in C++ using OpenGL.

I created a skybox using OpenGL's cube map but the camera can go outside of the skybox since it's an infinite world. Then I changed it to update the skybox's coordinate based on camera's coordinate like below but it didn't change anything.

How can I make a skybox stay at a relative position from the camera?

```
auto coord = camera.getCoords();
// positive x
skyboxMesh->addFace(
              coord.x + size, coord.y + size, coord.z - size,
              coord.x + size, coord.y + size, coord.z + size,
              coord.x + size, coord.y - size, coord.z - size,
              coord.x + size, coord.y - size, coord.z + size
              );

```

# Answer
The traditional way to do that is to create a modelView matrix that contains only rotation information. It should contain the same rotations as the camera, but not the translation, so that it's always at the origin. Use that with the same projection matrix as you use for the rest of the scene. Draw your skybox centered at the origin. After you draw your skybox, clear the depth buffer if you're using one, and then draw the rest of your scene as you normally would.

What this does is draws the skybox and then treats it like it's infinitely far away so that all other things draw over it.

As @DMGregory points out, you can reduce the amount of overdraw by doing this:

> A slight improvement is to draw all your opaque geometry first, then draw the skybox, setting its depth to the far plane in the vertex shader. This gives you a little less overdraw, since the skybox gets occluded anywhere ground was already written.
> 3 votes

---
Tags: opengl, c++, cubemap, skybox
---


# Question
Title: Unity 5 Standard Assets for Linux / Ubuntu
Unity recently has released Unity3D Editor for Linux machines. But in its website there is no support for Linux / Ubuntu. As of Unity 5 standard game assets have been removed from the editor itself and should be installed apart.

For installation I should follow these steps:

But there are only options for Windows and OS X, nothing for Linux. So what should I do? Is it possible to do it manually?

# Answer
According to that article, the link to the download is there. The link is: Unity Editor 5.1.0f3 For Linux. It is considered 'experimental'.

> there are only options for Windows and OS X, nothing for Linux

It is because the current build is `experimental` and is not very suitable for game development as there may be game-crashing bugs still.

You will be able to use any platform of standard assets. There is little to no difference between the standard assets for OSX and Windows. It is also available on the Unity asset store.

Referring to Unity on Linux Release Notes,

> The Unity Editor for Linux is packaged into two types of installers: A .deb package, which can be installed via the Ubuntu Software Center and is expected to work on installations of Ubuntu 12.04 or newer. A platform-agnostic self-extracting shell script, which is designed for other distributions.
> 3 votes

# Answer
I had the same problem using Unity3D for Linux.

I installed the Standard Assets by downloading the Window version of the standart assets (.exe), installed it with Wine and then copy the folder resulting from the installation into my Linux Unity folder (by default for me it was /opt/Unity/Editor)
> 3 votes

# Answer
Now 2016.09.20, Unity3d 5 for Ubuntu can install `standard assets` from Assets Store inner Unity3d.
> 0 votes

# Answer
You just download unity using the following link,

Unity 5.1 For Linux

It will contains standard asset also. Don't forget to select standard assets while installing.
> 0 votes

---
Tags: assets, unity, linux
---


title: Display object at different position

text:
# Question
Title: Display object at different position
Id' like to create impression of shaking holographic image of NPC in Unity 2018, but moving it with transform will cause unnecesary transform-rigidbody syncing, and using Rigodbody.position isn't an option for other reasons (too long to explain). I could write custom shader for moving vertices by given vector, but I'd like to keep flexibility of Standard Shader.

Is there any way to properly render object at different position than it's transform.position? I was thinking about passing custom matrix to shader, but not sure which matrix should I overwrite and if it's not gonna complicate things (like break shadows or something).

# Answer
> 2 votes
Yes, you have several options here:

* Use Graphics.DrawMesh (or one of its variants) to manually submit a drawing call, without a renderer component at all. You can provide your own position & orientation or matrix to control exactly where it's rendered, independent of any transforms. The mesh you draw this way can still cast & receive shadows from the given position & orientation.
* Use a Surface Shader, or a modified copy of the Standard Shader source (under Downloads -\> Built in shaders), make a shader that both has your position offset effect *and* has the flexibility of the Standard Shader.
* Place the Renderer into a nested transform, under the Rigidbody, with no Colliders attached to this Renderer object or its children. Then you can move it with impunity without impacting the physics, since it's strictly a display object. I use this trick to animate my dominos' wiggly walk cycles in Last One Standing while their physics stays smooth.

---
Tags: unity, rendering, matrix
---


# Question
Title: Average points per second in a world editing game
I am making an online single-player game (open beta here) with a huge emphasis on content creation and world design (sort of like Super Mario Maker or Little Big Planet but more designed for adventure or "short story" games). The default gameplay style is a sort of Zelda-esque action RPG but it can also handle things like platformers or arcade-style shooters. "Worlds" can vary greatly in scope, from a single short hallway to basically a full game.

In order to tie all of these diverse worlds together and make travel between them meaningful, I am using a universal currency (called Sparks) that world builders can use as collectibles and give as rewards for defeating enemies or completing challenges, and can also be used to purchase items and so on. To prevent their abuse and discourage boring "spark farming" worlds, the amount of sparks a player can take from a world is capped based on *the amount of time they spent in that world*, and the world builder is rewarded for another player exploring their world based on *how close the player gets to obtaining a certain percentage of that cap*, encouraging them to make it *easy* to obtain around that amount, and *possible* for a skilled player to acquire more (making it worthwhile for players to replay their world in order to master it) but not exceeding the cap.

Right now, the cap is one spark per second, and the "ideal average ratio" is one fifth of that. However, one point every five seconds seems *far* too low and unrewarding for most kinds of games, especially fast-paced arcade-style worlds where it is not uncommon to beat more than one basic enemy or pick up multiple collectibles per second. However, setting the cap too *high* can make spark collection feel meaningless since their total value just looks like "a big number".

I have done some searching for advice or writing on typical scoring rates for different game genres or even the psychological impact of using different scoring methods. I know that some old arcade games would add a few zeros to their score system to make things feel more rewarding but beyond that I could find very little writing on the subject. What is a typical "points per second" value that feels rewarding and can work for a large number of possible genres?

# Answer
> 1 votes
I'm not sure that there exists an established magic number like "0.77 points per second" that holds across families of games. This is the type of tuning we usually do in the context of a single game, specific to that game's needs and rhythm.

In fact, when you say...

> I know that some old arcade games would add a few zeros to their score system to make things feel more rewarding

this suggests that these sweet spots for a particular game can vary over several orders of magnitude. In some games, the base points are in 10s, others are in 100s. So I don't think you'll find research that argues convincingly that any particular value X is generally best, even within a single genre.

What you may want to consider instead is the **role of various rewards** in your game. Here I'm borrowing from a series of lectures & workshops on player psychology from Celia Hodent, author of the Gamer's Brain.

When you talk about getting these points every few seconds, it sounds like you're describing a **continuous reward**. This is the bread & butter layer of rewards for participating in the game, a regular hum of feedback saying you're making progress.

These rewards are important to game feel (eg. the "+100" points text or shower of coins flying out of a destroyed target), and to learning game systems. They tell the player what actions in the game are valued and useful. They're not so strong at creating sustained engagement though. Once the player learns that they can reliably get X points per second from a swath of different actions in your game, it's no longer a surprise or a reason to strive to complete *this particular* action. It's expected, and fades into the background of play.

For this type of reward, it's important to be reliable & consistent. So this might *not* be the layer you want to put into UGC player control. If not providing enough of these rewards in a given time span diminishes your game feel, then don't require creators to understand that design principle and exactingly reproduce this metronome of continuous rewards to keep the game feeling good. Instead, build your scoring rules into the system, so you can ensure every level created with the kit of parts you offer to players has a certain baseline level of feel.

Sustained engagement in games more often derives from **intermittent** rewards. These are rewards that don't come quite so regularly - like the cherry in Pac-Man instead of the continuous reward of the dots, or the UFO flying by in Space Invaders compared to the regular enemies. Because they're sporadic, they're less useful for establishing baseline moment-to-moment feel and learning, but they're also less impacted by habituation - they keep feeling exciting for longer, because opportunities to score them aren't continuously available, so players pay extra attention when they see an opportunity on the horizon.

By making these rewards somewhat rare or unpredictable, you build anticipation - maybe in the next room I'll find a chest! Maybe this boss drops some super loot!

This less predictable/reliable, more occasional layer reward might be the one you want to put into UGC player control, harnessing the unpredictability of players to create variety & interest in a few key areas, rather than painstakingly breadcrumbing out continuous rewards throughout. This can be in an entirely different set of units than your continuous rewards. Defeating a single basic enemy might score 100 points, while collecting just 5 "gems" placed by the creator might be a pretty good result for completing a whole level.

# Answer
> 0 votes
I think you've got a few exploitable issues here but I'll start with your main question.

You are right many games differ in their expected reward schedule, but **sparks don't have to be what is awarded for everything in game**. An arcade style game for instance could give arbitrary non-spark points for playing, but later convert points to sparks based on some ratio or table of thresholds. If having points other than sparks is a no-no then they could still be limited by making them based on more complicated goals. Destroying an enemy may be one thing, but to earn a spark you might need to destroy a whole squad before they leave the screen or indulge in other risk-reward behavior that will up the challenge for players hunting sparks.

With that out of the way though I think you should *reconsider your farming deterrents*.

If players get have a desire to gain more sparks then they will tend towards playing the games with the largest reward. If content creators desire more of their rewards then they'll make games that give out exactly what gives them the maximum reward, regardless of player ability. With these two factors I suspect you'd see most games starting out at giving the 1/5 per second you mentioned with some creeping upward hoping to make back in volume what they lose out on in giving out more. This assumes though that giving more than 1/5 per second actively harms the creator's reward, as otherwise they have no reason not to give the players as much as they can possibly receive in order to draw the most players.

On top of all that, relying on mutual greed to limit your economy is a dangerous game. This goes double when neither side loses anything when the other gains. All it takes to wreck the balance is to have one creator benefactor who isn't concerned with personal reward (or a player willing to make a second account to benefit their first) and you suddenly have idle games that spit out the maximum sparks per second allowable by the systems, at best possibly loosely hidden by weak gameplay mechanics.

In order to combat these behaviors, it's important to figure out what behaviors your ideal players would participate in, and then balance the systems such that the best way to *exploit* the system is to take part in those behaviors. You'll never be able to stop players from gaming the system, but you can make sure that gaming the system is fun for everyone involved, including those doing the gaming.

---
Tags: scoring, world-editor
---


# Question
Title: online game, NPC monster death and hit detection to gain experience points
I'm doing a simple idle game, HTML5 client and Node.js server, but I'm making it online, where the client talks to the server (websockets) and all the logic is in the server (I want to prevent cheating as much as possible, because I want to have leaderboards).

My idea is, when the player X attacks the mob Y and it hits for 10 (should gain 10xp), so I send that via websocket, "playerX|10". How do I validate the input, so that a cheater can't just send "playerX|100000000".

Also how do I handle mob deaths? Do I send a "playerX,mobY" and the server replies with a drop?

Am I worrying too much about security? The golden rule is never trust the client, but how?

I'm thinking maybe all the client does is send actions?

message: attack|mobY, and the server calculates everything, xp gains, hit values, but I still don't know how to handle mob death, without having to keep state for the current "fight" with that mobY.

Sorry if I'm not clear enough. If you can share some thoughts or articles about this stuff, I'll be very glad!

# Answer
> 3 votes
When you want a cheating-proof client/server game, then you need to handle all game mechanics which are worth cheating on the server.

Don't send "Player X hits enemy Y for Z damage". Just send "Player X attacks enemy Y". Leave the damage calculation to the server. Then tell the client how much damage they made and whether or not the mob is still alive and when it is dead how much exp the player has now. If you are limiting attack speed, then the server should also check how long ago the last attack was. But keep in mind that you can not rely on network latency being constant. So when you receive an attack-command which is 3 ms too early, don't just reject it. Execute it 3 ms later.

---
Tags: html5, security, online
---


title: How to calculate inverse of quaternion?

text:
# Question
Title: How to calculate inverse of quaternion?
I would like to calculate

```
Quaternion.Inverse(Vector3(45,85,96));

```

but I got error message

```
Expression denotes a `type', where a `variable', `value' or `method group' was expected

```

# Answer
It looks like you might be trying to write

```
Quaternion.Inverse(Quaternion.Euler(45, 85, 96));

```

Although in a shader language like hlsl you can just write `float3(45, 85, 96)` to get a vector, in C# the *type* `Vector3` is different from the *constructor method* used to create one. When you just write `Vector3`, you're referring to the type, but when you write `new Vector3(...)`, you're calling its constructor to make a new instance of the type. That's why you get the error:

> Expression denotes a 'type', where a 'variable', 'value' or 'method group' was expected

But, that's not the full problem here. The `Quaternion.Inverse()` method wants a `Quaternion` as its argument, not a `Vector3`, so even using the correct syntax to create a `new Vector3` instance, it's still going to complain that you're giving it the wrong ingredient.

Assuming that the three components of this vector are actually three Euler angles describing an orientation, you can create a `Quaternion` that describes that same orientation using the factory method `Quaternion.Euler()`
> 1 votes

---
Tags: unity, quaternion
---


# Question
Title: Choosing the correct normal for a collision
I have taken the task of building a basic impulse physics engine. Circle vs Circle collision resolution has been done and I moved onto Line vs Circle. I can detect a collision and know that the normal should be perpendicular to the line which can be calculated easily (2d physics engine). However it's the direction of the normal that I cannot work out.

From the image you can see there are 2 possible normals, one upwards (the correct one) and one downwards. How do I choose the correct normal?

# Answer
> 1 votes
Generally you'd check which side of the line your circle is on, and flip the normal if it's pointing away from the circle:

```
Vector2 outward = circle.center - line.startPoint;

if(Vector2.Dot(outward, normal) < 0f)
   return -1f * normal;

return normal;

```

This is susceptible to an error called "tunneling," where a small, fast-moving circle might move into and *juuuuust* past the line in a single update. Then, even if it came from the top side, our check above will see that the circle is currently on the bottom side and produce a downward-pointing normal instead.

For extreme cases of tunneling (where the circle hops all the way over the line and we never detect the collision at all), there's not much we can do except reduce the timestep, give the colliders some "thickness," or switch to more expensive continuous collision detection.

But for slight tunneling we can sometimes do better by checking against the incoming velocity instead of position - assuming that if we've encountered a collision, then whichever way the circle was moving should be opposite the surface normal. That would look like this:

```
// Compute relative velocity of the circle from the perspective of the line.
Vector2 inward = circle.velocity - line.velocity;

if(Vector2.Dot(inward, normal) > 0f)
   return -1f * normal;

return normal;

```

This can run into errors if you have multiple collisions being resolved in sequence, if an earlier collision resolution modified the velocity so it's not pointing in the direction that originally caused the collision. So watch out for that, and make sure you're looking at the snapshot of the velocity from the impact, not from a subsequent rebound.

---
Tags: physics, mathematics, vector, physics-engine
---


# Question
Title: using a wire-frame shader on a plane how can i also fill in the squares with a solid color so that each square's color can be changed?
I'm not sure if using a shader is the best way for what I'm trying to achieve, but I would like to apply a color to each of the squares like in the picture and have the ability to change each color separately. I got the shader on this site: Link to Shader site

```
Shader "Custom/Geometry/Wireframe"
{
Properties
{
    [PowerSlider(3.0)]
_WireframeVal("Wireframe width", Range(0., 0.5)) = 0.05
    _FrontColor("Front color", color) = (1., 1., 1., 1.)
    _BackColor("Back color", color) = (1., 1., 1., 1.)
    [Toggle] _RemoveDiag("Remove diagonals?", Float) = 0.
}
    SubShader
{
    Tags{ "Queue" = "Geometry" "RenderType" = "Opaque" }

    Pass
{
    Cull Front
    CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma geometry geom

    // Change "shader_feature" with "pragma_compile" if you want set this
keyword from c# code
#pragma shader_feature __ _REMOVEDIAG_ON

#include "UnityCG.cginc"

    struct v2g {
    float4 worldPos : SV_POSITION;
};

struct g2f {
    float4 pos : SV_POSITION;
    float3 bary : TEXCOORD0;
};

v2g vert(appdata_base v) {
    v2g o;
    o.worldPos = mul(unity_ObjectToWorld, v.vertex);
    return o;
}

[maxvertexcount(3)]
void geom(triangle v2g IN[3], inout TriangleStream<g2f> triStream) {
    float3 param = float3(0., 0., 0.);

#if _REMOVEDIAG_ON
    float EdgeA = length(IN[0].worldPos - IN[1].worldPos);
    float EdgeB = length(IN[1].worldPos - IN[2].worldPos);
    float EdgeC = length(IN[2].worldPos - IN[0].worldPos);

    if (EdgeA > EdgeB && EdgeA > EdgeC)
        param.y = 1.;
    else if (EdgeB > EdgeC && EdgeB > EdgeA)
        param.x = 1.;
    else
        param.z = 1.;
#endif

    g2f o;
    o.pos = mul(UNITY_MATRIX_VP, IN[0].worldPos);
    o.bary = float3(1., 0., 0.) + param;
    triStream.Append(o);
    o.pos = mul(UNITY_MATRIX_VP, IN[1].worldPos);
    o.bary = float3(0., 0., 1.) + param;
    triStream.Append(o);
    o.pos = mul(UNITY_MATRIX_VP, IN[2].worldPos);
    o.bary = float3(0., 1., 0.) + param;
    triStream.Append(o);
}

float _WireframeVal;
fixed4 _BackColor;

fixed4 frag(g2f i) : SV_Target{
    if (!any(bool3(i.bary.x < _WireframeVal, i.bary.y < _WireframeVal,
[![Plane with Shader attached][1]][1]i.bary.z < _WireframeVal)))
    discard;

return _BackColor;
}

    ENDCG
}

    Pass
{
    Cull Back
    CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma geometry geom

    // Change "shader_feature" with "pragma_compile" if you want set this
keyword from c# code
#pragma shader_feature __ _REMOVEDIAG_ON

#include "UnityCG.cginc"

    struct v2g {
    float4 worldPos : SV_POSITION;
};

struct g2f {
    float4 pos : SV_POSITION;
    float3 bary : TEXCOORD0;
};

v2g vert(appdata_base v) {
    v2g o;
    o.worldPos = mul(unity_ObjectToWorld, v.vertex);
    return o;
}

[maxvertexcount(3)]
void geom(triangle v2g IN[3], inout TriangleStream<g2f> triStream) {
    float3 param = float3(0., 0., 0.);

#if _REMOVEDIAG_ON
    float EdgeA = length(IN[0].worldPos - IN[1].worldPos);
    float EdgeB = length(IN[1].worldPos - IN[2].worldPos);
    float EdgeC = length(IN[2].worldPos - IN[0].worldPos);

    if (EdgeA > EdgeB && EdgeA > EdgeC)
        param.y = 1.;
    else if (EdgeB > EdgeC && EdgeB > EdgeA)
        param.x = 1.;
    else
        param.z = 1.;
#endif

    g2f o;
    o.pos = mul(UNITY_MATRIX_VP, IN[0].worldPos);
    o.bary = float3(1., 0., 0.) + param;
    triStream.Append(o);
    o.pos = mul(UNITY_MATRIX_VP, IN[1].worldPos);
    o.bary = float3(0., 0., 1.) + param;
    triStream.Append(o);
    o.pos = mul(UNITY_MATRIX_VP, IN[2].worldPos);
    o.bary = float3(0., 1., 0.) + param;
    triStream.Append(o);
}

float _WireframeVal;
fixed4 _FrontColor;

fixed4 frag(g2f i) : SV_Target{
    if (!any(bool3(i.bary.x <= _WireframeVal, i.bary.y <= _WireframeVal,
i.bary.z <= _WireframeVal)))
    discard;

return _FrontColor;
}

    ENDCG
}
}
}

```

# Answer
> 0 votes
Share an idea for you. Use shader can do that but maybe use `Plane` meshes is more simple . Each grid is covered with a plane.You may change the plane color property of its material by what you desired. I kown you care about the performance.So please read this : MaterialPropertyBlock

> MaterialPropertyBlock is used by Graphics.DrawMesh and Renderer.SetPropertyBlock. Use it in situations where you want to draw multiple objects with the same material, but slightly different properties. For example, if you want to slightly change the color of each mesh drawn.

At last, I supply a good example for this:

The magic of Material Property Blocks

This is my first answer at GameDevelopment.I hope this could help you.

---
Tags: unity, shaders
---


# Question
Title: How to use nodes in scene graph for game logic
I am working on a 3D 2048-game using Java with LWJGL to gain some 3D math and OpenGL experience. I built a small scene-graph (GroupNode and Box). My problem is that the tree structure of my scene-graph is not very convenient for the game-logic. For the game-logic I would use a 2D-array to store the tile-values, merge tiles and calculate points and so on. I think it would be a good approach to separate the view (SceneNodes) from the game-logic-type (Tile). What is best practice to link them, update views, and how to care about animations? If I merge two tiles and present this by move the source tile into the target tile, I need to know when the animation finished to do the next merge-move.

# Answer
Im not sure, what the "best practice" would be, but maybe what a good approach would be.

If you want to keep your seperation for view and game logic like that, consider adding sort of 'events' ir 'states' that do sort of their thing. Somethinglike "Start Animation" that blocks any input and starts the anmation of given tiles to merge. As the animation takes place, a certain time frame is given, after that the state is set back, whice should corrrespond to the time for the animation.

If you have an overarching game class with the game loop, this could keep the state, so neither your game logic nor your view need to be linked.

So, first your game logic detects a merge and sets the state with additional information of the two merger. Your view checks the state and draws like normal in addition to do the animation. After everything is done, in the last frame of animations, your view sets back the state, so inputs are processed again.

What is important to realise is, that neither your game logic nor your view are the sole owner of the tile information. Both of them need access to the data to draw and process.
> 1 votes

---
Tags: scene-graph
---


# Question
Title: Why am I getting this "Android SDK does not include any platforms!" error?
This question has been asked several times on the Unity answers website, but there's no solid answer to it!
**Problem:** While trying to build a game for android in Unity, I receive this error:

```
Android SDK does not include any platforms!

```

Yet I have all Android platform APIs downloaded.
I've tried all of the suggested solutions:

* Running Unity as Admin
* Manually modifying the AndroidSdkRoot registry value
* Deleting the old android platform folders
* Reinstalling Android SDK into a folder other than Program Files
* Reinstalling Unity
* Recreating the project
* Renaming "android-sdk" folder to "android-sdk-windows" since that was the default folder name value in the Unity's Browse dialog window.

Some Notes:

* The Android SDK Home in Preferences value gets reset every time I try to build the project!
* I'm also not using the Eclipse bundle, I installed Android SDK using the .exe installer.
* Using Windows 8 Pro x64 (if it makes a difference)

I'm absolutely clueless, but I feel like this is a bug on Unity's side which needs to get fixed. If not, please let me know what I'm doing wrong.

# Answer
Unity seems to suggest it's a three step process which seem to be missing from your list. If not it could be a driver error.

> http://docs.unity3d.com/Documentation/Manual/android-GettingStarted.html
>
> Android SDK Setup There are some steps you must follow before you can build and run any code on your Android device. This is true regardless of whether you use Unity or write Android applications from scratch.
>
> 1. Download the Android SDK Go to the Android Developer SDK webpage. Download and unpack the latest Android SDK.
> 2. Installing the Android SDK Follow the instructions under Installing the SDK (although you can freely skip the optional parts relating to Eclipse). In step 4 of Installing the SDK be sure to add at least one **Android platform** with API level equal to or higher than 9 (Platform 2.3 or greater), **the Platform Tools**, and **the USB drivers** if you're using Windows.
> 3. Get the device recognized by your system This can be tricky, especially under Windows based systems where drivers tend to be a problem. Also, your device may come with additional information or specific drivers from the manufacturer.
>
> For Windows: If the Android device is automatically recognized by the system you still might need to update the drivers with the ones that came with the Android SDK. This is done through the Windows Device Manager.
>
> http://docs.unity3d.com/Documentation/Manual/android-sdksetup.html

Could it be that you have no platform to emulate or run your .apk?
> 1 votes

# Answer
I've had a lot of trouble with Android SDK and unity. Forgive me if i sound condescending but my suggestions would be to

* Ensure that you have plenty of platforms installed on Android Studio (SDK Manager)
* I had some grief with spaces in the URL, my path to the android sdk included spaces, my android sdk is now located here: "C:/AndroidSDK" with platforms 21 - 28 installed.
* When i once received errors for Android SDK, they were actually pertaining to JDK, im currently using C:/Program Files/Java/jdk1.8.0\_161
* Im also using a reference to NDK which i've put inside of the Android SDK folder
* Try adding JAVA\_HOME to your "Path" in System variables too

Good luck, if i remember what other steps i attempted i'll add them here.
> 0 votes

---
Tags: unity, android
---


title: Lag Compensation in a Real-Time Game

text:
# Question
Title: Lag Compensation in a Real-Time Game
I have been trying to implement some lag compensation techniques for a real-time game, I've found some good resources online, but I don't think I fully understand the server-side part of the problem.

The game is a simple 2D game, where the player moves an entity around the map. There will be other entities with their own behavior that are controlled by the server, but I made it so that their movement can be easily interpolated. The player input is quite simple: an analog stick and some commands (pick target, loot objective, etc.). The game runs at a fixed 10 TPS (it's on mobile and it's not that action packed, 10 TPS will suffice). The client will send the input state every tick (even if no input is present, like the analog stick is in the default position).

It is worth mentioning that **only one player is connected** at the same time, so in a way this is not multiplayer, but I need to run this on the server as well to prevent cheating.

I understand client-side prediction and that's quite straightforward to implement. I am struggling with the server-side part. As far as I can see I have 3 options:

1. The server waits for the input from the client then computes the new game state and sends it to the client. This is a viable option only because there is only one player.
2. The server runs the game loop waiting up to 100ms (10 TPS -\> 100ms / tick) for an input. If it gets one, it will be taken into consideration when computing the next state, otherwise it will be discarded. If an input arrives after the tick was done, it will be discarded. If an input arrives during this timespan, but the tick numbers don't match (client send input for tick 5, but server is at tick 7) it will be also discarded.
3. The server runs the game loop waiting up to 100ms (10 TPS -\> 100ms / tick) for an input. If it gets one, it will be taken into consideration when computing the next state, otherwise it will be discarded. In this case it will not care if the input is not for the current tick, it will apply it anyways.

Option 1 is the easiest to implement and will be more consistent. The biggest issue with this is that I believe it's easy to cheat. Since the server is waiting for input, the player might be able to "pause" the game, analyze the situation then dispatch the action, basically allowing a cheating player to play in slow-motion. The client-side reconciliation in this case seems easy, when the player moves, it will move instantly on the screen and when it received the updated state from the server it will do it's reconciliation.

Option 2 is a tad harder to implemented (not by much though), but it will be unplayable (literally, the player won't be able to move) if their ping is higher than 100ms.

Option 3 has the same complexity as Option 2. It will work with pings higher than 100ms but it will most probably lead to some frustration on the player's side since their inputs will not arrive in time.

Is there a better way to do this? What are your thoughts?

# Answer
> 1 votes
From previous readings and a bit of experience your option 3 plus interpolation would work; essentially when the server receives input in the correct time frame it deals with it as usual, but when it receives input a bit late it will essentially add back in some extra input.

Say for example that the user can move the entity around at 1 unit per tick, and the input arrives 1 tick late(so it has been 2 ticks since the user pressed the input) then the server will treat that second tick of input as "extra input" and interpolate it back in by allowing the player to move slightly faster visually while the calculations are performed as if the player started the movement at the desired time. Its up to you to decide how fast you want that "extra input" to be evened out so you will have to test and tweak until it feels right for your game

---
Tags: networking, lag
---


# Question
Title: Issuing one-to-one inter-player challenges
I have a small game I have written in Unity (at present only for Android). It is a very simple game where you get more points the longer you last. Nothing complicated.

In order to help "spread the word," I want to enable players to challenge others to see who can score higher. I am not talking about their all-time high scores (these I save in the Google Game Play leaderboards).

How can I easily manage a one-to-one challenge?

I can't seem to find a straight forward way to do it using the Google SDK. It has the turn based play option but in my case each one plays separately. When both have played, the results get compared.

Short of setting up my own backend, how can I go about this?

Note: I am happy to use the FB SDK if necessary since that is how the challenges will be generally sent.

# Answer
You already seem to have a way of sending challenges using the FB SDK, so we'll skip right ahead to actual challenge matches; In short all you need to do is keep a database entry of the score the other user had and send along the ID of the match in your challenge requests.

If there is more information you need to save, say it is head to head gameplay and not competitive single player then things get a bit more complicated as you need to essentially save the gamestate along with the ID, but it doesnt seem to be the case for you as your game is competitive single player.
> 1 votes

---
Tags: unity
---


# Question
Title: How to create class for storing different types of vertex?
I am writing graphics engine for educational pursoses and have some problems.

I need to have ability to use different vertex formats (for example position+normal+uv or position+normal+uv+bones+weights). I have different structs for these formats and have a class HardwareBuffer that stores OpenGL vertex and index buffers. The problem is to give this class the ability to work with different types of vertices. There are a way to make this class template and use like this:

```
HardwareBuffer<VertexPosNormUV> buffer;
buffer.addVertex(VertexPosNormUV(vector3(1, 1, 1), vector3(1, 0, 0), vector2(1, 0)));

```

But in my engine there is an interface IRenderer that have virtual method `drawDataFromHardwaveBuffer`. Also there is a class OpenGLRenderer that is inherited from it. And now I can't pass my hardware buffer object to this method because there isn't a way to use template virtual methods.

```
Renderer renderer = createRenderer(GraphicsDriver::OpenGL3);
renderer->drawDataFromHardwaveBuffer(buffer); // can't make this method template

```

I can write functions for every type of vertex but this is not a solution.

How can I solve the problem?

# Answer
I'm not personally a fan of this architectural direction (giving the buffers strong vertex types and using runtime polymorphism in graphics abstractions). That said, a simple solution to this kind of problem is to hide the template argument by working with a base interface class.

In this solution your `HardwareBuffer<T>` type inherits from a `BasicHardwareBuffer` base, which provides the basic methods needed for the `Renderer` to use it. These basic methods are generally just ones that return a pointer to the buffer data (as a `void*` or similar), the size in bytes of the buffer, and some format enumeration that you can map to the underlying format enumeration for the concrete API.

In other words:

```
struct BasicHardwareBuffer {
  void* getBufferData();
  std::size_t getBufferSizeInBytes();
  BufferFormat getBufferFormat();
};

```

`HardwareBuffer` then is-a `BasicHardwareBuffer`:

```
template<typename VertexType>
struct HardwareBuffer : BasicHardwareBuffer {
};

```

`drawDataFromHardwaveBuffer` can take a pointer or reference to a `BasicHardwareBuffer`:

```
void Renderer::drawDataFromHardwaveBuffer(BasicHardwareBuffer& buffer) {
}

```

You can implement `BasicHardwareBuffer`'s methods by requiring the child types pass information about the buffer size and format up from their own constructors:

```
HardwareBuffer<VertexType>::HardwareBuffer(std::size_t elementCount)
: BasicHardwareBuffer(elementCount * sizeof(VertexType), VertexType::Format) {
}

```
> 2 votes

---
Tags: opengl, c++, architecture, vertex
---


# Question
Title: Handling different renderers Y axis direction in a single engine
I have an engine that uses either `three.js` (3D WebGL rendering library) or `pixi.js` (2D rendering library) depending on the game.

The problem is that `pixi.js` has y-axis pointing downwards (same as in most 2D applications), while `three.js` has it up, like most 3D rendering systems.

I am wondering if there is a way to gracefully handle the difference in the engine, so that the user doesn't have to remember to invert everything depending on if they use 2D or 3D.

Are there any known solutions or engines doing something similar? My first guess would be trying to invert all coordinates, but this seems like an ugly hack that won't necessarily handle all situations.

# Answer
> 2 votes
> My first guess would be trying to invert all coordinates, but this seems like an ugly hack that won't necessarily handle all situations.

That's the solution. You have to reconcile the coordinate systems at some point, and if your users aren't expected to, it becomes your burden to bear.

Pick the coordinate system you prefer, and in your abstraction over the API that uses the *other* system, transform the Y coordinates provided by your users to the expected values.

How "ugly" this ends up looking is largely a factor of how cleanly your code interfaces with the other API (and in how many different places). It may behoove you to try to minimize the surface area shared by your API and the one you're wrapping, so you have to do this coordinate system transform in as few places as possible.

Some APIs allow you to set global, override-like transforms when setting them up, which you can use if available to reduce the effort on your part. I don't know enough about either of the APIs you mentioned to know if that's true.

---
Tags: 2d, 3d, architecture, rendering, three.js
---


# Question
Title: What's the difference between length function and distance function in Unity Shader?
I'm confused about the two functions, do they return the same thing?

# Answer
> 2 votes
`length()` takes in one vector and returns the magnitude of that.

`distance()` takes in two and returns the distance between those. Basically, `distance(a, b)` is the same as `length(a - b)`

# Answer
> 0 votes
Distance is the length between **two** vectors. Length is the magnitude of **one** vector.

---
Tags: unity, shaders
---


# Question
Title: Move Object to another Object's position on click Raycast
I have one object, a knight, that I click on and want to move around on terrain.

```
private void OnMouseDown()
{
   if (Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit, 10000))
    {
        if (unitSelected)
            MoveUnit(hit);
        else if (unitSelected && hit.collider == home)
            GoHome(hit);
     }
}

```

And

```
private void OnMouseDown()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit))
            MoveUnit(hit);
    }
}

```

Both scripts work fine when clicking on the terrain.

**The Problem**

I want to click on different objects and send the knight towards whatever object I click on.

The knight does NOT move, though the object I click on registers a click (all objects have colliders).

Is Raycast the most appropriate way to do this? Checking another users question similar to mine, (how-to-move-one-object-to-another-objects-position) they seem to use a method similar to "Vector3.MoveTowards".

**EDIT:**

Moving my code from "OnMouseDown" to "Update" solves that issue. but is there a reason why OnMouseDown won't work or even how to make it work? I was trying to limit my code from going into Update as that's called every frame.

# Answer
> 1 votes
I would highly suggest not having multiple OnMouseDown methods, as conflicts might arise. It would probably be best to send the knight to the hit position, and not the "object" itself. Physics.Raycast wont care if its terrain or an object, if it hits something it will return a position.

---
Tags: unity
---


# Question
Title: How to organize passing data to shaders in cross-API render system?
I try to create rendering system that supports DirectX and OpenGL. I am trying to create class for constant buffer, but DirectX constant buffers and OpenGL uniform buffers have different memory organisation rules. Is there any way to to achieve the compatibility between DirectX and std140 from OpenGL?

Or probably will it be better to choose a other way to create abstraction of constant buffers for shaders? And how developers solve problem of passing data to shaders effectively in serious engines?

# Answer
Yes, you can solve this with another layer of abstraction.

The structure that client code uses to fill out shader parameters does not need to be the same structure the engine actually provides to the underlying API. So your engine could present the simple structure:

```
struct DrawParameters {
  Matrix4x4 worldTransform;
  float glowAmount;
  float chromaticAberationStrength;
  // ...whatever..
};

```

Within your engine code, you take the instances of the above structures that you're given in any particular set of draw requests and you copy the data into suitably-sized, suitably-aligned buffers that you'll actually give to OpenGL or DirectX or Vulkan or Metal or whatever you're really using under the hood.
> 0 votes

---
Tags: opengl, shaders, architecture, directx, design-patterns
---


# Question
Title: How to calculate angle for shooting bullet in 3D?
What I want to know is if I can calculate an angle similar to how I'm doing in 2D and update the x,y,z position of a bullet based on that angle in a similar manner I'm doing the update function below.

I wrote this function in Ruby to find the target angle between two 2D (x,y) vectors, but now I want to find out how to do this in 3D in a similar way:

```
  def target_angle(point1, point2)
    x1 = point1[0]
    y1 = point1[1]
    x2 = point2[0]
    y2 = point2[1]
    delta_x = x2 - x1
    delta_y = y2 - y1
    return Math.atan2(delta_y, delta_x)
  end

```

Given an object (like a bullet in this case), I can shoot the object given a target\_angle between the player (x,y) and the mouse (x,y), as such in the bullet update function:

```
  def update
    wall_collision
    # the angle here is the target angle where point 1 is the player and
    # point 2 is the mouse
    @x += Math.cos(angle)*speed
    @y += Math.sin(angle)*speed
  end

```

Is there a similar method to calculate a target angle in 3D and use that angle in a similar manner as my update function (to shoot a bullet in 3D)? How can I make this work for two 3D vectors (x, y, z), where you have the player position (x,y,z) and some other arbitrary 3d point away from the player.

# Answer
Instead of finding the angle using `atan2` and then reconstructing the vector using `sin` and `cos` you can store the direction using a normalised vector.

This works in both 2D and 3D.

```
  def target_angle(point1, point2)
    x1 = point1[0]
    y1 = point1[1]
    x2 = point2[0]
    y2 = point2[1]
    @delta_x = x2 - x1
    @delta_y = y2 - y1

    len = Math.sqrt(@delta_x*@delta_x+@delta_y*@delta_y);
    @delta_x = @delta_x / len;
    @delta_y = @delta_y / len;
  end

  def update
    wall_collision
    # the angle here is the target angle where point 1 is the player and
    # point 2 is the mouse
    @x += @delta_x*speed
    @y += @delta_y*speed
  end

```

To do it in 3D just add the math for `z` the same way `x` and `y` are calculated.

```
len = Math.sqrt(@delta_x*@delta_x + @delta_y*@delta_y + @delta_z*@delta_z);

```

You can even ditch `speed` and store it right inside `delta_x`, `delta_y`, and `delta_z` by multiplying them by `speed` after the division by `len` to normalise them into a unit vector.

```
    @delta_x = @delta_x / len * speed;
    @delta_y = @delta_y / len * speed;

```

...

```
    @x += @delta_x
    @y += @delta_y

```

So the whole thing in 3D becomes:

```
  def target_angle(point1, point2)
    x1 = point1[0]
    y1 = point1[1]
    z1 = point1[2]
    x2 = point2[0]
    y2 = point2[1]
    z2 = point2[2]
    @delta_x = x2 - x1
    @delta_y = y2 - y1
    @delta_z = z2 - z1

    len = Math.sqrt(@delta_x*@delta_x + @delta_y*@delta_y + @delta_z*@delta_z);
    @delta_x = @delta_x / len * speed;
    @delta_y = @delta_y / len * speed;
    @delta_z = @delta_z / len * speed;
  end

  def update
    wall_collision
    # the angle here is the target angle where point 1 is the player and
    # point 2 is the mouse
    @x += @delta_x
    @y += @delta_y
    @z += @delta_z
  end

```

This way 2D is just 3D where z is always zero (so it is removed). The code is otherwise identical in working principle.
> 1 votes

---
Tags: mathematics, first-person-shooter
---


# Question
Title: How to Make Snaky Inchworm Motion With Armature Staying Upright
I have a series of connected bones in a straight line. I want to be able to rotate each bone vertically and/or horizontally so that it can slither and arch randomly kinda like a snake mixed with an inchworm. When I do this, however, the axes get entirely botched. If I rotate one bone horizontally (i.e. on Y), then vertically (i.e. on X), then back horizontally the the other way, the bone is now rotated on the third axis (i.e. Z). This is further compounded when all the bones are trying to do the same thing. How can I keep these pieces "upright" while doing all these random rotations?

Edit: I think it comes down to this concept. If transform.right = (0.9, 0.2, -0.4) and transform.forward is (-0.3, -0.2, -0.9), how do I calculate how much I should rotate about transform.forward to make transform.right = (x, 0, z) from (0.9, 0.2, -0.4)?

# Answer
When you perform a local yaw or pitch in one frame, then a local pitch or yaw in the next frame, the earlier rotation moves the axes on which the next rotation happens, which can make the results different than expected.

There are a couple common ways to fix this:

1. Pitch locally, yaw globally

```
transform.Rotate(pitchIncrement, 0, 0, Space.Local);
transform.Rotate(0, yawIncrement, 0, Space.World);
```

This keeps the yaw axis fixed in world space, so it can't stray sideways and cause a roll.

It's also equivalent to totalling up your pitch and yaw and applying them from scratch in a single operation:

`transform.localEulerAngles = new Vector3(totalPitch, totalYaw, 0);`
2. Using basis vectors

Keep track of the forward direction that you want your bone to point, then construct an orientation that points in that direction, while keeping the local up vector vertical.

```
Vector3 forward = new Vector3(leftRightRandomization, upDownRanfomization, 1);
Vector3 worldForward = parentRotation * forward;
transform.rotation = Quaternion.LookRotation(worldForward);
```

You can also pass a different up vector as the second argument to `LookRotation` if you want a different twist.
> 1 votes

# Answer
What you are experiencing is Gimbal Lock this is usually 'fixed' by Quaternions.

Unity does use them, so consider building your rotations with AngleAxis then apply them to your transforms.

Eg. `bone.Transform * Quaternion.AngleAxis(30, Vector3.Up)
bone.Transform * Quaternion.AngleAxis(30, Vector3.Left)`
> 0 votes

# Answer
To "unroll" a bone that is pointing in the desired vector F (for forward) with the 90-degree vector R (for right) which needs the rolling (to avoid any upward or Y-value direction), the following math can be applied to find the degrees D to roll to achieve the flattened Goal vector G which R will align with after rotating about F.

```
// Solving for Goal Vector Values
// The angle at which the Goal vector G would cross the global axis of the
// desired plane as a function of being perpendicular to F. The global axis
// (a straight line) is 180 degrees. F to G is 90 degrees of that, F to the
// axis is a portion we can calculate, and with that we can know G's degrees
// off the axis by subtracting the other two angles from 180.
G.angle = 90 - Atan( F.z / F.x ) // Using Output as Degrees

// With the angle from the global axis and knowing we want zero rise, we can
// calculate G's vector values themselves.
G.x = Sin(G.angle) // Assumes normalized vector whose length is 1
G.z = Cos(G.angle)
G.y = 0 // Of course

// The Cosine of the angle between R and G is now the dot product of R and G
dProd = R.x * G.x + R.y * G.y + R.z * G.z
D = ArcCos(dProd) // Degrees to roll around vector F.

```
> 0 votes

---
Tags: unity, rotation, axis
---