# Question
Title: Help resolve territory acquisition design difference of opinion in MMO RTS
**TL;DR**: My business partner and I disagree about how to implement "territory acquisition" in an MMO RTS we are close to (alpha) launching:

1. My view: Small squares (5m edge) that get larger as you "level up", up to about 500m edge
2. His view: Fixed sized squares that are always 5km edge

Which is the better approach (mainly from a game design perspective)? And if you feel that my approach is better, how do I convince him of this?

**Detailed question:**

Hi there,

I’m an indie game designer and developer. My business partner and I are close to (alpha) releasing an MMO RTS, but we are stuck on how to handle one feature: territory expansion.

First, a few details about the game so that the answers can be in context:

* It’s played on a map of the world using the Google Maps API
* It is a “true” RTS – very little is abstracted.
* There are actual buildings you can place on the land, actual units that you can move around the world etc.
* Territory acquisition is currently by way of moving an infantry unit onto a “square” of land, which turns it blue meaning it’s now your territory (you can build buildings on it etc.)

Also, some details about our partnership:

* We have a 50/50 partnership on costs (and hopefully one day, profits!)
* We have shared, 50/50 responsibilities on design
* Everything else is assigned roles:
* Me: technical lead, coding etc.
* Him: Art, UI, marketing etc.
* We have been working together on this game for almost 2 years
* We live in different states and only work together remotely (although we have met in person)

Where we’re not seeing eye to eye is how territory expansion should work in the game. My view is this:

* Players start with a small “square” of territory (about 5m x 5m) and expand by claiming adjacent “squares”
* Once they hit a number of squares equivalent to a larger square (5 x 5 small squares, or about 25 x 25m), they can then claim squares at that size
* This keeps increasing until they can eventually claim 500 km x 500 km squares
* There is a mathematical model behind this, but I think all that is relevant is that the sizes align to degree increments, and that I have modelled it so that there are 10 “map levels” in the game, with the largest map level having about 2,500 large squares across the globe

I believe these are the pros and cons to my approach:

**Pros:**

* I feel that it adds a lot of “flavour” to the game having players grow in size and power from owning territory the size of a room in a house, then maybe a house, then a block, then a suburb, city, state etc. all the way up to small country size squares
* It allows players of different “power” to compete against each other in the same game world. Players at the smallest map levels can only see and claim territory from players of equivalent power, and likewise players at the largest level compete for vast tracts of land, and can leave smaller players alone
* It looks very neat – map squares always align on a grid, with no overlaps

**Cons:**

* Using this approach, players would not be able to see other players’ territories at different map levels. This is because territory would overlap, which not only looks terrible, it’s just not the way maps are represented, and also causes technical issues wherein any API you use (e.g. Google Maps) doesn’t know which layer you meant to click on
* However, players can see other, more/less powerful players’ territories by clicking on some up/down buttons so that players can see what’s going on around them at different power levels

His view is this:

* Squares should always be a fixed size, say 5 km x 5 km

I believe these are the pros and cons to his approach:

**Pros:**

* It’s simpler! My life as a developer and designer would be so much easier if squares were always the same size
* All players can always see all other players’ squares because everyone is basically at the same “map level”, all the time

**Cons:**

* It makes the game feel like a large checkered board game, or a big version of Risk rather than an RTS
* Basic grids like this have been done before in other games – I feel that my approach is more novel and interesting (albeit a bit risker since it’s new)
* Acquiring territory may feel “quicker and easier” as you start the game since you already start with a massive chunk of land, but I think that will quickly turn into a grind once you realise that there are about 26 million squares of this size on earth
* There is less aspirational value to capturing “more” squares, as opposed to a psychological player reward associated with being allowed to capture “larger” squares as you level up

A few more facts at this point:

* I was previously a professional game designer, so I believe I usually know what works and doesn’t work in games (although I’m only human, and can obviously be wrong)
* My business partner has no experience in the game industry. He is coming at this problem from a “this feels right to me” perspective
* I have already coded, implemented and tested my approach and it works perfectly (albeit with the constraint of having to choose to go up/down to view larger/smaller players’ territory)
* It has taken me about 2 months to design and develop this approach and it is an integral part of the (pre-alpha) version of the game
* The game has only been played by very few family members and friends, and we are maybe a month away from a private alpha launch to a closed group of people whom we both know

He is suggesting that we either go with his fixed square approach, start completely from scratch, or stop developing the game altogether (after almost 2 years of time and money, with maybe a few weeks to go before an alpha launch).

I guess I’m looking for advice on two things:

1. Which is the better game design approach: gradually increasing square sizes (with the constraints I mentioned above), or fixed square sizes (and their associated pros and cons)
2. If I’m convinced that my design makes more sense from a design, gameplay, technical, aesthetic and financial perspective (since I don’t want to waste the couple of months working on this feature, let alone the couple of years working on this game), how do I convince him of this?

Any external, objective advice on this is much appreciated.

# Answer
> 21 votes
Clearly, your business partner feels very strongly that your approach has some deep flaws and just won't work. If they didn't, they wouldn't be suggesting starting from scratch or abandoning the project entirely, especially not at this late stage.

What you should try to do first is **find out why they think your approach won't work.** This might be tricky, since their opinion might be based on just a "gut feeling" (to be fair, so is your opinion that it *will* work) which they may not be able to immediately explain in a clear and convincing way. They might also feel reluctant to get into a technical argument with you on a topic where you have much more professional experience, and where they may thus feel they're at a fundamental disadvantage just because they don't know the right jargon and buzzwords and can't lean on their authority from years of experience like you can.

So your first task will be to convince your business partner that **you don't want to argue with them** or to convince them that your approach is better, but simply to *understand* why *they* feel it's problematic.

You might want to start by telling your business partner that, if they think there's a problem with they way you've designed the territory acquisition mechanic, then **you believe them.** But also say that you can't really fix the problem unless you understand it, and that you'd like to try to help them analyze and explain the issue so that you can then find a good solution to it together.

If they bring up their previous suggestion of using fixed 5km tiles, say that you feel that has its own problems (as you've mentioned in your question above) and that, while it might be a possible backup plan, you'd really like to come up with a solution that still preserves some of the advantages of your original multi-scale solution, if at all possible.

In this case, be prepared to also have the same conversation from the other side, i.e. to try and explain to your business partner why *your* gut instinct is telling you *not* to go with the fixed-size tiles and what specific aspects of your original approach you feel would make the game more interesting and playable. And try to do that non-confrontationally, in a way that your business partner can understand and relate to, without unnecessary jargon and without leaning on the "I'm the expert so I know what works" argument. Remember that you're **not trying to convince them that they're wrong**; you're trying to make them understand where *your* gut feeling is coming from.

---

Anyway, if you manage to have that conversation and explain the sources of your respective gut feelings to each other, what you'll probably find out is that each approach has issues that one of you considers to be likely showstoppers. **It's even possible that both of you are right**, and that both approaches *do* have major problems.

However, with a bit of luck, you may also be able to identify a list of features that you both *do* consider desirable, and possibly even come up with **a third approach** that keeps as many of those desirable features while avoiding the showstoppers.

I won't try to suggest any such third approach here, both because I don't know enough about your game and also because it wouldn't really fit into the scope of this answer anyway, but I do wish to point out a few implicit assumptions that you both seem to be making, and some possible ways of breaking them:

* You're both assuming that the tiles that players can claim should be regular squares. What if they weren't? What if the tile shapes were instead irregular, and maybe (more or less) aligned with real-world map features? What if the tiles could have different sizes (even at the same "zoom level")? What if players could somehow move tile boundaries, or even join or split tiles?
* You're both assuming that players can or should only interact with other players at the same "zoom level". What if players could have hierarchical relationships, with smaller-scale players being able to act as (more or less temporary) "vassals" of higher-scale players? Or what if players had to team up to claim larger tiles?
* You're also both assuming that tiles should be claimed one at a time. What if placing a unit e.g. claimed all tiles within a certain radius of the unit (with some sort of nearest-neighbor and/or first-come-first-served rule to handle cases where the same tile is within range of multiple units)? Then you could maybe use a fixed tile size, but have higher level units claim a bigger area around them.

Ideally, with enough thinking outside the box, you'll be able to work out some new solution that isn't just a compromise between your opposing viewpoints, but actually something that you both consider better than either of your original approaches.

---

Of course, it's also possible that this *won't* happen, and that **your viewpoints turn out to be simply irreconcilable** — or that, even if you do come to understand each other's objections, you simply can't find any solution that would address all of them.

In that case, you may simply have to pick one option and go with it, flaws and all. Or, of course, you could also pick neither and just abandon the game — but so late in the process that seems like a bad idea. Sure, you don't want to fall into the sunk cost fallacy and continue with a doomed project just because of how much you've already invested in it, but you also don't want to abandon a nearly finished game just because it *might* not be as good as you hoped. In the end, at least in purely financial terms, releasing a crap game is still better than releasing no game at all.

One option might be for one of you to agree to assume full control of the project and of all costs and risks going forward, with a correspondingly higher share of any future profits. (Obviously, any prior investment should still entitle the other party to a share of the profits as well, unless they're bought out fully.) Depending on the agreement you come to, that might involve one of you starting to pay the other for any remaining work, or of one of you quitting the project entirely and the other one having to bring in additional people to finish any remaining tasks they can't complete on their own.

In general, that's also the point where you probably ought to involve a lawyer or two, if you haven't already. Still, if done right, this should allow one of you to continue with the project as they envision it, with the other one retaining a share commensurate with their past investment but no obligation to sink any more time or money into the project. If you really cannot reconcile your visions, that's really the best you can hope for.

(OK, one more option would be for you to find a third party willing you buy your whole game project in its current form and to assume control of it. Depending on just how promising and close to being finished your game is, that *might* be possible.)

# Answer
> 34 votes
This is opinionated question. It can be fun either way and boring as well. Only you (together) can decide what you like best and have a better chance of implementing well.

Start **playtesting!**

It does not have to be fancy - from what I can tell, you can try starting with an A5 piece of graph paper and play with your partner imposing 10-30 players with a set of color pencils. Or use an online Excel, or playtest in some online grid-cell 2D game like Factorio. You can even do it solo. Try it with static square size and try it with growing square sizes - see how it behaves:

* with growing player count
* dormant squares
* how world size restricts you
* how game dynamic feels
* how players get in the way of each other
* and how this can be resolved (e.g. player with 10x10 square level wants to capture 10x10 square area occupied by 100 different 1x1 players)
* how it scales up for 10, 100, 1k players
* most important - **does it feel fun?**
* etc.

Ask your partner about their concerns and scenarios - what plays well and what are the problem cases. You both need to try to convert your "gut feelings" into a deeper understanding of pros and cons design-wise (and effort-wise, since you have a strong limit on time/workhours) and compromise to pick one or another (or maybe a third alternative emerges).

That will be your answer.

# Answer
> 10 votes
TLDR;

# From a game design perspective. The complete, consistent, and well understood model beats out the incomplete model with unresolved (or unresolvable) technical or conceptual issues.

Based on your descriptions, it sounds like the con listed for the scaling territory design is ***technical*** in nature, and the cons listed for the non-scaling territory design are more a matter of ***personal opinion***.

In other words: The game could be made to work consistently in a readily understood manner with the non-scaling design, but the scaling design, as is, still has at least technical holes in it, but from my understanding it seems there are conceptual holes as well.

There are a lot of particulars that I think need to be answered but the biggest problem as I see it *is that players can't see/interact with players operating on scales above and below them*. This sounds great in that the big players can't just squash the newbies, but *complete isolation isn't going to be possible in practice because players need to be able to cross into the next scale up as they grow otherwise they are all just playing 10 different games*. Given that you indicated there were 10 different scales, this means that for any particular location, there can be 10 overlapping domains, but at any scale, the location can only be owned by one player.

Lets leave off the technical issues presented by the map API's for a moment, and just explore the multi-scale world conceptually for a moment:

Given these players, how does promotion work?
*The Insurgent* -- 'A' scale player getting promoted up to 'B' scale.
*The Overlord* -- 'B' scale player controlling the 'B' scale territory The Insurgent will be promoted into.
*The Rival* -- 'A' scale neighbor of The Insurgent before before promotion.

* How does control pass to *The Insurgent*?

+ Does *The Insurgent* automatically claim the territory from *The Overlord*?
    + Does *The Insurgent* have to fight *The Overlord* to win the territory?
* What happens if this was the only territory controlled by *The Overlord*? (Are they out of the game from a threat they had no options to defend against?)
* What happens *The Insurgent*'s new 'B' scale territory is in the middle of an area all owned by *The Overlord*?

+ *The Insurgent* has an advantage against *The Overlord* because *The Overlord* now suddenly has 8 more border territories to defend? (assuming diagonal attacks are possible)
    + Does *The Insurgent* quickly lose the game because now they suddenly have just 1 'B' scale territory, and *The Overlord* can call upon the production of their other 20 something 'B' scale territories to put down the insurgency? (just small enough they didn't get promoted to Over-Overlord before the insurgency.)
* What happens to the long standing 'A' scale border dispute between *The Rival* and *The Insurgent* after the promotion?

+ Since *The Insurgent* can no longer operate at 'A' scale are their territories now undefended?
    + Can *The Rival* now just walk in and snatch up *The Insurgent*'s 25 'A' scale territories in quick succession and get promoted into the same 'B' scale territory *The Insurgent* just claimed from *The Overlord*?

If you have solid answers for all this, the scaling design does seem like it could have some late-game benefits to it (no longer having to manage the minutia), but if not, it seems like the whole scaling scheme is incomplete at best, or completely broken at worst.

# Answer
> 3 votes
I very much agree with Ilmari Karonen's answer, and believe that the best solution here might be to generate more solutions to the problem, perhaps breaking away from assumptions you're making. Might I humbly suggest one that seems consistent with how your game appears to work?

Have you ever heard of a Voronoi diagram?

The basic idea is that, given a set of marked points on a field, each unit of area on that field is colored according to the marked point closest to it, with the result being an interesting emergent "mosaic" structure. More interesting patterns appear if the marked points are allowed to name their own colors and share colors with other points - you could imagine, say, in a field with red points on the left and yellow points on the right, a diagram with a red region on the left and a yellow region on the right with a jagged line in between depending on the points' arrangements.

I propose you could make territory acquisition work the same way: ownership of a given point of territory is determined by the building or unit closest to it. When someone tries to build a building, you simply figure out who owns the closest unit or building to it - if it's the current player, you let them build the building. When you want to highlight who owns what territory on the screen, you draw a Voronoi diagram with a marked point for each unit and building in the immediate area. To keep territory from extending too far (and avoid having to potentially query every single unit in the game), you'd impose a maximum distance for which a unit can be considered, either a fixed distance, or something similar to your scaling idea where the region of influence grows as you rank up.

A really cool pro to this approach is that territory acquisition becomes incredibly natural. For instance, if you have two armies fighting across a river (or other natural barrier), the territory acquisition pattern will more or less *follow the river*. If you have a small player marching into a much larger player's territory, the territory acquisition pattern will show the first player controlling a small enclave immediately around them. All of this works at any (continuous) zoom level, and it's all possible with not only not having to consider geological features separately, but also not even having to consider territory as a permanent entity at all - it is simply a function of the units and buildings currently on the field.

(As another plus, the lack of hard territory divisions also makes it easy to account for the fact that the world is round, allowing the game to be played just as well around the poles and avoiding inaccuracies caused by 2D map projections.)

Of course, there are some cons to consider, too:

* You had better make sure those units and buildings can be queried efficiently, especially if you have a scaling maximum distance. Using something like a quad tree, even in the database layer, is a must here.
* Gameplay would be slightly different: in order for a player to keep claim on territory, they would have to leave a building behind. You could probably make a cheap building for expressly this purpose, though, such as a flag.
* Depending on user feedback, you may need to account for geological features anyway. For instance, in the aforementioned river example, you may find that the results are really ugly when the territory line doesn't quite mesh with the river, so you'll want to make it a boundary of some kind for the distance calculations.
* Calculating exactly how much territory a person owns would be more difficult, because you'd have to consider all of the units on the field instead of just counting squares. It would be hard to give users a real-time update for how much territory they own, and you would need an efficient way to calculate an estimate on the server in order to grant rewards based off of it (essentially, you would need to draw a Voronoi diagram of the world on it very few hours, like a global census). Doing this might require you to supply your server(s) with GPUs, incurring additional hosting costs.

---

**ADDENDUM:** For something easier to calculate on a global scale, you could make it so that only buildings determine territory acquisition (i.e. marching units do not claim territory, but must build a building first). This makes it a lot easier to calculate global territory acquisition (since buildings normally don't move), but does come with some caveats:

* The fact that you have to build a building to acquire territory may be unworkable for your game's design. If it does work for you, you may find that you either need simple buildings to satisfy these requirements (such as flags), units that can still claim territory (perhaps a "commander" unit), or exceptions to the territory claim rule (such as being able to build on unclaimed territory, or perhaps a "campfire" building that can be built anywhere, including in enemy territory).
* You will probably also have to implement a maximum range of influence, so that you can feasibly have territory owned by no one. Otherwise, it becomes impossible for players to build if they don't have a building already.
* You wouldn't get the "cool" effect of territory acquisition following combat lines. You could probably calculate with units on a local scale and use global scales for the census, though.

# Answer
> 2 votes
# Why not **both**?

Go with your approach first, as it has already been implemented, let's for call it **Arj mode** for now.

Then implement the other approach later, let's call it **Partner mode**.

Offering two modes, means offering two servers, with double the effort to maintain. But if one server is offline, the players can still play your game on the other server. You can also sell Partner mode as a game expansion, to cover the costs of implementation.

You and your partner could collect server metrics, and if Partner mode (or Arj mode) shows to have too few players, you can decide to shutdown that mode later.

I can see that both modes growing with different rules could be enjoyable for different reasons. As a player, I would like to play both of them, and to form my own opinion. But over time, your players will stay with the most enjoyable mode.

Even if some rules are weak, together they are strong. Market the rules as features.

For **Partner mode**:

* Not grind, but **extremely hard**.
* By being able to attack everyone, **total freedom**.

For **Arj mode**:

* Not being able to attack weak opponents, and not being attacked by strong opponents, **fair**.
* Progression of conquest tile size, **dynamic growth**.

There is a lot of things that could make **Arj mode** or **Partner mode** dead-ends, like powerful players being unable to find opponents, or new players unable to expand. Both modes can fail, so there is still more design decisions to be made. This is why I believe both should be tried.

# Answer
> 0 votes
Have you considered negotiating equity? If you're confident that this design decision will impact the sales of the game, and that there is no other way to convince this person that the group should go in your direction, maybe you could give him some equity in exchange for more control. If he gets an extra 5 or 10% of the cut, this might be enough to sway him to go your way - and then in the end both parties get more of what they want. And then in the end if the design decision ended up helping the game by significantly more than 5-10%, then you'll come out ahead.

# Answer
> 0 votes
IF you have "rounds" (the world is not persistent and each game ends after some time), like most such games, then most relevant players will be competing on the same scale, likely with additional accounts used to undermine the opponent. It could be an interesting back-stabbing game, but I believe it would make a pretty poor "classic RTS" given you have threats you cannot even counter (without alts).

Assuming rounds, there is also a possible "compromise". Game starts with tiny scale tiles, possibly your 5m. Then, after some time, say a week (or some other threshold like top player strength), ALL tiles grow to the next size. Probability to get the next square is 4% per smaller tile comprising it. You start small, then grow in size and power so you don't have to manage many tiles. Inactive players would likely die during merge. The game would play much closer to his proposal of fixed-size tiles than yours, but it would retain your "no need to take care of thousands of tiles" reservation of his approach.

If you want to have persistent game, his approach (as well as this scaling mentioned) will likely not work. Area grows faster than length, so bigger players are less vulnerable and will easily smash smaller ones. Your idea is pretty good in this case - top dogs will be fighting on global scale, but you could still battle other newcomers (and alts) no matter when you join.

# Answer
> 0 votes
Why not both? What I mean by that is start off with small squared, and expand them, however make each bigger square contain smaller ones. This might add to diversity in the form of having "small" players attack "big" players, and thus being big doesnt mean you can not lose. As a big one attacked on multiple fronts you will not be able to defend each attacked small square. So even though you win 10 battles, you will lose 1, and this might help for a weirder shapes formed. At least this is how I imagine it.

# Answer
> 0 votes
I dislike idea #1—as a territory system—and will try to provide a compelling argument. Unfortunately, these kinds of design decisions are hard to reason about.

I do know about a game that has world-territories that's worth reviewing: Ingress (by Niantic)

---

# My Argument

I think, the multi-tiered territory feature is an over-engineered solution to a "solved" problem. That is, when I (as a player) think about games with territories, I think about static regions like squares, hexes, or polygons (Risk). This is an indicator that multi-tier territories won't meet expectations. I'm not suggesting you and your partner shouldn't have creative liberties in the game—but seeing what other similar games(products) do is a good way to reduce complexity—as someone else has solved it for you!

From a gameplay perspective, this sounds like a management nightmare. Most RTS's are about command bandwidth: quickly and accurately controlling your units. Having to zoom-in and out to regions seems like it would exponentially increase the complexity of controls at least one magnitude. Games with learning curves will limit your audience.

From a technical (maintenance) perspective, multi-tiered territories are significantly more complex to implement and maintain. In the future if you decide to refine your system, you are working with multi-tiered data versus an array of squares (oversimplified I know).

Finally, don't fall into a sunk-cost fallacy. Just because you spent 2 months designing and developing this for pre-alpha, shouldn't be an argument for keeping the feature in the game. A feature should be in the game because it's right, the only option, or because there isn't support/motivation to change it.

---

# My Recommendation

Although the grid idea works, I think a hybrid approach would feel better:

Have the world broken into a grid of a base size (e.g. 5km x 5km). All game logic only care about that. This simplifies the coding *and* the gameplay.

Then visually, you implement groupings of the territories so you can see who owns what at increasing sizes. These wouldn't have an affect on gameplay but satisfy most of your "pros".

---
Tags: game-design, rts, business, mmorts
---


# Question
Title: How to design components for tile-based movement in an RPG using ECS
I'm trying to re-write a small game of mine using ECS mostly for educational purposes and to see if it fits top-down RPG games in the style of Pokemon (gameboy). Since everything is tile based, initially I had a Position component that only holds the position of the player, and a Controller/Input component that, when a movement keypress is detected, starts to change the player's position until it falls into a tile. Then, the Rendering component would render the player based on a vector of clips that simulate the movement.

Thinking that my player should only move in tiles, I thought that it might be better to change the position tile-by tile every time, and then use some sort of interpolation in the Animation or Rendering component to figure out which of the clips to use (left foot forward, right foot forward etc.). This proved to be much less error prone, but now this means that I need to keep the actual position and the "visual" position (the one you can see on the screen). Thinking that logic should be not mixed with rendering, it seems that the "correct" thing would be to not keep the "visual" position in the Position component, but in one of the "front end" components like Animation or Rendering. Which would be the most correct thing to do? By correct meaning the thing that will keep the code truly decoupled in the vein of pure ECS.

# Answer
> 1 votes
*I haven't touched Haskell for about 17 years, so this answer will be more about an approach than an implementation... sorry.*

---

> Which would be the most correct thing to do? By correct meaning the thing that will keep the code truly decoupled in the vein of pure ECS.

I don't think there is *a most correct* thing to do, and I don't think a *pure ECS* exists: there is a correct thing to do for your context, and there is an ECS that works for you and for your game. The rest is pressure that you put on your shoulders, and it's hard to define what value this pressure adds to your skills and to your game.

So "perfectly" decoupling the logic from the visual might not be needed.

---

What if your "position" was actually the "world's position"? And you let your renderer convert world positions to screen position. (This way, you now think in "tiles per second" and not in "pixels per second", which can help port your game more easily to different resolutions -- everyone will be traveling at the same speed.)

Your world is based on tiles, so it could be fine to keep the tiles as "integer" values in "float" variables, but if your character needs to *move* then you can still use "float" values to place it.

Your position is then "logic", and not "visuals".

Then, what you could do is to work with a "state" in your animation component, along with a ratio and a starting and ending point.

Your character will be "walking". It's a logic state: where is their left foot - up or down? Where is their right foot - up or down? You'll need to know that eventually to produce the appropriate sounds, to produce the puffs of dust when walking on the sand, etc, so you can consider it's not just for the visuals.

Then you could have this kind of data in your animation component:

* Start (either the tile, or tile world coordinates)
* End (either the tile, or tile world coordinates)
* ProgressRatio (\[0..1\], where is the character between the Start and End)
* ProgressSpeed (how much progress should be done per frame, or per second, etc.)
* StatesList (LeftFootUp, RightFootUp, etc... this will match your animation)
* CurrentState (pointer to the current state)

Then each frame, a system will progress the Ratio by the Speed, then using the ratio, will update the current state (say, if your list has 4 states, the animation will have 4 frame, so 25% each; when the ratio will be at 33%, CurrentState will now point to the second state). The Position component will be updated with the start-end-ratio combo, while the render component, the one that holds the sprites, will be updated with the state.

I don't know if it makes any sense for your situation, but I hope it helps :)

# Answer
> 1 votes
If the visual position is needed by one set of systems and the logical position by another set of systems, then it might be a good idea to have a separate component for each.

* Have the Animation system and the Rendering system read the VisualPosition components.
* Have the game-mechanical systems read the LogicalPosition components.
* Have the Movement System update both visual and logical position components.

---
Tags: movement, rpg, grid, entity-component-system, haskell
---


# Question
Title: How do the PhysWalking and similar functions actually handle input?
As the title may suggest, I'm developing a `CustomMovementComponent` and I'm on the stage where I am developing my own `PhysCustom` function.

As such, I am trying to copy the style of Epic's development for these functions.

One thing that has bewildered me thus far is how these functions : `PhysWalking`, `PhysFalling` etc **actually handle input**.

I understand that they work based on time steps but where in these functions is the input actually taken into account?

Thanks

# Answer
> 1 votes
I'm going to answer my own question here, since I figured it out.

A Player's input is passed into `AddMovementInput`, which then affects `ControlInputVector`.

A `MovementComponent` then queries this `ControlInputVector` using `GetPendingInputVector`. It then uses the result of this to update/affect `Acceleration`.

The various `Phys` functions within `MovementComponent` will then query `Acceleration` (Henceforth known and used as input), to affect `Veclocity`, which is ticked and used to update the position of the `UpdatedComponent` for the player pawn.

---
Tags: c++, physics, movement, unreal-4
---


# Question
Title: In a MovementComponent, where should I initialize member variables?
I have a `MovementComponent` derived from `CharacterMovementComponent`

`MovementComponent`, attached to a `Character`, needs a reference to `GrappleComponent`, stored on the `Character`.

Where do I perform the `GetComponentByClass` call to obtain this reference to the `GrappleComponent`?

If this is the constructor, could I please have some information on how to override the constructor?

# Answer
> 2 votes
Normally you want to initialize default values of your member variables in the Constructor itself it will be the faster way since UE4 uses CDO, however if you want to get a reference/pointer to another component you shall do it in `virtual void BeginPlay()` because at the time your constructor is called the other component/actor/whatever object may not yet be initialized.

In BeginPlay you should normally have everything initialized (but, not began play yet).

Example:

In my constructor I am initializing the most common primitives:

```
UCNWCharacterMovementComponent::UCNWCharacterMovementComponent() //My Custom CMC constructor
{
    m_SmoothSpeed = 5.0f;
    m_bUsesApexCloth = false;
    b_astaring = false;
    bAutoRegisterUpdatedComponent = false;

    OldVelocity = FVector::ZeroVector;

    m_rotationSpeed = 4.0f;
    m_bVisualizeMovement = true;
    m_bIsMoving = false;

```

}

In my BeginPlay I am getting my pointers/references to components I am about to use:

```
void UCNWCharacterMovementComponent::BeginPlay()
{
    Super::BeginPlay();

    SetComponentTickEnabled(false);

    //Disable Automatic Rotation!
    bOrientRotationToMovement = false;

    bIgnoreClientMovementErrorChecksAndCorrection = false;
    m_SkipFloorChecks = true;

    m_ownerRef = (ACBaseUnitCharacter*)CharacterOwner;
    if (m_ownerRef.IsValid())
    {
        m_nwAIControllerRef = Cast<ANWAIController>(m_ownerRef->Controller);
        m_desiredRotation = m_ownerRef->GetActorRotation();
    }
    TArray<AActor *> grid;
    UGameplayStatics::GetAllActorsOfClass(this, ANavigationGridActor::StaticClass(), grid);
    if(grid.Num() > 0)
    {
        m_navGridActor = (ANavigationGridActor*)grid[0];
    }

    TArray<AActor *> ObstacleProvider;
    UGameplayStatics::GetAllActorsOfClass(this, ARVO2ObstacleProvider::StaticClass(), ObstacleProvider);
    if (ObstacleProvider.Num() > 0)
    {
        m_obstacleProvider = (ARVO2ObstacleProvider*)ObstacleProvider[0];
    }

    m_unitRadius = m_ownerRef->GetCapsuleComponent()->GetScaledCapsuleRadius();
    m_unitRadiusSQ = m_unitRadius * m_unitRadius;

    MaxSimulationIterations = 100;
    m_currentSimulatedPosition = GetActorLocation();
}

```

Begin play will always be executed after the constructor: As you can see i do have some primetives set in `BegnPlay` as well but that's only because I want to be sure that they will be in these values and noone will mess them up normally you don't want the primitives to be set (unless they are dependent on actors/components (run-time created stuff)).

---
Tags: c++, physics, movement, unreal-4
---


# Question
Title: Dealing damage over multiple frames without damaging the same enemy twice
I am using `Physics.Overlap` to find which enemies are in my damage range. But dealing damage in only one frame is not what I want. Some attacks should be active for a longer time, to catch enemies who come into range part-way through the attack.

But if I call the method again, I can get the same enemy multiple times. This means my damage will be higher if the framerate is higher. To avoid this I can:

1. Put a timer on the enemy that prevents damage for some period of time after taking damage. This is the simplest approach but it's bad if you have high speed, multi-hit attacks that damages the enemy multiple times quickly.
2. Keep track of damaged enemies with a list. As long as the hitbox is active, check every frame for enemies inside the hitbox. For each enemy found, check whether it's already in the list, add it to the list and damage it if not.
3. Same as #2 but use a dictionary/hashset.

Option #2 is my current approach. Hashsets are supposed to make dupe checks faster BUT I'm not sure how It does that. I use a `List<damageable>` to track damaged enemies and `Damageable` is an interface.

How does a `Hashset<Damageable>` differentiate between each entry if they are interfaces?

If I use dictionaries instead I'd need to generate different keys for each enemy. That's another problem unless game objects already have some sort of unique hash key. Even then, there's the possibility of ignoring a gameobject with multiple damageable components.

Then there's also the possibility that I'm getting nothing by doing this optimization. Most hitboxes will probably intersect with 3-5 enemies at most over it's lifetime. Would looping over a list be faster anyways?

# Answer
A Hashset is a collection that can't be sorted and cannot contain duplicate values, making it ideal for checking for duplicates especially due to how values are stored in memory.

It checks for equality first by calling GetHashCode(). Which is a method that all objects in C# implement, if you don't override it yourself it'll use the default implementation. For classes the default implementation should be fine. If you implement it yourself it is important that there are as few collisions as possible, a collision is when 2 unequal items produce the same HashCode.

If a hashset contains another item with the same hashcode, it'll call Equals() on these items (which is also a method all objects in C# implement and can be overridden) to check if they are equal. If they are equal you can't insert it as it is already present.

As for why a HashSet is faster is a bit technical and dependent on the actual implementation used. The simple (and incomplete) answer is that the hashcode is basically converted to an index, meaning that it doesn't have to loop the entire list to check whether an item is already inserted, but rather only the 1 at that index (or a few if there are some hashcode collisions). Making it more efficient **especially with large collections**.

A HashSet is basically a Dictionary with only keys and no values, so there is no reason to use a Dictionary over a HashSet unless you actually need to store a value with the key.

If you use the list only for duplicate checking, then I think a hashset would be better, even if just to simplify your code of duplicate checking by using the Add method.

```
if (myHashset.Add(myObject))
{
    // Do logic that should only happen if it wasn't in the hashset previously.
}

```

The performance difference will however probably not be noticeable with only 5 elements in the list.

As for the interface part, becasue you can't instantiate interfaces you never insert an interface in a HashSet. You insert a class (or struct) that implements an interface in the HashSet, meaning it uses that default (or your custom overridden) implementation.
> 1 votes

---
Tags: unity, c#, physics, optimization, gameobject
---


title: Mana regeneration formula

text:
# Question
Title: Mana regeneration formula
Suppose my mana regeneration rate was calculated in this way:

ManaRegenRate = 0.01 × (BaseManaRegen + ManaRegenMultiplier × Willpower) × TotalMana

Where willpower is my attribute ranging from 0 to 100 and BaseManaRegen and ManaRegenMultiplier are some constants.

With this formula I would get mana regenerated per second.

How could I rearrange this formula to get the total amount of seconds to regenerate mana from 0 to full?

# Answer
Assuming your "ManaRegenRate" is the mana regenerated per second, you just have to divide the TotalMana through the mana regen rate.

$$ TotalMana \over 0.01 × (BaseManaRegen + ManaRegenMultiplier × Willpower) × TotalMana $$

But because TotalMana appears on both sides of the fraction, you can simplify the fraction by removing it and arrive at:

$$ 1 \over 0.01 × (BaseManaRegen + ManaRegenMultiplier × Willpower) $$

You might notice that the time it takes to fully regenerate mana in your game is completely independent from how much mana the character can actually have.
> 3 votes

---
Tags: mathematics
---


# Question
Title: How to set up an architecture and a strategy allowing the persistence of the data of a MUD in a relational database?
How to set up an architecture and a strategy allowing the persistence of the data of a MUD in a relational database?

**Type of game:**

My question relates to the design of a Multi User Dungeon (MUD).

A MUD is a textual online game, considered today as the ancestor of the MMORPG. Players create characters and then control them in a completely text-based world using commands. For example, they can move from room to room, kill monsters, collect items, equip themselves with armour and weapons, solve quests, etc.

From a technical point of view, it is simply a server written in C++. Players connect using MUD clients or directly via the telnet protocol.

**My objective:**

I would like to ensure the persistence of the game using a relational database.

For performance purposes, I do not intend to load and save my data from the database in real time.

I plan to:

* load all my data in memory at the launch of the MUD
* save only objects that will be modified during runtime at regular intervals of time (every minute for example)

If possible, I would obviously like the code that ensures the persistence of the data to be completely independent of the game data.

**My problem:**

I have a hard time knowing which architecture to set up.

For instance, I do not know how to manage the dependencies of the objects between them. For example:

* an object of type **Character** has a pointer to an object of type **Room**
* this object of type **Room** itself has a list of pointers of **Objects** placed on the ground
* these **Objects** themselves have a pointer to their **Prototype** (a prototype corresponds to the model of the object)
* etc.

How do I do to load all these dependencies properly? I could obviously hack a code that does it. However, I do not see how to do it cleanly. Is there a relatively simple way to do it, without coding an entire ORM for that?

All the examples that I find on the internet mention the different Design Patterns put in place by the ORMs. It looks complex. It must be a lot of code to write!

Or they give answers that do not seem satisfactory. For example:

*“You may have objects that point to too many other objects for them to be loaded immediately. Sometimes linked objects will link to other objects further increasing the amount of data to be loaded if you want to load all dependencies at once. It may even happen that you encounter endless reference loops leading to stack overflows or script timeouts. This means that most of the time we need to make a judgment where to cut off the dependency chains.”*

Source: https://pkp.sfu.ca/wiki/index.php/Data\_Access\_Objects\_(DAO)#One-to-many\_or\_many-to-many\_relations\_of\_independent\_objects

I don’t want to cut the dependency chains. I just want my entire object graph. Not less. Not more!

The problem I encounter, however, seems relatively basic. It had to be solved millions of times. However, I can not find examples or solutions that are clear and relatively simple.

**My first approach:**

I could maybe:

* load all my objects without any dependency
* once all my objects are loaded and accessible in memory, some methods might have the task of solving all these dependencies and recreating all the links between the objects

In this case, does that mean that I will have to store the Primary Keys of the different objects directly in the objects? It would break the total independence of my game objects and the way I persist my data.

**My question would be:**

In the case of an online game and since my different game objects will be strongly linked to each other, what would be a possible strategy and architecture allowing the saving and the loading of these data in a relational database, while managing the dependencies of the objects between them?

How do people usually solve this problem?

# Answer
> 1 votes
I know this question was asked a few months ago but I figured i'd go ahead and answer.

The way I do it in my mud, is every player / mob have a home area/home room, and a current area/room field in their code, and each of those is associated with an integer which corresponds with the area id\_number / room id\_number so when they go through exits, the numbers get updated. So when i save/load from the database, the system knows which area/room they are in (just make sure you load the areas/rooms first!).

---
Tags: c++, architecture, databases
---


# Question
Title: Stuttering when using movetowards in a coroutine
I have the following problem with a WebGL project I'm working on:

I have an object which I want to zoom out and move to a specific position at the same time, for this, I've created a coroutine which is called on click. On my computer, everything works perfectly fine, but whenever I try this function on a not that high-end computer, this coroutine stutters a bit.

I've tried deactivating every single shader or sprite that this object is using in order to discard high graphic usage, but the problem persists even if the object is a blank circle.

This is the coroutine I'm using:

```
  IEnumerator restorePosition() {
    float counter = 0;
    while(counter < duration) {
      counter += Time.deltaTime;

      if (counter > duration) {
        counter = duration;
      }

      float framesPerTime = Vector3.Distance(zoomedTransform.position, storedPosition) / (duration - counter) * Time.deltaTime;
      zoomedTransform.position = Vector3.MoveTowards(zoomedTransform.position, storedPosition, framesPerTime);

      float framesPerTimeZoom = Vector3.Distance(zoomedTransform.localScale, storedScale) / (duration - counter) * Time.deltaTime;
      zoomedTransform.localScale = Vector3.MoveTowards(zoomedTransform.localScale, storedScale, framesPerTimeZoom);

      //restore solar system to original position
      float solarSystemFrames = Vector3.Distance(solarSystem.position, solarSystemStartPOS) / (duration - counter) * Time.deltaTime;
      solarSystem.position = Vector3.MoveTowards(solarSystem.position, solarSystemStartPOS, solarSystemFrames);
      yield return null;
    }

    //zoomedTransform.position = storedPosition;
    zoomed = false;
    spriteMask.frontSortingLayerID = originalFrontLayerID;
    spriteMask.backSortingLayerID = originalBackLayerID;
    zoomedTransform.localScale = storedScale;

    foreach(SpriteRenderer s in spriteChildren) {
      s.sortingLayerName = originalLayer;
    }

    foreach(OrbitController o in planets) {
      o.restartAnimation();
    }
    inTransition = false;

    //set moon layer  values back to original
    if (moon != null) {
      moon.gameObject.GetComponent<SpriteMask>().isCustomRangeActive = true;
      moon.gameObject.GetComponent<SpriteRenderer>().sortingLayerName = moonLayerName;
      foreach (Transform child in moon) {
        child.GetComponent<SpriteRenderer>().sortingLayerName = moonLayerName;
      }
      moon.GetComponent<MoonBehaviour>().zoomOut();
      //reset null transform and layer names
      moon = null;
      moonLayerName = null;
    }
    yield break;
  }

```

Could you give me an idea of what I'm doing wrong? , I've also tried Lerp and that didn't solve the problem. Thank you!

# Answer
> 1 votes
If you use things that are Framerate Dependent (Update or things with deltatime) then it can cause this.

If you do not want the routine to be framerate dependent then you can use `WaitForFixedUpdate()` or put the movement in `FixedUpdate()` These have a fixed timestep loop

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


# Question
Title: Help with NPC following the player in a sidescroller
I'm a beginner with C# and am having a bit of trouble coding an NPC that follows the player in a 2D sidescroller. The player has two speeds, a walk and a sprint. I have a very basic companion follow script but it's only set on one speed, and if I increase the speed so that the NPC will keep up when the player sprints, the NPC jitters when it follows the walking player, which makes sense. I'm just wondering if there's a way in which the NPC can dynamically follow the player in the exact same speed as the player so that this issue doesn't arise. I figure this would inquire an entirely new script, but that's fine. Again, I'm still new to all this, so any help would be greatly appreciated! Thanks!

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CompanionFollow : MonoBehaviour
{
public float speed;
public float stoppingDistance;

private Transform target;

// Start is called before the first frame update
void Start()
{
    target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}

// Update is called once per frame
void Update()
{
    if(Vector2.Distance(transform.position, target.position) > stoppingDistance)
    {
        transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }
}

```

}

# Answer
try smoothing it out a bit with something like `Vector3.SmoothDamp()`

```
public Transform target;
float damping = .05f;
float followDistance = 2;
private Vector3 currentVelocity;

private void Update()
{
    if (target != null && Vector3.Distance(transform.position, target.position) > followDistance)
    {
        Vector3 newPos = Vector3.SmoothDamp(transform.position, target.transform.position, ref currentVelocity, damping, 10);
        transform.position = newPos;
    }
}

```

you can adjust the follow distance and damping to your project.
> 0 votes

---
Tags: unity, c#, 2d, side-scroller, npc
---


# Question
Title: Need help with an 'Exception thrown:write access violation:this was nullptr' in a c++ - SFML project
I'm currently learning how to program a 2d game with SFML using a tutorial series by Suraj Sharma.This's his channel:

https://www.youtube.com/channel/UC2i39AOpDSlO1Mrn1jQ8Xkg

The tutorial series:

https://www.youtube.com/watch?v=IdKZpv6xqdw&list=PL6xSOsbVA1ebkU66okpi-KViAO8\_9DJKg&index=1

Recently i'm making an animation class that works with a player class. Everytime i push a button repeatedly the debug will tell me i have a 'write access violation:this was nullptr'.

Here's the code.

AnimCmp.h:

```
#ifndef ANIM_CMP_H
#define ANIM_CMP_H

#include "pch.h"

class AnimCmp
{
private:
class Anim {
public:
    //Vars
    sf::Sprite& Spr;
    sf::Texture& TexSheet;
    sf::IntRect StartRct;
    sf::IntRect CurrRect;
    sf::IntRect EndRct;

    bool Done;
    float Timer;
    float AnimTimer;
    int w;
    int h;

    Anim(sf::Sprite& Spr, sf::Texture& TexSheet, float AnimTimer, int stx, int sty, int frx, int fry, int w, int h)
        :Spr(Spr), TexSheet(TexSheet),AnimTimer(AnimTimer),Timer(0.f),Done(false),w(w),h(h){
        this->w = w;
        this->h = h;
        this->StartRct = sf::IntRect(stx * w, sty * h, w, h);
        this->CurrRect = this->StartRct;
        this->EndRct = sf::IntRect(frx * w, fry * h, w, h);

        this->Spr.setTexture(this->TexSheet, true);
        this->Spr.setTextureRect(this->StartRct);
    }
    //virtual~Anim();
    //Functions
    void Pause();
    void Reset() {
        this->Timer = this->AnimTimer;
        this->CurrRect = this->StartRct;
    }

    const bool& Play(const float& dt) {
        //Update Timer
        this->Done = false;
        this->Timer += 100.f * dt;
        if (this->Timer >= this->AnimTimer) {
            //Reset Timer
            this->Timer = 0.f;
            //Animate
            if (this->CurrRect != this->EndRct) {
                this->CurrRect.left += this->w;
            }
            else {//Reset
                this->CurrRect.left = this->StartRct.left;
                this->Done = true;
            }
            this->Spr.setTextureRect(this->CurrRect);
        }
        return this->Done;
    }

    const bool& Play(const float& dt, float modprcnt) {
        //Update Timer
        if (modprcnt < 0.5f)
            modprcnt = 0.5f;

        this->Done = false;//access violation occurs here
        this->Timer += modprcnt * 100.f * dt;
        if (this->Timer >= this->AnimTimer) {
            //Reset Timer
            this->Timer = 0.f;
            //Animate
            if (this->CurrRect != this->EndRct) {
                this->CurrRect.left += this->w;
            }
            else {//Reset
                this->CurrRect.left = this->StartRct.left;
                this->Done = true;
            }
            this->Spr.setTextureRect(this->CurrRect);
        }
        return this->Done;
    }
    //Access
    const bool& isDone()const {
        return this->Done;
    }

};

sf::Sprite& Spr;
sf::Texture& TexSheet;
std::map<std::string, Anim*> Anims;
Anim* LastAnim;
Anim* Priority;
public:
AnimCmp(sf::Sprite& Spr,sf::Texture& TexSheet);
virtual~AnimCmp();
//Access
const bool& isDone(const std::string key);
//Functions
void AddAnim(const std::string key,float AnimTimer, int stx, int sty, int frx, int fry, int w, int h);

void Start(const std::string Anim);
void Pause(const std::string Anim);
void Reset(const std::string Anim);
const bool& Play(const std::string key, const float& dt, const bool priority = false);
const bool& Play(const std::string key, const float& dt, const float& mod, const float& modmax, const bool priority = false);
};

#endif // !ANIM_CMP_H

```

AnimCmp.cpp:

```
#include "AnimCmp.h"

AnimCmp::AnimCmp(sf::Sprite& Spr, sf::Texture&    TexSheet)
:Spr(Spr), TexSheet(TexSheet), LastAnim(NULL),   Priority(NULL)
{
}

AnimCmp::~AnimCmp()
{
for (auto& i : this->Anims) {
    delete i.second;
}
}

const bool& AnimCmp::isDone(const std::string key)
{
return this->Anims[key]->isDone();
}

void AnimCmp::AddAnim(const std::string key,float AnimTimer, int stx, int sty, int frx, int fry, int w, int h)
{
this->Anims[key] = new Anim(this->Spr, this->TexSheet, AnimTimer, stx, sty, frx, fry, w, h);
}
//Functions
void AnimCmp::Start(const std::string Anim)
{
}

void AnimCmp::Pause(const std::string Anim)
{
}

void AnimCmp::Reset(const std::string Anim)
{
}

const bool& AnimCmp::Play(const std::string key, const float& dt, const bool priority)
{
if (this->Priority) {//If priority present
    if (this->Priority == this->Anims[key]) {
        if (this->LastAnim != this->Anims[key])
        {
            if (this->LastAnim == NULL)
                this->LastAnim = this->Anims[key];
            else {
                this->LastAnim->Reset();
                this->LastAnim = this->Anims[key];
            }
        }
        //Priority done,remove
        if (this->Anims[key]->Play(dt)) {
            this->Priority = NULL;
        }
    }
}else{//Play animation
    if (priority) {
        this->Priority = this->Anims[key];
    }
    if (this->LastAnim != this->Anims[key])
    {
        if (this->LastAnim == NULL)
            this->LastAnim = this->Anims[key];
        else {
            this->LastAnim->Reset();
            this->LastAnim = this->Anims[key];
        }
    }
    this->Anims[key]->Play(dt);
}
return this->Anims[key]->isDone();
}

const bool& AnimCmp::Play(const std::string key, const float& dt, const float& mod, const float& modmax, const bool priority)
{
if (this->Priority) {//If priority present
    if (this->Priority == this->Anims[key]) {
        if (this->LastAnim != this->Anims[key])
        {
            if (this->LastAnim == NULL)
                this->LastAnim = this->Anims[key];
            else {
                this->LastAnim->Reset();
                this->LastAnim = this->Anims[key];
            }
        }
        if (this->Anims[key]->Play(dt, abs(mod / modmax))) {
            this->Priority = NULL;
        }
    }
}
else {//Play animation
    if (priority) {//If is priority,set it
        this->Priority = this->Anims[key];
    }
    if (this->LastAnim != this->Anims[key])
    {
        if (this->LastAnim == NULL)
            this->LastAnim = this->Anims[key];
        else {
            this->LastAnim->Reset();
            this->LastAnim = this->Anims[key];
        }
    }
    this->Anims[key]->Play(dt, abs(mod / modmax));
}
return this->Anims[key]->isDone();
}

```

Player.h:

```
#pragma once
#ifndef PLAYER_H
#define PLAYER_H

#include "Entity.h"
class Player :
    public Entity
{
private:
    //Vars
    bool atking;
    //Init Funcs
    void InitVars();
    void InitComp();
public:
    Player(float x, float y, sf::Texture& TexSheet);
    virtual ~Player();
    //Funcs
    void UpdateAtk();
    void UpdateAnim(const float& dt);
    virtual void Update(const float& dt);
};

#endif // !PLAYER_H

```

Player.cpp:

```
    #include "Player.h"

//Init Funcs
void Player::InitVars()
{
    this->atking = false;
}

void Player::InitComp()
{
}

Player::Player(float x, float y, sf::Texture& TexSheet)
{
    this->InitVars();
    this->setPos(x, y);

    this->CreateHboxCmp(this->Spr, 20.f, 0.f, 80.f, 128.f);
    this->CreateMovCmp(200.f, 10.f, 4.f);
    this->CreateAnimCmp(TexSheet);

    this->animCmp->AddAnim("Idl", 10.f, 2, 0, 2, 0, 128, 128);
    this->animCmp->AddAnim("Walk", 10.f, 0, 6, 5, 6, 128, 128);
    this->animCmp->AddAnim("PShoot", 30.f, 3, 0, 5, 0, 128, 128);
}

Player::~Player()
{
}
//Funcs
void Player::UpdateAtk()
{
    if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
        this->atking = true;
    }
}

void Player::UpdateAnim(const float& dt)
{
    if (this->atking) {
        //Chk for anim end and animate
        if (this->animCmp->Play("PShoot", dt, true)) {
            this->atking = false;
        }
    }
    if (this->movCmp->GetSt(IDL)) {
        this->animCmp->Play("Idl", dt);
    }
    else if (this->movCmp->GetSt(LFT)) {
        if (this->Spr.getScale().x < 0.f) {
            this->Spr.setOrigin(115.f, 0.f);
            this->Spr.setScale(-1.f, 1.f);
        }
        this->animCmp->Play("Walk", dt, this->movCmp->getVel().x, this->movCmp->getMaxVel());
    }
    else if (this->movCmp->GetSt(RGT)) {
        if (this->Spr.getScale().x > 0.f) {
            this->Spr.setOrigin(0.f, 0.f);
            this->Spr.setScale(1.f, 1.f);
        }
        this->animCmp->Play("Walk", dt, this->movCmp->getVel().x, this->movCmp->getMaxVel());
    }
    else if (this->movCmp->GetSt(UP)) {
        this->animCmp->Play("Walk_up", dt, this->movCmp->getVel().x, this->movCmp->getMaxVel());
    }
    else if (this->movCmp->GetSt(DN)) {
        this->animCmp->Play("Walk_dn", dt, this->movCmp->getVel().x, this->movCmp->getMaxVel());
    }

}

void Player::Update(const float& dt)
{
    this->movCmp->Update(dt);
    this->UpdateAtk();
    this->UpdateAnim(dt);
    this->hbCmp->Update();
}

```

The Exception occurs right after the 'bool Done' variable was declared.

Here's the video where that happened:

https://www.youtube.com/watch?v=Ou3vegN3Yz4&list=PL6xSOsbVA1ebkU66okpi-KViAO8\_9DJKg&index=38

I've also checked the 'this' pointer in debug mode.It said that it wasn't able to get the value of the following variables:

TexSheet

Spr

StartRect,CurrRect and EndRect

I hope this is enough information.Can anyone help me ?

# Answer
> 'this' was nullptr

and

> It said that it wasn't able to get the value of the following variables \[...\]

You're trying to modify an object that does not exists. This could have worked in the older days, and you would have had a really hard time to figure out what was going on. Today, the systems are smarter and it's really harder to shoot yourself in the foot: they detect such issues and crash right away.

One of the ways to answer questions such as: *What is the nullptr' object? Who's calling the function? What are the values that would help me pin-point the issue?* is by **using the callstack debug window.** This will tell you who's calling it, and you can click on all those steps to get more info; the Visual Studio debugger will also reveal information such as the values of the variables that were involved.

Or, if you don't have such tools, like here, spend more time understanding your code and what goes on.

Here, I suspect you try to call an animation that does not exists: from the looks of it, it appears that you try to access animation `Walk_up` or `Walk_dn`, but I don't see it initialized in the `Player` constructor.
> 1 votes

---
Tags: c++, game-loop, sfml, visual-studio
---


# Question
Title: I cannot move my player to right on Godot
I'm beginning with Godot making a simple Sprite which should move both left and right but when right key is pressed the `KinematicBody2D` doesn't move right. According to the logic it should does but it does not.

I leave the code below hoping someone could help me to find the error

```
extends KinematicBody2D

const VEL = 50
var vec_mov = Vector2()

func _ready():
    pass # Replace with function body.

func _physics_process(delta):
   if(Input.is_action_pressed("ui_right")):
       vec_mov.x += VEL
   if(Input.is_action_pressed("ui_left")):
       vec_mov.x -= VEL
   else:
       vec_mov.x = 0

   move_and_slide(vec_mov)

```

Thanks

# Answer
Your problem is in the code here:

```
   if(...):
       A
   if(...):
       B
   else:
       C

```

You are causing it to go into C only if it does not go into B. The statement about A is a separate statement and has no effect. So the velocity value is getting turned off because you are not in B.

Try putting all the statements together like this:

```
   if(...):
       A
   elif(...):
       B
   else:
       C

```

It should fix your problem.
> 3 votes

---
Tags: godot
---


# Question
Title: Resolving collisions after initial collision
Given a sweep test for a ray, how do we check collisions after the 1st collision has been detected, and the ray has been deflected.

Physics system steps are:

1. Update velocities (gravity, etc)
2. Resolve collisions
    * The ray will intersect the floor, and will be moved back at the penetration amount.
    * The new velocity is calculated as a reflection
3. Update positions
    * The ray is now on the wrong side of the wall

This all happens in 1 frame

If the orange ray hits the floor just before the wall, the new velocity will tunnel the ray through the wall within one frame. The naive way to fix this would be to after each collision check all the bodies again with the new velocity, but this can take multiple iterations if the ray bounces around in a corner. There is no way of knowing how many times the ray will need to be processed.

What would be a good way to fix this issue?

# Answer
It sounds like you already understand the solution:

Keep iterating.

When the swept test intersects an object, reflect it, and perform a second sweep along the new direction and remaining distance.

This remaining distance only decreases with each bounce (especially if you apply a small skin offset to prevent tunnelling), so this will terminate eventually.

If you're worried about performance cost spikes from the occasional tight bounce, you can also enforce something like a 3-bounce limit and accept discarding some time as an approximation error. On the last bounce, place the object at the beginning of the reflected ray, rather than at the end, and resume its sweep testing motion next frame.

You can tune the limit to your liking to find the right balance between performance control and accuracy — from a 0-bounce limit where objects hesitate a frame on every contact (large error), to a 10-bounce limit where hopefully very few objects will ever hit the cap in a single frame. You can even adjust the cap dynamically based on load, or object importance.

I show an example of a 2-bounce limit (well, sliding, not bouncing) in this answer.
> 1 votes

# Answer
Well, you need to know the time to collision. Then negate it from the simulation time: and pass new velocity with new time to the 2. So you will check the collisions along the reflection vector and still simulate collisions until the simulation time is 0. The step 2 should look like: while (time \>= some\_tiny\_epsilon\_as\_close\_as\_possible\_to\_zero) { Perform ray traces and collisions... }

In case when move is completed and no collision occured just set the time to 0.

Hope it helps
> 0 votes

---
Tags: collision-detection, physics
---


# Question
Title: using #if UNITY_EDITOR && !UNITY_ANDROID greys out the code
I'm trying to exclude part of my code when building(android) but keeping it while in the editor for testing purposes.

Using `#if UNITY_EDITOR` only will result in this code getting built, but using `#if UNITY_EDITOR && !UNITY_ANDROID` will grey out the code making it unusable in play mode.

# Answer
The editor grays them out to remind you the code doesn't work in the current build platform you chose.

For example if in the editor you have chosen Android as the current build platform, it will gray out code that is on other platforms to remind you that this code only works on Android build.

Sometimes you'll write code for debug and testing, so you'll put it in `UNITY_EDITOR` so it only works in Unity editor.

When you write:

```
#if (UNITY_EDITOR && !UNITY_ANDROID)
// your code
#endif

```

it means the platform should be Unity editor and also shouldn't be android to let this code work. So you platform is not both of them. So it doesnt work.

If you only want it not to work on Android just write:

```
#if !UNITY_ANDROID
// your code
#endif

```

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if
> 4 votes

---
Tags: unity, android
---


# Question
Title: Unity List script field with +/- buttons in editor
I am using Unity 2018.4.11f1 LTS. I have a script with a public `List<GameObject>` field.

In the property inspector, Unity provides a UI to this field where you specify the size of the list and then assign elements:

```
public List<GameObject> receivers;

```

My question is: Is there a way (perhaps a different field type) to have Unity provide an editor UI that consists of a +/- button where you can add and remove elements, rather than a list-size-based UI?

Something more along the lines of e.g. what it gives you for `UnityEvent`s:

# Answer
> 2 votes
you can use NaughtyAttributes

> NaughtyAttributes is an extension for the Unity Inspector.
>
> It expands the range of attributes that Unity provides so that you can create powerful inspectors without the need of custom editors or property drawers. It also provides attributes that can be applied to non-serialized fields or functions.
>
> It is implemented by replacing the default Unity Inspector. This means that if you have any custom editors, NaughtyAttributes will not work with them. All of your custom editors and property drawers are not affected in any way.

### ReorderableList

Provides array type fields with an interface for easy reordering of elements.

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


# Question
Title: How can I find the offset rotation and position between two objects in 3D?
I have two objects in 3 dimensions, one of them (`Child`) is attached to the other one (`Parent`) using the offset between them (XYZ - position and rotation). Using the `Vector3` library, how can I find that `Child` offsets from the `Parent`?

Further explanation: let's say we have the parent at position `X:0 Y:0 Z:0 with rotations RX:0 RY:0 RZ:0`, and there is an attached Child to it with the offset `X:10 Y:10 Z:10, RX:90 RY:45 RZ:90` (which is what I want to know). Supposedly, I had the Parent with a different position and rotation, how can I get the offset between it and the Child (which in this case, it should be `X:10 Y:10 Z:10, RX:90 RY:45 RZ:90`) (in another word, I want the `Child` position and rotation as the `Parent` is the center of the map)

I've tried simple math and some other ways on the internet but with no success, since I'm pretty bad at calculating rotations (since vector3 libraries are pretty identical, so as Math libraries, any language should be fine).

# Answer
To get the local position, rotation you can decompose the local matrix of the child object. You can calculate the local matrix by multiplying the inverse global matrix of the parent with the global matrix of the child. Like this (example with glm)

`Matrix4 invParentMatrix = glm::inverse(GetParent()->GetGlobalMatrix());
 LocalChildMatrix = invParentMatrix * GlobalChildMatrix;`

You can also calculate the local position seperatly by using the same inverse parent matrix. Calculating the local rotation is a bit more work and also depends on your implementation.

`Matrix4 invParentMatrix = glm::inverse(GetParent()->GetGlobalMatrix());
 LocalChildPosition = invParentMatrix * glm::vec4(GlobalChildPosition, 1.f);`
> 1 votes

# Answer
```
Transform  A , B;

Vector3 avg_transform_up = (A.up + B.up)/2f;
Vector3 avg_position = (A.position + B.position)/2f;

transform.position = avg_position ;
transform.up = avg_transform_up;

```
> -2 votes

---
Tags: mathematics, rotation, transformation
---


# Question
Title: How do I change the level of my game by changing the file loaded?
I am making this 2d canvas game in JavaScript and I want to switch to file `level2/level2.html` when the boss of level 1 (`level1/level1.html`) is dead. This way I can have my stuff organized better.

This is the condition statement where I want to put the file change.

```
if(e.bosshealth <= 0){
  enemies = [];
  alert("LEVEL 1 COMPLETED");
  // I want the file switch to be here if possible.
}

```

# Answer
> 1 votes
You can navigate to another URL by setting the variable `window.location.href = url` or with the function `window.location.replace(url)`.

The difference between the two methods is how the browser's back-button will behave. The first one will generate a separate navigation history entry for each level while the second one will not.

**But**, you should consider if making each level an own HTML document is really a good architecture. It will cause a variety of problems:

* Technical complications with passing data between two levels.
* Long loading times on level changes, because the whole game needs to be reloaded from the server.
* It makes development more tedious, because when you change something, you might have to make the change to the files of every single level.
* Each level having its own URL will allow players to bypass your level navigation by sharing the URLs to later levels

For these reasons, you should look into ways to create your game as a single-page application. When the player completed a level, load the data for the next level and switch out the level without leaving the application.

---
Tags: javascript, html-canvas
---


title: Velocity and drag in unity

text:
# Question
Title: Velocity and drag in unity
So I have an object that is bouncing around the screen randomly, physics still works on it so it will speed up or slow down depending on what it hit and when. To try to normalize the speed I want to apply force or drag when ever it goes above or below the thresh hold. My question is, do I need to make note of the direction the object is moving to add force? Or can I just add force to the way it is currently traveling?

# Answer
Forces are directional, so if you want to decelerate an object by using `rigidbody.AddForce`, you need to do that with a force vector which goes in the opposite direction of the current velocity. The easiest way to obtain such a vector is by multiplying `rigidbody.velocity` with a negative value. For example, if you want to add a deceleration force which reduces the speed by 10% per second, you would do:

```
rigidbody.AddForce(rigidbody.velocity * -0.1);

```

`rigidbody.drag`, on the other hand, is a scalar value. When you increase the drag value, you increase it in any direction.

If you want to prevent an object from comming to rest, then you could always add a force which accelerates it into its current movement direction. I would recommend you to do that by taking the `normalized` property of the velocity. This gives you a vector which points in the same direction as the current velocity, but with a length of exactly 1 unit. If you always want to permanently accelerate the rigidbody with a constant force in its current movement direction:

```
 rigidbody.AddForce(rigidbody.velocity.normalized * 0.1)

```

But this does need a minimum velocity to work with. If the object is perfectly at rest (`rigidbody.velocity == Vector3.zero`) then it will stay there until something gives it a little nudge.
> 1 votes

---
Tags: unity, c#, physics, game-design
---


# Question
Title: How to get reference to board tile object another game object is sitting on?
I am trying to get reference of the object underneath my Player.

I don't know if I am approaching this correctly. Right now, I have a player simply put in the scene, like this:

Then I am trying to get reference of it like this (does not work)

```
public void CheckTileUnder()
{
    Vector3 halfExtents = new Vector3(0f, -1 / 2.0f, 0f);
    Collider[] colliders = Physics.OverlapBox(transform.position, halfExtents);

    foreach (Collider item in colliders)
    {
        Tile tile = item.GetComponent<Tile>();
        if (tile != null)
        {
            RaycastHit hit;

            if (Physics.Raycast(tile.transform.position, Vector3.down, out hit, 1))
            {
                currentTile = tile;
            }
        }
    }
}

```

Another approach that I thought of would be to put the player under the Tile like this: Then I guess I would have to change parents like suggested in one of the answers here?

How should I select the Tile under the Player?

# Answer
> 0 votes
It depends on how your game works. Both of your leads are correct if you just need to know what tile is under the player. Between the two, again depending on your type of game and gameplay, I'd use the one using a Raycast.

---

**TL;DR:** if you organize your grid objects in a linear way (from first to last) you could easily find the cell your player is on with a simple calculus.

However, on a grid based game, there is something less consuming than a Raycast based system or a hierarchy swap system. You could simply use Maths :) if you know the size of your grid cells, the origin of your grid, and the world position of your player... then it'd be easy to know what tile your Player is on.

Let's say that your grid is a width 5 and height 6 grid of 2 units cells. Your player is on, let's say, x: 1.2 and y:3.5. The origin (bottom left) of your grid is on 0,0.

```
cell_x = player_x / cell_size = 1.2 / 2 = 0.12 = 0
cell_y = player_y / cell_size = 4.5 / 2 = 2.25 = 2

```

In this example your player is on cell x 0 and y 2. So now... "I know the cell coordinate, but I still do have the reference of it". Now let's say you have a GameObject named grid that contains all the cell GameObject as child. The first one would be cell id 0, the second one would be id 1, ... and the last one would be id width * height - 1, in our case id 29 (5 * 6 - 1).

How to convert a x,y cell position into and id? That's pretty simple: `id = y * width + x`. In our example above, position x 0 and y 2 would give us `id = y * width + x = 2 * 5 + 0 = 10`.

To get your GameObject reference, you can get the cell child you want on your grid GameObject by: `GameObject cell = grid.transform.GetChild(id).gameObject;`. Et voila.

---
Tags: unity, c#, collision-detection, collider
---


# Question
Title: Unity app crashes when using unmodified custom Android manifest (didn't find class "UnityPlayerActivity")
*Note: I find/replaced my actual company name with 'companyname' below for anonymity, it's not the actual package name I am using.*

I have Unity 2018.4.11f1 LTS and the platform I'm having issues with is a Google Glass Enterprise Edition 2 running Android 8.1.0.

I'm new to both Unity and Android programming. My goal is to add some extra category specifiers to AppManifest.xml. As I understand it, to modify the manifest, I need to take Unity's generated manifest, copy it to my project to use as a starting point, then modify it.

However, when I perform the following steps:

1. Export the project from Unity.
2. Take the generated manifest (*src/main/AppManifest.xml*) and copy it into my project (*Assets/Plugins/Android/AppManifest.xml*).
3. Build and run the project **without modifying the manifest file** just as a test.

... the app crashes immediately, with the following showing up in logcat:

```
10-28 18:09:31.612: D/AndroidRuntime(2560): --------- beginning of crash
10-28 18:09:31.613: E/AndroidRuntime(2560): FATAL EXCEPTION: main
10-28 18:09:31.613: E/AndroidRuntime(2560): Process: com.companyname.glass.screen, PID: 2560
10-28 18:09:31.613: E/AndroidRuntime(2560): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.companyname.glass.screen/com.companyname.glass.screen.UnityPlayerActivity}: java.lang.ClassNotFoundException: Didn't find class "com.companyname.glass.screen.UnityPlayerActivity" on path: DexPathList[[zip file "/data/app/com.companyname.glass.screen-hmosf9MV2zscOjvPt7Az6A==/base.apk"],nativeLibraryDirectories=[/data/app/com.companyname.glass.screen-hmosf9MV2zscOjvPt7Az6A==/lib/arm, /data/app/com.companyname.glass.screen-hmosf9MV2zscOjvPt7Az6A==/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib]]
10-28 18:09:31.613: E/AndroidRuntime(2560):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2682)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2859)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at android.app.ActivityThread.-wrap11(Unknown Source:0)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1592)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at android.os.Handler.dispatchMessage(Handler.java:106)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at android.os.Looper.loop(Looper.java:164)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at android.app.ActivityThread.main(ActivityThread.java:6518)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at java.lang.reflect.Method.invoke(Native Method)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
10-28 18:09:31.613: E/AndroidRuntime(2560): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.companyname.glass.screen.UnityPlayerActivity" on path: DexPathList[[zip file "/data/app/com.companyname.glass.screen-hmosf9MV2zscOjvPt7Az6A==/base.apk"],nativeLibraryDirectories=[/data/app/com.companyname.glass.screen-hmosf9MV2zscOjvPt7Az6A==/lib/arm, /data/app/com.companyname.glass.screen-hmosf9MV2zscOjvPt7Az6A==/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib]]
10-28 18:09:31.613: E/AndroidRuntime(2560):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at android.app.Instrumentation.newActivity(Instrumentation.java:1175)
10-28 18:09:31.613: E/AndroidRuntime(2560):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2672)
10-28 18:09:31.613: E/AndroidRuntime(2560):     ... 9 more
10-28 18:09:31.619: W/ActivityManager(1203):   Force finishing activity com.companyname.glass.screen/.UnityPlayerActivity

```

Where the primary error is:

> java.lang.ClassNotFoundException: Didn't find class "com.companyname.glass.screen.UnityPlayerActivity"

Normally the app runs fine. I don't understand what is happening, because this is the exact unmodified manifest that Unity generates, no changes. But when I put it in my project, the app crashes.

Here's the manifest that Unity generates, which is the one I'm using:

```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.companyname.glass.screen" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application android:theme="@style/UnityThemeSelector" android:icon="@mipmap/app_icon" android:label="@string/app_name">
    <activity android:label="@string/app_name" android:screenOrientation="landscape" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:hardwareAccelerated="false" android:name="com.companyname.glass.screen.UnityPlayerActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>
    <meta-data android:name="unity.build-id" android:value="5bffbf6f-0a59-4843-8b47-d3b5ac51b8dd" />
    <meta-data android:name="unity.splash-mode" android:value="0" />
    <meta-data android:name="unity.splash-enable" android:value="True" />
  </application>
  <uses-feature android:glEsVersion="0x00020000" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>

```

My question is: Why is this happening and how do I make it not happen so that I can add the `<category/>` element I need to add?

---

Update: So I just took a look inside the generated APK file, and I see that it *does* include a class named *com.unity3d.player.UnityPlayerActivity*. I am not sure why it's looking for *UnityPlayerActivity* in my app's package instead of *com.unity3d.player*.

---

Ok, I got it working, I manually changed `android:name` in the `application` element from *com.companyname.glass.screen.UnityPlayerActivity* to *com.unity3d.player.UnityPlayerActivity*. But I'm not going to attempt to post a self-answer because I have no idea why I had to do that or if that was the "proper" solution. Will accept any reasonable explanation of this. (I arrived at this conclusion by comparing the manifests from the APKs both with and without my custom manifest; I do not understand why Unity filled in an incorrect application class name with "Export" vs "Build and Run").

# Answer
I do not think you can have a id of `'com.companyname.glass.screen'`

try replacing that to `'com.companyname.glassscreen'` and see if that compiles.

make sure you changed that part in the manifest

`package="com.companyname.glassscreen"` and matched to the same name in **File\>BuildSettings\>PlayerSettings\>**

then in inspector it will be package name there by Identification

the main thing is that they all match one way or another.
> 0 votes

---
Tags: unity, android
---


# Question
Title: Unassigned reference exception when proceeding from scene to scene
So, I have built a script in unity in c# called parralax. It basically parallaxes two backgrounds and looks like this:-

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Parralax : MonoBehaviour {

    public float startPos;
    public GameObject cam;
    public float parallaxEffect;

    public float length;
    public GameObject player;
    public float playerStartPos;
    public float maxDisplacement;
    void Start () {
        maxDisplacement = 0f;
        playerStartPos = player.transform.position.x;
        startPos = transform.position.x;
        cam = GameObject.Find ("Main Camera");
        length = GetComponent <SpriteRenderer> ().bounds.size.x;
    }

    void Update () {

        float dist = cam.transform.position.x * parallaxEffect;
        transform.position = new Vector2 (startPos + dist, transform.position.y);

    }
}

```

If I put it in respective background and assign a value to it, it works fine and runs smoothly. But, if I play the game scene-wise i.e. 1st scene to 2nd scene to 3rd scene; it crashes and says:-

```
Unassigned reference exception:- You need to set variable cam in inspector

```

Even though, it runs on the same scene, it doesn't run after I play it scene- wise. Please help!

# Answer
# When you change scenes, the camera gets destroyed

Because the camera gets destroyed (and the new scene has a new one) your `cam` variable no longer points to the main camera. You can detect this and do the appropriate thing,

```
void Update () {
    if(cam == null) cam = Camera.main
    float dist = cam.transform.position.x * parallaxEffect;
    transform.position = new Vector2 (startPos + dist, transform.position.y);
}

```
> 2 votes

# Answer
Like it says. "You need to set variable cam in inspector".

To do this:

1. In Hierarchy panel right and click choose "Create Empty" to add a new Game Object and rename it as ParralaxController (you can give any name you want).
2. In Inspector panel press `Add Component` and type Parralax then choose the Parralax script below.
3. When this ParralaxController is selected drag your "Main Camera" and drop it to the area of `Cam` in Inspector Panel.

Alternatively define your camera object like this:

```
public Camera cam;

```

and in Start Method write this.

```
cam = Camera.main;

```
> 1 votes

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


# Question
Title: Avoid players getting stuck by placing items in the same place
Let's assume a multiplayer game of two players. These two players have to place six elements at six different positions. The order or exact place does not matter. As the items are placed correctly, they cannot be replaced anymore.

Issue: Both place an item at the same position and now there are basically two items at a position where only one should be. This makes the task impossible to complete, as one item is missing now for the last position.

My assumption is that while both are really doing that in parallel, the communication between both computers is too slow so the other player can't know there is already an item.

I encountered this issue in a game recently and I wonder how to avoid this.

The simplest solution would be that the items can be replaced when placed. But let's see it more technical: A correctly placed item cannot be replaced - so how to circumvent or how to avoid this situation?

# Answer
> 1 votes
In a typical multiplayer game, clients are not all authoritative about the outcomes of their actions. They say what they're trying to do, not what the outcome was.

This avoids the classic playground bicker in imaginary play, "I hit you!" "Nuh-uh! You missed!" - if both players are equally authoritative about the outcome, then we can't resolve who's right.

To fix this, we make one party the recognized & trusted authority. In a LAN game, this will generally be the player who first started the game session for others to join - usually denoted the "host". (To make your game code more symmetric & consistent, you can make the host server a separate process that runs on the host player's machine, and both the host player and client players run identical client logic communicating with that server process - either over the LAN or via the localhost/loopback address 127.0.0.1. This will make it easier if you decide to port it to an online multiplayer with a dedicated server in future.)

Clients tell the host/server their actions, and the host tells the clients the results of those actions. Because the events arrive at the host in some order, it can authoritatively dictate which action happened first and succeeded, or which happened second and failed.

So it might go like this:

Client 1 and client 2 simultaneously report "I try to place my carried object at point X"

Client 1's request arrives at the server first, and the server updates the game state to say there is an item at point X, and replies back to client 1 to say their action succeeded. Client 1 sees their placement animation complete normally.

Client 2's request arrives at the server second. The server checks point X, and finds there's already an item there, so it replies back to client 2 "you can't do that - it's occupied". Client 2 sees an animation where the item bounces off of the item client 1 just placed and returns to their hand, so they stay in the carrying state.

Over a LAN, the latencies of these messages will be very short, so you might not need any complicated lag compensation algorithms or fancy animations to cover the delay between action and result, or the cases where the server has to invalidate an action the client thought they could do. As long as your placement action takes more than one frame, you should have time to get an authoritative response back and decide whether to complete the action or interrupt it and roll it back.

---
Tags: unity, multiplayer, synchronization
---


# Question
Title: Problems putting my game in fullscreen on GameMaker
All the rooms in my game have the size of 1280x720, so normally my game runs like this:

When I try to enable fullscreen, none of the game's buttons respond to clicks, but the keyboard still works. So in the initial menu I clicked on the button to go to the settings room (**image 1**) and nothing happened, but when I typed "c" on my keyboard went to the settings room:

**OBS** \- There is a distortion, but not the view in that image (I had to convert **image 3 to jpg**, because in png it was over 2MB in size).

I've thought about switching to **1920x1080** and hiding the **title bar**, but I'd really like to do things the "right way".

---

**EDIT 1** \- Another way to enable full screen. (It also does not work)

```
create event:

window_set_fullscreen(true);
```

**EDIT 2** \- By doing a few tests I noticed that when it is in full screen, the clicks behave as if it had a ghost room at the top left of the screen. Like this:

That is, I click the right side of the word music (in blue) and the language changes.

**OBS** \- The buttons in my game are mostly sprites that I mapped and added a **global left pressed** event.

# Answer
> 0 votes
**The way to detect mouse click was as follows (Global Left Pressed):**

```
if(point_in_rectangle(window_mouse_get_x(),window_mouse_get_y(),1250,690,1280,720)){
    game_end();
}

```

That way it just happened to have a "ghost room" (as I said in the question).

**Just change the click logic to the following (Global Left Pressed):**

```
if(mouse_x>=1250 && mouse_x<=1280 && mouse_y>=690 && mouse_y<=720){
    game_end();
}

```

The problem was exactly how to get the values of **X** and **Y**. Because if you use the function `point_in_rectangle` and use `mouse_x`/`mouse_y` instead of `window_mouse_get_x`/`window_mouse_get_y`, it works as expected.

**Se below (Global Left Pressed):**

```
if(point_in_rectangle(mouse_x,mouse_y,1250,690,1280,720)){
    game_end();
}

```

# Answer
> 0 votes
You are using the **global left press event**, which as far as I know does not work in the manner you desire (screen resizing). Use the non-global version.

If that fails then implement your own click detection code and also contact the creators of Game Maker (shoot them an email) because that should be working and did work with rescaling as of version 8.1 which is only 7 years old. There’s no reason for the event functionality to have changed. That’s bedrock level stuff. Change that on purpose and thousands of games will be reporting bugs so I’d certainly expect the non global to work in your case.

---
Tags: game-maker, fullscreen
---


# Question
Title: problem changing texture from one to another
I have a problem that, when exceeding the maximum or minimum texture in the matrix, is giving this error, what can I do?

**IndexOutOfRangeException: Array index is out of range.**

```
    public void previous(){
    currentTexture--;
    shouldChange = false;
}

public void next()
{
    currentTexture++;
    shouldChange = true;
}

void Update()
{
    if (texture.Length == 2)
        return;
    if (texture.Length == 0)
        return;
        {
            for (int i = 0; i < arrays.Length; i++)
                arrays[i].material.mainTexture = texture[currentTexture];
        }

```

# Answer
An `IndexOutOfRange` exception is an exception that is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds (index \< 0 or \>= length of the array)

You need to make sure your `currentTexture` does not go outside those bounds. Here is a solution to make the `currentTexture` loop (of value was supposed to go below 0, it will take the value `length - 1`, if the value was supposed to go over `length - 1`, it will have a value of `0`)

```
public void previous()
{
    currentTexture = (currentTexture + texture.Length - 1) % texture.Length;
    shouldChange = false;
    SetTexture();
}

public void next()
{
    currentTexture = (currentTexture + 1) % texture.Length;
    shouldChange = true;
    SetTexture();
}

private void SetTexture()
{
    if (texture.Length == 2 || texture.Length == 0)
        return;
    for (int i = 0; i < arrays.Length; i++)
        arrays[i].material.mainTexture = texture[currentTexture];
}

/*
// Remove this unnecessary Update
void Update()
{
    if (texture.Length == 2)
        return;
    if (texture.Length == 0)
        return;

    for (int i = 0; i < arrays.Length; i++)
        arrays[i].material.mainTexture = texture[currentTexture];
}
*/

```
> 1 votes

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