# Question
Title: How to create an RTS gameplay experience where all phases of a match are equally engaging without spikes in required concentration?
In games such as Starcraft Brood War, players at the start of the game don't have as much to do compared to later on when they have to manage multiple battles and multiple bases at once. This means at the start of the game, the gameplay is fairly dull, whereas later in the game it becomes so frantic that only extremely high APM players can play competently.

This is especially a problem in Total Annihilation where being able to quickly react to incoming enemy bombers allows for the minimization of damage from the bombing run, which means a player who can react faster has an advantage over a player with a slower reaction time.

In general, for any RTS game with a fog of war such that when enemy units are discovered, fast reactions would grant an advantage, this is a problem.

I want to create a game which not only removes micro but also removes any requirements for fast reactions throughout the game. In other words the gameplay experience should be "flat" without any spikes in activity, and there should be no surprises possible.

Players should not be sitting around waiting for something to happen and then have to frantically try to click as fast as possible once that something happens. In other words the game should feel more like a slow and steady tug of war than paintball. *There are such games in other genres, such as fighting games where, ignoring the power-up bar, gameplay does not change much at all over time*.

In my opinion, this means that all changes perceived by the players must be a constant stream throughout the game (to avoid spikes in gameplay) as well as that players must have plenty of time to react to each change, and that reacting faster to the change gives no advantage.

How can I go about designing this kind of game? I can't even think of any RTS game that comes remotely close to this.

# Answer
I would like to challenge the framing of the primary thrust of this question: the notion that "flat" design is a good idea.

Game design is really not that different from plot structure in narrative entertainment (movies, TV shows, books, etc). In a plot, things start off simple. Then, a complication occurs. Then a couple more. More conflict is added. This builds and builds until finally you reach a climactic encounter, followed by the resolution.

How fast such dynamics in plot structure change over the course of a story represents the "pacing" of a story. In a fast-paced story, things change quickly and dynamically, with new complications happening sometimes faster than you can react to. In a slower-paced story, complications are added more deliberately.

But in pretty much every work of fiction, the plot gets *more complex* with time, not less. Or at the very least, the complexity is frequently *changing*. New characters are added, other characters are removed. New villains crop up, or new plans are revealed. Etc.

And this works in game design as well. At the start of a game, you have a few tools to tackle challenges. Over the course of the game, you either gain new abilities, or you learn how to use your existing toolset to deal with greater and more complex challenges. And so forth and so on, until it builds to a climactic encounter that (presumably) tests a great many of your acquired/understood skills.

A game of StarCraft works much the same way. You start off small and slow. Over the course of the game, you gain new abilities and powers, and you choose to employ them in a variety of ways. You have skirmishes, then major fights for territory. You're forced to expand, lest you fall behind. At some point, you have a decisive encounter which decides who wins.

This is how it works, and this is a *good thing.* Having a game play out in a well-paced way allows players to follow through on that narrative progression. A slow build over the course of play, gradually testing their abilities until at last there is the climax.

StarCraft is fast paced, such that it's essentially impossible to feel comfortable about anything. At all times, there is something more you could be doing, or something you ought to be worried about. That "drinking from a firehose" effect is exactly how SC is supposed to work, and that is due to the game's pacing.

Even board games like Chess and Go have pacing. People often talk about phases of the game, because as the game progresses, it becomes a very different game. And that's a good thing; that's one of the reasons why these games have been around for as long as they have.

Making a game "flat" would be analogous to a plot that doesn't change. Where it's the same plot from the beginning of the movie/book/TV show to the end. There's no build-up, no increasing complexity, no climactic encounter. It's just two people looking at each other and maybe swinging a sword every now and then.

It would get incredibly boring. You have to switch things up, change the dynamics, move from one idea to the next. Your plot/game design must *advance* or it is stagnant. And advancement means adding complexity, changing and reinterpreting the dynamics of play.

Change is just as necessary for game design as it is for plot structure. To throw that away, to discard pacing as a game design tool, is to effectively throw away what people are interested in.

---

> There are such games in other genres, such as fighting games where, ignoring the power-up bar, gameplay does not change much at all over time.

This seems to show that what you're not interested in is not "flat" play, but something else. Fighting games very much *do* change over time. They have dynamic evolution of play. Positioning matters in a fighting game. If you're in the corner, you lose the ability to control distance effectively. If you're knocked down, you have to deal with all kinds of stuff your opponent can do to you.

The gameplay of fighting games very much does change. What fighting games do not have that RTS's do have is this: *permanence*.

In an RTS game, you win by denying your opponent the ability to play the game anymore. And I don't mean in the sense that the game declares you the winner. I mean that your every minor victory denies something to your opponent. You destroy some of their units, so the time spent building them is lost. You destroy a base of theirs, so the time and resources spent on them is lost.

Forever.

You may be able to rebuild an army you lost, but it won't be that particular army that you just lost. Much like Chess; you may be able to promote a pawn, but they still lost whatever thing they replaced. In an RTS, you are fighting for your fundamental ability to affect the game.

In a fighting game, you're fighting for *points*. A round ends when one side scores enough "points" to defeat the other.

Because of this, every advantage in fighting games is entirely transitory, of the moment. Vortex setups on wake up can still be beaten if you guess right. Being pinned in the corner is a situation you can fight out of. And once you do get out of the bad positioning, you're back to essentially a neutral game (mechanically speaking. Mentally speaking, you're in a very different place).

Worst case, you lose a round. Yet another "point" you've lost, but it's just another point. You restart the next round back at neutral positions, with (more or less) the same situation you started the last round in.

Even damaging your opponent is a temporary victory. They go into hitstun and move backwards, giving you the potential to combo them. But after that, they're either still standing or on their back, a state that they'll recover from quickly enough.

In a fighting game, advantages are temporary. That's what gives you the sense that their gameplay is "flat", that it doesn't change. It does change; it simply resets quickly.

But the reason for this difference is that RTS games are primarily and mechanically about *growth.* You build stuff, whether its units, buildings, or both. You move out onto the map and gain territory. And so forth. You lose the game when your opponent destroys your ability to grow anymore (more or less).

If you want to make an RTS more like a fighting game, you have to make it less like... an RTS. You have to take away growth. You have to be able to make advantages transitory. You have to make victory work based on a more abstract system, rather than some battlefield condition of still being able to participate.
> 53 votes

# Answer
*Very good advice in comments (which got moved into chat). I'll just add, since I'm in the middle of implementing such "flattening" into my RTS (Knights Province) right now.*

Classic strategies are unlike many other kinds of games:
They deliver **too big of a change from 1st to last minute**. In other games the main “gameplay element” is evenly spread along all the game with slight variations. In each session you essentially play the same thing - driving a car, running and fighting mobs, jumping on platforms, etc. Essentially you can restart and dive into the same kind of action within a dozen of seconds. Unlike that, in RTS you slowly build up and need to pass through several stages to get to the “fun” late-game (where you are reaping products of your earlier development successes). If you hit “restart” you are back to square one (collecting ore with a single peon, waiting).

On the other hand, the game needs to give player some time to get up to speed (which is why race cars take time to accelerate. FPS games start in “safe” rooms, etc.) Typically that’s ~10 of seconds (depending on game’s complexity).

Two general pathways are:
\- Allow to quickly get past the boring stage (e.g. by prebuilding core town or speeding up the game dynamically). Actually, it is already scratched with giving more serf and builders at the start. Having more of them greatly speeds up the early game! I don’t want to invest into this approach any deeper though. This is a “wider instead of deeper” solution. It sounds good for multiplayer - we can let players engage in MP activity faster. Yet it’s a half measure. Second options sounds much more like fun.
\- **Enrich initial boring stages with new gameplay elements.** It is more favorable for single-player gaming, where player can control himself amount of time to engage with the game. Make those elements go away towards the late-game, to be replaced with expanded town-management and PvP fighting.

**Player needs to engage with something.** Early-game lacks enemies. Some wild nature elements, enemies that player can fight on his “conditions”, that will prepare him for mid-late-game brawls. Can be seen as guarded spots or natural obstacles. Wolves, bears, boars, etc. These could be single animals or packs. Could be even spawning points (dens, etc.)

Proposed solution is to add more mid-late-game elements into early-game. Give players some basic force (army), some wildlife enemies, bonuses for exploring terrain, control points on terrain (encounters, prizes, fights, etc.). All of this will naturally decline towards late-game as no unexplored/unconquered terrain is left (wildlife destroyed or players get superior fighting forces or something else). Thus flattening the experience.

Also take note on **keeping late-game less overwhelming**.
> 17 votes

# Answer
Ideas for **removing micro** from the game :

* No units at all (at least physically present in the game) : you win by spreading your control over areas like in the Go game.
* You have units but you can't control them, they automatically go attack some critical point of the enemy. This could work like the minions in League of Legends by following a line or as in Starcraft when you do an Attack move (it will find its way to the critical point and attack automatically every enemy unit it crosses by). If you really wish to control them you could make it only possible to choose the building to attack.

Ideas for **making progression "flat"** :

* You can't gain new abilities during a game (like a new building to build, or the ability to launch a nuke) so that you will always have to deal with the same actions throughout the game and make the best of them.
* Some kind of evolutive gameplay where your actions change at some point of the game (think of it as a new age in Age of Empire) so that the gameplay evolves but not the number of actions available.
* If you still want to control units you could create a maximum unit number and make it pretty low so that you can reach it very soon and it won't change in late game.
> 11 votes

# Answer
Fair warning: if you don't find this sort of game play in the RTS world, that means there's a good chance that your market of gamers don't find value in this sort of game. Always be careful with the "if you build it they will come" argument.

What makes a non-twitchy RTS tricky is the limited interface that we have to our computer. It's very good at making well timed decisive actions. It's not so good at providing nuanced feedback. If you have a non-twitchy game, it's going to have to have nuances or it won't keep the attention of anyone. Nobody wants to play a murky game of tic-tac-toe at a slow pace.

One question might be to ponder whether you actually want to make an RTS at all. The "real time" part of the game encourages tactics to appear beneath the strategy, and tactics are always time critical. You might want to make a turn based game instead.

Or perhaps you want to make a hybrid. Perhaps you can make a slow strategic game in which armies enter "battles" instead of actually fighting each other. Then, on their own time, players join those battles and fight in them RTS style. This would feel similar to how RPGs often have an overworld which then enters a "fighting mode" when you run into a monster.

I'd also point out that Poker meets most of your criteria, especially when played face-to-face. You can't gain an advantage from betting faster than your opponent, so you have all the time in the world to study their face and try to figure out what they have without revealing what you have.
> 8 votes

# Answer
## Have an action budget

A straightforward approach to reducing the value of having lots of action per minute is to directly limit the number of actions one can take per minute.

For example, a player may have an energy meter that constantly refills (possibly at a rate depending on how empty it is), and each type of action like constructing a building or directing a unit group or manually controlling a single spellcaster consumes energy.

So that it doesn't feel artificial, the game will likely need to be designed around it — e.g. arrange things so that:

* You are able to burn through all of your energy as soon as you get it to get a meaningful economic advantage over someone who keeps it more topped off
* You can burn energy to make an attack more effective
* You are less able to respond effectively to attack with low energy

so that you get a metagame around budgeting your energy

## Have more high level commands

A big reason for APM being important in a game like Starcraft is that you can't issue orders like "My marines should form a nice firing arc before engaging" or "My high templar should psi storm groups of mutalisks" — in fact, Starcraft's spellcaster system is practically *designed* around rewarding reaction times and APM.

Instead, you want to design combat and abilities so that they can take effective actions with few inputs, so that there is simply less *reason* to constantly micromanage everything. And ideally, so that you can't gain a significant advantage through large numbers of low-level inputs. (e.g. the energy budget would help with that)

Of course, you still need to make sure that you still have enough depth that the player choices are still significant and meaningful.

## Make preparation trump manual execution

Arrange combat so that most of the attacker's effort is spent in *preparing* an attack, rather than directly overseeing combat and taking constant action. This would have effects such as:

* It would mean that fast reaction times are less important for carrying out an attack
* You could design in a delay between when the attacker is done with his preparations and when the attack actually strikes, allowing you to alert the defenders

I would say the same about preparing a defense, but that sounds like a harder thing to achieve.
> 8 votes

# Answer
Most RTS games provide you with automation tools to automate some menial tasks, but in many cases these are implemented poorly, as to give you a disadvantage. If you made **sure** that these systems don't penalize someone for using them then that would go a long way to alleviate your problem.

Problem 1: **Queues** should not consume resources. Most RTS games allow you to queue somewhere between 5-20 commands given to a unit or building. But resource costs are immediately applied. Therefore you have a significant advantage if you keep your queues low, yet your buildings productive. In other words, you need precise timing. If you allow some slack by only charging the cost when a unit actually starts production, it helps a lot.

Warlords Battlecry is an example of an RTS game that did this when you turned on continuous production.

Doing so can result in some problems when a player doesn't have enough resources to initiate production. Of course, as resource income is near-continuous (happens in small chunks), such a thing can only happen if you build too many production buildings. Some games with useful queues also resolve this issue in varying ways:

One solution employed by Total Annihilation is to deduct resources not when starting to build a unit, but in a continuous fashion while building a unit. E.g. while buliding a 50 cost unit over a timespan of 25 seconds, 2 would be deducted every second. If not enough resources are available, the unit construction 'skips' a tick: the unit takes longer to build. The end result is that the inefficiency from having slightly more production than your resource income is very small; units are delayed by a fraction of their production time. Compare this to the 'plain' queue where every unit queued is a unit you could have had a full build time earlier.

A second method is to simply cancel the production, and leave a message exactly -what- got cancelled.

A third method sometimes employed is that the start of the production is delayed until the player has enough resources, sometimes also leaving a message or indicating it by flashing the resource icon in the player's display of resource totals.

Problem 2: Queuing should be available when a command can be macroed by a macro keyboard; there's no decision making involved. If an ability is essentially always automatically casted, then pre-queuing should always be possible. E.g. Queens in starcraft are a notorious example of something that breaks this rule.

Problem 3: Low line of sight. A lot of the problems could be resolved if you reduce the surprise factor. In most RTS, fog of war is so low that units can fire from it to hit yours. That means hyperactively constantly tabbing through units becomes the norm. If you make sure warning systems are cheap and plentiful enough you can increase the "lead time" a surprised player has: do you have some time where acting quicker has little impact, or does every 16 milliseconds count? Other small details that can help are:

1. Make enemy units provide line of sight to them and appear on the minimap when they use an offensive ability.
2. Make long range projectiles slow.
3. Make sure line of sight is available beyond projectile range. Total Annihilation Kingdoms is an example game that had many flying scout units available that could give you plenty of warning.

Ken Bourassa's answer also illustrates an important point: fight duration. If a fight is decided in a second (like in starcraft) the faster player just plain wins unless outnumbered 2:1. Slowing down the pace of combat, reducing the number of manual abilities or having sensible automatic casting of them, having units that can deal near-optimal damage without too much manual control helps a lot too. Age of Empires 2's Mangonels is a great example of a unit that fares really poorly without manual control. It has to be manually fired or the opponent can easily exploit it to kill your own army.
> 7 votes

# Answer
## Micromanagement

There are a few approaches to minimizing the impact of actions-per-minute on the outcome of the battle. Other answers have touched on these:

1. Removing micromanagement by only allowing you to issue macro commands. You issue objective-based orders and the units fulfill them. The downside to this is that AI is often remarkably dumb and frustrating for the players and very difficult to get right for the game maker.
2. Reduce the overall scope of the battle. Several people have suggested limiting the number of units allowed in the game and indeed many games do this (Starcraft supply limits with variable supply cost per troops, Warcraft upkeep and supply limits, Total Annihilation unit limits).

Several answers go over how to maximize player control by grouping e.g. your production buildings together.

What hasn't been covered so far is self-organizing units. Say you build up 20 infantry. In a micro intense game like Starcraft, they behave as a mob, clustering up when pathing, running into each other etc. There is a benefit for treating them as individuals. Instead of the classic `ctrl` \+ `1` makes a simplistic group, you could allow the player to organize their forces into platoons, battalions. An infantry brigade with tank support will attack smarter and take fewer casualties. Assigning fighter escorts to a bomber wing automates them to act cohesively and multiply their effectiveness.

Several games do this sort of thing automatically at the unit level, such as the Total War series. Several games allow you to set unit formations such as a column for assault or spread for taking ranged fire. These are macro tools to enhance your armies effectiveness.
3. Penalize micromanagement. In reality, no commander has real-time control over all troops. Orders take time to be delivered – force players to get it right the first time. Sending many orders at once is going to confuse and paralyze your soldiers.

## Pacing

The idea of gathering resources and building your army in the field is a conceit of the RTS genre. No military operation in history has trained and equipped soldiers on the field of battle. (Admittedly, history has little to do with game design...) Resources in RTS's are an element of conflict, and you can't remove this conceit without morphing the game from a self-contained battle to a long form campaign.

However, this start-from-nothing approach is the chief culprit to the slow-start portion of the pacing you're talking about.

There are a few successful games that work around this. Age of Empire III was about colonial wars had an element of receiving supplies from your home country. Several long-form campaign games have automated reinforcements where your backup arrives on an timeline that's roughly known before the game begins.

There are also games that have made a go of the pre-game point-buy, where you receive a budget to spend as you see fit. Let your players define their army up front. To prevent it from feeling like an all-in royal rumble, you can allow players to purchase reserves at a discount that scales with the length of time before the reinforcements arrive.

Another option is to put players on a fixed resource income. One reason RTS's get so hectic in the late game is that resource collection has scaled up to two or three times what it was in the early game. If you control the resource allocation and keep it even for both players, that enforces more of a tug-of-war dynamic. This also eliminates one thing to micromanage while the action is occurring.

## Tug-of-War Inspiration

One recent game that has found success by combining these elements – fixed resource income, no micromanagement, pre-game army selection – is Clash Royale. However, the game *does* have a phase of peak mental concentration. The matches are 3 minutes long with a 1-3 minute sudden death overtime: in the last minute of the regular time, the game provides double resources. This forces you to be twice as active for the rest of the match.

Clash Royale has developed a competitive E-Sports scene, helped generously along by the developer putting together cash money tournaments. People who play or comment on the game at a competitive level describe the matches in terms of 'pushes' – a player builds up a bevy of units on their side and the opponent will defend and counter-push with their surviving units.

It's a freemium mobile game, so critics complain it doesn't feel so much like a tug-of-war as a wallet-warrior, rock-paper-scissors metagame. But it's undeniably a success, undeniably real-time and arguably an RTS.

But for the best overall example of tug-of-war mechanics, I strongly recommend you look at Ultimate General: Gettysburg and its sequel Ultimate General: Civil War. It has most of the elements I mentioned in the answer: cohesive units at the brigade and battalion level, macro commands that rely on realistic unit-level AI behaviors, delayed implementation of player orders reflecting the realism of 19th century communication limits, scheduled-but-slightly random reinforcement arrivals, and serious penalties for trying to micromanage everything a unit does. It definitely accomplishes a strategic run-up to a battle climax without demanding peaks in actions-per-minute. Every battle I played felt like there was simultaneously too much and not enough I can do to steer the fight to victory.
> 6 votes

# Answer
Tactics win battles. Strategy wins wars.

Either remove, or disincentivise the ability or need to micromanage tactics, whilst allowing and incentivising the player to focus on strategy.

The fact that your units stand under a bomber's path in TA unless you tell them not to is a flaw in the game. They should dodge even if you don't tell them to.

I started making a game a while ago (never finished it because I am lazy/terrible at programming), which was a deliberate attempt to make an a.i. that was much better at the tactics part of the game than a human would be, in virtually all situations.

It was a space naval battle game. While I built the ability for the player to directly control the engines, guns etc, I also had (or at least started to develop) a.i. routines to micromanage those things for you. The idea was the player was the fleet admiral. They shouldn't be firing the guns, they should be issuing orders down the chain of command.

Rather than making micromanaging easier, I intended to discourage the player from micromanaging by making it very hard. Like, impossible.

Firstly, the number of ships to be used was to be very large.

Secondly, I used actual Newtonian physics. Engines provide linear acceleration and rotation based on force x distance from center of the ship. There were no speed limits. Bullets were fired off with a muzzle velocity relative to the velocity of the ship they were fired from. Firing guns forwards propels your ship backwards. Getting hit by a bullet on the front right of your ship both moves and rotates your ship.

There's a reason no-one made space games like this. It's so difficult to control. Even just catching up to a ship and matching speed with them is difficult. So the player would simply click the 'match speed with target at optimum firing range and arc' button and let the helmsman take it from there. The helmsman a.i. would attempt the maneuver, and would report back if they failed "sir, the enemy ship is retreating and they're too fast for us to catch up. Should we abandon the chase? y/n" or "they're too manueverable. I can try to get us a firing arc but we'll be outside of our optimum range y/n."

There would also be default a.i. routines to allow them to react to surprises without input from the player. If they spot an enemy, the a.i. would decide to fight or flee, accelerate to a speed that allows evasive manuevers etc.

I believe this game would have met your criteria:

* At the start, with only a small number of ships, the player would take direct control over more. As their fleet grew in number, they would delegate more. There is just as much micro at the start of the game as the end.
* People who are good at micromanaging would have little or no advantage over people who are poor at it. The a.i. is likely to be better than either person and the game decided by who is the best at strategy.
* Surprises should be handled competently by the a.i. at least in the short term. This then gives the player time to decide whether to go aid the ship that's been ambushed or if it's worth losing the pawn to focus on the checkmate.
> 6 votes

# Answer
*Making an answer of my comment.*

You could remove the parts where the user has to create their base and their army. So when the player starts the game, the base and the army they have is all that they'll get for the rest of their play session.

There could be a way to regenerate these units automatically (a clone bay, in space) and to auto-repair the buildings. And there could be an automatic upgrade program which upgrades the units/building as time go by.

Automate all this stuff.
> 5 votes

# Answer
Regarding an RTS that comes remotely close to this, I recommend experimenting with StarCraft II, archon mode: 2 players control a single side.

If you got a couple friends to experiment with, you can try to figure out which of the tasks you want to offload to the second player to get the kind of steady experience you're looking for, and then for your game you keep only the elements that remain.

In general, to fight micro overload you can implement **micro elements that feature diminishing returns** with larger army sizes. An example is Stalker Blink micro (teleporting low HP stalkers to the back of the line one by one): In a small army this micro makes your army significantly stronger, while in a large army, where any focused unit dies instantly, it's negligible.

You also want to **make macro easier as the game progresses**. Allow players to group all factories on a single hotkey instead of requiring them to click through every single one of them. Have a saturation point where you no longer need to build miners and depots.

---

Another example is the Starcraft II arcade mode: Most versions of Nexus Wars are rather chill, as they feature macro exclusively. A similar concept is used for some competitive tower defense games.
> 3 votes

# Answer
You might wish to look at games like Galcon and Auralux, in which players direct units from one node to another.

They largely remove the reaction time requirement by removing fog of war and slowing the pace of the game, giving you plenty of time to react to changes in the opponent's strategy.

There's also no great mechanical skill requirement, because the actions are relatively simple (select units, select destination) and the units move slowly (you don't need to issue directions very often).
> 2 votes

# Answer
In any RTS, reaction time and APM will always yield an advantage.

Games like Starcraft 2 are notoriously biased toward the "RT" part, and less toward the "S" part of their genre. I believe it's not really possible to really make the experience flat. I don't think it would "work" in a RTS. On the other hand, there are some things you CAN do to shift the bias from "RT" to "S".

One such mechanic you can adjust is the DPS to HP ratio (dps = damage per second, HP = Hit point). If instead of losing half your army in 5 seconds, your units would only lose 10-20% of their HP, you can reposition, bring nearby reinforcement to flank your enemies, etc. Positionning and strategy become much more important and reaction time becomes a lesser component.

That's the main aspect I can think of at the moment... I'll come edit if any other comes to mind.
> 2 votes

# Answer
I'm going to attempt to address the lack of information due to the fog of war, and ways to mitigate that.

Perhaps taking a look at the assumptions around the fog of war. In my experiences with RTS games, the fog of war exists immediately at the start of the game. But perhaps instead, put it to the players to create the fog of war.

I can't recall or find it at the moment, but I believe one of the Red Alert games had a structure that created a black out on the other players map. This was a counter to players being able to launch something like a GPS satellite and have full map vision.

But if you start with the assumption of full map vision, and make it part of the early game to decide whether to build obstructions to that vision or build buildings and units that would be visible to the opponent. You could then cut down on the lack of knowledge in the early game, and provide some more meaningful options as well.

Another assumption in your question seems to be that players will have no idea what the other player is doing. However, in games like Starcraft, some units exist with the intention of being able to scout for information. Or there are some other means of revealing information like scanning from a Terran Command Center.

The problem is that with so much going on, many inexperienced and even experienced players may forget or miss information this way. So another approach might be to make that aspect of the game more approachable for novice players. Perhaps a easier to use scanning ability, or some form of automated spying.
> 2 votes

# Answer
While many answers focused on unit tactics, and others focused on army size one of the primary reasons that the mid-late game in SC II is so intense is because you have to use army tactics *and* macro. If you want the game to have a more even tempo, then the most obvious thing to do is force the user to manage a non-trivial amount of macro from the beginning. So either give them a large pre-defined base with one or two expansions, or give them enough resources to build out an entire base + expo right at the start.

Another big difference is that the first minutes are spent scouting. Again, you can remove this early-game task by, say, making the fog of war transparent to building placement, so that both sides can see where they are placing buildings, at least at first.

To reduce reaction time, you need to reduce surprise. That means you need to make the visibility range for buildings and units much larger than normal. You should only be able to surprise the enemy on the strategic level, not the tactical one. And, you need to give units/squads the ability to automatically retreat in the face of superior force, so that an attacker needs to actually pinch/trap a force to annihilate them. So you could switch between "Stand Ground" and "Retreat to Nearest Base".

As others have said, to reduce micro, and thus, APM, you need to make the units much smarter, so that humans will generally not be able to out-micro the AI. Whatever micro techniques that humans use (like kiting, walling, etc.), the AI needs to be able to do on its own.
> 2 votes

# Answer
There might be some value (whether for you, or others...) in taking your root question (*How can I go about designing this kind of game?*) in more of a process-oriented direction. I'll reluctantly lean on the tradition of the war/battle-oriented RTS for simplicity.

1. Start with a clean slate. I.e., don't default to any traditional RTS idioms. Don't add things like structure construction, unit production, resource gathering, minimaps, fog of war, etc. until you can make a compelling *mechanical* case for how they contribute to the game experience you want to achieve.
2. Speaking of the gameplay experience--map out the role you *want* strategy and/or tactics to play in that experience. When and how can players make strategic and tactical decisions? Think about "when" not just in terms of blocking out any "phases" you might want to see in a match, but also in relation to other game events. To float a few of many possible questions:

* Is the emphasis on extensive strategic planning before players directly engage, with relatively little ability to correct for oversights once the action heats up?
    * Do you want the majority of the match to be a tense series of strategic posturing/probing/positioning moves followed by a relatively decisive direct engagement?
    * Should the players engage multiple distinct times throughout the match with an emphasis on how their strategies and/or tactics evolve in response to each other?
    * Will most matches require players to adjust their strategy or tactics in response to random game events?
    * Do you want players to hone a fairly distinct individual style over many matches, or do you want every match to require experimentation and triangulation to arrive at appropriate strategy/tactics?
3. Brainstorm about the kinds of crude conditions/causality from which you might be able to compose a *stream of changes* or a *tug of war* that requires what you want from your players. I'll try to model what I mean by brainstorming about conditions that *might* support the mentioned strategic posturing dance kind of gameplay. You might be able to come up with more than one set, or some mix-and-match options.

* Big situational advantages/disadvantages (composition, terrain, weather, leadership, morale, supplies, technology, flanking, etc.) that *can* make engagements very one-sided
    * **Significant** uncertainty about that situation which can only be resolved by extensive research/spying/scouting/skirmishing (I don't just mean fog-of-war; even a reliable intuitive grasp of how long it takes to research and build sufficient anti-air defenses adds up to a lot of certainty)
    * No or minimal ability to disengage/recover from a poorly-considered engagement
    * Through changing game conditions (weather, resource exhaustion, etc.) and/or the availability of viable strategic/tactical counters, limit the formation of boring/unassailable equilibria.
4. When you feel like you have outlined some promising conditions and causal relationships that might lead to the gameplay you want, I think you've got enough of a foundation to try to come up with a few different takes on what content and mechanics might make a good fit (and which are likewise incompatible). At this point you've probably got enough information to evaluate whether common RTS idioms are going to support or undermine your goals, but there might also be some value in making yourself come up with a take or two that use *none* of those tropes.
> 2 votes

# Answer
As other people have mentioned, most people want the pace of a game to change during gameplay. I think what you're really looking for is a way to have an RTS game where APM doesn't matter.

## Combat action delays

It's possible to change the micro so that it doesn't favour the high-APM player without removing it entirely. You could introduce a five second delay for the attacker between sending orders to a unit and the unit responding, to give the defender time to respond. That way, the defender has a bit of time to respond to anything the attacker does. The attacker can't respond quickly to the defender's tactics, no matter what their APM is. For the attacker, the game becomes about predicting the defender's tactics and developing tactics that don't depend on fast reactions.

This will encourage hit-and-run strikes against an invading army while it is in your territory. You'll need good AI to let the attacking army resist that, and you'll also want low-range, quick-moving anti-raider units that can stay on the edge of an invading army, but run back towards the bigger units if there's a threat. You should also create holograms of new units being trained, so that the attacker can target them. Make sure that any counter units take more than five seconds to train, or else accept that some units have a few seconds' immunity to attacks.

You could divide the entire map between the two teams from the start, and put a command hub in each map. A unit is attacking when it is moving into enemy territory or attacking an enemy unit which isn't already attacking. That determines whether it gets a delay or not. This could lead to weird fights near territory boundaries, so don't put anything strategically useful near the territory boundaries. Either player should gain a tactical advantage by pulling their units away from the territory boundary before attacking, without losing anything.

When someone orders their unit to move into their opponent's territory, show their opponent a blue hologram of where the unit is moving to, and show the path the unit will take from its current position to the hologram. Show a red hologram of the unit when it's told to attack, as well as a path. In-universe, you could explain this knowledge through analysts with precognitive powers, or delays due to radio intercepts, or oracles or anything. You could explain the delay as communication delays or as time for the soldiers to think about and respond to the order.

## Research queues

Another reason that APM is important in RTS games is that responding to a battle can mean you aren't researching upgrades as fast as possible. Interesting decisions about resource allocation are important to RTS games, but you don't want decisions about research to be time-critical or they would provide an advantage to high-APM players who can make research decisions during battles. So let players queue their research from the beginning of the game, and make it easy to change the research queue or put all research on hold.
> 1 votes

# Answer
That RTS's increasing need for concentration is unnecessary, or even that the begining of a game is devoid of it is your assumption.

RTS are like board games like chess or go, except that your opponent's moves are usually hidden from your sight.

Like reactives and products concentrations in chemical reactions, board games have two composants that evolve as time goes :

* Your possibilities
* Your planning

At the begining of the game, you have almost nothing, so the variety of your moves is at its minimum of the entire game. Meanwhile, since the game just started and you haven't built anything yet, the variety of moves you can **plan** is at its maximum. Your strategies aren't yet limited by the options you would have sacrified by prefering others and not knowing what your opponent did - since he hasn't done anything either - don't guide you toward a path in particular.

As time goes, you will make moves, these moves will give you opportunities. The more concrete means of interacting with the game you have, the less you will have room for planning, since each choice you made closed some of those that you didn't choose. Take the example of your first base : Once you've built it, you won't be able to build your first base again. You will certainly build others, but hopefully you will take the positions of your assets into account while deciding where to expand.

The balance in RTS come from that basic relationship, which itself has been exploited for millenias in various pre-electrical strategic games.

If you are interested in that aspect of games, look at Game Theory, that's the name of the mathematical field that study the behaviour of rational agents being able to interact with a system in various ways, which apply to actual games as well as more abstract situations like negociations, conflicts or parking your car.

To answer your question, you could perfectly design a game which flatens the player's need for concentration simply by flatening the moves the player has : If the complexity of the player's opportunities is constant through the game, it's concentration will reach its maximum right after the begining of the game, which will also be its average. That's how FPS work, by the way, and MOBA in a lesser extent.

However, it may be quite hard to apply that to RTS : it would imply that players are already met with various and complicated moves available right at the begining of the game, and that this complexity doesn't change through the game. Strategic games are about setting and using assets on a field in order to reach your objective against one or more opponents with their own objectives that are (often) mutually exclusive with yours.

Reshaping the battlefield to your own purpose so that you get the edge and win is the basis of strategic games. Remove that mechanic and you are stuck with something that looks like a RTS but isn't, like dummy food.

That's, I believe, why you can't think of a single game that works like it, or even how you would do it yourself.

I strongly advise you to reconsider it and ask yourself the good questions, like : **Why do you want this, what's the reason ?** and **Considering that reason, would there be another way of reaching what you want without breaking the game ?**

And, by the way, concentration **is** flat throughout the game. It's just that you focus less and less on planning and more and more on using your assets, but the focus doesn't increase, **it just shifts**.
> 1 votes

---
Tags: game-design, rts, realtime
---


# Question
Title: How could you parallelise a 2D boids simulation
How could you program a 2D boids simulation in such a way that it could use processing power from different sources (clusters, gpu).

In the above example, the non-coloured particles move around until they cluster (yellow) and stop moving.

The problem is that all the entities could potentially interact with each other although an entity in the top left is unlikely to interact with one in the bottom right. If the domain was split into different segments, it may speed the whole thing up, But if an entity wanted to cross into another segment there may be problems.

At the moment this simulation works with 5000 entities with a good frame rate, I would like to try this with millions if possible.

Would it be possible to use quad trees to further optimise this? Any other suggestions?

# Answer
The master's thesis Parallel Simulation of Particle Fluids by Mattias Linde might offer some insight into data partitioning and algorithms for large-scale simulation.

His paper is geared towards Smoothed-Particle Hydrodynamics, which for the naive solution tends to use Spatial Hashing with a bucket size around the size of the kernel footprint of the particles in the simulation.

As the interaction distance is hard-clamped in typical SPH kernels, such partitioning optimizations are almost essential in scaling up the system.
> 8 votes

# Answer
The term I learned a long time ago was a game's speed of information.

If the speed of your boids is 1 and they only care about their neighbours, then the speed of information is 3, that is, a boid that is two squares away from you could be within the range you care about within one frame:

1 square movement per boid in the interaction (1+1) plus the distance that you can notice things (1) equals 3.

Given this, we learn that we can chunk off a map into pieces, sized as small as we like, but with this speed of information overlap into any neighbouring chunks.

I'll assume you're allowing your boids to move only one square, but they can see three

If you want to run a massive parallel sim, you chunk off into 10x10 grids, but overlap by 5 squares on each edge. Whenever one of your ends up being within the information distance from the local chunk's edge, you should update the neighbour, and once they traverse the boundary, they don't belong to you. If a neighbour says that a boid they are controlling has moved into your chunk, you have to take over it's AI.

This means that communication is localised to the neighbouring chunk managers, and the traffic is reduced to a minimum. The more jobs you run, the more CPUs you can use to power the simulation, but the more jobs you run, the more overlap their is, and therefore the more information passing between jobs/chunks as the simulation progresses. This is where you have to get heavy handed and tune the chunk size based on the AI complexity and what hardware you have available.
> 5 votes

# Answer
By reading your quesiton it seems you can take benefit of quad trees, create a quad tree and run simulation for each segment on a diffrent processing unit. This will cause checking only happen to objects near to each other. but you'll need to sync you threads every cycle. Which means to transfer some of those boids from one processing group to another. in general every cycle will consist of 3 steps :

1. Move all boids by one unit. (which can easily be processed using multiple threads)
2. Assigning each boid to a group\*. This means using an algorithm of O(n) you have to select which boids are most likely to make a collision. This can also be handled using multiple threads.
3. In the end you have to check if two boids in a same group made collision.

\*To create groups you can use the pattern below:

note that some boids may be a part of more than one group, but this pattern gives you a more accurate results. you may also create as many groups as you want using this pattern it's just a number you have to find for how many boids and the screen which screen size, what's is the best number of groups you need to create.

--edit--

there is another idea about segmentation which is described in the paper @LarsViklund sugested, this way there is far fewer double checkings and there is no need to increase/decrease number of threads between steps:

note that some areas are still a part of two groups. and width of area both group cover is exactly `2*maximum speed`. In your case if boids move one pixel per simulation step you only need to share 2 pixel width area between each 2 group. and there is a small area which is a part of 4 groups. but in general this method is easier to implement and by far faster if implemented correctly. and by the way there is no reverse move this way, if some object can move it can move no more checking is required.
> 3 votes

# Answer
I tackled this problem recently using some of these answers as a starting point. The most helpful thing to keep in mind is that boids are a sort of simple n-body simulation: each boid is a particle that exerts a force on its neighbors.

I found the Linde paper difficult to read; I suggest instead looking at S.J. Plimpton's "Fast Parallel Algorithms for Short-Range Molecular Dynamics", which Linde referenced. Plimpton's paper is far more readable and detailed with better figures:

> In a nutshell, atom-decomposition methods assign a subset of atoms permanently to each processor, force-decomposition methods assign a subset of pairwise force computations to each proc, and spatial-decomposition methods assign a sub-region of the simulation box to each proc.

I recommend you try AD. It's the easiest to understand and implement. FD is very similar. Here is nVidia's n-body simulation with CUDA using FD, which should give you a rough idea of how tiling and reduction can help drastically surpass serial performance.

SD implementations are generally optimizing techniques, and require some degree of choreography to implement. They're almost always faster and scale better.

This is because AD/FD requires building a "neighbor list" for each boid. If every boid needs to know the position of its neighbors, the communication between them is O(*n*²). You can use Verlet neighbor lists to reduce the size of the area each boid checks, which allows you to rebuild the list every few timesteps instead of every step, but it's still O(*n*²). In SD, each cell keeps a neighbor list, whereas in AD/FD every boid has a neighbor list. So instead of every boid communicating with each other, every cell communicates with each other. That reduction in communication is where the speed increase comes from.

Unfortunately the boids problem sabotages SD slightly. Having each processor keep track of a cell is most advantageous when the boids are somewhat evenly distributed across the entire region. But you *want* boids to cluster together! If your flock is behaving properly, the vast majority of your processors will be ticking away, exchanging empty lists with each other, and a small group of cells will end up performing the same calculations AD or FD would.

To deal with this, you can either mathematically tune the size of cells (which is constant) to minimize the number of empty cells at any given time, or use the Barnes-Hut algorithm for quad-trees. The BH algorithm is incredibly powerful. Paradoxically, it's extremely difficult to implement on parallel architectures. This is because a BH tree is irregular, so parallel threads will traverse it at wildly varying speeds, resulting in thread divergence. Salmon and Dubinski have presented orthogonal recursive bisection algorithms to distribute quadtrees evenly among processors, which must be restated iteratively for most parallel architectures.

As you can see, we're clearly in the realm of optimization and black magic at this point. Again, try reading Plimpton's paper and see if it makes any sense.
> 2 votes

# Answer
I'm assuming yours is a toroidal system, you can partition to the space so each unit has its sub area.

At each step the particles are moved, the particles that goes out the sub area are sent to the relevant processor; a communication step will syncronize the processors and a last poststep is taken to elaborate the foreign particles position (if any).

Here there are three problems here:

* 1) the shape of the sub area:

One can opt to rectangles but the show a small Area/perimeter ratio compared to cirlces. The bigger the border the more particles will leave. While the cicles exhibits the best A/p ratio, can not be used for tessellation, so you should indagate for some (possibily semi regular) tessellation with a good average A/p ratio. Obviously computing the tassel index by cell coordinate should be simple so consider this before to try a very exotic tasselation.

* 2) the communicationprotocol:

Depending upon what kind of communication infrastructure you have, you can think how to scatter the border-crossing informations among the processors. Broadcasting vs peer-to-peer reconstruction vs peer-to-peer communication are all options.

* 3) the sub-Area Allocation:

You should keep your elaboration balanced since there is a syncronizzation at each step. You can choose to statically or dynamically allocate areas to processors. This is not a big issue if your space is unifomly covered by active particles but i belive that it can be untrue in this case as collisions deactivate the particles.Changing the allocation requires an heavier communication step; some shortcut can be taken if all the processors shares the cross-border informations but you have to do some consideration about it
> 1 votes

# Answer
Try my simulation for clues https://github.com/wahabjawed/Boids-Simulation

I developed this on XNA
> -1 votes

---
Tags: software-engineering, physics, mathematics, algorithm, simulations
---


# Question
Title: Preventing character's movement if it won't fit(Unity2D)
I'm creating a pacman game copy and I set up my movement. But there's a problem. My character can try to go up whenever I press but in the original you cannot go if there's a wall above you or your character won't fit.

For example in this situation you can still go up but you'll bounce off wall. So my question is how to prevent character from movement if there's a wall or it won't fit there.

# Answer
You don't have to use raycasting. The simplest solution would be adding rigidbody2D to your pacman, and then apply some force to this body with AddForce(...) method when pressing button. PS Set gravity scale of body to 0.
> -1 votes

---
Tags: unity
---


# Question
Title: Lib-GDX GWT build will not load without Flash on some browsers
I am trying to load my LibGDX application. Using *Firefox without Flash* on a freshly installed *Ubuntu* system, it does not load.

---

I get this printed in the console:

```
SoundManager: No Flash detected. Trying HTML5-only mode. soundmanager2-jsmin.js:32:357
SoundManager V2.97a.20130512 (AS3/Flash 9) + HTML5 audio soundmanager2-jsmin.js:32:357<br/> SoundManager 2: soundManager: Fatal error: Flash is needed to play some required formats, but is not available. soundmanager2-jsmin.js:32:357
SoundManager 2 HTML5 support: mp3 = false (using flash), mp4 = false (using flash), ogg = true, opus = true, wav = true soundmanager2-jsmin.js:32:357
soundManager: No Flash response within expected time. Likely causes: Flash blocked or JS-Flash security error. soundmanager2-jsmin.js:32:357
soundManager: Waiting indefinitely for Flash (will recover if unblocked)...

```

And this on my screen:

I am assuming this is because of the lack of Flash and the fact that these audio formats are not supported in this version of Firefox. However, I am not using **any** audio in my game at all.

In my LibGDX HtmlLauncher, I have:

```
public GwtApplicationConfiguration getConfig () {
    GwtApplicationConfiguration config
        = new GwtApplicationConfiguration(getWindowInnerWidth(), getWindowInnerHeight());
    config.preferFlash = false;
    return config;
}

```

This did not fix anything. I am on the latest version of LibGDX, and the latest GWT SDK version. *How do I fix this?*

# Answer
It turn out the browser was just too old. With such an old browser, it cannot play mp3s without flash, which it crashes. You can see the github issue I made for more details: https://github.com/libgdx/libgdx/issues/4590
> 0 votes

---
Tags: libgdx
---


# Question
Title: Creating a custom mouse cursor with LWJGL2 in Java
I have been trying to create a custom mouse cursor in my LWJGL2 application running under Linux and I am almost there. I have implemented the following method that I call right after creating the game window:

```
public void loadCursor(BufferedImage img) throws LWJGLException
{
    final int w = img.getWidth();
    final int h = img.getHeight();

    int rgbData[] = new int[w * h];

    for (int i = 0; i < rgbData.length; i++)
    {
        int x = i % w;
        int y = h - 1 - i / w; // this will also flip the image vertically

        rgbData[i] = img.getRGB(x, y);
    }

    IntBuffer buffer = BufferUtils.createIntBuffer(w * h);
    buffer.put(rgbData);
    buffer.rewind();

    Cursor cursor = new Cursor(w, h, 2, h - 2, 1, buffer, null);

    Mouse.setNativeCursor(cursor);
}

```

The resulting cursor is almost perfect, except for a horizontal blank line in the middle.

Note: The image is being flipped vertically in my code because otherwise the cursor is displayed upside down in OpenGL. I have seen other implementations that flip the IntBuffer instead of doing this in the for-loop but they lead to the same result for me.

I don't think it has to do with screen tearing either since I enabled VSync and the blank line is always at 50% of the cursor's height (there is no flickering).

Can anybody tell what I am doing wrong or if my code example is missing something essential in order to find the problem? Thank you!

# Answer
> 1 votes
It's not that your code might be wrong but the size of your buffered image. LWJGL imaging uses increments of 2 (2, 4, 8, 16, 32, 64, 128...), so then your image should be just that. I have used your code and it works just fine.

# Answer
> 0 votes
A guess as to why that line is there is that your flipping algorithm doesn't handle odd/middle lines well. I recommend the classical algorithm for flipping, `for(int i = 0;i<length/2;i++) array[i] = array[array.length-i - 1]` (psuedocode).

# Answer
> 0 votes
At first glance, this looks far too complicated. Lwjgl should have something to the effect of 'getmouseposition()'. Call this function every iteration of your game loop, cast or set it as a Vec2d, then use that position to blit or draw the mouse you want. All of your blits should be called every game iteration in some kind of draw loop.

Mind you, I was trying to use Lwjgl in java, and ended up needing opengl and a shader program to discard the background color of the images I was blitting.

As I recall, with opengl there were issues with blitting images of certain sizes - I think the dimensions had to increase by set numbers for it to blit correctly. Since, if I remeber correctly, Lwjgl uses opengl, this could be what your problem is.

---
Tags: opengl, lwjgl
---


# Question
Title: Unity: SpritePacker Atlas with Dynamic Access
Here are current conditions for a game I'm building in Unity 5.6.3:

* SpritePacker is used to create atlases (it would be ideal if that didn't change, but it could, if no other options become evident).
* Config file describing game state which specifies IDs referring to specific sprites, is loaded.
* `Resources.Load()` worked fine with individual sprites, but doesn't work properly with SpritePacker - can't access elements by ID, programmatically.
* Programatic access to SpritePacker sprites is done via an object in the scene that has inspector-set arrays of all correctly-named assets. From these, the script on that object creates a public static dictionary keyed by those IDs. This dictionary supplies sprites, by key, to rest of game.
* Memory use and draw calls are reduced, but Android crashes about 50% of the time on startup (game killed by the OS), which seems to result from a delay caused by loading the large Atlas element in the scene... could be wrong though.

So...

How do I use SpritePacker AND get dynamic access to atlas entries? (AFAIK, it is not possible in 5.6)

OR

What other solutions can solve this without a major overhaul?

# Answer
> 0 votes
This problem was caused by having a large, in-scene dictionary of SpritePacker sprites (around 400 textures in total) in the startup scene. Initial testing show that the moment this figure was reduced to around 200 textures, the game begun loading again without hassles on an LG G3.

Since the total number of in-game sprites could not be reduced, it remained to be seen how this could be eliminated from the scene altogether.

The simplest path to a solution was to break the single, monolithic prefab down into smaller atlas *prefabs* which were then loaded using `Resources.Load()`, and `Instantiate()d` at the appropriate time: These smaller units were pertinent to each "location" in the game which is a series of connected "rooms", so were loaded as the player entered each location. On leaving each location, that location's sprites were then unmapped from the global static sprite dictionary, the instantiated prefab was `Destroy()ed`, and lastly, `Resources.UnloadUnusedAssets()` was called to clean up.

This left a relatively flat texture memory profile of about 400mb regardless of where in the game the player went, or when, as opposed to the over 1 gigabyte previously seen.

# Answer
> 0 votes
Here's a rough sketch I have not yet tested, based on our comments above. I've omitted a bunch of error checking and convenience items so it still needs work to refine into a complete solution.

First, we take each grouping of sprites that are commonly used together and make a small directory asset just for them. (You could also auto-generate these assets based on packing tags of your sprites)

When we load this directory at runtime, we'll load only the atlasses it references, not every sprite atlas in the game, which can speed up loading. To keep peak memory use down, you can also unload directories you're no longer using, but I haven't shown that here.

```
[CreateAssetMenu]
public class SpriteDirectory : ScriptableObject {

    // Populate this in the inspector to map your sprite IDs
    // to their corresponding packed Sprite assets.
    public KeyValuePair<SpriteID, Sprite> [] idMaping;

    Dictionary<SpriteID, Sprite> _index;

    void Awake () {
        // Unpack our id mappings into a dictionary for O(1) lookups.
        _index = new Dictionary<SpriteID, Sprite>(idMaping.Length);
        foreach (var entry in idMaping)
            _index.Add(entry.Key, entry.Value);
    }

    public Sprite GetSprite(SpriteID id) {
        return _index[id];
    }
}

```

Next, we need a way to find the right directory for the sprite we want to load, given only its ID. (If your IDs for each group are integers in non-overlapping ranges, or if your sprite-consuming logic has knowledge of what sprite set it's working with, this can be much simpler, but here I'm assuming the most general case of random sprite access)

Here I've got a master directory that doesn't have direct links to the individual sprite directories (so it doesn't pull them all into the scene's dependency list and force all their atlases to be loaded before the game starts), instead, it just knows where to find them, and handles loading them asynchronously when needed:

```
public class SpriteMasterDirectory : MonoBehaviour {

    [System.Serializable]
    class DirectorySlot {
        public string path;
        public SpriteDirectory asset;
        public bool pending;
    }

    Dictionary<SpriteID, DirectorySlot> _index;

    [SerializeField]
    [HideInInspector]
    List<KeyValuePair<SpriteID, DirectorySlot>> _flattenedDictionary;

#if UNITY_EDITOR
    // Use this in the editor to link the master directory to the
    // individual directories it needs to pull from. The list will
    // be stripped from the built game so it doesn't load *everything*.
    public SpriteDirectory[] directories;

    void Reset() { OnValidate(); }
    void OnValidate() {
        // When the asset is deserialized or changed in the editor,
        // update its mapping of sprite IDs to their corresponding directories.

        _flattenedDictionary.Clear();
        foreach (var directory in directories) {
            var slot = new DirectorySlot();
            slot.path = UnityEditor.AssetDatabase.GetAssetPath(directory);
            slot.path = slot.path.Substring(
                slot.path.LastIndexOf("Resources/") + 10);
            foreach (var entry in directory.idMaping)
                _flattenedDictionary.Add(
                    new KeyValuePair<SpriteID, DirectorySlot>
                        (entry.Key, slot));
        }
    }

#endif

    private void Awake() {
        // Unpack our flattened dictionary into one we can search in O(1).
        _index = new Dictionary<SpriteID, DirectorySlot>
                     (_flattenedDictionary.Count);
        foreach (var entry in _flattenedDictionary)
            _index.Add(entry.Key, entry.Value);

        // Don't need this anymore.
        _flattenedDictionary = null;
    }

    public class SpriteRequest {
        public Sprite sprite;
        public bool isReady;
    }

    // Call this when you want to access a sprite that might not be loaded yet.
    public bool LoadSprite(SpriteID id, out SpriteRequest request) {
        request = new SpriteRequest();

        var slot = _index[id];
        if (slot.asset != null) {
            request.sprite = slot.asset.GetSprite(id);
            request.isReady = true;
        } else {
            // Currently we'll start multiple coroutines & load requests
            // if the same directory is requested multiple times before
            // it's loaded in. Hoping Resources.LoadAsync is smart enough
            // to only load it once, but more sophisticated queuing here
            // is another potential solution.
            StartCoroutine(LoadFromPendingDirectory(slot, id, request));
        }

        return request.isReady;
    }

    // Asynchronously load a sprite directory (and all its sprite atlasses).
    IEnumerator LoadFromPendingDirectory(
        DirectorySlot slot,
        SpriteID id,
        SpriteRequest request) {

        var loading = Resources.LoadAsync(slot.path);

        yield return loading;

        slot.asset = (SpriteDirectory)loading.asset;
        request.sprite = slot.asset.GetSprite(id);
        request.isReady = true;
    }
}

```

---
Tags: unity, loading
---


# Question
Title: How to code dragging of objects in 3d space in Unity (Android/ iOS)?
I have been working for many hours trying to figure this out and i can't so I thought once again i'd trouble you kind folks.

Basically I am trying to keep this as simple as possible so I can get to grips with it, but eventually I am wanting to use it in a First Person Slingshot/Catapult style 3d game (knocking things over a bit like Angry Birds but first person 3d)

I've set up a dedicated class attached to my camera and it takes in the touchPos in screen coordinates and I have managed to figure out how to make a ray see which object its selecting, also have managed to convert the screen pos into either Viewport or World coordinates. But for some reason the World coordinates just keep coming throw as my camera coordinates no matter where I touch my screen (ie. My cameras transform position is 0,4,-1) and the touch was always 0,4

I changed to converting the actual touchPos and dividing by me screen width, height. And I've managed to get the things to move but they dont stick to my finger they move in a sort of wierd wave

I've been trying lots of things now, so the code is a little bit mixed up bute its not too lengthy and is only 2 classes so far so here it is (The summary of whats on screen right now is, an empty plane for ground, and one sphere unity object at position 0,4,0. The camera is also as stated above, there is nothing else except a light. All I want to learn at this stage really is how to 'grab' the ball and make it follow my finger EXACTLY along the X and Y axes):

```
public class TouchHandler : MonoBehaviour {
RaycastHit hit;
public LayerMask touchInputMask;

// Update is called once per frame
void Update () {
    if (Input.touchCount > 0)
    {
        foreach (Touch t in Input.touches)
        {
            Ray ray = gameObject.GetComponent<Camera>().ScreenPointToRay(t.position);

            if (Physics.Raycast(ray, out hit, touchInputMask))
            {
                GameObject objectThatsTouched = hit.transform.gameObject;

                if (t.phase == TouchPhase.Began)
                {
                    objectThatsTouched.SendMessage("OnTouchStart", t, SendMessageOptions.DontRequireReceiver);
                    //objectThatsTouched.SendMessage("OnTouchStart", hit, SendMessageOptions.DontRequireReceiver);

                }
                if (t.phase == TouchPhase.Moved)
                {
                    objectThatsTouched.SendMessage("OnTouchMoved", t, SendMessageOptions.DontRequireReceiver);
                }
                if (t.phase == TouchPhase.Stationary)
                {
                    objectThatsTouched.SendMessage("OnTouchStill", t, SendMessageOptions.DontRequireReceiver);
                }
                if (t.phase == TouchPhase.Ended)
                {

                    objectThatsTouched.SendMessage("OnTouchEnded", t, SendMessageOptions.DontRequireReceiver);
                }
                if (t.phase == TouchPhase.Canceled)
                {

                    objectThatsTouched.SendMessage("OnTouchCancelled", t, SendMessageOptions.DontRequireReceiver);
                }
            }
        }
    }
}
}

```

and:

```
public class Projectile : MonoBehaviour {
enum moveState { IDLE, PLAYER_AIM, MOVING }
moveState currentMoveState = moveState.IDLE;
Vector3 startPosition;
Rigidbody rb;
Camera cam;

Vector2 leftFingerPos = new Vector2();
Vector2 leftFingerLastPos = new Vector2();
Vector2 leftFingerMovedBy = new Vector2();

float slideMagnitudeX, slideMagnitudeY;

Vector2 myTouch = new Vector2();

// Use this for initialization
void Start () {
    startPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
    rb = GetComponent<Rigidbody>();
    cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}

// Update is called once per frame
void Update () {

}

void OnTouchStart(Touch t)
{
    leftFingerPos = Vector2.zero;
    leftFingerLastPos = Vector2.zero;
    leftFingerMovedBy = Vector2.zero;

    slideMagnitudeX = 0;
    slideMagnitudeY = 0;

    // record start position
    leftFingerPos = t.position;
}

void OnTouchMoved(Touch t)
{
    leftFingerMovedBy = t.position - leftFingerPos; // or Touch.deltaPosition : Vector2
                                                    // The position delta since last change.
    leftFingerLastPos = leftFingerPos;
    leftFingerPos = t.position;

    // slide horz
    slideMagnitudeX = leftFingerMovedBy.x / Screen.width;

    // slide vert
    slideMagnitudeY = leftFingerMovedBy.y / Screen.height;

    myTouch = new Vector2((t.position.x / Screen.width), (t.position.y / Screen.height));

    // move this object
    transform.Translate(myTouch.x, myTouch.y, 0);
    Debug.Log("transform pos updated to = " + transform.position);

}

void OnTouchStationary(Touch t)
{
    //leftFingerLastPos = leftFingerPos;
    leftFingerPos = t.position;

    slideMagnitudeX = 0.0f;
    slideMagnitudeY = 0.0f;

}

void OnTouchEnded(Touch t)
{
    slideMagnitudeX = 0.0f;
    slideMagnitudeY = 0.0f;

    // TODO:  calculate force to apply based on currentPosition as opposed to startPos
}

void OnTouchCancelled(Touch t)
{
    slideMagnitudeX = 0.0f;
    slideMagnitudeY = 0.0f;
}
}

```

Thanks in advance for any suggestions

EDIT: I've also tried this (but RaycastHit hit.transform.position is always equal to the spheres position again and I dont know why):

```
public class TouchHandler : MonoBehaviour {
RaycastHit hit;
public LayerMask touchInputMask;

// Update is called once per frame
void Update () {
    if (Input.touchCount > 0)
    {
        foreach (Touch t in Input.touches)
        {
            Ray ray = gameObject.GetComponent<Camera>().ScreenPointToRay(t.position);

            if (Physics.Raycast(ray, out hit, touchInputMask))
            {
                GameObject objectThatsTouched = hit.transform.gameObject;

                if (t.phase == TouchPhase.Began)
                {
                    objectThatsTouched.SendMessage("OnTouchStart", hit, SendMessageOptions.DontRequireReceiver);
                    //objectThatsTouched.SendMessage("OnTouchStart", hit, SendMessageOptions.DontRequireReceiver);

                }
                if (t.phase == TouchPhase.Moved)
                {
                    objectThatsTouched.SendMessage("OnTouchMoved", hit, SendMessageOptions.DontRequireReceiver);
                }
                if (t.phase == TouchPhase.Stationary)
                {
                    objectThatsTouched.SendMessage("OnTouchStill", hit, SendMessageOptions.DontRequireReceiver);
                }
                if (t.phase == TouchPhase.Ended)
                {

                    objectThatsTouched.SendMessage("OnTouchEnded", hit, SendMessageOptions.DontRequireReceiver);
                }
                if (t.phase == TouchPhase.Canceled)
                {

                    objectThatsTouched.SendMessage("OnTouchCancelled", hit, SendMessageOptions.DontRequireReceiver);
                }
            }
        }
    }
}

```

}

# Answer
OK i actually found the solution. I had to use the hit.point variable. Then it was easy:

```
public class TouchHandler : MonoBehaviour {
    RaycastHit hit;
    public LayerMask touchInputMask;
    GameObject objectThatsTouched;

    // Update is called once per frame
    void Update () {
        if (Input.touchCount > 0)
        {
            foreach (Touch t in Input.touches)
            {
                Ray ray = gameObject.GetComponent<Camera>().ScreenPointToRay(t.position);

                if (Physics.Raycast(ray, out hit))
                {
                    objectThatsTouched = hit.transform.gameObject;
                    Debug.Log("Hit Point = " + hit.point);
                    if (t.phase == TouchPhase.Began)
                    {
                        objectThatsTouched.SendMessage("OnTouchStart", hit, SendMessageOptions.DontRequireReceiver);
                        //objectThatsTouched.SendMessage("OnTouchStart", hit, SendMessageOptions.DontRequireReceiver);

                    }
                    if (t.phase == TouchPhase.Moved)
                    {
                        objectThatsTouched.SendMessage("OnTouchMoved", hit, SendMessageOptions.DontRequireReceiver);
                    }
                    if (t.phase == TouchPhase.Stationary)
                    {
                        objectThatsTouched.SendMessage("OnTouchStill", hit, SendMessageOptions.DontRequireReceiver);
                    }
                    if (t.phase == TouchPhase.Ended)
                    {

                        objectThatsTouched.SendMessage("OnTouchEnded", hit, SendMessageOptions.DontRequireReceiver);
                    }
                    if (t.phase == TouchPhase.Canceled)
                    {

                        objectThatsTouched.SendMessage("OnTouchCancelled", hit, SendMessageOptions.DontRequireReceiver);
                    }
                }
            }
        }
    }
}

```

and then I have classes like this to do the movement on the objects:

```
void OnTouchStart(RaycastHit hit)
{
    transform.position = new Vector3(hit.point.x, hit.point.y, transform.position.z);
}

void OnTouchMoved(RaycastHit hit)
{
    transform.position = new Vector3(hit.point.x, hit.point.y, transform.position.z);
}

```
> 1 votes

---
Tags: unity, input, raycasting, touch, gestures
---


# Question
Title: Board game: Move entity direction based on position and angle
I have a board game where you have entities on a tiled map and you can only move forward, left, and right. Each tile represents a position of the entity, and based on the entity's angle and position, I need to make a method that processes the move. For example if the entity has decided to move left, my function needs to perform a left movement.

An example:

My ship is currently on the tile where the arrow **starts** and the entity selected to move left, the arrow represents how the entity should move, with a motion.

So it slowly goes up and then slowly starts to go left and changing its rotation.

My question is, how can I make such a function which will know the entity's position, current angle (rotation), and where it should move to, and then with these parameters, it will process the movement animation motion to the target tile?

I am trying to solve this for a long time now, but no luck. Thank you a lot!

# Answer
Something like this:

```
Vector2 prevGridTile = new Vector2();
Vector2 currentGridTile = new Vector2();
bool allowRightMovement = true;

enum facingStates {LEFT, RIGHT, UP, DOWN}
facingStates currentFacingState = facingStates.RIGHT; // just a randomly    picked default as right, you could set this to how it starts

void update()

if (prevGridTile.x > currentGridTile.x){
currentFacingState = facingStates.LEFT;
}
// etc etc etc for each case

// then to access that information, you can do switch:

switch (currentFacingState){
    case facingStates.LEFT:
        allowRightMovement = false;
        break;
    case facingStates.RIGHT:
        allowLeftMovement = false;
        break;
    case ETC ETC ETC:
        break;
       }
}

```

This was just a quick example i knocked up without seeing your code. This is c# and pretty much same in java. Of course , this wont work just pasted in youll have to adapt it to your own project. Hope it works out for u
> 1 votes

---
Tags: java, libgdx, animation
---


# Question
Title: How to determine the values of parameters controlling the game objects?
I am a C# developer and now trying to change to my dream field: Game Development.

I am new to Game Development and currently self learning Unity3D.

To me Unity is component based tools and we can set different parameters to control the behavior of the game object.

---

There's a question which kept me wonder for a long time:

**Is there any "scientific" method to determine the value of the parameters of the component other than trial & error (brute force)?**

Like when I watch some tutorials, the tutors normally will just tell you "change this value to x, change that to y" without tell you why is it so.

I just want to know how industry game developers set the value, is there a common standard, etc.

# Answer
> 1 votes
For all kinds of game developent you need to know things like vectors, triginometry and other types of math. You can calculate everyting from how to animate how gravity effect an object, to how each particle in an exploding fireworks, should behave when they explode. All this is mathematically calculating code. The x and y, is coordinates, but you have to start with understanding that in a computer we do not use degrees but radian, and the grades go the other way than you learned in school. It goes with the clock, so when you go from 0 to 20 to 45 degrees, you go down and left, and not up. There are many thins you need to start to learn if you want to do game development. Coding Math on Youtube.com is the beste intro tutorial i know. I teaches you everything in javascript, but you should not care about the language he is using, it is just to make it easy to learn that he is using javacript, because it is running in a browser. Good luck :-)

---
Tags: unity, component-based
---


title: Vector movement on a circle

text:
# Question
Title: Vector movement on a circle
My progress so far: https://codepen.io/anon/pen/OjxLeO

Currently the player has only x and y coordinates.

I want to change that to vectors, like described in http://natureofcode.com/book/chapter-1-vectors/

Let's say the player should start at 12:00 and move clockwise 1 degree per second.

No clue how to implement it.

Any hints?

# Answer
> 1 votes
You can use trigonometry to get the next position of the player with the formulas

```
x = cos(angle)
y = sin(angle)

```

where angle is the angle in radians (0 is 3:00 and it goes counter-clockwise in the positive direction).

If you have a variable called `time` which stores the current seconds, then to get the position at that time you need to use

```
x = cos(pi / 2 - time * pi / 180)
y = sin(pi / 2 - time * pi / 180)

```

# Answer
> 0 votes
Let me show you this with HTML and Javascript, so you can run in in your browser:

```
<!DOCTYPE html>
    <html>
        <head>
            <title></title>
            <style>
                html, body{
                    margin:0px;
                }
                canvas {
                    display: block;
                }
            </style>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body>
            <canvas id="canvas"></canvas>
            <script type="text/javascript" src="main.js"></script>
        </body>
</html>

```

THis is the javascript

```
window.onload = function () {

    var canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d"),
        width = canvas.width = window.innerWidth,
        height = canvas.height = window.innerHeight;

    var centerX = height * .5,
        centerY = width * .5,
        radius = 200,
        xradius = 100,
        yradius = 300,
        angle = 0,
        speed = .01,
        x,y;

    render();

    function render(){

        context.clearRect(0,0,width,height);

        x = centerX + Math.cos(angle) * xradius; // Lenght of adjesant side of triangle
        y = centerX + Math.sin(angle) * yradius;

        context.beginPath();
        context.arc(x,y,10, 0, Math.PI * 2, false);
        context.fill();

        angle += speed;
        requestAnimationFrame(render);
    }

}

```

If you have problems running this, try a newer version of Crome. You can just make an index.html file and a main.js and fill them with this content and open the html file in your browser.

---
Tags: movement, vector
---


# Question
Title: Send failed since rewinding of the data stream failed
I'm using WWW class to sent a WWWForm to an asp.net server.
it used to work in unity 5.3.x but since I migrated to 5.6.3f1, it is not working and sending `Send failed since rewinding of the data stream failed` message.
I tried doing it with the `UnityWebRequest` but it couldn't send the data in the form and I would get null values in the server side. here is my code:

```

        WWWForm WF = new WWWForm();
        WF.AddField("UserID", ServerProperties.user.UserID);
        WF.AddField("UserEmail", ServerProperties.user.Email);
        WF.AddField("UserPassword", ServerProperties.user.Password);
        //I'm sending some json as strings. I don't need to do anything to the json data on the server
        WF.AddField("PlnFile", Export);
        WWW www =new WWW(ServerProperties.ServerAddress + "/Unity/SaveDesign", WF);
        while (!www.isDone)
        {
            yield return www.progress;
        }
        if (www.error != null)
            debug.Log(www.error);
        else
            debug.Log(www.text);

```

And I'm getting this request with `[HttpPost]` on the server.

```

        [HttpPost]
        public ActionResult SaveDesign(DesignViewModel _Design)

```

I'm reaching a deadline and I really need this, any ideas is appreciated.

# Answer
> 1 votes
For anyone getting this error in the future, your server might be configured to redirect some kinds of requests.
In my case I was requesting GET with an address like:"http://www.website.com/". AFAIK this should have worked for the POST requests as well, but it didn't, and after searching around I found this address to be working:"http://website.com/".
Maybe this is an obvious thing and I just didn't know about it. But anyway, this fixed it for me.

---
Tags: unity, networking, server
---


# Question
Title: How can i get random two random objects out of a grid of objects from outer arrays?
For example i have a grid that it's size is 10x10 But the script should be working for any size of grid but to explain let's say the size is 10x10. So i have a grid of 100 GameObject.

```
12345678910
11121314151617181920
212223242526........

                 100

```

So if i take the left side of the grid it will be: 0,11,21,31,41,51,61,71,81,91 The right side: 10,20,30,40,50,60,70,80,90,100 The top 1,2,3,4,5,6,7,8,9,10 The bottom 91,92,93,94,95,96,97,98,99,100

Now i want in the code in the script that each time i will running the game it will pick a random number from each side of the grid. For example:

21,30,1,98

Then i want to destroy this 4 numbers to destroy this 4 GameObjects from the grid.

What i tried first to do considering the grid size is 10x10:

```
private void GenerateRandom()
    {
        var arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int mynum = arr[Random.Range(0, arr.Length)];
        GameObject Top = objects[mynum];

        int[] arr1 = new int[] { 1, 11, 21, 31, 41, 51, 61, 71, 81, 91 };
        int mynum1 = arr1[Random.Range(0, arr1.Length)];
        GameObject Left = objects[mynum1];

        int[] arr2 = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
        int mynum2 = arr2[Random.Range(0, arr2.Length)];
        GameObject Right = objects[mynum2];

        int[] arr3 = new int[] { 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 };
        int mynum3 = arr3[Random.Range(0, arr3.Length)];
        GameObject Bottom = objects[mynum3];
    }

```

And this is how i create the Grid it self:

```
for (int x = 0; x < mapWidth; x++)
        {
            float positionWidth = Spacing * (float)x;

            for (int z = 0; z < mapHeight; z++)
            {
                float positionWidth1 = Spacing * (float)z;
                GameObject block = Instantiate(Node, Vector3.zero, Node.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.localPosition = new Vector3(positionWidth, 0, positionWidth1);
                block.transform.localScale = new Vector3(nodeScale.x, nodeScale.y, nodeScale.z);
                block.tag = "NodeDestroyable";
                objects.Add(block);
            }
        }

```

But in this way i have some problems.

First in the two loops i start them from 0:

```
int x = 0; x < mapWidth; x++
int z = 0; z < mapHeight; z++

```

So when i make arrays to get random numbers from should i start them from 0 or maybe from 1 ?

```
var arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

```

Should the array start from 0 or 1 ? 0 to 9 or 1 to 10 ?

The second problem it didn't work fine didn't destroyed objects like i wanted and sometimes gave me exception/s out of range index.

This is the completed code:

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class GeneratorTesting : MonoBehaviour
{
    public GameObject Node;
    public Vector3 nodeScale = new Vector3(4, 1, 4);
    public int mapWidth = 10;
    public int mapHeight = 10;
    public float Spacing = 2.0f;
    public float spawnSpeed = 5;
    private List<GameObject> objects = new List<GameObject>();

    private void Start()
    {
        Generate();

        GenerateRandom();
    }

    private void Generate()
    {
        if (objects.Count > 0)
            objects = new List<GameObject>();

        if (Node == null)
            Node = GameObject.FindGameObjectWithTag("Main Node");

        for (int x = 0; x < mapWidth; x++)
        {
            float positionWidth = Spacing * (float)x;

            for (int z = 0; z < mapHeight; z++)
            {
                float positionWidth1 = Spacing * (float)z;
                GameObject block = Instantiate(Node, Vector3.zero, Node.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.localPosition = new Vector3(positionWidth, 0, positionWidth1);
                block.transform.localScale = new Vector3(nodeScale.x, nodeScale.y, nodeScale.z);
                block.tag = "NodeDestroyable";
                objects.Add(block);
            }
        }
    }

    private void GenerateRandom()
    {
        var arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int mynum = arr[Random.Range(0, arr.Length)];
        GameObject Top = objects[mynum];

        int[] arr1 = new int[] { 1, 11, 21, 31, 41, 51, 61, 71, 81, 91 };
        int mynum1 = arr1[Random.Range(0, arr1.Length)];
        GameObject Left = objects[mynum1];

        int[] arr2 = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
        int mynum2 = arr2[Random.Range(0, arr2.Length)];
        GameObject Right = objects[mynum2];

        int[] arr3 = new int[] { 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 };
        int mynum3 = arr3[Random.Range(0, arr3.Length)];
        GameObject Bottom = objects[mynum3];

        DestroyImmediate(Bottom);
        DestroyImmediate(Left);
    }

    public void GenerateNew()
    {
        for (int i = 0; i < objects.Count; i++)
        {
            DestroyImmediate(objects[i]);
        }
        Node = GameObject.FindGameObjectWithTag("Main Node");
        Generate();
        GenerateRoute();
    }

    public void DestroyNodes()
    {
        GameObject[] nodes = GameObject.FindGameObjectsWithTag("NodeDestroyable");

        if (nodes.Length == 0)
        {
            Debug.Log("No nodes to destroy found");
        }
        else
        {
            for (int i = 0; i < nodes.Length; i++)
            {
                DestroyImmediate(nodes[i]);
            }
        }
    }

    private void Update()
    {
        Erase();
    }

    private void Erase()
    {
        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "NodeDestroyable")
                {
                    Destroy(hit.collider.gameObject);
                }
            }
        }
    }
}

```

So the first thing is to fix the arrays and getting random number from each side of the grid.

Second to make it for any size of grid not only 10x10 the grid might be in size 3x4 or 40x2 or 9x9

Since this is not working fine i thought maybe adding a helper class but not sure if it's right idea and how to use it:

```
public static class ArrayExtensions
{
    public static T SelectRandomElement<T> ( this T[] source )
    {
        if (source.Length == 0)
            return default(T);

        var index = s_random.Next(0, source.Length - 1);

        return source[index];
    }

    private static readonly Random s_random = new Random();
}

```

And inside the ArrayExtensions i should also use this two methods:

```
//Extension methods in the class given earlier
public static T SelectRandomElementFromLeft<T> ( this IEnumerable<T[]> source )
{
    //First select a random array
    var totalArrays = source.Count();
    var arrayIndex = s_random.Next(0, totalArrays - 1);

    //Now select the first element from that row
    var arr = source.Skip(arrayIndex).Take(1).FirstOrDefault();
    return arr.FirstOrDefault();
}

public static T SelectRandomElementFromRight<T> ( this IEnumerable<T[]> source )
{
    //First select a random array
    var totalArrays = source.Count();
    var arrayIndex = s_random.Next(0, totalArrays - 1);

    //Now select the last element from that row
    var arr = source.Skip(arrayIndex).Take(1).FirstOrDefault();
    return arr.LastOrDefault();
}

```

But not sure how to use it with the arrays in GenerateRandom()

The goal the main idea is each time running the game to get 4 random numbers each from each side of the grid. And i think there might be two cases that there can be same numbers so if there is such a case to automatic generate new random numbers or to check and make sure there will be no same numbers like 1 and 1 or 91 and 91 or 100 and 100.

# Answer
> 0 votes
The first problem as you stated, when you initialise 10x10 grid (array), **its elements are indexed from 0-99**. You are getting unexpected behaviour and also *indexOutOfBounds* error because you give an exceeding index for your purpose for example:

```
var arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int mynum = arr[Random.Range(0, arr.Length)];
GameObject Top = objects[mynum];

```

Here you are trying to pick an element from the top side, however the top side of the grid contains only 10 elements, but you give the random function a range consists of 11 elements (0 and 10 are inclusive for that function). Hence you need to set the `arr[]` to include 10 numbers.

For the second problem (picking the same elements via selecting corners), I suggest you to keep the selected items in a `List<int> selectedNumbers;` and each time you pick random element for the sides, check if the currently selected element is already been selected before. And also modify the `GenerateRandom()` function as follows, in order to decouple the selecting procedure from the size of the grid:

```
private void GenerateRandom(int gridWidth, int gridHeight)
{
    List<int> selectedIndexes = new List<int>();

    //Create an array for indexes of the TOP side
    var arr = new int[gridWidth];
    for(int i = 0; i < gridWidth; i++){
       arr[i] = i;
    }
    int mynum = arr[Random.Range(0, arr.Length)];
    GameObject Top = objects[mynum];
    selectedIndexes.add(mynum);

    //Create an array for indexes of the LEFT side
    var arr = new int[gridHeight];
    for(int i = 0; i < gridHeight; i++){
       arr[i] = i * gridWidth;
    }
    do {
       mynum = arr[Random.Range(0, arr.Length)];
    }
    while(selectedIndexes.contains(mynum));
    GameObject Left = objects[mynum];
    selectedIndexes.add(mynum);

    //Create an array for indexes of the BOTTOM side
    var arr = new int[gridWidth];
    for(int i = 0; i < gridWidth; i++){
       arr[i] = (gridWidth * (gridHeight - 1)) + i;   //Reach the last row and iterate with i.
    }
    do {
       mynum = arr[Random.Range(0, arr.Length)];
    }
    while(selectedIndexes.contains(mynum));
    GameObject Bottom = objects[mynum];
    selectedIndexes.add(mynum);

    //Create an array for indexes of the RIGHT side
    var arr = new int[gridHeight];
    for(int i = 0; i < gridHeight; i++){
       arr[i] = (i * gridWith) + gridHeight - 1;
    }
    do {
       mynum = arr[Random.Range(0, arr.Length)];
    }
    while(selectedIndexes.contains(mynum));
    GameObject Right = objects[mynum];

    selectedIndexes.clear();
}

```

**Note**: Please beware you need to check the size of the grid before calling this function since it cannot iterate on grids which have height or width as 1.

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