# Question
Title: Unity PlayMode Tests - Lifecycle Events don't fire when running 21 or more tests together
I'm experiencing an issue with my PlayMode tests, where all tests pass individually, but when running 21 or more tests together (using Run Selected or Run All), the same 2 tests fail. From further investigation, it appears that the MonoBehaviour lifecycle events aren't firing when running all of the tests - when I run the tests individually, they fire as expected.

**Failing Tests**

**Tests passing when run individually**

These two tests are the only ones that depend on the `OnEnable()` lifecycle event being triggered. Here is the first test, `GivenCursorHasState_WhenEnabled_ThenTheCursorPositionShouldBeRestoredFromState()`

```
[UnityTest]
public IEnumerator GivenCursorHasState_WhenEnabled_ThenTheCursorPositionShouldBeRestoredFromState()
{
    // Disable the component, expect OnDisable() to fire
    selection.enabled = false;
    yield return null;

    var state = new CursorState { cursorPosition = 5 };
    StateCache.Store(cursor, state);

    // Enable the component, expect OnEnable() to fire
    selection.enabled = true;
    yield return null;

    var expectedItem = menuItems[5];
    var actualItem = selection.GetCurrentItem();

    // The next line is where the failure is triggered
    Assert.AreEqual(expectedItem, actualItem);
    Assert.AreEqual(expectedItem.transform.position.y, cursor.transform.position.y);
    Assert.AreNotEqual(expectedItem.transform.position.x, cursor.transform.position.x);
    Assert.AreEqual(originalCursorPositionX, cursor.transform.position.x);
}

```

This is the components, `OnEnable()` method:

```
void OnEnable()
{
    var state = StateCache.Get<CursorState>(gameObject);

    if (state == null)
    {
        SelectFirstEnabledItem();
    }
    else
    {
        // We might be retaining a position already in state
        cursorPosition = state.cursorPosition;

        UpdateCursorPosition();
    }
}

```

I'm setting up the test with the following method:

```
[SetUp]
public void Setup()
{
    var prefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Prefabs/UI/Menu.prefab");
    var menu = GameObject.Instantiate<GameObject>(prefab);
    selection = menu.GetComponentInChildren<MenuItemSelection>();

    menuItems = selection.menuItems;
    cursor = selection.gameObject;
    originalCursorPositionX = cursor.transform.position.x;
}

```

I've checked the `StateCache` between steps, and that appears to be working as expected - as in there is no pollution between tests with it being a static class.

I'm hoping I'm just misunderstanding something about how the tests and/or lifecycle events work here. Any guidance is appreciated!

# Answer
> 1 votes
In the end, I reworked this solution. Instead of using a static `StateCache` instance with static data that was clearly bleeding through my tests when run in batch, I made use of dependency injection. The framework I used for this was Zenject.

In my game code, I now setup my `StateCache` as a singleton dependency, but within the context of my tests, I change this to a transient instance. This allows my tests to be completely isolated, and therefore no state bleeding occurs between tests.

---
Tags: unity, testing, unit-testing
---


# Question
Title: Find a encircliement in Hexagonal grid (optimization issue)
I have a hex grid of 10000 cells (100x100). The player can grab a cell next to one of his cells (borders). If the player has formed a ring after placing a cell, I want to get a list of cells that ended up in the encircliment. This is what it looks like before creating the enсircliment

**The player clicked, and got the cells that were in the ring**

**It could also look something like this:**

```
var visited = new HashSet<int>();
    var queue = new Queue<int>();
    //6 Starting squares (the player clicks on a cell, we get the neighbors of that cell and count them as starting cell)
    foreach (var tile in startingTiles)
    {
        //If we found the end of the grid, we did not find the encircliment
        if (tgs.CellIsBorder(tile))
        {
            continue;
        }

        visited.Clear();
        queue.Clear();

        visited.Add(tile);
        queue.Enqueue(tile);
        bool failed = false;

        while (queue.Count > 0)
        {
            var currentTile = queue.Dequeue();

            if (tgs.CellIsBorder(currentTile))
            {
                failed = true;
                break;
            }

            //List of cells that the player owns + visited cells
            var skipCells = player.myCells.Select(x => x.Index).Concat(visited);

            //We get a list of cells to go through further in the search
            var iterate = tgs.CellGetNeighbours(currentTile).Select(x => x.index)
                .Except(skipCells);

            //add cells to check further
            foreach (var neighbor in iterate)
            {
                visited.Add(neighbor);
                queue.Enqueue(neighbor);

            }
        }

        //WE FOUND A ENCIRCLEMENT!
        if (failed == false)
        {
            result = GetCellModelFromIndexes(visited);
        }

```

Of course I have code that works, but only on small grids. If the grid is 10,000, there is already a noticeable delay. Can anyone suggest a more suitable algorithm, or a code fix?

# Answer
# 1. Optimize Needlessly Slow Operations

Your basic approach should work well on small to medium maps, it's just that the way you've chosen to implement it is unnecessarily slow:

* You search the same regions multiple times. If neighbour #1, 2 and 3 are all connected to the outside, you search the outside of the map *three times* when you already knew the right answer from neighbour 1's visited set.

Start at an adjacent tile of your own territory, then walk the neighbours in order until you come to another player's territory. Search there. Then walk until you find the next tile of your own territory, skipping any others (since you know they border the same set). Check if the next other-player tile after that is already in the visited set before starting a new search. This simple optimization should cut the search time down by half or better.
* You're using LINQ expressions like `player.myCells.Select(x => x.Index).Concat(visited)`. This is great for compact, expressive, readable code, but you pay a cost in performance.

Consider having a read-only array of tile offsets. Then this code could look something like:

```
for (int i = 0; i < 6; i++) {
    int neighbourIndex = currentTile + NeighbourOffests[i];
    if (playerOwner[neighbourIndex] != thisPlayer
        && !visited.Contains(neighbourIndex)) {

        queue.Add(neighbourIndex);
        visited.Add(neighbourIndex);
    }
}

```

It's a little more verbose, but it's dead simple to execute.
* You're re-creating your data structures every time you call this function. Since this is something your game needs to do frequently, create your data structures once, and re-use them.

C#'s `System.Collections` types get created with a small capacity at first, and gradually re-allocate to larger and larger sizes as you fill them up. If you're creating new ones all the time, you're paying that memory re-allocation cost on every tile placement. But if you re-use them, you pay the "warm-up" cost once, and then continue benefitting from it for free.

This is also why, if you have a good idea of how many items you'll need to store in the collection (and that number is big), it's a good idea to pass in that initial capacity to their constructor so they can pre-size themselves appropriately, rather than working up to it over several re-allocations as the collection grows.
* You're using a `HashSet` for what could be a visited flag on each cell in an array. Yes, they're both \\$O(1)\\$, but looking up this information in a `HashSet` requires hashing the key and pseudo-random memory access, so it will be noticeably slower. `HashSet` structures are good for when the space of all possible set members is too big to reasonably allocate memory for all of them in an array, but here it's just your map size, so simpler options are available.

In particular, *iterating* the keys of a hashmap is slow, which is what `Concat(visited)` has to do.
* You're using breadth-first search. This explores cells in order of their distance from the starting point, meaning if your new tile is in the middle of the map, you'll explore an expanding ring out to 50 tiles in all directions (about 7 850 tiles), instead of walking the 50 tiles to the nearest edge. This could be a good use case for depth-first search, or possibly even A\* with a heuristic to seek toward the closest edge of the map.

A quick hacky version of that would be to use depth-first search with an array of neighbour offsets as suggested above, but select which neighbour offset array to use based on the position of your starting tile. You can have 6 different orderings of the neighbours, one trying each cardinal direction first. So choosing the down-prioritized neighbour set when your starting tile is close to the bottom of the map might get you similar behaviour to A\*'s heuristic-seeking, but with lower code complexity.

---

# 2. Algorithmic Efficiencies

I'd recommend trying the simple fixes in suggestion 1. first, and profiling to see if that's enough to make the cases you care about fast. But if you need to scale up to truly massive (or even infinite) maps, a flood fill looking for the edge won't suffice and we'll need a strategy that keeps the iteration more tightly bounded. Here's a sketch of one such strategy...

You can recognize whether a move closes a ring by looking at the pattern of 6 neighbours immediately surrounding the clicked tile:

1. It must have at least two neighbours that are the player's own territory.
2. It must have at least two neighbours of other players' territory.
3. These territory bands must alternate: reading around the hex, it has to go `mine -> other -> mine - other` or `mine -> other -> mine -> other -> mine -> other` (counting contiguous runs of neighbours of the same territory as just one word in the sequence).
4. Two of these "mine" territories on either side of an "other" must be from the same connected shape. If so, the ring has successfully cut off this "other" from the rest.

You can determine 4 very quickly (amortized to nearly-constant time) using a disjoint set data structure, as I explain here in the context of determining connectivity in road networks.

Once you know that a ring has been closed, you need to access all the cells inside the ring to change their colours. The trouble is, the method above doesn't tell us which side is "inside".

Instead of doing a flood fill to check (taking time proportional to the area - \\$O(n^2)\\$), we can walk the border of the shape (proportional to the perimeter - \\$O(n)\\$). I explain a method here to walk along territory borders of a hex grid. For each `other` in the list above, start a perimeter walk from an edge between that `other` and the newly-placed tile, with your "right hand" in your territory and your feet in the other.

Do a little book-keeping: each time your hand moves from one column to another, append its y position to a list for that column. Add +60 to an angle counter whenever you move your hand, and subtract 60 whenever you move your feet.

When you return to your starting point, check the winding of the path by looking at the sign of the total angle accumulated. Negative means the border you walked was the "outside", while positive means you walked the "inside" of the loop.

Either way, your list of y-coordinates where you entered and exited each column now give you a collection of contiguous spans of `mine` territory. You can iterate over them in a tight loop updating their ownership (and disjoint set) data. You can either do this once for the "outside" border, at the cost of redundantly re-visiting parts of your territory far from the new loop, or for each "inside" border (of which there could be up to two, if the new tile pinched was placed at the junction of a Y shape of `other` territory, breaking it into three disconnected branches, only one of which still connects to the outside).

This is algorithmically a bit more complicated, but saves you from ever flood-filling the whole map, so it can scale to arbitrarily large maps with cost that stays bounded to the perimeter of the largest/most convoluted contiguous shapes.
> 6 votes

---
Tags: unity, c#, algorithm, grid, hexagonal-grid
---


# Question
Title: Why does the "ColorRect" created in code not display?
When I try to create a "ColorRect" in code, it doesn't display. It still seems to exist, but I can't see it.

I am expecting to see both the rect created in the editor at `x=32 y=32` and the one created in GDScript at `x=128 y=32`, but I can only see the one created in the editor, as shown in the following picture:

I am using version 3.5.2 of Godot.

# Answer
Answered by Reddit

The default size when created in code is `Vector2(0,0)` instead of `Vector2(40,40)`.
This issue is fixed by giving the Rect a size.
> 0 votes

---
Tags: gdscript, godot-3
---


# Question
Title: How do I prevent memory-modification cheats?
There are many memory-altering programs out there nowadays (*Cheat Engine* & co). Is there an efficient way to keep a constant variable *actually* constant?

I had two ideas:

1. Make a separate thread updating the constant variable to a constant value, e.g. 200 every minute. Problem: One can also alter the second value.
2. Store the value on the server. Problem: I want to keep the network traffic as low as possible.

I need this mechanism for both constants and variables only allowed to contain a certain range of values.

Are there better ways to do this?

# Answer
**If your game is singleplayer:** it's not possible, but *you shouldn't care*.

**If your game is multiplayer:** then you should store all your important state on the server, which is much harder to hack than a local machine.
> 22 votes

# Answer
**It can't be done**, https://security.stackexchange.com/a/4639 is about DRM, but the same applies to anything which the user doesn't want on his computer including Anti-Cheat mechanisms. (Which has the tendency to be even harder to do than DRM.)

But why would you, really why would you? It's your customers computer, not yours, the customer does with his computer whatever he pleases to do with it. You have no rights about it. Your program is removed if the customer doesn't like it.

For multiplayer games it's not about designing the binary running on, but designing the communication. Letting the users just send *"I've won with 20000 points"* doesn't work, neither does *"I've 2000 Gold"*. You'll need to simulate the game yourself and just let the players send what they are doing like **"I ordered the soldier to move to point X/Y"** or **"I've bought Item number 43"**, not what the result of that actions are. The server decides what the results are, and who won in the end.

If it is a single player game with online high score, a option would be to have the player send you a replay, simulate it and decide the result from that.
> 14 votes

# Answer
The first is not effective and won't stop any determined person from attacking your game - and it's also error prone. However, you can make it a lot **tougher**, not **full proof**, if you would like. Some common strategies are available all over the web but as other people have mentioned - you have to ask yourself if it's worth it.

For arguments sake, here's a couple ways to prevent hacking in a single player environment:

1. Open a handle to every other process on the users machine (invasive and not portable) and over-write their WriteProcessMemory with a dummy function or warning. The choice is yours. **This can be defeated because...** *applications are free to do the same and over-write the handle once again or do things to prevent this.*
2. Checksum your application and have it verify itself through a hack shield - this is useful for many permanent edits to your application but won't stop a common memory attack. **This can be defeated because...** *tools like ADA, OllyDbg and even simple hex edits can make permanent patches and changes to your application to remove the offending code - this includes your threaded timer idea!*
3. **Scan for known hack tools.** This also can be defeated by recompiling a tool or attacking your client directly. **This can be defeated because...** *a recompile, rename of the application or change in what your scanner uses as a heuristic will render this useless. Consider using a special portion of memory an application is known to use if you opt for this.*

The alternative, of course, is to just store everything on the server and make a game server that is a master. Not only is this expensive, requires upkeep, and increases development time... fans are not so impressed from the implementation of popular games like Diablo III. Or here. I should note for an online flash RPG like Adventure Quest this model has actually been working pretty well for them, however.

I can't provide much guidance on how to implement this type of approach as it's very broad, wide and requires a lot of planning. The basis to know is that the server decides everything and the client is nothing more than a mere input and display console.
> 4 votes

# Answer
A lot of people use these programs to search for a score stored in a variable e.g

```
int score = 10;

```

to do this they need to know the score, ususaly from the score displayed in game.

I was thinking, would this help put them off...

```
public static float randomVal; // at start of level generate random float

private float 1a3sf5vhh4; //represents score

void hjgkkj4(int val) //add score method
{
   var 5vhh4 =  1a3sf5vhh4/randomVal+val;
   1a3sf5vhh4 =  5vhh4*randomVal;
}

```

then when you need to display score do...

```
string displayScore = ""+ 1a3sf5vhh4/randomVal;

```

this will make the cheaters search for what they think is the score( the score being displayed) so they will only find the displayed value.

The real score will be Score\*randomVal stored else where. They cant change the score by changing the displayed value.

would this help?

p.s I'm no expert so take it easy on me lol.
> 3 votes

# Answer
**In regards to single player games**, you can not *prevent* cheating, and you *should not*.

---

***Why can't I prevent cheating in my own game?***

As other answers have pointed out, even the best efforts could be potentially circumnavigated by a single hacker, and provided to the rest of your player base. You can still *make effort* against this, but look to other answers for suggestions *how*. This answer means to save you the trouble, if your game only aims to provide single player gameplay.

***Why should I let players cheat in a single player game?***

To quote *Sam*,

> Spend more time on creating a great game and less time on preventing morons from spoiling their own fun - simple.

This misses the point *entirely*. Games are a form of *entertainment*. Generally, your player base is playing your game to have *fun*. If a player uses cheats in your game, there is a *reason* they are using cheats. It is safe to assume that that we can not guarantee each individual player's definition of fun; if they use *cheats*, perhaps that is their way of making your game more enjoyable, to them.

***How does cheating make a game more enjoyable?***

While every individual is unique, there are a few conditions in which cheats could make a game more entertaining, off the top of my head:

* The game is a little slow, and the player wishes to use cheats to bring out the action before they are put off, completely.
* The player is unable to get past a certain challenge; they would not normally cheat, but they are close to giving up, in frustration. They can stop playing your game, or they can use a cheat to bypass the obstacle, and go on to play the second half of your game.
* The player can not devote the amount of time your game requires for the intended experience. By applying cheats, the user can get a "running start" and be able to enjoy the intended content of your game. *If you think this does not sound plausible, consider that this is the reason I have personally played very little of Fallout 4. In comparison, it is the only game I preordered in the past 5 years, and the only game I have ever preordered and purchased for more than one platform. I love the game; I don't have the time for it.*
* Your game has a *bug*, and this stops the player from progressing further. A cheat bypasses the bug, so the player can keep playing. *Recent Elder Scrolls games are notorious for this situation*.

***Why does this only apply to single player games?***

It is important to stress that this only works in *single player* games; if the player tells you they want to use cheats to have more fun in their game, no harm done. As soon as there are *multiple* players in the game, the exploits of that first player could become an unfair disadvantage to the other players. This is the only real situation where you *should not* allow cheating.
> 3 votes

# Answer
The only way to protect your game from modding and memory editing is making it **ONLINE only and processing vital values server-side**.

Maybe you can encrypt the values so that rookie memory edoits wont get to them, but all the communities, such as Cheat Engine, GameGuarian for Android, ArtMoney, Game Hacker ect have people that are going to be able to hack anything you process client-side and show the others how to do it or publish trainers.

Its is a futile effort to try and deter cheaters cleint-side in my opinion. Also not really fair, since it is their device and if they want to memory edit stuff happening on their device, why would you hinder them? The customer is king afterall.
> 1 votes

# Answer
**What does a memory hack tool do?**

There are two ways to operate the hack tool.

1. It either accepts a known address where the player's variables are stored.
2. You feed in the changes in the variable and it scans the memory for changes.

**What can you do about it?**

1. You can use dynamically allocated variables to store player variables so that the address keeps changing on startup. There won't be any fixed address which a cheat website could list.
2. Encrypt the player variables: scaling the value, adding a constant, etc. This brings a new problem: a hardcore hacker could disassemble your program and find the numbers you use for encrypting your player variables. For this, use random numbers. You can also scale up the values of your player variables and then add a random number such that the added number does not significantly alter the value (adding 10 or 20 to a scaled up value of 2000 does not make a lot of difference).

Of course, some serious hacker can still find ways to overcome these hurdles but it won't be easy.

```
  std::default_random_engine myRNG;
  std::uniform_int_distribution<int> myDist_padding(10,100);
  class Player
  {
      public:
          Player()
          {
              Health = new float;
              Armor = new float;

              std::uniform_int_distribution<int> myDist_scale(1000,10000);
              scale = myDist_scale(myRNG);
          }
          float GetPlayerHealth() const;
          void SetPlayerHealth(float health);
      private:
          float *Health;
          float *Armor;
          int scale, constant;
  }

  //wrappers for Set/GetPlayerHealth
  void Player::SetPlayerHealth(float health)
  {
      this->Health = health * scale + constant + myDist_padding(myRNG);     //random padding; adding 10 or 100 to a number that is scaled up by 1000 will cause an increase in 1%
      //1% of error is ok I guess?
  }
  int Player::GetPlayerHealth() const
  {
      return (this->Health - constant)/scale;
  }

```

While the above code solves some serious issues, it is still crackable. The only information the hacker will need is: the player variables are accessed through a pointer (he could also find out by disassembling your game but it is going to be annoying and hard). Once the hacker has the address to your player variables along with other secret random variables, it is going to be an easy task for him to develop a cheat.

In my opinion, without disasembling, you cannot really write a hack tool for such a system. The result is unpredictable as you are going to add a random number to the player variabels each time it is modified. The range in which the player variables are stored isn't the same on every startup either.

**What more can you do?**

Keep changing the address of the player variables occasionally. Does it hamper the readablity of the code? Well, it does to some extent but you can abstract the entire process in a single class which has well-explained comments. The interface provided by the class will have simple Set/Get functions. The frontend programmer wouldn't have to worry about the underlying complexity.
> 0 votes

# Answer
Economics:

If you want to harden your game against cheaters, the best way is to buy a software solution that does that for you. There are several providers, and you can find quite a few of them by googling for *"anti cheat breaks my game"*.

The professionals are much better at actually preventing cheats than you are, and much better at not breaking your game than you are (and still don't succeed 100%, at either of these). So if you feel there's value in putting such a solution into your game, buy it. Doing your own will be vastly more expensive.

A related question is "is there value in using anti cheat software?". The answer is: Not unless a decent part of your game relies on an online competitive mode.
> 0 votes

# Answer
While reading the responses, I had an idea:

Cheaters usually use tools like Cheat Engine, and to change a memory value they need to get the address for the value they want to edit. I've seen a video where the method to find the desired address is to look for, say, a health address. If you have 100 health, you would search for the value '100' in the memory. You'll get (probably) multiple addresses with values of '100'. Then, you try to change your health by taking damage or healing. You'll filter the addresses and search for the new value (e. g. '89'). You repeat this until you have one address. Now you can change that address and you'll change the in-game health value.

I think to prevent this, create some variables with gibberish names which get updated to the actual value every (n-th) frame. This way, if the cheater tries to seek the address, he will always have multiple options and will (probably) have to be patient to find the real address.

There are downsides to this:

* Increased RAM usage because of the extra values stored in memory
* Increased CPU usage due to the constant updates of the fake variables
* A Cheater can edit the binary to remove the fake variables
* A Cheater can find the real variable after some time

This method is just to make the cracking process "tougher". I'm not an expert so I don't know if this will help.
> 0 votes

# Answer
I mean its not that hard. You can keep 99% of the memory edit cheaters (those Game Guardian, Cheat Engine ect at bay by simple multiplying values. Even multiplying by 10 in the memory will keep most of the at bay.

I remember a lot of flash games back in the day would multiply by 8 or 6. Or if you are really serious about it, code some checks or encrypt the values in memory.
> -1 votes

# Answer
### ***The best way to do this is...***

---

Let's say you have a **score** variable, very important.

Make a duplicate variable, let's call it **scoreAntiHack**.

**scoreAntiHack** will be encrypted with your choice of encryption.

The best way to encrypt your **scoreAntiHack** is to make a **multiplyVariable**, **divisionVariable**, and **additionVarible**.

**mulitply, division, and addition variables** will be a random number generated at the beginning of the game.

Your **score** variable will be *equal* to the **scoreAntiHack** * **mulitplyVariable** / **divisionVariable** \+ **additionVariable**;

when you *update* your **Score** also *update* the **scoreAntiHack** (Unencrypted).

*Every frame check* your **score** to **scoreAntiHack**. If they don't match up, end the game.

It will be nearly impossible for someone to hack the score. It will take shear luck to find both variables and guess the encryption.
> -1 votes

# Answer
You can't - I repeat you can't. There is no answer to this question that cannot be undone by a good hacker.

But - so what? If someone wants to cheat at your game (assuming no monetary loss or achievement is involved), who cares? They only cheat themselves.

Spend more time on creating a great game and less time on preventing morons from spoiling their own fun - simple.
> -2 votes

# Answer
Encrypt the hell out of it! Store important numbers broken up in multiple locations conjoined with other values so that they will constantly change! Use dummy numbers that if altered tells them they are cheaters.

Everything can be cracked, but most wont take the time to do so.
> -3 votes

# Answer
The way I deal with it in online games is this.

I'm not going to help the hackers that much so bear with me. I will not mention any programs that I use to do this. You will have to figure that out. The only way to truly stop them is to know one thing. They do not want their hack program to be detected.

So far, all of the hacker/trainer users that I have defeated. The developer of the hack will put a detector on it to see if something is watching. If something is, then the hacker/trainer program will either close automatically on their end or it will only half work.

For instance in dirt 3, trainer users can make your car spinout automatically. But if you put up a detector on your end the cheats own detector will detect it and it will close part of the cheat. Not all of it.

The only part of the trainer program that I have seen effected from my meddling is super brakes(perfect braking) and the spinout(car losing control for no reason). I have mostly racing games as you can see. They are all from codemasters and sadly those games do get abused by cheaters quite often.

I believe that I am only able to stop them because of the way that we connect to each other while playing. It's probably the same reason that they could cause a spinout for a normal player that has no clue about security.

My biggest suggestion is to get a very good internet security antivirus(Norton, Mcafee, Avast, and all the other shitty av's will not help you). Be willing to spend $50 to $90 on a very good av that I have not listed and then learn how to experiment with it to effect online play.

It takes a lot of patience and a lot of guinea pigs. I've had a lot of success with this but also a lot of years of experience in dealing with trainer users. I don't know any code whatsoever. It has nothing to do with it. The code part, is locked down and you can't do anything about it. You could think that you can but it's just not possible to actually stop what they are doing on their end.

You can still ban them with things like VAC because Vac detects signatures and certain behaviors and modifications of files that it already knows about. It only bans the account associated with the cheat.

They don't actually stop the cheat though. They can't be bothered with it. They just ban your account. The other thing that I would like to mention has to do with Wolfenstein ET. A very old game. But to me it had the best and harshest security measure of all.

I never got to see how they did it. I did give them the idea on what would actually stop cheaters and suggested to one of the jaymod devolopers to ban by way of guid. What has an easily accesible guid when playing games? Graphics cards. The reason they implemented that is because people would just change ip addresses and you didn't need an account for the game so you could just change your name, your mac address which would also change your ip address.

But when they did the graphics card bans. If you wanted to play again you had to RMA your card or buy a new one. That's off the subject though. This is supposed to be about detection and I went off on a tangent. Sadly I don't play games nearly as much now. But man I loved all my gunea pigs. Especially the ones from project cars. The only racing game that was not codemasters. But still effected by the same nonsense.
> -4 votes

---
Tags: anti-cheat
---


# Question
Title: ScrollView in editor window never reaches the bottommost items
```
string searchString;

void OnGUI()
{
    int counter = 0;
    GUI.color = Color.white;
    GUILayout.Space(30);
    GUILayout.FlexibleSpace();
    searchString = GUILayout.TextField(searchString, GUI.skin.FindStyle("ToolbarSeachTextField"));
    if (GUILayout.Button("", GUI.skin.FindStyle("ToolbarSeachCancelButton")))
    {
        searchString = "";
        GUI.FocusControl(null);
    }

    GUILayout.Space(25);

    scrollPos =
        EditorGUILayout.BeginScrollView(scrollPos, false, true,
        GUILayout.ExpandWidth(true), GUILayout.Height(position.height));

    foreach (GameObjectAndScriptName item in gameObjectAndScriptNames)
    {
        EditorGUILayout.BeginHorizontal();

        if (searchString != null)
        {
            if (item.ScriptName.Contains(searchString, StringComparison.CurrentCultureIgnoreCase))
            {
                EditorGUILayout.ObjectField(counter.ToString(), item.GameObject, typeof(GameObject), true);
                counter++;
                foreach (UnityEngine.Transform g in item.GameObject.transform.GetComponentsInChildren<UnityEngine.Transform>())
                {

                }

                num.Add(EditorGUILayout.TextField(item.ScriptName).Length);
            }
        }
        else
        {
            EditorGUILayout.ObjectField(counter.ToString(), item.GameObject, typeof(GameObject), true);

            num.Add(EditorGUILayout.TextField(item.ScriptName).Length);
            if (counter != gameObjectAndScriptNames.Count)
            {
                counter++;
            }
        }

        EditorGUILayout.EndHorizontal();
    }

    GUILayout.EndScrollView();
}

```

The result when I scroll down is there are still items below the bottom of the scroll range.

The farthest I can scroll down is to item 49, and I see half of item 50, but there are 55 items. Why is it not scrolling to the very bottom?

# Answer
what is working for me is to remove this part:

```
GUILayout.Height(position.height)

```

from the line:

```
scrollPos =
            EditorGUILayout.BeginScrollView(scrollPos, false, true,
            GUILayout.ExpandWidth(true), GUILayout.Height(position.height));

```
> 0 votes

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


title: Pyglet.gl has no attribute glTranslatef

text:
# Question
Title: Pyglet.gl has no attribute glTranslatef
I have just started working with pyglet trying to make a simple game as a hobby. However, I have run into an issue. I am working with this demo:

https://github.com/pyglet/pyglet/blob/pyglet-1.5-maintenance/examples/window/camera.py

and I am getting the error:

`AttributeError: module 'pyglet.gl' has no attribute 'glTranslatef'`.

I was wondering if anyone might have some ideas as why this might happen. I have installed pyglet using `pip install pyglet` and I am running on a MacBook if that matters.

Thank you

# Answer
I am not familiar with `pyglet`, but the latest published version is 2.0.6 (found on PyPI) and you are using an example from version 1.5. So, it is likely that the library has made some changes to what things are called.

You should use an example from the version you installed, instead.
> 1 votes

---
Tags: python, pyglet
---


# Question
Title: How to create a ScriptableRenderPass that renders normally, with lighting?
**What I'm trying to do:** Render GameObject(s) of a specific Layer in my custom pass. I want to do something more later, but I'm just trying to get it to render exactly as URP would for now.

I'm just learning about ScriptableRenderPass/ScriptableRendererFeature, and so I'm starting basic.

Here's what I want:

Here's what I'm getting:

This is what my pass's Execute looks like:

```
    public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
    {
        CommandBuffer cmd = CommandBufferPool.Get("EnemyClearDepthPass"); // Take this outside if you don't need this to change at all.

        foreach (var renderer in _associatedObjects)
        {
            if (renderer.isVisible)
            {
                cmd.DrawRenderer(renderer, renderer.sharedMaterial);
            }
        }

        context.ExecuteCommandBuffer(cmd);
        CommandBufferPool.Release(cmd);
    }

```

It looks like it's rotation (thus, its MVP matrix) is correct... but it has no lighting. And I don't know what the 2nd cube of darkness is about. So:

**Option #1)** Figure out what commands I need to pass to the command buffer in order to apply lighting... and fix whatever the dark square is about... and hope that's it when I start to draw much more complex shaders.

But then I had a thought:

**Option #2)** Maybe I could use ScriptableRenderContext.DrawRenderers(...) in order to draw it, as I presume then it would work more "out of the box".

Here's what I get, no matter what I try to do with that approach:

(I know I could have just said nothing... but...)

To just get started on that approach, I am just trying to make a pass that draws everything. But I can get it to work. Why?

```
using System;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
public class JustDrawSomethingPls : ScriptableRendererFeature
{
    // https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@12.1/manual/containers/create-custom-renderer-feature-1.html
    class DrawEverythingPass : ScriptableRenderPass
    {
        public DrawEverythingPass() { }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cmd = CommandBufferPool.Get("DrawEverythingPass");
            // https://docs.unity3d.com/ScriptReference/Rendering.DrawingSettings.html
            DrawingSettings drawingSettings = new DrawingSettings();
            drawingSettings.mainLightIndex = 0;
                SortingSettings sortingSettings = new SortingSettings();
                sortingSettings.criteria = SortingCriteria.None;
            drawingSettings.sortingSettings = sortingSettings;
            // https://docs.unity3d.com/ScriptReference/Rendering.FilteringSettings.html
            FilteringSettings filteringSettings = new FilteringSettings();
            filteringSettings.excludeMotionVectorObjects = false;
            filteringSettings.layerMask = int.MaxValue;
            filteringSettings.renderingLayerMask = uint.MaxValue;
            filteringSettings.renderQueueRange = new RenderQueueRange(0, 5000); // The upper bound must be at least 0 and at most 5000
            filteringSettings.sortingLayerRange = new SortingLayerRange(0, Int16.MaxValue);
            // https://docs.unity3d.com/ScriptReference/Rendering.RenderStateBlock.html
            RenderStateBlock renderStateBlock = new RenderStateBlock(RenderStateMask.Everything);

            context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref filteringSettings, ref renderStateBlock);

            // Execute the command buffer
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
    }

    private DrawEverythingPass _drawEverythingPass;
    public override void Create()
    {
        _drawEverythingPass = new DrawEverythingPass();
    }
    public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
    {
        renderer.EnqueuePass(_drawEverythingPass);
    }
}

```

# Answer
While I haven't full achieved what I wanted to do via the command buffer, a big step is to not use

```
cmd.DrawRenderer(renderer, renderer.sharedMaterial);

```

as it will draw all shader passes on top of each other, but instead use specific shader pass ("**myShaderPass**"):

```
cmd.DrawRenderer(renderer, renderer.sharedMaterial, 0, myShaderPass);

```

The main problem in this post was the fact that it was drawing the shadow pass on top of everything else. Note that getting lit shaders to work is going to be more work than getting an unlit shader to work via the command buffer.
> 1 votes

---
Tags: unity, rendering, graphics, graphics-programming, unity-urp
---


# Question
Title: Variable "is not blueprint visible" in function library
I am trying to create a function that simply returns some hardcoded values so that I can use them in other functions within the function library. However, I'm getting the error:

```
GetGridMeasurements.HexHeight is not blueprint visible (BlueprintReadOnly or BlueprintReadWrite). Please fix mark up or cease accessing as this will be made an error in a future release.

```

I'm pretty new to Unreal (currently using 5.1) and don't really understand what this means. I created everything through the UI and haven't touched any C++. I realize I could just return the values without making variables but I am still wondering why this specifically doesn't work.

# Answer
The issue ended up being caused by having a local variable wired to an output parameter of the same name. Changing the output parameter name resolved the issue.
> 3 votes

---
Tags: unreal, blueprints, unreal-5
---


# Question
Title: Huge memory size with huge amount of voxels
I'm currently using a tridimensional grid for pathfinding, think of it as a huge cube with voxels (3d nodes) inside it, each voxel ita a class containing information about the voxel, if its an obstacle, its costs (for A\*) and position. The problem is, there are too much nodes, which consumes a lot of memory, if I increase it too much it like a 120x90x120 volume it consumes 1gb of ram. I know that its obvious it will be this huge because there are 1.296.000 voxels, but how could I solve it with less memory?

I'm using C# and Unity for it.

# Answer
> 4 votes
> class containing information about the voxel, its costs (for A\*) and position ...

Why do you need to store a voxels position, are they going to move? just use the array indices as the position. i.e. if you want voxel at position (3, 5, 9) then just access your voxel datastructure at index \[3\]\[5\]\[9\].

The only thing you NEED to store for each voxel is the type, i.e. is it air, water, ground etc... and if you can make do with 256 different types then we can use a byte to store the voxel type.

120 * 90 * 120 = 1,296,000 That's only 1.2 million, and if we can represent each voxel with a single byte, then it'll only be 1.3 MB, which is tiny. Don't maintain an array of 1 million classes, that's not what they're designed for. An array of bytes should do fine.

```
int width = 120; int depth = 120; int height = 90;
byte[][][] voxels = new byte[width][depth][height];

```

If you also need to store A\* information, then consider a separate data structure

```
byte[][][] voxel_costs = new byte[width][depth][height];

```

Which brings us to 2.6 MB, still tiny. Having this separation might also help enforce encapsulation, i.e. the rendering code needs to know what each voxel will look like, but it doesn't care about path finding information.

This is not the most ideal solution, as Philipp said, Unity isn't really geared towards making a minecraft clone. Any decent voxel engine is a HUGE undertaking. But it's definitely a fun project that I've considered myself numerous times, and there are plenty of resources online. A Mojang developer has posted a couple relevant blog posts you should check out http://tomcc.github.io/2014/08/31/visibility-1.html

# Answer
> 1 votes
Look into spatial subdivision and defining implicit spaces.

You do not need to specify all voxels at a time in memory. For the current location, you just generate them from a function taking that location as a parameter.

The algorithms that define how the world is generated should do the rest, as you move to a new area.

This is much like the way `y = ax^2 + bx + c` defines a parabola, even if you currently haven't plotted the points on a line that would *show* that curve. Indeed, in computational geometry, implicit surfaces are defined the same way - by some mathematical function.

# Answer
> 1 votes
A little late here, but in my case I just had to remove the unused vertices that I had, simplifying the mesh.

When inspecting the chunk meshes that I was generating through code, I realized that I had chunks with `786432` vertices `(6 * 4 * 32 * 32 * 32)`, when I really only used `20K` or so. By removing unused vertices and assigning a smaller array to the mesh instead of the original array (with `786432` vertices), I was able to reduce the RAM usage in a scene with `9x9` chunks, with `32x32x32` blocks from around `10GB` to only `120MB`.

By doing that, I also got a huge performance boost - from `50ms` long frames to potentially `0.1ms`, taking into account the profiler's rendering time metric.

---
Tags: unity, c#, 3d, path-finding
---


# Question
Title: Is it legal to use the exact same proportions as Minecraft's Steve character model in software without permission?
I am developing a game (or a game engine) that includes a low-poly human-like character model that follows the same proportions as Minecraft's Steve character model. Specifically, the model consists of 6 cuboids for the head, torso, arms, and legs.

I would like to make my character model compatible with the community skins available for Minecraft's Steve by following the same dimensions for the body parts. However, I would not use any copyrighted assets from Minecraft or Mojang Studios, and my character model would have a different default skin. The texture applied to my character model is separate. It is intended to be compatible with the skin format used in Minecraft so that players who have customized their skins in Minecraft can import and use them in my software program.

The exact proportions of the body parts of Minecraft's Steve are the following:

Head: 8 pixels x 8 pixels x 8 pixels Torso: 8 pixels x 12 pixels x 4 pixels Arms: 4 pixels x 12 pixels x 4 pixels (each arm) Legs: 4 pixels x 12 pixels x 4 pixels (each leg) The low-poly aspect is important in 3D graphics as it reduces the number of polygons needed to render a model, making it less computationally intensive, and the proportions in Minecraft's Steve character are intentionally simple to maintain this efficiency.

My software is a game (or game engine) that does not resemble Minecraft at all, I just want to use similar human-like characters. Quite possibly my game and its assets will be published as Open Source software.

My question is: Is it legal for me to use the exact same proportions as Minecraft's Steve character model for my low-poly human-like character model in order to support texture compatibility with community skins, even if I am not using any copyrighted assets from Minecraft, or Mojang Studios? Are the proportions of a low-poly human-like character model, consisting of 6 cuboids for the head, torso, arms, and legs, copyrightable?

# Answer
> 8 votes
I am not a lawyer, and you should not put too much value into the legal opinions of anonymous strangers from the Internet.

But personally, I would not risk it. While I doubt that Minecraft Steve will pass the "well-delineated character" test and the "story being told" test for copyright of fictional characters, Moyang's lawyers could probably argue that the distinct look of their characters is so well-known that they have a notoriety trademark on it. And personally I would agree. Show me a character in that exact proportions and with that exact texture resolution, and I am going to think "Minecraft". Would they win in court with that argument? Well, do you have the money and the nerves to find out? I wouldn't.

And it is not as if it would be so hard to make a simple humanoid character that does not immediately say "Minecraft". Just bevel the edges and it will look nothing like Minecraft anymore. Yes, it will increase the polygon count. But this is 2023, not 1993. Todays hardware can handle a hundred polygons per character. Yes, even low-budget phones. And if you want mass scenes with so many characters on the screen that it *does* matter, then you should use impostors.

---
Tags: models, copyright, character, intellectual-property, low-poly
---


# Question
Title: How achievable is determinism when client and server run on different hardware?
Soon I'll have to start implementing networking for a game. To be able to simulate the game on both client and server and have no deviation, **simulations need to be deterministic**.

But how can any simulation be deterministic and produce the same output, if it is run on different hardware? (which implies execution of instructions at a different pace).

Should we treat server and client state as "approximately equal" opposed to equal and not correct the client when states are a little different? I missing something and deterministic simulation is possible?

# Answer
> 2 votes
The problem with determinism in multiplayer games is not just that people use different hardware, but also that due to network latency the order in which events happen is not always the same for each player. For example, in a fast-paced shooter with high latency it is pretty common that two players will both believe that they shot the other player first.

A common solution is to have an **authoritative server**. Authoritative server means that the servers simulation of the game is always right. Clients *might* use their own simulation to extrapolate the game to provide a more fluent game experience to the player. But when it turns out that client and server disagree, then the client has to correct accordingly. That can result in phenomenons like "rubber banding": The player under fire sprints into cover and sees their character reach it. But then the game moves them back a couple meters and kills them. That's because the server says someone killed them while they were on the run, but due to latency the client didn't know it yet.

Yes, this can be frustrating for the players. But authoritative servers are really the only practical way to make a fast-paced multiplayer game fair. Because without authoritative servers, it becomes really easy to develop cheats.

---

However if your game is very slow-paced, for example a turn-based strategy game with concurrent moves, then there is another option: Using a network protocol that's based on a fixed lockstep.

1. Every player makes their move but does not yet update their simulation
2. The clients exchange each others moves (which might or might not require a server, but using a server would probably make a lot of things a lot easier)
3. When every client knows the moves of all other players, they update their simulation according to a deterministic algorithm.

Note that this algorithm must include rules for how to resolve player moves that contradict each other. For example, when two players move into the same tile, but the game rules say only one player is allowed there, then there must be a rule to resolve that tie which does not just rely on who clicked first (because that's impossible to determine). What could that rule be? That's a game design question, not a technical one.

The problem with this method is that it is slow. At least one full network roundtrip. That makes it infeasible for fast-paced action games.

---
Tags: networking, client-server, synchronization, determinism
---


# Question
Title: irregular physics using character controller
I recently made the switch to the unity built in character controller, as it better suited the needs of my project. However, after refactoring my code to work with the character controller I've noticed some irregular behaviour with my jump logic. The character seems jump and once they reach the apex they hang in the air for a few frames longer than they should, resulting in a jump that doesnt follow an arc. Here is a gif to show it in action:

Link to gif of issue

Here is how I calculate my gravity value and jump velocity:

```
 readonly float maxJumpHeight = 10.5f;
 readonly float maxJumpTime = .5f;

timeToPeak = maxJumpTime/2;
gravity = (-2 * maxJumpHeight) / Mathf.Pow(timeToPeak,2);
initialJumpVelocity = 2 * maxJumpHeight/timeToPeak;
currentGravity = gravity;

void HandleJump(){

        float jumpHeight = 10;
        if(_jumpPressed && (_isGrounded) && !_jumping) {
            velocity.y = initialJumpVelocity;
            _jumping = true;
             currentJumps --;
            _jumpPressed = false;
            _playerSm.jumpDash = false;
            //controller.Move(new Vector3(0,velocity.y,0) * Time.deltaTime);

            return;
        }

        else if(_jumpPressed && currentJumps > 0 && _jumping && !_isGrounded){
            velocity.y = initialJumpVelocity;
             currentJumps --;
            _jumpPressed = false;
            return;
        }
        else if((!_jumpPressed && _isGrounded && _jumping) || currentJumps <= 0){
        _jumping = false;
        }
    }
    void ApplyGravity(){
        bool isFalling = ((velocity.y <= 0.0f) || !_jumpPressed);
        float fallMultiplier = 1.0f;
        float previousYVelocity = velocity.y;
        float nextYvelocity = 0;
        float newYVelocity;
        if(isFalling){
            newYVelocity = velocity.y + currentGravity * fallMultiplier;
            nextYvelocity = (previousYVelocity + newYVelocity) * 0.5f;

        }

        if(!_isGrounded)velocity.y += Mathf.Max(nextYvelocity,-500) * Time.deltaTime; else velocity.y += groundedGravity * Time.deltaTime;
        //if (!_isGrounded) velocity.y += currentGravity * Time.deltaTime;
    }
//This is my classes update method, it gets run every frame
 public void Tick(){
        ApplyGravity();

        _move = _controls.GroundMove.Move.ReadValue<Vector2>();

        currentYSpeed = Vector3.Distance(new Vector3(0,_prevPos.y,0), new Vector3(0, _playerTransform.position.y, 0))/Time.deltaTime;

        GroundCheck();
        // SlopeCheck();
        HandleRotation();
        HandleAttack();

        if (!lockOnPressed)
        {
            ApplyRotation();
        }

        HandleJump();

        controller.Move(velocity * Time.deltaTime);

        Vector3 currentVelocity =  velocity * ( 1 - Time.deltaTime * dragForce);
        if (!_isGrounded)
        {
            velocity = new Vector3(currentVelocity.x, velocity.y, currentVelocity.z);
        }
        else
        {
            velocity = currentVelocity;
        }

        //update the animator on our various attributes
        publisher.updateGroundedStatus(_isGrounded);
        publisher.updateAimStatus(_aiming);
        publisher.updateSpeedStatus(new Vector3(velocity.x,0,velocity.z).magnitude);
        publisher.updateYSpeedStatus(velocity.y);
        publisher.updateForce(velocity);
        publisher.updateVelocity(velocity);
        publisher.updateSubmerged(Physics.CheckSphere(_groundCheck.position, 0.25f , _waterLayer));
    }

 void OnJump(InputAction.CallbackContext context){
    Debug.Log("jump performed " + context.performed);
    if(currentJumps > 0)
    {

        _jumpPressed = context.performed;
        _playerTransform.parent = null;

        if (_jumpPressed && currentJumps > 0)
        {
            if(_isGrounded)
                publisher.updateJumpedStatus(1);
            else
                publisher.updateJumpedStatus(2);
        }
    }
}

```

Its odd as sometimes this code produces a perfect arc and sometimes it doesnt, which leads me to believe it might be an issue with my unity project or something else, if anyone could help or insight I would greatly appreciate it!

# Answer
So, I did some more testing, it seems like when I locked the frame rate it seemed to solve the issue. Initially, the game ran at 300-400 fps with an unlocked frame rate, whereas using `Application.targetFrameRate = 60;` seems to have solved the issue. I'm guessing the really low value for `Time.deltaTime` may have been introducing irregularities.
> 1 votes

---
Tags: unity, 3d, character-controller
---


# Question
Title: In Bevy ECS, what is a good way to have entities reference each other?
I am wondering if there is a better way than storing the entity ID. For the sake of example, let's assume I have a world with many entities who implement the component Name. Every x amount of time I want these entities to print "Hello, I am *greeterName*, have a nice day *greetedName*".

My current way to go would be to create a component `BestFriend`, and to store in it the entity ID of the best friend entity. Then I would make a system `GreetBestFriend` that query all of the entities with the `Name` and `BestFriend` components and loop through that query to find the entity that matches the `BestFriend`'s stored ID.

My concerns about this method are:

* Can I be sure that the referenced entity ID will not be changed at some point?
* Having to loop through all the instances of the query seems inefficient.

As mentioned, the above case is just for the sake of example. I am more generally interested in learning patterns that allow entities to reference each other.

# Answer
> 9 votes
You shouldn't have to "loop through" all instances of a query. Query lookups are typically implemented in such a way that they are fast -- often constant or logarithmic time complexity. Bevy queries have a `get` method for exactly this purpose:

```
#[derive(Component)]
struct BestFriend(Entity);

fn greet_best_friends(greeters: Query<(&Name, &BestFriend)>, friends: Query<&Name>) {
    for (greeter_name, &BestFriend(best_friend)) in greeters.iter() {
        let best_friend_name = friends
            .get(best_friend)
            .expect("My best friend got despawned!");
        println!(
            "Hello, I am {}, have a nice day {}",
            greeter_name, best_friend_name
        );
    }
}

```

In the example, I `panic!` if my `friends` query fails to find `greeter`'s friend because entity IDs are guaranteed to be stable and unique to a specific entity. If the `Entity` was returned by a call to `spawn`, it will remain valid until it is despawned. Let's go ahead and add some test entities:

```
let alice = world.spawn(Name::new("Alice")).id();
world.spawn((Name::new("Bob"), BestFriend(alice)));

```

Now when we run our system, the `greeters` query will match Bob since he has a name and best friend. Then we'll pull the ID of his best friend Alice and run it through our `friends` query (which only requires that Alice have a name) and say hello to her. We can be sure the query will complete properly unless Alice was despawned along the way.

As far as efficiency, the Bevy docs show that `Query::get` has constant time complexity, so you don't need to worry about implementation potentially looping over many entities.

---
Tags: entity-component-system, rust, bevy
---


# Question
Title: Do I need to hit the database and check if that quest is accomplished every time?
I'm creating an MMO questing system and one of the quests is to mine ore.

Does this mean every time a user mines ore I need to hit the database and check if that quest is accomplished? It is only one quest and users mine ore often.

Does this seem like overkill? Or is it fine and I just cache the result of that database query... What do you all think?

# Answer
Database queries are slow and expensive. When you hit the database on every player action in an MMO, then that database will soon become the bottleneck of your whole architecture.

The database in an MMO should only be used for "cold" data. That is to store the data of characters who are currently *not* in the game. The "hot" data, which is the data of those characters who are currently online, should be copied completely to the gameserver so your game's systems can access and change that data directly withot requiring an expensive network round-trip to the database. When the client disconnects, then that data should be written back into the database and removed from the memory of the gameserver to free up RAM. Additionally, persisting the player-data every couple minutes is also recommended, so players don't lose too much progress in case of a sudden server crash.

If your game is a typical MMO, then "collect X of resource Y" quests will probably be rather common. MMOs tend to have *hundreds* of those. So it would be useful to find an architecture that scales well no matter how many quests you have. Checking for *every single collection quest* you have whenever a player picks up an item could become wasteful even if you do it on the gameserver. It might be wiser if each player would maintain a list of *currently active* collection quests, and check only against that list whenever a player receives an item.
> 2 votes

---
Tags: mmo
---


# Question
Title: When loading only one item from the asset bundle in Unity, does the whole asset bundle need to get downloaded?
I am deciding on how to package my asset bundles that will be loaded from the web server at some point in the game. Currently I am thinking of packing them by types: for example, I would have one asset bundle that contains all the backgrounds, another for some UI elements and so on.

In-game I would load only specific background at a specific time by its name (I will know the name in advance so I don't have to get it from the bundle).

If I do it this way, will only that background get downloaded, or the whole bundle?

The target platform will be WebGL, so limiting memory and download time is important.

# Answer
> 2 votes
Yes, the whole asset bundle will be downloaded. A webserver can't look into the asset bundles and deliver just a part of it. It's all or nothing.

So if you want to optimize the loading times and memory footprint by streaming only the assets you need, then you need to organize your asset bundles so that the files you usually request together are in the same bundle. And dependencies between bundles should be avoided, unless you are going to need almost everything from both bundles anyway.

Addressables can help you as an abstraction layer between your game code and your asset bundles. When you refer to assets by Addressable addresses instead of a combination of a specific asset bundle and filename, then you can easily experiment with moving assets between bundles without having to edit your code.

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


# Question
Title: How to inspect code relating to specific content like villagers?
I’m trying to make an add-on for Minecraft Bedrock edition.

I am following tutorials. How do I see the code of certain stuff so that I know how to edit it? Some of the stuff I'm going to be making requires me to understand how the code of certain things work so I can edit it.

# Answer
> 1 votes
You can download the vanilla behavior and resource packs here. The villager code is in the `behavior_pack/entities/villager_v2.json` file.

---
Tags: minecraft-modding, minecraft-bedrock-modding
---


# Question
Title: Calculating score for a level with time and lives variation
I am developing a game where based on steps to be performed in a particular level, time and lives are pre-calculated. As the level gets completed, remaining lives and time are retrieved. Calculating score based on remaining time and lives will not work in this system, as the same level with smaller number of steps will have less time and lives than level with more steps. Can I count score based on time and lives efficiency? If yes, then how to calculated the score so that it is unbiased? I am stuck as it is my first game development. Any constructive criticism is appreciated.

# Answer
> 0 votes
**Do nothing**

Consider that you are deciding the time and lives to complete the level. If the margin the player has to complete the level remains the same, then the player would complete both the short and the long levels with about the same time and lives remaining. In which case there would no need to adjust for it, as the adjustment was already done when you decided how much time and lives to give the player.

*Also, perhaps correctness is not the goal. You might want it to be easier or harder to get points on advanced levels.*

---

**Simple normalization**

The idea is to use a proportion. *Or percentage, if that makes it easier for you to reason about.* So instead of using the remaining time directly, you use how much is the remaining time of the total time. And the same idea for lives.

This would be correct the time and lives you give the player grows linearly with the complexity of the game. *Again, perhaps correctness is not the goal.*

---

**Complexity metric**

You would have some complexity metric that tries to capture how hard the levels are. *Then you do some computation over your complexity metric to come up with the time and lives.*

An example of complexity metric would be the number of steps needed to solve the level. Yet, it does not consider all the alternative options the player might try, only the ideal path. The more things the player could do at any particular moment, the more work they *might* need to figure out the solution.

*Submitted to your consideration: We know that any - standard - Rubik Cube can be solved in at most 20 steps. But that 20 does not capture all the possible moves that do not solve the Rubik Cube, nor the skill needed to know which moves to do in order to solve it.*

So, the actual complexity of the game might actually be an exponential function of the number of steps needed to solve the level.

---

It might be a better idea to incorporate your complexity metric into the scoring directly.

So you can use the quickness to solve the level in complexity over time for scoring. In other words, the score could be based on the complexity of the level divided by the time the player took to complete it.

---

**Experiment**

What do engineers do when they don't know? They fuck around and find out do basic research.

Which in this case would mean to get a set of test players to try the games and record how much time and lives they take to complete the levels, and compare it to the time and lives you would be given them.

This will give you some idea of:

* How generous is the computations you are using to give them time and lives.
* How does the time and lives used by the players scale with your complexity metric.

*You might also discover that the player struggle in unexpected ways and times. Even might struggle more in levels you consider easier. Also, players might give you ideas.*

And then, having your results, you can decide if you are going to adjust the computation, or the score, or both.

And then you repeat the experiment. This time adding more test players so you have a mix of people who have tried the game before and other that don't. And perhaps you do further refinements or stick with what you got.

Ultimately what you do is tweak values and pick something that works in practice. Even if you don't fully understand it, you would have empirical evidence that it works.

---

**Other Alternatives**

Perhaps it is better to add collectibles for points, or the game design allows for style points.

Or perhaps the game does not need score at all. Losing a live is already lost time, so a leader board based on time might be enough.

---
Tags: mathematics, game-design
---


title: Show an image as Tooltip in a Unity 3D

text:
# Question
Title: Show an image as Tooltip in a Unity 3D
I got the following question:

How to show an image as Tooltip in a Unity3D? The image should only be visible if the user hovers over the 3d object.

Thanks in advance,

hidayah

# Answer
First we need to find out what object the mouse cursor is pointing at. You can do that by combining `Input.mousePosition` with `camera.ScreenPointToRay` and `Physics.Raycast`. Keep in mind that the object needs a collider for raycast hits to register. Here is an example from the official manual.

Now that we got the position and the object, we need to visualize the tooltip itself. I recommend to do that with a fullscreen UI canvas with a single panel that contains whatever you currently want to show. You can control the panel's position by getting its `RectTransform` component and setting its position to the `Input.mousePosition`.
> 1 votes

---
Tags: unity, image, unity-ui, image-effects
---


# Question
Title: My character gets stuck when It's running on a straight level ground
My project is an infinite runner that goes right in a straight line. Sometimes when it just runs without jumping the Player stops. Sometimes the Player doesn't stop. When you jump the Player usually stops a lot earlier. I've been trying to fix this, but I can't find the solution.

How I'm doing this is by making the character move to the right all the time with 1 point in the front for ground generating and 1 point in the back for deleting ground. The camera is following the player and the points are going forward at the same pace as the player. The ground is even, but the player always stops. Please help.

Code for generating the ground:

```
using UnityEngine;
using System.Collections;

public class PlatformGenerator : MonoBehaviour {

public GameObject thePlatform;
public Transform generationPoint;
public float distanceBetween;

private float platformWidth;

// Use this for initialization
void Start () {
    platformWidth = thePlatform.GetComponent<BoxCollider2D>().size.x;
}

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

    if (transform.position.x < generationPoint.position.x)
    {
        transform.position = new Vector3 (transform.position.x + platformWidth + distanceBetween, transform.position.y, transform.position.z);

        Instantiate (thePlatform, transform.position, transform.rotation);
    }

}

```

}

Code for controlling the Player:

```
using UnityEngine;
using System.Collections;

public class PlayerControl : MonoBehaviour {

public float moveSpeed;
public float jumpForce;

private Rigidbody2D myRigidbody;

public bool grounded;
public LayerMask whatIsGround;

private Collider2D myCollider;

private Animator myAnimator;

// Use this for initialization
void Start () {
    myRigidbody = GetComponent<Rigidbody2D>();
    myRigidbody.velocity = new Vector2(moveSpeed, 0);

    myCollider = GetComponent<Collider2D>();

    myAnimator = GetComponent<Animator> ();
}

// Update is called once per frame
//void Update () {
//  myRigidbody.velocity = new Vector2(moveSpeed, myRigidbody.velocity.y);
//
//  if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0));
//  {
//      myRigidbody.velocity=new Vector2(myRigidbody.velocity.x, jumpForce);
//  }
void Update () {

    grounded = Physics2D.IsTouchingLayers(myCollider, whatIsGround);

    if (Input.GetKeyDown(KeyCode.Space))
    {
        if(grounded)
        {
            Jump();
        }

    }

    myAnimator.SetFloat ("Speed", myRigidbody.velocity.x);
    myAnimator.SetBool ("Grounded", grounded);

}

void Jump () {
    myRigidbody.AddForce(new Vector2(0, jumpForce));
    }

```

}

# Answer
If you have several platforms connected in Unity your character might sometimes, (not always) slow down/stop.

There are 2 fixes that might work for this :

---

**1. Circle Collider**

If you have a box collider on your moving object/character, the corners of the collider might collide with the corners on the connected platforms, causing the object to slow down while it's trying to go over it, or just stop completely. To fix this, simply replace the players box collider with a circle collider instead.

**2. Physics Material**

If your still having the same problem as before, you can try to apply a physics material to the player and play around with the values until it gets "un-stuck" on the platforms.
> 1 votes

# Answer
Try decreasing the Default Contact Offset in Edit/Project Settings/Physics 2D

Changing it from 0.01 to 0.0001 worked for me

Source
> 0 votes

# Answer
You can set the Edge Radius of the BoxCollider to something like 0.1 Then the Edges are rounded and it does not get stuck on a tiled plan Ground. Or use a CapsuleCollider.
> 0 votes

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


# Question
Title: Solving distortion with non-linear scaling in a shader
I am currently working on implementing an older paper in Unity to show the progression of some graphics technologies, and part of that involves sprites being able to cast shadows. A trivial implementation would be to simply use a sprite of the object we already use, change it's colour, and project it underneath whatever casts that shadow.

Because shadows don't spread out directly the shadow casting object if one were to use a spherical light source, it would be nice to be able to adjust the width of the shadow so that the "top" of the shadow can be wider than the "base" (similar to a trapezium).

My approach has been to use a shader that can modify the vertices with a transformation matrix, as seen in the relevant code snippet below.

```
v2f vert(appdata_t IN) {
v2f OUT;
OUT.texcoord = IN.texcoord;
OUT.color = IN.color;
float sX = _ScaleX;
float sY = _ScaleY;
float scaleX = sX * OUT.texcoord.y + 1.0;

float4x4 transformMatrix = float4x4 (
    scaleX,0,0,0,
    0,sY,0,0,
    0,0,1,0,
    0,0,0,1
);

float4 skewedVertex = mul(transformMatrix, IN.vertex);
OUT.vertex = UnityObjectToClipPos(skewedVertex);

#ifdef PIXELSNAP_ON
OUT.vertex = UnityPixelSnap (OUT.vertex);
#endif

return OUT;

```

This unfortunately produces these strange results, which I can't seem to figure out the cause of, but my suspicions are that the UV-coordinates having an origin in one corner of the sprite might have at least something to do with it. Changing the pivot of the sprite from bottom to bottom left doesn't solve it, and instead produces different distortions. The shape displayed in the preview panel of the inspector looks right as well, so I am quite confused.

---

Thanks to a reply from DMGregory the problem likely arises from applying a non-affine transformation. In order to remedy this, one could use projective coordinates. What I am reasonably certain I've done is add an extra dimension to the input texcoord. This doesn't change anything when I scale everything with a set constant (like 2.0 in this case, picked very arbitrarily) as one would expect, since we would just be multiplying and dividing by the same value, but how does one go from this to proper projected coordinates described in the answer to another question, also by DMGregory.

```
v2f vert(appdata_t IN) {
    v2f OUT;
    OUT.texcoord = float3(IN.texcoord.xy * 2.0, 2.0);
    OUT.color = IN.color;
    float sX = _ScaleX;
    float sY = _ScaleY;
    float scaleX = sX * OUT.texcoord.y/2.0 + 1.0;

    float4x4 transformMatrix = float4x4 (
        scaleX,0,0,0,
        0,sY,0,0,
        0,0,1,0,
        0,0,0,1
    );

    float4 skewedVertex = mul(transformMatrix, IN.vertex);
    OUT.vertex = UnityObjectToClipPos(skewedVertex);

    #ifdef PIXELSNAP_ON
    OUT.vertex = UnityPixelSnap (OUT.vertex);
    #endif

    return OUT;
}

fixed4 frag(v2f IN) : SV_Target {
    float2 uv = IN.texcoord.xy / IN.texcoord.z;
    fixed4 c = tex2D(_MainTex, uv) * IN.color;
    c.rgb *= c.a;
    return c;
}

```

# Answer
You missed a step:

> Given a scale factor at each point (say, equal to the breadth of your strip at that spot), you can construct the 3D projective uvw coordinate from your regular 2D uv coordinate this way:
>
> ```
> Vector3 uv3 = ((Vector3)uv2) * scale;
> uv3.z = scale;
>
> ```

In your case that's:

```
float scaleX = sX * IN.texcoord.y + 1.0;
OUT.texcoord = float3(IN.texcoord.xy, 1.0f) * scaleX;

```

The the texture coordinates need to know about `scaleX` if you want them to be able to adapt to the distortion it introduces.
> 1 votes

---
Tags: unity, shaders, sprites, projection
---


# Question
Title: How do I spawn the tiles on the global z axis instead of local z?
I'm trying to spawn infinite tiles in a 3D runner game, but the tiles are spawning at the wrong position and on the wrong axis.

Technically, the code is working as it should, it is spawning and deleting tiles, but it is doing so on the wrong axis: local z, instead of global z.

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

public class TileSpawn: MonoBehaviour
 {
public GameObject[] tilePrefabs;
public float zSpawn = 0;
public float tileLength = 20;
public int noOfTiles = 4;

public Transform plyTrns;
private List<GameObject> activeTiles = new List<GameObject>();
void Start()
{
  for(int i = 0; i < noOfTiles; i++)
    {
        if (i == 0)
            SpawnTile(0);
        else
            SpawnTile(Random.Range(0, tilePrefabs.Length));
    }
}

void Update()
{
    if(plyTrns.position.z -25 > zSpawn -(noOfTiles * tileLength))
    {
        SpawnTile(Random.Range(0, tilePrefabs.Length));
        DeleteTile();
    }

}

public void SpawnTile(int tileIndex)
{
    GameObject go = Instantiate(tilePrefabs[tileIndex], transform.forward * zSpawn, transform.rotation);
    activeTiles.Add(go);
    zSpawn += tileLength;
}

private void DeleteTile()
{
    Destroy(activeTiles[0]);
    activeTiles.RemoveAt(0);
}
}

```

# Answer
```
GameObject go = Instantiate(tilePrefabs[tileIndex], transform.forward * zSpawn, transform.rotation);

```

`transform.forward` is "*this object*'s local z direction".

If you want the global z direction, use `Vector3.forward` instead, or construct your vector directly:

```
var spawnPosition = new Vector3(0, 0, zSpawn); // = Vector3.forward * zSpawn
var go = Instantiate(tilePrefabs[tileIndex], spawnPosition, transform.rotation);

```
> 0 votes

---
Tags: unity, c#, vector, tiles, transformation
---


# Question
Title: How to set up view and model matrices for 3D rendering?
For various reasons I am building a very simple graphics engine. I have a pretty good 2D thing using plain SDL2 and C that essentially boils down to a single "putpixel" function. I can create a window of arbitrary dimensions and draw pixels wherever I want. It's rad.

I would like to expand it to enable me to draw 3D stuff. I have dabbled with OpenGL before and have drawn cubes and triangles so I understand the concepts. For different reasons, I can't use OpenGL currently, and I thought it would be fun anyway to make something "from scratch". And now I'm stuck.

I have a standard cube:

```
typedef struct {
    float x;
    float y;
    float z;
} vec3;

typedef struct {
    float x;
    float y;
    float z;
    float w;
} vec4;

vec3 mesh[36] = {
    {-1.0f, -1.0f, -1.0f}, {-1.0f, 1.0f, -1.0f}, {1.0f, 1.0f, -1.0f},
    {1.0f, 1.0f, -1.0f}, {1.0f, -1.0f, -1.0f}, {-1.0f, -1.0f, -1.0f},

    {-1.0f, 1.0f, -1.0f}, {-1.0f, 1.0f, 1.0f}, {1.0f, 1.0f, 1.0f},
    {1.0f, 1.0f, 1.0f}, {1.0f, 1.0f, -1.0f}, {-1.0f, 1.0f, -1.0f},
... etc

```

I have a matrix struct:

```
typedef struct {
    float e00; float e01; float e02; float e03;
    float e10; float e11; float e12; float e13;
    float e20; float e21; float e22; float e23;
    float e30; float e31; float e32; float e33;
} mat4;

```

I also have a `vec4`, and some functions to do the basic maths:

```
vec4 vec3_multiply_mat4(vec3 vector, mat4 matrix); // lazy hardcodes the w as 1
vec4 vec4_multiply_mat4(vec4 vector, mat4 matrix);
mat4 mat4_multiply_mat4(mat4 a, mat4 b);

```

So. Where I'm stuck - I know that in order to convert my universal device co-ords for my mesh, into pixel coordinates, I need 3 matrices: model, view, projection. I have defined my projection matrix because this seems to be pretty well documented. I'm using a perspective matrix:

```
projection = perspective(to_radians(90.0f), (float)WIDTH / (float)HEIGHT, 0.1f, 100.0f);

mat4 perspective(float fov, float aspect, float near, float far) {
    float tan_fov = tanf(fov / 2.0f);

    mat4 m = {
        1.0f / (aspect * tan_fov),  0.0f,             0.0f,                                 0.0f,
        0.0f,                       1.0f / tan_fov,   0.0f,                                 0.0f,
        0.0f,                       0.0f,             -( (far + near) / (far - near) ),     -( (2.0f * far * near) / (far - near) ),
        0.0f,                       0.0f,             -1.0f,                                0.0f,
    };

    return m;
}

```

I'm lost on how to properly define the model (world?) and view (camera?) matrices to properly control how my cube is displayed. For testing, I've set my view matrix to the identity matrix, and my model matrix to scale the cube to half (poking numbers in for a bit got me to this point, and it displays something on the screen).

```
mat4 model = {
        0.5f,   0.0f,   0.0f,   0.0f,
        0.0f,   0.5f,   0.0f,   0.0f,
        0.0f,   0.0f,   0.5f,   0.0f,
        0.0f,   0.0f,   0.0f,   1.0f,
};

mat4 view = {
        1.0f, 0.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 1.0f, 0.0f,
        0.0f, 0.0f, 0.0f, 1.0f,
};

```

Here's my draw:

```
void draw(void* arg) {
    pixel_cls(palette[DARK_GRAY]);

    vec4 point;
    for (uint32_t i=0 ; i<36 ; i++) {
        point = vec3_multiply_mat4(mesh[i], model);
        point = vec4_multiply_mat4(point, view);
        point = vec4_multiply_mat4(point, projection);

        point.x += 1.0;
        point.y += 1.0;

        point.x *= 0.5f * WIDTH;
        point.y *= 0.5f * HEIGHT;

        object[i] = point;
    }
    for (uint32_t i=0 ; i<36/3 ; i++) {
        pixel_line(object[i*3].x, object[i*3].y, object[i*3+1].x, object[i*3+1].y, palette[WHITE]);
        pixel_line(object[i*3+1].x, object[i*3+1].y, object[i*3+2].x, object[i*3+2].y, palette[WHITE]);
        pixel_line(object[i*3+2].x, object[i*3+2].y, object[i*3].x, object[i*3].y, palette[WHITE]);
    }
}

```

Which gets me 2 triangles. It appears to be drawing the cube, but I'm looking directly at one face, so everything essentially lines up.

I don't understand how to define the model & view matrices in a way that allow me to move things around and look from different angles. I also don't understand why I had to hack in some extra math to make it work (I was following a video elsewhere but I'm missing something somewhere) - this should be handled in one of the matrices no?:

```
point.x += 1.0;
point.y += 1.0;

point.x *= 0.5f * WIDTH;
point.y *= 0.5f * HEIGHT;

```

I know what I have to do. I just can't quite work out how to do it!

# Answer
The model matrix converts from object space to world space, so it represents the position, rotation, and scale of the object relative to the world origin.

The view matrix converts from world space to view space, so it represents the position, rotation, and scale of your world relative to the viewpoint.

Put another way, if you create a "camera model matrix" that positions your virtual camera in your world (transforming from camera-relative coordinates to world coordinates), your view matrix is just the inverse of that matrix.

The reason you barely see anything with your current view matrix is that it represents a camera placed at the origin - it's *inside* the cube.

Try picking some point on a hemisphere a distance away from the cube, with the camera's local z axis rotated to point back at the cube (or away from the cube, if you're using the convention that the view space z axis points out of the screen, not into it, which it looks like you are). Make a matrix to represent that position and orientation, then invert it to make your view matrix. You should see something a little more interesting.

> this should be handled in one of the matrices no?

No, what you have there is usually handled by another stage of the pipeline. It's conventional to arrange the projection matrix so that, after perspective divide, x and y coordinates of on-screen points are in the range -1 to +1, with 0 in the middle of the viewport. That makes it very easy to clip/cull off-screen triangles, since the clipping planes are always x = ±1, y = ±1, regardless of the size or aspect ratio of the screen/viewport. When we want to convert to pixel coordinates in the range 0 to `pixelWidth` and `pixelHeight`, we need to add one, halve, and multiply by the viewport size on that axis, as you're doing here. When using a rendering API, this part is handled automatically between clipping and rasterization, so we don't need to bake it into our matrices.
> 1 votes

---
Tags: 3d, matrix, transformation, c, linear-algebra
---


# Question
Title: Where can I find a reference to the possible arguments of AddBinding?
In the new input system of Unity, the function AddBinding gets a string as an input. In this link there are several examples, such as "\<Mouse\>/delta" or "\<Keyboard\>/alt". Often, I need to add a binding and I do not know what string to use. Where can I find a reference including all possible strings that can be used as an input?

# Answer
I'd recommend creating an `InputAction` in the Unity editor, then you can peek at what binding string is associated with any binding you can create in the UI:

```
public class BindingInspector : MonoBehaviour
{
    public InputAction action;

    [TextArea(3,8)]
    public string binding;

    void Start() {
        if (action == null) {
            binding = "No action configured.";
            return;
        }
        string text = "";
        foreach (var binding in action.bindings) {
            text += $"{binding.ToString()}\n";
        }
        if (text == "") text = "No bindings configured.";
        binding = text;
    }
}

```
> 2 votes

---
Tags: unity, input
---


# Question
Title: Why use sprite tile maps on the GPU in WebGL?
I'm trying to figure out the best way of rendering my layered tiled maps with WebGL, and have come across this tutorial several times: https://blog.tojicode.com/2012/07/sprite-tile-maps-on-gpu.html

Someone even created a library for it here: https://github.com/englercj/gl-tiled

The gist of this "GPU abuse" seems to be generate a texture where each pixel as a lookup table into the tileset spritesheet. That is, the red component refers to the x coordinate and the green component refers to the y coordinate. Additionally, in the library, the blue component refers to the corresponding tileset to use.

This seems to accomplish exactly what I am attempting to do, but I am confused on two parts.

For one, the author describes this is a neat little trick and "GPU abuse". I feel as if the implication there is, "this is a fun little exercise, but don't actually use this for your game or any serious code."

Is this the case, or is this actually a potentially serious technique that I could use to power my map rendering?

Secondly, I'm somewhat confused why this is even necessary. I am still learning WebGL, so I might mess up a few terms here, but couldn't this same exact thing be accomplished in a more straight-forward manner? Why go through all these steps of creating a custom generated texture of your map, when you can just create a (static?) Vertex Buffer Object, load it with all your tiles, and then just render them?

I'm not really understanding what exactly this technique buys as that can't be accomplished in the same way by just creating a large buffer that just contains all our tile data, and then just rendering it like that. Isn't that conceptually simpler, arguably easier to implement, more straight-forward, and doesn't have weird restrictions like maximum tile count or width?

Basically, I'm having trouble understanding what advantages this has over traditional rendering where you just load up a buffer with tiles. If there are some advantages, should this technique be seriously used in a game?

# Answer
> 1 votes
This technique has the advantage that you can render the whole tile layer as one single quad. That means that there are just 4 vertices that need to go through the vertex shader. The rest happens in the pixel shader. You do a lookup in the tiny texture to see in which part of which tileset texture you need to do the lookup that provides the actual RGBA values for the tile. This could (potentially) be a pretty fast way to render a tilemap. Much faster than rendering each tile as a separate quad, or even as a separate draw-call.

However, I am a bit skeptical if you really *need* to resort to such tricks with today's hardware. This is 2d, after all. I wrote tilemap-based engines using the 2d API of HTML5 canvas (so even slower because you do quite a lot on the CPU layer) and didn't have any performance issues - and that was 10 years ago. So if VBOs work for you, then I doubt that there is much reason for you to change that.

# Answer
> -2 votes
WebGL is not really needed for sprite tilemaps at this point in time. The overhead for WebGL would slow a sprite based web game down.

One sprite sheet that has all image data, animations, and everything loaded as an Image, drawn from directly to canvas, that's all that's needed.

---
Tags: opengl, javascript, sprites, tilemap, webgl
---


# Question
Title: What is the name of the website which rates games based on how ethical / predatory / addicting they are?
I'm not sure if this is the right category since it's not a programming question. If this is wrong please can someone tell me which Stackexchange would be the correct one?

My question is the following: Some time ago I had found a website which rates games based on how ethical / predatory etc games are. There were a lot of interesting categories. Games with a bad score had a lot of psychological tactics to make it addicting or make you spend money. and a good score were more ethical games. I just can't find the site again, does anyone know it? It looked like it was a pretty well known site with lots of rated games. That's why I'm wondering why it's so hard to find again. It would be great if someone can help! thanks! Kevin

# Answer
> 3 votes
I found it! Stumbled over the tern "dark pattern" in a random user experience StackExchange post and that's the word I needed. darkpattern.games is the website

---
Tags: web
---


title: Designing a system for delivery

text:
# Question
Title: Designing a system for delivery
I'm writing a game where deliveries are made to specific people. These people act in different ways depending on what the delivery is. At times one character might ask the player to make a delivery to a difference character.

I'm having a hard time figuring out a healthy architecture for this. Currently I have a **story manager singleton** class, a **quest class** (which has subclasses like letter, package etc) which keeps track of the character sending/receiving the delivery and its' contents, and a **character class** that handles the behavior upon receiving a quest.

This works for the small version of the game that I'm working on at the moment since the order of interactions is fairly simple, so if x gets a package from y we have a switch statement handling this in y, but it doesn't feel scalable whatsoever - what if x sends y multiple packages throughout the story? Also, this mean I would have to manually mark the quest as complete from the character class and it feels wrong.

Of course I could give each quest an ID but it also doesn't feel great to do, since many IDs are difficult to read and expand upon. I don't necessarily want to end up with a giant switch statement that's just numbers (or enum), especially since that would have to be done for each character and it sounds like a nightmare.

Are there any design patterns applicable here? Do you have any advice? I'm working in gdscript at the moment but it doesn't seem like a language-specific problem.

Thanks!

# Answer
Games with lots of quests often use some kind of **domain-specific language** (DSL) to define quests. That means that the quests are created in a text format that is interpreted by the game at runtime. In simple cases, the DSL can be based on a standard data markup format like JSON or XML. This has the advantage that you can make the implementation much easier by using a library to parse those formats. Here is an example how a simple fetch-quest could look in a DSL based on JSON:

```
{ "quest_type": "delivery",
  "min_level" : 5,
  "time_limit": 1200,
  "steps": [
         { "npc":"Alice",
           "text":"I got a job for you. Can you bring this small package to Bob?",
           "item_received":"small_package_A"
         },
         { "npc":"Bob",
           "text":"Sorry, but that's not for me, it's for Charlie. Alice always keeps mixing us up."
         },
         { "npc":"Charlie",
           "text":"Thank you for the package. Can you bring this thank-you letter back to Alice?" ,
           "item_lost": "small_package_A" ,
           "item_received":"letter_C"
         },
         { "npc":"Alice",
           "text":"How nice of Charlie to send me this letter. Here is your payment.",
           "item_lost": "letter_C",
           "reward_money": 1000,
           "reward_exp": 500
         }
    ]
}

```

You would store this as a text file so your quest system can read it at startup, convert it into the appropriate data-structure and reference that data-structure during gameplay.

When there is a requirement to add some custom logic and mechanics to quests, then such a DSL can be more than just a linear data format. It can be a full-fledged scripting language supporting variables, loops, conditions, math and everything else you would expect from a programming language. Some games invent their own scripting language, but to keep development time reasonable it's often far wiser to just use an existing one with an existing implementation for your technology stack. But even this is something you should really think hard about if you *really* need it. It's easy to get carried away and turn your scripting engine into an inner platform that isn't any less complex than the platform you are already working with. So in the end you might end up with a scripting language that is even less convenient to work in than just hardcoding the quests in GDScript. So consider carefully what logic should be described in the scripting engine and what logic would be better to do with a call to GDScript that hides the nitty-gritty technical details of the quest scripts.
> 1 votes

---
Tags: architecture, design-patterns
---


# Question
Title: How can I initialize a sprite programmatically in Unity
Hello everyone and thank you so much for your help! I've tried following the answer at Unity 5 2D drawing sprites programmatically but nothing happened. I have a blank screen with just a background image (my game is 2d). I want to programmatically create 6 (or more) platforms (rectangles) one above another in the center of the camera view. If you've played the game Doodle Jump - that's sort of what I want to accomplish, but the movement is for a later day. My background is in swift and SpriteKit developing for iOS. I'm completely stumped here. I've tried to create a gameObject and then add the component SpriteRenderer and then tried to create a square texture which I can scale into a rectangle. But no platforms appear. I'm really at a loss of what to do because I don't see how to create a sprite. I've tried the Sprite.Create method but that didn't work for me either. Please will you help me?

# Answer
I found a solution while looking through a tutorial. I created a prefab of the platform I wanted to programmatically create. Then I wrote the following inside a `for` loop:

```
GameObject platform = Instantiate(platformPrefab, spawnPosition, Quaternion.identity);

```

This created the 6 platforms I needed through iteration. `spawnPositon.y` increased at every loop. `Quaternion.Identity` is so the platforms aren't rotated.
> 2 votes

---
Tags: textures, rendering, sprites, platformer
---


# Question
Title: Multiple Node/Express/Socket.io servers for game lobbies?
Building a multiplayer game on the web that will be able to handle thousands of players at once, separated into independent lobbies/sessions. There may be 20 players in one lobby, 10 in another, 30 in another, etc.

I'm using NodeJS, Express, and Socket.io, but I'm not sure on a few things. I assume my entire application will run on a single NodeJS server, but that each game lobby will have spawn their own express server and or their own socket.io server.

Alternatively, they may all share the same central single express server, but that express server will produce independent socket.io servers for them (if even possible)

The least likely scenario to me would be to have only one socket.io server for all lobbies as well, and divy them up using socket.io's "rooms" feature. That seems incorrect given that rooms are a server-side only concern, all client's' would emit to the same server likely impacting performance.

To formalize my uncertainty into four questions:

### Will it all run on a single NodeJS instance?

### Will I want multiple Exress/HTTP servers?

### Will I have multiple Socket.IO servers?

### What are the implications/requirements on multi-threading/concurrency?

# Answer
This is a pretty large question and the answer is "It Depends".

You'll see benchmarks for hundreds of connections on a single node.js instance, but those are normally useless because they're not really doing any "work". Just sending messages without any processing. That's not what your server will likely be doing so they're not that helpful. There is some load testing information on the socket.io website that will probably be more helpful to ensure that your particular game would scale.

That being said some considerations:

Scaling sockets can be tough. When you introduce multiple servers then you need to introduce a way to ensure that users that are in the same game lobby are actually connecting to the same socket.io instance so that you're not communicating between users across the network. This may be difficult or trivial depending on how you let users join lobbies (maybe they can only see lobbies on the same instance they're connected to).

When you're spawning a separate socket.io instance for your game lobby, if it exists on the same instance (IE: you're using fork or some subset) then you're still limited by the hardware of the host system anyway.

If you're spinning up individual processes for each game lobby, then I'm not sure if you really care that much about concurrency/multi-threading wrt to your game itself. The fact that you can split it into lobbies to me means that whatever happens within that lobby is constrained within it and shouldn't affect anything outside the lobby (except maybe the player). The problems you'll encounter with concurrency/multi-threading is reaching "across". That is whenever you need to touch something that another process is touching. Without knowing anything about your game it's hard to say where you'll run into issues.
> 1 votes

---
Tags: networking, multiplayer, node.js, web, websocket
---