# Question
Title: Detect Particle System based particles within a radius and get their position
I am working on a feature where I want to detect particle system-based crops within a certain radius of my harvester. I have tried **OverlapSphere** but seems like Unity doesn't detect particle systems through raycast or any type of casting.

Few forums say that try getting all particles and check those particles that are closest but the problem is that this will get overwhelming since I have up to 20k particles spawned and each frame traversing all particles to check which particles are within a radius does not seems like a good idea since harvester will be moving.

Need opinions here since I haven't yet found a proper solution.

# Answer
I'm not sure I'm understanding properly, but it sounds like you have `GameObjects` with particle emitters that render the individual meshes making up the crops?

Since individual particles in an emitter aren't tracked with the same fidelity as other collision systems (for performance reasons), it may be worth attempting a solution like this:

> **Note:** I don't have a lot of experience with customizing particle emitters, but hopefully some API exploration can net you results using this high-level approach.

---

### A

1. Ensure each crop tile contains a collider covering the particle emission area.

* Optionally split the colliders (and emitters) into a grid on top of your crop tile to improve performance.
    * Optionally sleep/disable colliders belonging to crop tiles far away from the player to aid in performance.
2. If your OverlapSphere intersects with a crop tile, GOTO B.

### B

* If you have a single collider per crop tile, iterate through each particle in the appropriate emitter, compare its position to the area of your OverlapSphere and zero out the lifetime and/or kill the particle if it's within the area.
* If you have multiple colliders (and multiple emitters) per crop tile, determine which collider(s) have been intersected with. Within those colliders / each accompanying emitter, either:

1. Iterate through each particle in the emitter, compare its position to the area of your OverlapSphere and zero out the lifetime and/or kill the particle if it's within the area.
    2. Potentially higher performance depending on how you've subdivided your crop tile colliders: kill all particles within the emitter. If you've subdivided your crop tile colliders into an 4x4 grid, for example, you only need to check for collision on - at most - 16 objects, but your crops will disappear in square chunks rather than by individual particles.

---

The idea here is to add one or more colliders (maybe 4, maybe 9, maybe 16) within each crop tile that correspond with event emitters. Use these colliders and emitters as a form of quantization to more cheaply collide with and control groups of particles rather than iterating through each particle individually.
> 0 votes

---
Tags: unity
---


# Question
Title: Why are some gameplay systems set up to `exist in the world`, with full collision and kinematics, whereas others seem like `complex event timelines`
I wanted to ask a question I've always wondered about to the larger crowd of gamedevs out there:

> #### Why is there often a disconnect between the locomotion / kinematic systems that a player controls vs. the ones used by NPCs, in cutscenes, or by other \[interactive\] props?

This is a super open-ended and broad question, so I'll give some examples:

---

## As a player in a game with a 3rd person action RPG style camera system, I run to a ledge and press the jump button.

1. My character is propelled upwards and then falls to the ground below.
2. The speed at which I feel rise to the apex of my jump and the speed at which I fall to the ground are consistent with jumps I've made in other areas of the game.
3. Everything feels grounded and consistent.
4. **Nice!**

## As a player in a game with a 3rd person action RPG style camera, an in-game event begins.

1. An NPC spawns on a ledge above me and moves towards the edge. 1. They jump off the ledge, but rather than rising to the apex of their jump and falling to the ground at a consistent speed, they seem to travel more quickly or more slowly than I would as a player.
2. The NPC appears stiff, glued to a precalculated path, their animations playing out at whatever speed will guarantee they travel from Point A to Point B in exactly 1.2 seconds.
3. Do the physics calculations in this world not apply to them as they do to me?
4. I feel pulled out of the world and hyper aware of the "gaminess" of what is happening on screen.
5. **Bleh.**

---

## As a player, I'm zooming around the world of Destiny 2.

1. I'm on my sparrow, a space-magic imbued mount that has S+ tier game-feel baked in every way.
2. My field of view changes as I speed up.
3. I turn and opt to engage the "cornering" button which modifies the sparrow's friction in the environment.
4. I snap around a corner and press another button to hop off my sparrow.
5. The momentum of my action launches the sparrow into a nearby wall, and then it falls down a chasm.
6. I'm so immersed! So present in the game world!
7. **Nice!**

## As a player, a new "Public Event" starts in the shared game world of Destiny 2.

1. A "move the payload" prop appears and I hop onto the object.
2. It's velocity immediately changes from 0 to 100 \[insert units\] per second.
3. Ooof, that was a bit jarring.
4. My field of view does not change while on the payload, despite the speed change.
5. The payload comes up on a corner and rounds it. It does so with absolute precision, a clean 90-degree arc.
6. There is no banking of the payload; it does not "lean into" the turn.
7. An obstacle ahead blocks the path, and the payload stops suddenly. The velocity changes from 100 \[insert units\] per second to 0.
8. There is no momentum or sense of physicality to its movements.
9. I'm pulled from the game world and note the disparity between my actions and those of the props in the world.
10. **Yuck.**

---

Hopefully these examples are illustrative enough to paint the picture I'm trying to communicate. With my understanding of game development systems, I imagine a lot of these disparities are due to developers needing to ensure the determinism of these systems that interact directly with the player.

## The Jumping NPC

> The NPC needs to spend only X number of seconds in the air, so their act of jumping off a ledge isn't calculated via the physics constants in the world but is instead calculated in a way where gameplay programmers can ensure Actor A can reliably navigate from Transform B to Transform C without unforeseen physics sandbox issues.

## The Stiff Payload

> Along with the needs of the above w/r/t avoid physics sandbox issues, the payload needs to arrive at each checkpoint in a fixed amount of time. It is simpler to attach the payload to a path and have it advance at a fixed speed, ensuring it arrives at the appropriate time and triggers the next set of event behaviors. The payload does not slow down if it hits a player or a physics prop; it triggers collision on other objects but is not influenced by collision itself.

---

This all seems to suggest that determinism is the motivating factor here.

In all honesty, my question is almost entirely answered by now, just by typing this all out, but I'd still like to pose it to anyone who may want to weigh in with anecdotes or wisdom.

My gut tells me: **cost** and **scope** are huge factors.

While the game-feel and satisfaction of interacting with systems of type `A)` is unparalleled (think Rockstar's Red Dead Redemption 2, or Arkane sandboxes like Dishonored / Prey), it creates an enormous soup of variables and testing edge cases. Type `B)` is simply cheaper to implement, more predictable and more easily reasoned about during development and QA cycles.

---

Jeez, anyways, this is a huge post now so I'm going to sign off on it for now.

Very much looking forward to hearing from folks who have come across these decisions themselves in their games (2D, 3D, VR, I imagine these decisions aren't unique to genre or technologies) and hope to learn more about how y'all make the choice between interactivity + emergent gameplay vs. predictability + guided experiences.

# Answer
> 3 votes
One cause for this that I think it is worth noting is that, in many cases, the people making the different parts of the game that you find to be clashing, are *different people*, using *different tools*.

Using your jumping example, the player physics are probably determined through procedural code that is, on some level, simulating aspects of real-world physics. The NPC jump was probably placed by someone dragging a Bézier curve around in a visual editor of some sort.

These very different ways of describing motion naturally lead to discernible disconnects, if one pays attention to the differences.

---
Tags: physics, game-design, architecture, game-mechanics, project-management
---


# Question
Title: How to Play YouTube Videos Within Asset Store for Unity
On every computer I've ever tried to use Unity, the Asset Store seems incapable of showing the YouTube video previews of assets. It always claims my "browser" does not currently recognize any of the video formats available and recommends I click for a visit to a FAQ about HTML5 video. I would expect this to be built into Unity, yet it seems not to be. I can't find anything online about what the deal is. So how do I get the videos to work within the Asset Store within Unity??

# Answer
> 1 votes
You need to enable Functional Cookies. It should prompt you to change your cookie settings when you try to play the video.

# Answer
> 0 votes
I don't believe there is a fix for it. The best you can do is hope that Unity Dev's eventually add the supported codec. Until then just right-click the video and select copy video url, then paste it in a browser to watch the Demo

# Answer
> 0 votes
Functional cookies is what does it in the Unity settings. They also work with other video and digital content services.

---
Tags: unity, html5
---


# Question
Title: JsonUtility deserializes list of strings, but all strings come out empty
# What I have

## JSON file

```
{
  "Story": [
    {
      "Name": "JsonTest",
      "Content": [
        "Sample",
        "Sample2",
        "Sample3",
        "Sample4",
        "Sample5",
        "Sample6",
        "Sample7"
      ]
    },
    {
      "Name": "Jasper_First",
      "Content": [
        "sample",
        "sample2"
      ]
    },
    {
      "Name": "BlackSmith_Sword",
      "Content": [
        "sample",
        "sample2"
      ]
    }
  ],
  "Quest1": [
    {
      "Name": "FirstEncounter",
      "Content": [
        "sample",
        "sample2"
      ]
    },
    {
      "Name": "QuestDetail",
      "Content": [
        "sample",
        "sample2"
      ]
    }
  ]
}

```

## C# classes

```
[System.Serializable]
public class JsonListMember
{
    public string Name;
    public List<string> Content;
}

[System.Serializable]
public class Root
{
    public List<JsonListMember> Story;
    public List<JsonListMember> Quest1;
}

```

## Accessing the JSON data

```
    private string Texts;

    private void Start()
    {
        Texts = Resources.Load<TextAsset>("Texts/Test").text;
        Root JsonData = JsonUtility.FromJson<Root>(Texts);
        foreach (var item in JsonData.Story)
        {
            print(item.Name + " : {" + string.Join(",", item.Content) + "}");
        }
    }

```

## and here's the result:

So as you can see the code can read the JSON data and correctly shows the `Name`s but the same can't be said about `Content`. The console shows that the program knows how many texts are in each `Content` but they are all empty strings(`""`) and I've no idea why this is happening.

# Answer
> 0 votes
The problem was neither the code nor the JSON file. As it turned out, the program I was using for writing the JSON file had some issues for saving, and by solving that the program is working fine. Use the code if it helps you, cheers!

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


# Question
Title: how do i NOT let this object spawn at a certain area?
```
void Treetree()
{
    for (int i = 0; i < TreeCount; i++)
    {
        xPos = Random.Range(-140.5f, -13.51f);
        yPos = Random.Range(163.47f, 35.53f);
        Instantiate(treeFab, new Vector3(xPos, yPos, 1.6f), Quaternion.Euler(-90, 0, 0));
        Debug.Log(TreeCount);
    }
}

```

I set a perimeter to where I want it to spawn but I don't want these objects to spawn at a specific area that is within the xPos and yPos range. what should I do?

# Answer
A simple solution which covers a wide variety of circumstances which could invalidate spawn locations can be to simply check if the randomly generated position is within a "forbidden zone" and when that's the case just roll it again and again until it is not.

```
do {
    xPos = Random.Range(-140.5f, -13.51f);
    yPos = Random.Range(163.47f, 35.53f);
} while PositionBlocked(xPos, yPos);

```

The problem with that method is that there might be circumstances where it is *impossible* to place the desired object. The above algorithm would be unable to detect that and get caught in an infinite loop.

OK, perhaps there is a way for you to detect if the forbidden zone covers the spawn area completely, so you can detect and handle the *impossible* case separately. But what about the *nearly impossible* case? Like one where there is a tiny 0.001% area of the designated rectangle that are valid spawn locations? The above algorithm would hit that spot *eventually* (assuming a good random number generator), but it could take a very, very long time until it does. Unless the "forbidden zones" in your game are so small and few that you can guarantee that this is never going to happen (and that's a pretty bold assumption in most games), you have to handle this case somehow.

A good way to do that is by adding a counter and throwing an exception when it exceeds a predefined maximum of tries. The exact value of `MAX_TRIES` is a tradeoff between performance and reliability of tree placement in situations where there are very few valid positions:

```
try {
    int tries = 0;
    do {
        tries++;
        if (tries > MAX_TRIES) throw new CantPlaceTreeException();
        xPos = Random.Range(-140.5f, -13.51f);
        yPos = Random.Range(163.47f, 35.53f);
   } while PositionBlocked(xPos, yPos);

    Instantiate(treeFab, new Vector3(xPos, yPos, 1.6f), Quaternion.Euler(-90, 0, 0));
    Debug.Log(TreeCount);
}
catch (CantPlaceTreeException e) {
   // handle failure to find a valid spawn position for the tree
}

```

How exactly could you handle this failure condition in the `catch`-block? Well, there are several options. When the trees are mostly cosmetic and the exact number of trees in a region isn't that important, then you could simply *not* place it. But when it is crucial for the game that the tree spawns no matter what, then you could place it on the last rolled position anyway, either ignoring or removing whatever obstacle would prevent it from spawning there. Or you could find some other solution which is more appropriate for your particular game.
> 5 votes

# Answer
I would like to write an alternative answer which would be superior to my previous one if you have a situation where you:

1. Have a finite set of possible spawn locations. Like, for example, when you have a tilemap and each tile can only contain one object.
2. Want to place a lot of objects
3. Want to guarantee that all possible spawn locations are occupied before you start to deal with "impossible" spawns.

In this case you can enumerate all possible spawn locations, check each one if it is valid and then store them in a list. You can then place objects by taking a random element of the list and then removing it from the list so it won't be used again. You can do that until the list is empty. Now you can be certain that there are no more spawn positions available and can act accordingly.

This method is faster than the algorithm I describe in my other answer when you have a small number of available spawn locations, because it won't go into long trial-and-error loops. However, if you have a large number of possible spawn locations and a low number of objects to spawn, then the time it takes to create the list of possible spawn locations would probably take much longer.
> 0 votes

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


# Question
Title: Network mechanism for an RTS multiplayer game
I'm writing a real time strategy game in Rust. In this game each player controls one of two armies facing off on a battle zone. To better understand the gameplay, my project is an open source version of Close Combat games.

I will work on the network part soon, and I have some questions about that. This is my theoretical design:

* Game playable as 2+ players (but not a lot, max 6 players)
* One player act as "Server"
* Other players are "Client" of the "Server" part
* The Server part own the game state and logic (soldiers positions, players orders, path finding, which gunshot kill another soldier, etc.)
* The client part send to the Server part all the player state change requests (like soldier move request)
* The server send to the clients all the state changes (new soldier position, sound to play, etc)

To communicate between server and clients I' considering using ZMQ sockets (I already use it in another project, but I don't know if it is a good choice for game design):

* Clients connects on Server REQ/REP to be able to send theirs "state change requests" (like soldier move request)
* Clients connects on Server PUB/SUB to receive all state changes

This design is correct? Do you have comments about that?

# Answer
First, there are already libraries out there that can help you create this kind of setup without having to code too much on your end. Depending on your engine, there are various options like FishNetworking, or Mirror on Unity. As far as I know, Photon is the most used in Unity. Other engines like Unreal already offer multiplayer networking.

Now, my opinion on your design. The first part about building the netcode is sound for an RTS. You're sending RPC when the client needs to send information to the server and the server is sending the state based on a tick rate that you can configure.

One comment for the "client-server" would be that calculating the pathfinding of all the units on it could end up consuming a lot of CPU on that specific player. So, you could run into some issues there. The more units you have, it can become too heavy for your average computer to handle.

I don't know much about ZMQ sockets, nor how performant they'd be for an RTS game. That said, in an RTS, there can be a lot of things happening at the same time (every single unit can move in a different direction at the same time through pathfinding) so messages between the client and the server have to be optimal. I don't know if ZMQ can offer you that, so if you can run some tests as to how much traffic these connections can generate on ZMQ, you would have a better idea of whether you can use it or not.
> -1 votes

---
Tags: networking, rts, synchronization, rust
---


# Question
Title: How do I use version controls for teams?
I have a question and I haven't found a topic, which fits it. I want to create a small mobile game and I plan to work on it with some friends later on. Do you guys have any tips for me how I can use git and GitHub the right way with teams? If So how to set up branches and so on the right way?

I would be happy if some of you have some information for me to share :)

# Answer
There are two main competing philosophies regarding how to use git for collaborative software development.

The first is the more simple **"trunk" process**. In this case there is one main branch, and everyone commits to that branch. Everyone is responsible for making sure that their commits don't break anything. Developers are encouraged to pull regularly from the trunk branch and integrate the commits from other developers with their own work-in-progress and thus avoid diverging too far from the trunk.

This process has the advantage that looking at the main branch gives a very good idea of what is currently going on in the project. And the lack of red tape also means that small and simple changes are easy to get into the main branch and then to end-users. Unfortunately careless developers can easily cause chaos in such a project by committing poorly tested code changes or half-finished features to the main branch which they then never get around to finish.

The second is the so-called **"git flow" process**. In this case there is still one main branch, but nobody commits to that branch directly. All the development happens on separate branches, usually one for each feature. When a feature is completed, that branch is reviewed, and only then merged into the main branch. Github supports this process very well. The website makes it easy for users to create branches of other peoples projects, and then request for their branch to get merged back into the main project by creating a "pull request" which the maintainer of the main project can then accept or reject.

The git flow has the advantage that the main branch is always free of any untested or half-completed features. But on the other hand, having branches with longer histories developed independently over longer timeframes can make merging challenging at times.

When you enter "git flow vs. trunk" into your favorite search engine, then you are going to find a lot of blog posts which make lots of arguments about when to use which one and why. But in the end, which process is "the right" process *for your team* is for your team to decide.
> 0 votes

---
Tags: unity, c#, version-control, git
---


title: Three.js camera rotation and behavior

text:
# Question
Title: Three.js camera rotation and behavior
I'm just getting into Three.js and the camera is causing some problems. Basically, I want to implement spectator-like movement controls, so that I can move around freely in the scene. The problem is that the camera seems to have it's own coordinate system, so rotating it rotates the camera, while the system itself is left untouched. This, in turn, causes problems when moving the camera.

To better illustrate the problem, please have a look at the scene. Use the arrow keys to look around and press w to move forward.

http://jsbin.com/anarid/1/

Ideally, I'd like to apply the rotation to the 'whole' camera instead, including its coordinate system. I know that Three.js provides controls, but I'd like to implement them myself for learning purposes. I also know that a lot of people do have this problem and that there are a couple posts dealing with this. However, I mostly fail to understand the solutions. If someone could shed some light on this, I'd really appreciate it. :)

Greetings

# Answer
You don't move a "whole coordinate system." The world coordinate system is meant to be completely independent of the camera (you might even have more than one camera, after all).

Take your movement vector, apply the camera's world-space rotation, and then add that the camera's world position. It's as simple as that.

That is, if you want to move forward (negative Z for sake of example), you'd have a movement vector `<0,0,-1>`. If your camera was turned 90 degrees right then after applying the rotation matrix to this vector you'd get `<1,0,0>`. Now add this vector to the camera's position to move along the positive X axis, which is the way the camera is facing and what you wanted.
> 1 votes

# Answer
I am creating a Third Person game and i just add the player mesh to the camera like this.-

```
camera.add(charactermesh);

```

That is a simple way of moving the camera with your mesh.Hope this helps
> 0 votes

---
Tags: javascript, three.js
---


title: Creating Dictionary from JSON file

text:
# Question
Title: Creating Dictionary from JSON file
```
[System.Serializable]
public class JsonList
{
    public string Name;
    public List<string> Content;
}

[System.Serializable]
public class Root
{
    public List<JsonList> Story;
    public List<JsonList> Quest1;

    Dictionary<string, Dictionary<string, List<string>>> _contentLookup;

    public Dictionary<string, List<string>> this[string name]
    {
        get
        {
            return GetContent(name);
        }
    }

    public Dictionary<string, List<string>> GetContent(string name)
    {
        return _contentLookup[name];
    }

    public void CreateDic()
    {
        _contentLookup = new Dictionary<string, Dictionary<string, List<string>>> { };
        foreach (var item in Story)
        {
            if (!_contentLookup.ContainsKey(nameof(Story)))
                _contentLookup.Add(nameof(Story), new Dictionary<string, List<string>> { });

            _contentLookup[nameof(Story)].Add(item.Name, item.Content);
        }
    }
}

```

Let's say I have `Root a;`, so I would access different `List<string>`s like this: `a["Story"]["Cave_start"]` (assume I've called `a.CreateDic()` and all of the keys such as "Story" exist)

The problem is that it's not efficient. if I want to access `Quest1` then I have to manually add

```
foreach (var item in Quest1)
        {
            if (!_contentLookup.ContainsKey(nameof(Quest1)))
                _contentLookup.Add(nameof(Quest1), new Dictionary<string, List<string>> { });

            _contentLookup[nameof(Quest1)].Add(item.Name, item.Content);
        }

```

in `CreateDic()`

Obviously, this is nothing I would desire to do for Quest2, Quest3, HiddenLevel1, etc. in `Root`.

Any idea how to make it better?

# Answer
The issue was a grave mistake in the JSON file, the structure I used was this:

```
{
  "Story":
  [
    {"Name":"FirstEncounter", "Content":[
      "sample",
      "sample2"
    ]},
    {"Name":"LaGrandDuel", "Content":[
      "sample",
      "sample2"
    ]}
  ],
  "Quest1":
  [
    {"Name":"FirstEncounter", "Content":[
      "sample",
      "sample2"
    ]},
    {"Name":"QuestDetail", "Content":[
      "sample",
      "sample2"
    ]}
  ]
}

```

The problem is that I use `Story` and `Quest1` as **Keys**, not **Values**!

and so I changed the structure to this:

```
{
  "Main": [
    {
      "FamilyName": "Story",
      "Divisions": [
        {
          "Name": "JsonTest",
          "Content": [
            "sample",
            "sample2"
          ]
        },
        {
          "Name": "Jasper_First",
          "Content": [
            "sample",
            "sample2"
          ]
        },
        {
          "Name": "BlackSmith_Sword",
          "Content": [
            "sample",
            "sample2"
          ]
        }
      ]
    },
    {
      "FamilyName": "Quest1",
      "Divisions": [
        {
          "Name": "FirstEncounter",
          "Content": [
            "sample",
            "sample2"
          ]
        },
        {
          "Name": "QuestDetail",
          "Content": [
            "sample",
            "sample2"
          ]
        }
      ]
    }
  ]
}

```

And by doing this you will get rid of writing a new part of code for each `Quest2`, Quest3\`, etc.
> 0 votes

---
Tags: c#
---


# Question
Title: Can a 2 player mobile game support P2P if a dedicated server is used to establish the network?
The dedicated server would be a lobby where all the players connect and find matches. Once a match is found the server hooks to two players and sends them off on a p2p network. Once the match is over, the players would reconnect to the lobby to find a new match. Is this a viable approach? Or does WiFi not handle P2P under any wide band situations (unlike Wifi direct (very local) or bluetooth (extremely close))?

As far as trying it out, I attempted to record an ip address and port number at the server and send that information in a packet to my other mobile device. Once the client A "had" client b's address + port, and vise versa, I assumed I could send messages, but that didn't really seem to work.

I'm using java NIO, so it would look something like this (pseudo):

```
Client A creates a datagram channel and set it to non blocking
Send connection request message to the server using the datagram channels send function
Server receives request and routes the address to the first available client, Client B (already connected and waiting)
Server sends Client A's address, to Client B's address and vise versa
Each client rebinds there datagram channel to the new address
Client A and B should be able to send messages to each other (this though did not seem to work)

```

# Answer
Instead of trying to connect the two players directly, you should use a relay to mediate the connection between the two players. That way, you won't run into NATing issues because the data is being transmitted through a 3rd party.
> 0 votes

---
Tags: java, client-server, matchmaking, peer-to-peer
---


# Question
Title: Converting mesh vertices to world coordinates for raycasting
My goal is to figure out if a point exists within a 3D polygon. To do this here is what I am doing:

1. Load obj mesh

```
from openmesh import *

points = []
triangles = []

mesh = read_trimesh(filename)
for (x, y, z) in mesh.points():
    points.append((float(x), float(y), float(z)))
for (v0, v1, v2) in mesh.face_vertex_indices():
    triangles.append((int(v0), int(v1), int(v2)))

```
2. Use Raycast library to figure out if point exists inside of mesh

```
for x in range(5):
    for y in range(5):
        for z in range(5):
            is_inside = mesh.is_inside(x, y, z)

```

I realized that majority of points are returning false from `is_inside`. I then started to take a look at the mesh file and realized that all the vertices were less than 1:

```
v  0.1234 0.3644 0.4345
v  0.1234 0.3644 0.4313
v  0.1186 0.3493 0.4313
v  0.1186 0.3493 0.4345

```

So, that means that points like (0, 0, 9) would not exist in the mesh. I started reading up and it seems like I need to convert the model coordinate system to the world coordinate system. However, how do I define the world coordinate system? Would I have to create a transformation matrix?

# Answer
You need to choose a different step for your for loops - currently your for loops are checking the co-ordinates at integer increments: (0, 0, 0), (0, 0, 1), ..., (4, 4, 4)

See https://docs.python.org/3/library/stdtypes.html#range for the full documentation.

The key part you will find useful is the definition of range `range(start, stop[, step])`

So, to find points inside the mesh between -1 and 1 with 0.1 step increments, you would do

```
for x in range(-1, 1.1, 0.1):
    for y in range(-1, 1.1, 0.1):
        for z in range(-1, 1.1, 0.1):
            is_inside = mesh.is_inside(x, y, z)

```

Transforming to world co-ordinates would be useful if you had a world co-ordinate system that defines the "position" of the mesh in the world, and the vertex positions are offsets from that, which doesn't appear to be the case.
> 1 votes

---
Tags: python, raycasting, 3d-meshes, coordinates, obj
---


# Question
Title: Animating 3D characters in 2D platformer where the characters don't look good from directly side-on? (Eg. Kirby from Nintendo)
I am working on a 2D platformer with 3D characters where the design/intention is somewhat similar to Kirby:

https://www.youtube.com/watch?v=MuhLDoNobPw

Specifically, Kirby does not look good exactly from side on so just like in the original NES game they keep him somewhat angled towards the screen at all times:

The potential challenge with such a design in 3D is that then when the character "walks", if you animate it accurately, it would be as if they are walking into the camera and off the platform towards you. Yet they obviously cannot do that as it is a 2D platform, so thus it is as if 30-60% of their walking (anything in the direction of the camera) just "slides" under their feet and does not manifest as anything productive. This creates an image almost like they are walking on ice or not truly connected to the ground.

I am new to this situation so I'm not sure if this is something others think about or have debated. It seems to me from the new Kirby platformers (eg. video above) that is what is happening - ie. It looks like they are animated with a "normal" walk cycle but then simply sliding left and right (since they are all slightly angled but can't walk into the camera).

The only other solution would be to animate them almost doing a sideways shuffle like this:

That might work for funny characters and cartoony goons but if your main character is humanoid to any extent I think this will perhaps be even weirder looking.

So it seems to me the three options are:

1. Let the characters stand perfectly sideways so they can walk perfectly in either direction, but then you'll almost never see their full faces which is bad for cartoony characters like Kirby.
2. Let the characters stand on a 3/4 angle and give them a "natural" walk cycle so their feet just slide a bit on the ground to lock to 2D motion.
3. Let the characters stand on a 3/4 angle and give them a sideways shuffle.

I'm just wondering if this is a topic that is ever discussed or contemplated in game development and what people usually do or think about it. It's the first time I'm thinking about this but I imagine many people have thought about the same issue before. Is there a name for any of this stuff as well?

Thanks.

# Answer
It is possible to create animations that make sense in a 3D space. However, it is a different challenge to create animations that look good from every angle, than making animations that look good from a particular one.

---

I want to highlight a few things that remain important regardless if you are doing 2D or 3D:

* You want easy to read poses. And that means proper use of negative space.
* You want to be aware of feet sliding on the ground, because it as it affect the feel of the motion.
* You want proper use of exaggeration. In particular if your character takes small space in the screen, big motions will be easier to understand.

*And I'll also remind you to use references for your animation. And to remind you that you can iterate on your animations.*

---

Please look at the animation of Kirby in 2D games. He always had some feet slide. I believe this is part of the character, not an artifact of the animation.

For a good contrast to Kirby, consider Sonic. Original Sonic also had some feet slide while speeding up, but there it conveys that he was putting effort in accelerating but his feet take a moment to gain traction. Sonic is also a good contrast to Kirby on how it translates to 3D. For that I recommend having a look at the animation of Sonic Generations. In particular, I want to point out that Sonic looks to the side while running, which I believe works better for Sonic than looking slightly to camera.

Now, you mention a less cartoony more humanoid character. Consider the characters in the Castlevania series. In 2D they have the head held steady to the side, with virtually no face features. Some have the torso fully sideways, but most swing their torso so you see both their back and chest at different points of their walk cycle. (Except in Allucard and Soma Cruz - and I'm not sure if somebody else - they have a clear 3/4 angle, they seems a little *\- put glasses -* unnatural). And we can see in The Dracula X Chronicles and in Grimoire of Souls that this style translates well to 3D.

Another character that makes for a good case study is Mega Man. While sticking to 3D side view, we have seen him in 3D looking to the side in Mega Man Powered Up, and we have seen him take something closer to a 3/4 view in Mega Man 11 (and with no feet slide). However, I believe the best adaptation is the one for Smash Bros.

---

The Smash Bros series has excellent examples of faithfully recreating 2D animations in 3D.

Masahiro Sakurai explain in the GDC talk "Development - SUPER SMASH BROS. BRAWL" (Audio at GDCVault (English)) that he documented the poses of the characters from their source material as reference, and created a design document with photos of articulated toys making the poses he wanted, along with their times for the animation. Sometimes he changes poses to work better in the game (e.g. switching what leg was in front). That design document is what the animators used to create the initial animations, over which they iterated to reach the final animations.

Be aware that some of the characters had official 3D models that they had to stick to in Smash Bros - *to some degree, I don't know how much freedom they had, or how easy/hard was to get changes approved*. But that does not apply for characters that are previously only seen in 2D. So they had more freedom with those.

The resulting animations are not a representation of how a real person would move, the path between poses is not always the most realistic (In fact, some animations results in the models self-intersecting, but it is rarely noticiable), and does not look good from every angle… But they are a representation of how the characters move in their games, they recreate the poses very well, and they look good from the angle they have to look good.
> 2 votes

---
Tags: game-design, animation, skeletal-animation, character, character-development
---


# Question
Title: How do I adjust the start diameter of a spotlight in Unity?
To clarify, I'm an experienced 3D modeller, but there are hiccups here and there getting used to Unity's interface.

I'm working with an adjustable spotlight for a game; it can be mounted and directed just like a turret. To do this properly, I need the *start diameter* of the spotlight to match the aperture size of the model. To clarify that this is not the inner diameter, I've made a drawing.

That is, I need to be able to make a spotlight that begins further down its cone. I can't just back the light up, as the emitted light will invariably collide with its own mesh and it won't work at all. I would also have artefacts like the player standing behind it and being lit by some invisible light source...

I expected this to be a lot easier than it is. Can someone point me in the right direction? Thank you!

# Answer
You are asking two different questions in the same post. My answer will address the tricky part of setting a spotlight that accounts for different user-defined parameters.

If you want a light to not illuminate certain GameObjects, simply assign them to a different layer and disable that layer in the Culling Mask property of your Light.

---

So, you want to design a Spotlight by defining its start and end diameters. However, built-in spotlights in Unity are cone-shaped, with no option for a starting area of light. My solution is a workaround on this, by conveniently setting a spotlight to behave as you want.

### Slant angle of a cone

Unity only exposes the Spot Angle variable. Fortunately, we can solve this with simple trigonometry. Geometrically speaking, a Spotlight resembles a cone. If we look at a cone from the side, its silhouette becomes an isosceles triangle. We can then divide such triangle into two complementary, right triangles:

In this context, \\$tan(\theta) = \frac{r}{h}\\$ and therefore \\$\theta = \arctan(\frac{r}{h})\\$. The diameter is twice the radius: \\$d = 2r\\$. Then, the final formula is:

$$ \theta = \arctan(\frac{d}{2h}) $$.

### Slant angle of a truncated cone

Until now, we only had a base diameter. Let's extend this with a new parameter: the top diameter.

The introduction of a new diameter transforms the cone into a truncated cone. A side-view of a truncated cone is an isosceles trapezoid. We can then divide such trapezoid into two complementary, right trapezoid:

We need some more steps before writing a new formula. Let's draw a new line inside one of the right trapezoids, so we divide it into a rectangle and a right triangle:

I'm now assuming you are only interested in the distance between your diameters. So, here \\$h\\$ represents the truncated cone height, not the whole cone height.

Due to similarity, we know that the whole cone's slant angle and the sub triangle's acute angle are the same value. However, we need the length of the opposite edge. Its value is the difference between the base and top radii: \\$l = R-r\\$. Let's plug this value into the formula we used before: \\$\theta = arctan(\frac{R-r}{h})\\$. Finally, let's swap radii for diameters. The final formula is:

$$ \theta = arctan(\frac{D-d}{2h}) $$

Be aware that \\$\theta\\$ is the Spotlight's cone slant angle, not the Spotlight's Spot Angle. The Spot Angle is simply twice the slant angle.

## Sample source code

Let's convert all this maths into code! We are going to create a `MonoBehaviour` script. It will compute the values we need when changing its parameters. Once assigned to the Light GameObject, it will update the light properties automatically:

```
using UnityEngine;

public class CustomSpotlight : MonoBehaviour {
    public float SD {
        get { return _startDiameter; }
        set { _startDiameter = value; }
    }
    public float ED {
        get { return _endDiameter; }
        set { _endDiameter = value; }
    }
    public float H {
        get { return _length; }
        set {
            _length = value;
            float theta = Mathf.Atan2(ED-SD, 2*H);
            float H_add = SD/(2*Mathf.Tan(theta));
            _lt.range = H + H_add;
            _lt.spotAngle = 2 * theta * Mathf.Rad2Deg;
            _lt.shadowNearPlane = H_add;    //EDIT: update near plane distance
            transform.localPosition = -H_add * transform.forward;
        }
    }

    [SerializeField]
    float _startDiameter = 1f;
    [SerializeField]
    float _endDiameter = 2f;
    [SerializeField]
    float _length = 1f;

    Light _lt;

    void OnValidate() {
        _lt = GetComponent<Light>();
        _lt.type = LightType.Spot;

        SD = _startDiameter;
        ED = _endDiameter;
        H = _length;
    }
}

```

This code doesn't check against wrong values or trigonometric edge cases, you should include them if you want to use this in production.

After re-computing values, we must also update the light position. We need this offset because e.g. a constant start radius requires the light source position to move back and forth (because the "outside hull" is still a cone).

Then, we **must** parent the GameObject with the `Light` and `CustomSpotlight` components to an empty GameObject. Such GO will be used to move and rotate the spotlight around the scene, while its child Light will adjust its local transform to get the desired effect.
> 2 votes

---
Tags: unity, lighting, geometry
---


# Question
Title: How can I make pygame use a specific input device as the mouse?
I am working on (not really a game, but it's using pygame so I hope my question is on topic here).

The program appears to be looking at `/dev/input/event0`, which is random USB mouse, just like the desktop environment and everything else is. But what I need is for `pygame.mouse` to be "connected" (not sure of the right word here) to `/dev/input/event2`, which is the USB touchscreen.

I've figured these two paths out by using `evtest /dev/input/event2` and seeing which one responds to being fingered but I have not figured out how to configure pygame to look at the right one, is there a way or is this hardwired somehow?

# Answer
> 1 votes
It turns out that this is controlled by environment variables.

You need to set `SDL_FBDEV`, which controls which framebuffer to use. Then, you can use `SDL_MOUSEDEV` to control which device to use for the mouse.

Something like this:

```
SDL_FBDEV=/dev/fb0 SDL_MOUSEDEV=/dev/input/event2 sudo python3 muffin.py

```

(I haven't yet figured out why I need sudo here to use that framebuffer. It has 660 perms and I'm a member of the `video` group, so maybe some other process is interfering somehow)

---
Tags: input, pygame, linux
---


# Question
Title: Why when the transform position and the radius position is the same it keep changing the transform position?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateAroundTarget : MonoBehaviour
{
    public Transform target;
    public float speed;
    public Vector3 axis;
    public DrawCircle dc;

    private float lastRadius;
    private bool move = false;

    private void Start()
    {
        lastRadius = dc.xRadius;

        move = true;
    }

    private void Update()
    {
        Vector3 radiusPosition = new Vector3(target.position.x, target.position.y, dc.xRadius);

        if (transform.position == radiusPosition)
        {
            transform.RotateAround(target.position, axis, speed * Time.deltaTime);
        }

        if (lastRadius != dc.xRadius)
        {
            move = true;
            lastRadius = dc.xRadius;
        }

        if(move)
        {
            if (transform.position != radiusPosition)
            {
                float step = 1 * Time.deltaTime;
                transform.position = Vector3.MoveTowards(transform.position,
                    radiusPosition, step);
            }
        }
    }
}

```

The transform is moving towards the radius position and then should start rotating on the radius.

The problem is that after the transform is reaching the radius position and for example the transform position and the radius position is the same and true :

In this case the position of the transform and the radiusPosition is "(0.0, 0.0, 2.0)" and the condition is true but still it's getting inside and changing the transform position.

So it's not moving between the lines :

```
transform.RotateAround(target.position, axis, speed * Time.deltaTime);

```

And

```
float step = 1 * Time.deltaTime;
                transform.position = Vector3.MoveTowards(transform.position,
                    radiusPosition, step);

```

I can't figure out why.

What i'm trying to archive is to make the transform to move on the start towards the radius and then to start rotating around on the radius. but for some reason the IF conditions are not working as expected.

The transform is rotating around it self and shaking like it's trying to move/rotatearound but never rotate around.

# Answer
The problem is you are using `if (transform.position == radiusPosition)` and it rarely becomes `true` because the two vectors are rarely the same. (even if they are visually the same Vector, your programs detects a very small difference like `0.000007`)

What you should do is using this code: `if(Vector3.Distance(transform.position, radiusPosition) <= 0.2f)` And using it, `transform.RotateAround(target.position, axis, speed * Time.deltaTime);` should be called just as you've expected
> 1 votes

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


# Question
Title: Unity: How to "make sure GameObjects are aligned"?
I'm following the "Unity Essentials" tutorial series on learn.unity.com. In the module Create a structure with primitives, it says,

> As you build this structure, you might want to change your view of the Scene to make sure GameObjects are aligned. For a review, see Navigating the scene.

I do not understand what it means by "change your view of the Scene to make sure GameObjects are aligned". I have previously completed the linked tutorial, and I reviewed it again to see if I missed something; I can find no reference to the alignment of Game Objects. I understand that it is possible to align scene view to camera view (select camera, then choose Game View \> Align view to selected), but I'm not certain that is what is meant. Google searching has turned up several hits for aligning objects to one another by a certain attribute (center, corner, etc) but that also sounds wrong.

What is the intent of the instruction, and what's the best way to achieve it?

# Answer
> 3 votes
The term simply means to:

* Move/Pan (use the hand tool)
* Orbit (drag with left-click while holding alt)
* Zoom (drag with right-click while holding alt)
* Focus (by pressing the **F** button while your cursor is in the scene view and the game object is selected)

To ensure that your structure looks just as you want. Though, if your future project is 2D then there is no need to orbit around as it is not available.

The main thing to remember here is from which angle the object would be seen in the game, if you have a fixed camera then it just needs to be okay in that angle (this is more of a personal preference than a fact)

Also, have a look at the flythrough mode, It's used for navigating too.

---
Tags: unity, 3d
---


# Question
Title: How can I calculate the average probability of drawing one of many combos out of a deck of size n?
Let's say I have a deck of n cards (e.g. 50), and will draw x cards from it (e.g. 5). I also have a few combos that are derived from combining two or more cards, and want to know if at least one of them was found in my hand.

For example, let's say my decklist looks like this:

```
Card A x3
Card B x3
Card C x1
Card D x43

```

and I have a few combos:

```
Combo 1
Card A + Card B

Combo 2
Card B + Card C

Combo 3
Card A + Card D + Card D

```

Thus, one possible hand that would be considered successful is `Card A, Card A, Card D, Card B, Card A`, since `Combo 1` is in that hand.

I've ran a simulation like this across 10,000 different hands, and the percentage of drawing at least one combo has ranged from 7% to 12%. Obviously luck is a factor here, but is there a way for me to calculate an "average" chance that is static? I don't know much about statistics, so I'm not sure how to give proper feedback about these data.

# Answer
> 5 votes
To compute the probability of a success, we count how many ways a success can happen, and divide by how many ways *anything* could happen. That gives us the fraction of all the anythings that are a success.

In this case, our "anythings" are all the possible 5-card hands drawn from a 50 card deck. If we sort the cards in our hand before counting, so the order of dealing doesn't matter (this keeps our numbers a bit smaller), we can use the Combinations function to compute this. You'll see this written various ways:

$$ n C k = Choose(n, k) = \binom n k = \frac {n!} {k!(n-k)!}$$

...or in spreadsheet software like Excel or Google Sheets as `COMBIN(n, k)`. It's the number of unordered subsets of size \\$k\\$ that can be made from an initial set of size \\$n\\$.

For our total hands, that's `COMBIN(50, 5) = 2 118 760`.

To make a combo, we're restricting our choices for part of the hand.

There are 6 families of ways to make Combo 1 (at least 1 A and at least 1 B), where X stands for any of the 44 cards that are neither A nor B:

* **A B X X X**: `COMBIN(3, 1) * COMBIN(3, 1) * COMBIN(44, 3) = 119 196`
* **A A B X X**: `COMBIN(3, 2) * COMBIN(3, 1) * COMBIN(44, 2) = 8 514`
* **A A A B X**: `COMBIN(3, 3) * COMBIN(3, 1) * COMBIN(44, 1) = 132`
* **A A A B B**: `COMBIN(3, 3) * COMBIN(3, 2) * COMBIN(44, 0) = 3`
* **A A B B X**: `COMBIN(3, 2) * COMBIN(3, 2) * COMBIN(44, 1) = 396`
* **A B B X X**: `COMBIN(3, 1) * COMBIN(3, 2) * COMBIN(44, 2) = 8 514`
* **A B B B X**: `COMBIN(3, 1) * COMBIN(3, 3) * COMBIN(44, 1) = 132`
* **A A B B B**: `COMBIN(3, 2) * COMBIN(3, 3) * COMBIN(44, 0) = 3`

So in total that's 136 890 ways to make that combo. Dividing by our total number of hands that's a 6.46085% probability.

We can use a spreadsheet like this one to repeat the calculation for each of the other combos:

That gives us these probabilities:

* Combo 1 P(A \>=1 && B \>= 1) = 6.46085%
* Combo 2 P(B \>=1 && C \>= 1) = 2.29809%
* Combo 3 P(A \>=1 && D \>= 2) = 27.53205%

Now if we just add all these up, we'll get an over-estimate, because we're counting some hands that contain more than one of these combos. So we also need those probabilities:

* Combo 1 AND 2: 0.42081%
* Combo 1 AND 3: 6.39289%
* Combo 2 AND 3: 0.38357%
* All Combos: 0.38357%

So, the probability a hand has at least one combo is the sum of the three single-combo probabilities, minus the three double-combo probabilities (eliminating the double-counts), plus the triple-combo probability (since subtracting the double-counts subtracted all three of our initial counts of these hands, we need to add them back in). That gives 29.47729%.

---
Tags: statistics
---


title: Raycaster Textures Scrolling?

text:
# Question
Title: Raycaster Textures Scrolling?
I am making a raycaster, I Have currently got textures rendering, but with North and South faces it appears that the texture is scrolling infinitely. I have read Shimmering, scrolling/panning a texture but that appears to be a something different. Here is what it looks like here I have been following https://lodev.org/cgtutor/raycasting.html to make the raycaster.

DDA:

```
double cameraX = 2 * x / (double)w - 1;
            double rayDirX = camera.rotation.x + camera.plane.x * cameraX;
            double rayDirY = camera.rotation.y + camera.plane.y * cameraX;
            double deltaDistX = Math.abs(1 / (double) rayDirX) + 0.0000001;
            double deltaDistY = Math.abs(1 / (double) rayDirY) + 0.0000001;
            int mapX = (int)camera.position.x;
            int mapY = (int) camera.position.y;
            double sideDistX;
            double sideDistY;
            int stepX;
            int stepY;
            boolean hit = false;
            int side = 0;

            if(rayDirX < 0) {
                stepX = -1;
                sideDistX = (camera.position.x - mapX) * deltaDistX;
            } else {
                stepX = 1;
                sideDistX = (mapX + 1.0 - camera.position.x) * deltaDistX;
            }
            if(rayDirY > 0) {
                stepY = -1;
                sideDistY = (camera.position.y - mapY) * deltaDistY;
            } else {
                stepY = 1;
                sideDistY = (mapY + 1.0 - camera.position.y) * deltaDistY;
            }
            while(!hit) {
                if(sideDistX < sideDistY) {
                    sideDistX += deltaDistX;
                    mapX += stepX;
                    side = 0;
                } else {
                    sideDistY += deltaDistY;
                    mapY += stepY;
                    side = 1;
                }
                if(!(mapX >= 0 && mapX < width && mapY >= 0 && mapY < height)) {
                    break;
                }
                if(map[0][mapX][mapY] > 0) {
                    hit = true;
                }
            }

```

this following code is what I believe to be the issue:

```
double perpWallDist;
            if(side == 0)  perpWallDist = (sideDistX - deltaDistX);
            else           perpWallDist = (sideDistY - deltaDistY);
            int lineHeight = (int)(h / perpWallDist);
            int drawStart = -lineHeight / 2 + h / 2;
            if(drawStart < 0) drawStart = 0;
            int drawEnd = lineHeight /2 + h / 2;
            if(drawEnd >= h) drawEnd = h - 1;
            int textNum = map[0][mapX][mapY]-1;
            double wallX;
            if(side == 0)
                wallX = camera.position.y + perpWallDist * rayDirY;
            else
                wallX = camera.position.x + perpWallDist * rayDirX;
            wallX -= Math.floor(wallX);
            Texture tex = textures.get(textNum);
            int texX = (int)(wallX * (double)tex.width);
            if(side == 0 && rayDirX > 0) texX = tex.width - texX - 1;
            if(side == 1 && rayDirY < 0) texX = tex.width - texX - 1;
            double step = 1.0 * tex.height / lineHeight;
            double texPos = (drawStart - h / 2 + lineHeight / 2) * step;
            for(int y = drawStart; y<drawEnd; y++)
              {
                // Cast the texture coordinate to integer, and mask with (texHeight - 1) in case of overflow
                int texY = (int)texPos & (tex.height - 1);
                texPos += step;
                int color = tex.getRGB(texX, texY);
                //make color darker for y-sides: R, G and B byte each divided through two with a "shift" and an "and"
                if(side == 1) color = (color >> 1) & 8355711;
                renderer.pixel[y * renderer.width + x] = color;
              }

```

Also, the "renderer" is just a class that holds an array of pixels (stored as RGB) that are later blitted onto the screen.

# Answer
I Found the issue. In the DDA there are these lines:

```
if(rayDirY > 0) {
                stepY = -1;
                sideDistY = (camera.position.y - mapY) * deltaDistY;
            } else {
                stepY = 1;
                sideDistY = (mapY + 1.0 - camera.position.y) * deltaDistY;
            }

```

it was this `if` statement: `if(rayDirY > 0)` needs to be changed to `if(rayDirY < 0)` . the problem was the greater than sign needed to be the less than sign.
> 0 votes

---
Tags: java, textures, raycasting
---


title: Testing player preferences in unity

text:
# Question
Title: Testing player preferences in unity
I have a section of a script that is pretty simple and works but I am wondering the best way to rewrite it to be testable.

```
        var stats = other.gameObject.GetComponent<ItemStats>();
        var itemReturn = other.gameObject.GetComponent<ReturnItemToPositionIfDroppedOrStolen>();

        var prefrenceName = "";

        switch (stats.itemNumber)
        {
            case 0:
                prefrenceName = Constant.Tree_Bark_Upgrade_One_Unlocked;
                break;
            case 1:
                prefrenceName = Constant.Tree_Bark_Upgrade_Two_Unlocked;
                break;
            case 2:
                prefrenceName = Constant.Tree_Bark_Upgrade_Three_Unlocked;
                break;
            case 3:
                prefrenceName = Constant.Extra_Coconut_Upgrade_One_Unlocked;
                break;
            case 4:
                prefrenceName = Constant.Extra_Coconut_Upgrade_Two_Unlocked;
                break;
            case 5:
                prefrenceName = Constant.Extra_Coconut_Upgrade_Three_Unlocked;
                break;
            case 6:
                prefrenceName = Constant.Grandpaps_Cane_Unlocked;
                break;
            case 7:
                prefrenceName = Constant.Whackin_Bat_Unlocked;
                break;
            case 8:
                prefrenceName = Constant.Whackin_Golf_Club_Unlocked;
                break;
            case 9:
                prefrenceName = Constant.Bamboo_Staff_Unlocked;
                break;
            case 10:
                prefrenceName = Constant.Whackin_Mallet_Unlocked;
                break;
            case 11:
                prefrenceName = Constant.Whackin_Hammer_Unlocked;
                break;
            case 12:
                prefrenceName = Constant.Crabby_Bomb_Unlocked;
                break;
            case 13:
                prefrenceName = Constant.CraboPolt_Unlocked;
                break;
            case 14:
                prefrenceName = Constant.Big_Bomb_Unlocked;
                break;
            case 15:
                prefrenceName = Constant.Sap_Bomb_Unlocked;
                break;
            case 16:
                prefrenceName = Constant.Boombox_Unlocked;
                break;
            case 17:
                prefrenceName = Constant.Inflatable_Palm_Tree_Unlocked;
                break;
        }

        var hasItem = PlayerPrefs.GetInt(prefrenceName, 0);

```

I could set up an individual test to make sure the correct pref string is returned but wondering if there is a less breakable way

```
public class PreferenceHelper
{

public string getItemPreferenceByNumber(int num)
{
    switch (num)
    {
        case 0:
            return Constant.Tree_Bark_Upgrade_One_Unlocked;
        case 1:
            return Constant.Tree_Bark_Upgrade_Two_Unlocked;
        case 2:
            return Constant.Tree_Bark_Upgrade_Three_Unlocked;
        case 3:
            return Constant.Extra_Coconut_Upgrade_One_Unlocked;
        case 4:
            return Constant.Extra_Coconut_Upgrade_Two_Unlocked;
        case 5:
            return Constant.Extra_Coconut_Upgrade_Three_Unlocked;
        case 6:
            return Constant.Grandpaps_Cane_Unlocked;
        case 7:
            return Constant.Bamboo_Staff_Unlocked;
        case 8:
            return Constant.Whackin_Bat_Unlocked;
        case 9:
            return Constant.Whackin_Mallet_Unlocked;
        case 10:
            return Constant.Whackin_Golf_Club_Unlocked;
        case 11:
            return Constant.Whackin_Hammer_Unlocked;
        case 12:
            return Constant.Sap_Bomb_Unlocked;
        case 13:
            return Constant.Crabby_Bomb_Unlocked;
        case 14:
            return Constant.Boombox_Unlocked;
        case 15:
            return Constant.CraboPolt_Unlocked;
        case 16:
            return Constant.Inflatable_Palm_Tree_Unlocked;
        case 17:
            return Constant.Big_Bomb_Unlocked;
        default:
            return "";
    }
  }
}

```

Test :

```
    [UnityTest]
    public IEnumerator UserGetsTreeBarkUpgrade()
    {
        int num = 0;
        String pref = _preferenceHelper.getItemPreferenceByNumber(num);
        Assert.AreEqual(pref, Constant.Tree_Bark_Upgrade_One_Unlocked);
        yield return null;
    }

```

# Answer
> 2 votes
This looks like a job for an enumeration type!

```
public enum ItemId {
      TreeBarkUpgradeOne,
      TreeBarkUpgradeTwo,
      TreeBarkUpgradeThree,
      //...
      InflatablePalmTree
}

```

Now instead of a `public int itemNumber`, your `ItemStats` component has a `public ItemId id`.

Bonus: this gives you a drop-down in the Inspector that's a lot more legible than a bunch of magic numbers, and it still fits in the same `int` worth of storage and serializes/deserializes fine, because an `enum` value is still just a number under the hood.

You can then use these names directly as your player prefs IDs:

```
public static string GetPreferenceName(ItemId id) => id.ToString();

```

Or you can modify the name:

```
public static string GetPreferenceName(ItemId id) => $"{id}_Unlocked";

```

Or if you need names that are very different than the internal names of your enum members, and not in a consistent way you can boil down to a formula, you can store those in an array and look them up by exploiting the fact that an `enum` value is an integer:

```
static readonly string[] ITEM_PREFS_IDS = new string[] {
    "Tree Bark Lv 1",
    "Tree Bark Lv 2",
    //...
    "Inflatable Palm"
};

public static string GetPreferenceName(ItemId id) =>ITEM_PREFS_IDS[(int)id];

```

With any of these, your prefs string lookup is just a one-liner instead of a massive switch statement.

For the first two, you may not even need a test for this at all, since you're guaranteed that the names the designer sees in the inspector when configuring the item will always map 1:1 with the prefs names generated from them.

The last option with the array gives you more flexibility to work with two different nomenclatures, but you do introduce an extra point of failure where the array and the enum could get out of sync (say you reorder items, or insert/remove items in one place but not the other).

For that, you're basically back to your switch statement to have a second, independent check. But you can write that more concisely with a little helper:

```
static void CheckPrefsIdMatch(ItemId id) {
    string expected = id switch
    {
        ItemId.TreeBarkUpgradeOne => "Tree Bark Lv 1",
        ItemId.TreeBarkUpgradeTwo => "Tree Bark Lv 2",
        //...
        ItemId.InflatablePalmTree => "Inflatable Palm",
        _ => "Unknown ID!"
    };
    string observed = GetPreferenceName(id);
    UnityEngine.Assertions.Assert.AreEqual(expected, observed,
         $"Mismatched prefs id for Item Id {id}: expected {expected} but found {observed} instead."
    );
}

```

Then your tests can be simpler and less repetitive:

```
[UnityTest]
public IEnumerator UserGetsTreeBarkUpgrade()
{
    CheckPrefsIdMatch(ItemId.TreeBarkUpgradeOne);
    yield return null;
}

```

But the obvious downside is that now if you want to change your item IDs, you have to change them in *three* places: the `enum`, the array, *and* the test. So for that reason, I'd generally lean toward the options that use the `enum` names/values directly, without any secondary name storage anywhere that could go out of sync. Minimize surface area for potential bugs.

# Answer
> 0 votes
using `switch` and `case` this way doesn't seem to be convenient.

Why not create a list? then you can just write `MyList[num]`

And for testing, you can use a loop:

```
for (int i = 0; i < MyList.Length; i++)
{
    print (getItemPreferenceByNumber(i));
}

```

or you can completely remove getItemPreferenceByNumber():

```
for (int i = 0; i < MyList.Length; i++)
{
    print (MyList[i]);
}

```

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


# Question
Title: How do game clients handle actions that occurred in the past?
Imagine you’re playing an online game with consistent latency. Your local clock is synced closely with the server.

Your character is moving along a straight line, you’re receiving information about the actions of the things around you, life is good.

You experience a latency spike and receive no data for 2 seconds. The local clock and simulation keeps chugging along, and then suddenly you receive a flood of actions that took place in the past.

If the code assumes that time is monotonic and going back in time isn’t possible, how can you resolve this divergence or prevent the local simulation from getting too far ahead?

# Answer
For a short period of time you can extrapolate/predict movement, and then interpolate when the connection is working again.

However, it makes less sense to do that as the period with no data becomes longer, since the state the player sees is bound to differ more and more from the truth. How long you can afford to rely on this approach depends on the game (a game that requires quick user reactions can't afford as much latency as - say - a turn based game).

At some point the best idea is to put at indicator on screen if it is not getting data for for a while (e.g. half a second). That way the player is aware that there is some issue with the connection - if things moving weird or stopping moving was not enough clue.

When the connection is working again, the client can simulate the actions it got and warp everything to the result. Yes, it would be jarring, but so is the period with no data.

Furthermore, if the server is not getting data from the client for several seconds (e.g. five seconds), you can have the server consider it a disconnection and stop sending data.

Then when the connection is working the client, the client can ask for the current state. This mechanism should take care of situations where simulating all the actions would be take longer than just requesting a full state update.

*Engineer the means to interrupt the connection to test the solution works correctly. And take advantage of said testing to tweak the time periods to something sensible for your game. It might very well be that after two seconds you should consider it a diconnection.*
> 2 votes

---
Tags: networking, client-server
---


# Question
Title: How to duplicate a transform and then disable the original transform and keep the clone?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Cinemachine;

public class MyOtherScript : MonoBehaviour
{
    public Transform target;
    public bool go = false;

    private bool once = false;

    private void Start()
    {

    }

    private void Update()
    {
        if (go && once == false)
        {
            GameObject newobj = Instantiate(transform.gameObject) as GameObject;
            newobj.transform.localPosition = transform.localPosition;
            transform.gameObject.SetActive(false);

            once = true;
        }
     }
}

```

Even if I'm using the `once` flag bool to make sure it will Instantiate only once, for some reason it's Instantiating nonstop cloning all the time.

Also, the cloned objects are have `activeSelf == false`, not the transform itself.

I want to make some kind of replacement between the transform this script is attached to and a clone of the transform. I want to use this to simulate smooth unparenting of the transform.

Doing just:

```
transform.parent = null;

```

is ugly, so I want to make the unparenting to be smooth, slow, and much more natural than just setting it to null. So instead of unparenting it, I thought it would be good to clone it at the right time and position.

This script is triggered by an event in my animation to mark the time I it to unparent:

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

public class DropObject : MonoBehaviour
{
    public MyOtherScript myotherscript;

    public void DropEvent()
    {
        myotherscript.go = true;
    }
}

```

# Answer
> Even if I'm using the `once` flag bool to make sure it will Instantiate once for some reason it's Instantiating nonstop cloning all the time

This becomes obvious if you think about it for a moment.

1. Your original object (which has `go == true` and `once == false`) instantiates a clone of itself.

This clones the *whole* object, including the `MyOtherScript` component with all its variables (including `go == true` and `once == false`)

Your original object then sets its own `once = true` (but not the clone's) and turns itself off.
2. Now your cloned object gets *its* `Update()` called. Since it was spawned with an exact copy of the variables in your original (`go == true` and `once == false`), it proceeds to clone itself, then turn itself off.
3. Now the clone of the clone gets *its* `Update()` called...

etc.

> the cloned object/s \[have\] SetActive false and not the transform itself.

Check the API documentation for the `Transform` component. `SetActive()` is not there. A `Transform` component does not have an active or inactive state.

Now look at your code:

```
transform.gameObject.SetActive(false);

```

You *do not* tell the `Transform` to become inactive. You tell ask the `Transform` "Hey, what `GameObject` are you attached to?", and then you take its reply and tell *that `GameObject`* to become inactive.

> I want to make some kind of replacement between the transform this script is attached to and a clone of the transform

> I want to simulate smooth unparenting the transform.
>
> doing just :
>
> ```
> transform.parent = null;
>
> ```
>
> is ugly, so I want to make the unparenting to be smooth, \[slow, and\] much more natural

It is not clear to me what this even means, but I'm fairly confident that whatever it is you want to do, the way you have chosen is not an effective route to that goal.

I would recommend asking a new question. Take a step back from this code and try to describe the current situation in your game. Explain what player-observable behaviour you want, and ask how to achieve that behaviour. In particular, explain what specific unwanted outcomes arise from `transform.parent = null` \- we need to understand clearly what problem we are solving to be able to offer an effective solution.
> 3 votes

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


# Question
Title: How to handle bloat that comes with derivative ScriptableObjects?
I have ScriptableObjects with special code functions that all are slightly different in their interaction, all derived from one main ScriptableObject. This has lead to making the ScriptableObject script and then having to use the CreateAssetMenu attribute and then making the actual instance in the inspector. It creates a situation where I have two files bloating up the project, once I get many different derived ScriptableObjects it gets quite chaotic. How would I solve this?

To further clarify, I have "Pickups" that contain special functionality for what they do, some heal you, some give you bonuses, some move you in a certain direction, some change your gravity, work over time effects.. etc. so I'm using ScriptableObjects to handle the functions of them and the data. When you activate them they call an Activate function, a Tick function, and a Deactivate function, and all the special code is in there so it's not bloating up the player classes with each individual pickup code.

# Answer
I hear what you are saying; my solution is simply to keep the project organized so that the scripts are in one folder, and the objects themselves in another.

In the example below I have numerous "TileBehavior" scripts which all derive from an abstract base TileBehavior that derives from ScriptableObject.

Many (but not all) of the Objects that are created from them are singletons and I put them all at the root of a TileBehavior folder, in the case where there are multiple versions of an Object I put them in child folders named accordingly.

To group similar types of objects into a single context submenu, you can use a path-like structure in the menuName parameter of the `CreateAssetMenu` attribute:

```
[CreateAssetMenu(menuName = "TileBehaviors/Break Up Tile Behavior")]

```
> 0 votes

# Answer
I think your question is two parts: how do I deal with a massive number of subclasses and how do I deal with many data objects. I'll address the first question.

> To further clarify, I have "Pickups" that contain special functionality for what they do, some heal you, some give you bonuses, some move you in a certain direction, some change your gravity, work over time effects.. etc

You could change the way you think about your behaviours to be less specific. Instead of a pickup that heals you, create one that modifies one of your stats for a period of time. Then a single ScriptableObject behaviour can heal, damage, decrease speed, increase damage, etc. The time period could accept a negative value meaning that it's permanent.

A stat could be another scriptable object -- while this adds a new family of scriptable objects, they'd be a smaller set that is less likely to grow and are heavily referenced in your pickup behaviours.

This would reduce the number of pickup ScriptableObject classes you write, but you'd have the same number of ScriptableObject instances. For those, put them in folders and use project search to keep them clean.

---

For another take on this problem: try using Unity's quicksearch to activate the "Create Asset" menu and to locate your ScriptableObject instances.
> 0 votes

---
Tags: unity, architecture
---


# Question
Title: Unity: How to determine and highlight map region under mouse pointer efficiently
In a 3D Scene, I have a table asset on which sits a game board asset, displaying a map with countries. My map is quite large- 7776 × 3456 pixels. The Main Camera looks down at an angle, can be moved via WASD controls, and be zoomed in/out by moving along its local Y axis (relative to the "look down" angle). This is all working well.

Next, I want to identify, and highlight, the "region" on the map (country, ocean, etc.) under the mouse cursor. Region borders are irregular (like a world map). The region count will be under 255, so I could use a single byte index to identify each region. I have a strategy that I believe should work:

1. Create another copy of my map image, painting each region in a different color (call this the "country mask"). If I can save this as a "palletized" image, or a single-channel greyscale image, I can just use the pixel value (0-255) as the index of the map region. Load this into memory without displaying it.
2. Trace a ray from the camera, through the mouse, onto the game board map, getting the coordinates on the map (texture) where the ray hits.
3. Use those coordinates to get the color of the same location on the Country mask, and read the pixel value to get the map region index. This solves the Identification requirement.
4. To solve the highlighting requirement, use the country mask in some fashion to highlight the hovered country. For example, if map region 29 is selected, I should be able to identify all pixels in the country mask with pixel value 29, then use that as a mask to apply some sort of effect on the actual map for just those pixels.

This leads me to the following questions:

1. What's the most efficient way to load the country mask as a 2D array of index values? Ideally, 1 byte per pixel as opposed to 3 or 4 color channels.
2. Is there a particular image format that I should use for the mask texture asset to facilitate this (e.g., storing only 1 byte per pixel).
3. What's the right way to implement step 4? I'm sure that iterating all the pixels in both images via x/y loops would be very slow.

# Answer
I solved this problem once by creating my map in Blender and then slicing it into separate objects for each region. The map doesn't even need to be 3d for that. You can just create a plane, put your 2d map texture on it, and then slice it.

Or alternatively, if you want to do this completely within Unity, you can do that with ProBuilder. Create a plane with your map texture, and then use the "Cut" and "Detach faces" tools to slice it into countries.

That way each country is now a separate gameObject with a separate mesh and an own MeshCollider. This also allows to change the material properties of each country individually. You can use that to color countries depending on who controls them or highlight the country under the mouse cursor.
> 1 votes

---
Tags: unity, c#, textures, maps
---


# Question
Title: How to design a save system for both desktop and webgl builds?
I am in the process of designing a save system for a game. I would like to save to a file and upload this file online so that it can be securely accessed via login from any computer. This works fine for a desktop build but I would also like to have a webgl build accessible online so players can play the game without needing to install the desktop version. However webgl does not support a file based system for saving/loading and uses playerprefs instead.

I am trying to work out if there is a way that these two builds can coexist so that if one build is played the progress will be saved and picked up when continuing in the other build. At the same time though playerprefs obviously has a limit to what it can store which is much less than the save file so I am wondering how this would work and what should be saved and loaded and what shouldn't?

# Answer
> 1 votes
You could implement "Cloud Saves". Upload the savegames to an online webservice. You can access a webservice from Unity via the class `UnityWebRequest`. There are countless technology options for implementing a webservice on the server-side, and which one to use depends on personal requirements, preferences and skills. So I will leave this choice to the reader.

In order to permit the player to access the same savegames from multiple devices and web browser, you need to give them personalized account with username and password.

This also gives you the advantage that all the savegames on your own server give you lots of information about how your players play the game, which you can data-mine to find out if your game works the way you intended. But it also means that you need to have a privacy policy and might need player consent for analyzing their savegame data (just storing the savegame data for the user and never looking at it *seems to me* to fall under "legitimate interest" and thus would not require explicit consent, but IANAL).

Unfortunately, this means that you are now responsible for keeping that savegame webservice running indefinitely, or the game becomes unable to save which could render it unplayable. So in order to still keep the game playable when the server is offline, you might still want to use PlayerPrefs as the primary source of truth and synchronize the data stored in PlayerPrefs via webservices when possible.

---
Tags: unity, savegame
---


# Question
Title: In a portal-based engine where Items are owned by a room, how to do inter-room collision detection?
My engine consists of Rooms. Rooms are connected via Portals. Items have a `roomNumber` field to indicate which room they belong to. And rooms have a linked list of items they have.

How would I achieve inter-room collision detection between items without iterating over each item?

If I have an item that is so big it crosses portals from room A, to room B to room C should be potentially colliding with items from room A,B and C.

Since it's portal based, it is possible that rooms overlap but items on the same 3D coordinate should not collide, so a conventional 3D structure won't fit on the first glance

# Answer
> 1 votes
The naive approach would be to do collision detection by not just querying the room but also the adjacent rooms, but this does not cover the case that an item might be so large that it passes through multiple rooms.

So we need a different solution.

One would be to dissolve the ownership of items by rooms and have an object which intersects multiple rooms owned by *all* those rooms. But you might have other reasons for maintaining a `1:n` relationship between rooms and items. In that case you might need a separate linked list of items per room which are *in* the room but not *owned by* the room.

Keep in mind that this will create some redundancies in case of collisions which happen on edges. When both A and B are on the edge between the same two rooms, then they will be found in both rooms. So when you check for collisions with A, you will find B twice. So you might want to use a three-step process for collision detection:

1. Create a list of potentially colliding items by iterating the "owned" and "inside" lists of all rooms the current item intersects.
2. Remove all duplicates from that list.
3. Check for collision.

You could combine 1 and 2 by storing the potentially colliding items in a binary tree instead of a list. That allows you to detect duplicates the moment you try to insert them into the tree and discard them.

---
Tags: collision-detection, algorithm, portals
---


# Question
Title: Unity addressables errors with Android split binary
We're using Unity 2020.3.18f1 and Addressables 1.19.4 (we've also tried 1.18.15)

Google requires us to split the game up before uploading it to the google play store. We built the game into an .apk and an .obb file and after installing it, the game crashes immediately with Addressables errors.

Installation Procedure:

1. Build the game with split binary option checked
2. adb install game.apk
3. adb push main.4.studio.shortsleeve.game.obb /sdcard/Android/obb/studio.shortsleeve.game/

I verify that the obb file is there, then I run the game and get the following errors. I've also tried the build & run option to make sure the OBB ends up in the correct location.

```
09-15 10:50:56.639 27740  2255 E Unity   : RemoteProviderException : TextDataProvider : unable to load from url : jar:file:///data/app/~~689q54a8zSXXloEqeqgmbA==/studio.shortsleeve.voodoodetective-XMFOqP0J2uMakI-c6HOVJQ==/base.apk!/assets/aa/settings.json
09-15 10:50:56.639 27740  2255 E Unity   : UnityWebRequest result : ProtocolError : HTTP/1.1 404 Not Found
09-15 10:50:56.639 27740  2255 E Unity   : ResponseCode : 404, Method : GET
09-15 10:50:56.639 27740  2255 E Unity   : url : jar:file:///data/app/~~689q54a8zSXXloEqeqgmbA==/studio.shortsleeve.voodoodetective-XMFOqP0J2uMakI-c6HOVJQ==/base.apk!/assets/aa/settings.json
09-15 10:50:56.639 27740  2255 E Unity   :
09-15 10:50:56.639 27740  2255 E Unity   : System.Action`2:Invoke(T1, T2)
09-15 10:50:56.639 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:set_OperationException(Exception)
09-15 10:50:56.639 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:Complete(TObject, Boolean, Exception, Boolean)
09-15 10:50:56.639 27740  2255 E Unity   : UnityEngine.ResourceManagement.ResourceProviders.InternalOp:CompleteOperation(String, Exception)
09-15 10:50:56.639 27740  2255 E Unity   : UnityEngine.ResourceManagement.ResourceProviders.InternalOp:RequestOperation_completed(AsyncOperation)
09-15 10:50:56.639 27740  2255 E Unity   : System.Action`1:Invoke(T)
09-15 10:50:56.639 27740  2255 E Unity   : UnityEngine.AsyncOperation:InvokeCompletionEvent()
09-15 10:50:56.639 27740  2255 E Unity   :
09-15 10:50:56.640 27740  2255 E Unity   : RuntimeData is null.  Please ensure you have built the correct Player Content.
09-15 10:50:56.640 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.InitalizationObjectsOperation:Execute()
09-15 10:50:56.640 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:InvokeExecute()
09-15 10:50:56.640 27740  2255 E Unity   : System.Action`1:Invoke(T)
09-15 10:50:56.640 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.<>c__DisplayClass57_0:<add_CompletedTypeless>b__0(AsyncOperationHandle`1)
09-15 10:50:56.640 27740  2255 E Unity   : System.Action`1:Invoke(T)
09-15 10:50:56.640 27740  2255 E Unity   : DelegateList`1:Invoke(T)
09-15 10:50:56.640 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:InvokeCompletionEvent()
09-15 10:50:56.640 27740  2255 E Unity   : UnityEngine.ResourceManagement.ResourceManager:ExecuteDeferredCallbacks()
09-15 10:50:56.640 27740  2255 E Unity   : UnityEngine.ResourceManagement.ResourceManager:Update(Single)
09-15 10:50:56.640 27740  2255 E Unity   : System.Action`1:Invoke(T)
09-15 10:50:56.640 27740  2255 E Unity   :
09-15 10:50:56.641 27740  2255 E Unity   : OperationException : Addressables - Unable to load runtime data at location UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationHandle`1[[UnityEngine.AddressableAssets.Initialization.ResourceManagerRuntimeData, Unity.Addressables, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]].
09-15 10:50:56.641 27740  2255 E Unity   : System.Action`2:Invoke(T1, T2)
09-15 10:50:56.641 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:set_OperationException(Exception)
09-15 10:50:56.641 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:Complete(TObject, Boolean, Exception, Boolean)
09-15 10:50:56.641 27740  2255 E Unity   : UnityEngine.AddressableAssets.Initialization.InitializationOperation:Execute()
09-15 10:50:56.641 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:InvokeExecute()
09-15 10:50:56.641 27740  2255 E Unity   : System.Action`1:Invoke(T)
09-15 10:50:56.641 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.<>c__DisplayClass57_0:<add_CompletedTypeless>b__0(AsyncOperationHandle`1)
09-15 10:50:56.641 27740  2255 E Unity   : System.Action`1:Invoke(T)
09-15 10:50:56.641 27740  2255 E Unity   : DelegateList`1:Invoke(T)
09-15 10:50:56.641 27740  2255 E Unity   : UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:InvokeCompletionEvent()

```

I've verified that the game runs when it's built into a standard .apk. As far as I am aware, the addressables library should be assigned to the auto-generated streaming assets pack by default. That's from an official Unity representative.

> Since Addressables moves all content to StreamingAssets during a player build, by default all your Addressables content will be assigned to the auto-generated streaming assets pack. The sample project primarily demonstrates how to assign content to custom fast-follow or on-demand asset packs. We have also taken the approach of assigning any content meant for install-time delivery to the streaming assets pack.

But that doesn't seem to be the case? Or something else is going wrong? We're a little stumped over here and there's very little documentation. Any help would be appreciated.

UPDATE 1: All Resources.Load() calls are failing to load data too.

# Answer
> 0 votes
This is a bug in Unity for specific Android devices (in this case, Galaxy S21).

https://issuetracker.unity3d.com/issues/android-streamingassetspath-and-datapath-return-the-path-to-apk-instead-of-obb-when-split-application-binary-is-enabled

# Answer
> 0 votes
Just to drop my issue and solution to it, it might help some other addressables wonderer :)

I also had an issue with loading settings.json from the first Exception in the log posted in the question. The reason for it was that we are exporting android project and then performing build from Android Studio (apk + obb) and then deploying manually on the phone. I believe that settings.json ends up in the the .obb (since it gets copied in StreamingAssets during Player build) and that is why it had trouble loading it. In order to make the work, the following steps should be respected:

1. Connect the phone to PC
2. Copy .apk
3. Install .apk and launch the game (not sure if launching is mandatory)
4. During install the folder will be created in \[your phone\]\Internal shared storage\Android\obb\\\[bundle id\]. **This folder is recreated each time you install the apk so you'll need to copy it each time you reinstall apk**
5. Find your .obb created by Android Studio and rename it to main.\[build version\].\[bundle id\].obb
6. Copy it to the folder from step 4.
7. Launch the game and it should work

---
Tags: unity, android, addressable
---


# Question
Title: How do you pass arguments with UnityEvents?
I was inspired by a great talk at Unite by Ryan Hipple.

https://youtu.be/raQ3iHhE\_Kk?t=28m

His examples didn’t cover passing arguments with UnityEvents

Do I need to extend UnityEvent, GameEvent and GameEventListener from a generic base class for this to work properly?

If so do I need to make a new set of classes for each Type and combination of Types that I want to pass?

Game Event Scriptable Object

```
[CreateAssetMenu]
    public class GameEvent : ScriptableObject
    {
        /// <summary>
        /// The list of listeners that this event will notify if it is raised.
        /// </summary>
        private readonly List<GameEventListener> eventListeners =
            new List<GameEventListener>();

        public void Raise()
        {
            for(int i = eventListeners.Count -1; i >= 0; i--)
                eventListeners[i].OnEventRaised();
        }

        public void RegisterListener(GameEventListener listener)
        {
            if (!eventListeners.Contains(listener))
                eventListeners.Add(listener);
        }

        public void UnregisterListener(GameEventListener listener)
        {
            if (eventListeners.Contains(listener))
                eventListeners.Remove(listener);
        }
    }

```

Listener Class

```
public class GameEventListener : MonoBehaviour
    {
        [Tooltip("Event to register with.")]
        public GameEvent Event;

        [Tooltip("Response to invoke when Event is raised.")]
        public UnityEvent Response;

        private void OnEnable()
        {
            Event.RegisterListener(this);
        }

        private void OnDisable()
        {
            Event.UnregisterListener(this);
        }

        public void OnEventRaised()
        {
            Response.Invoke();
        }
    }

```

# Answer
Yes, you will have to create a sub-class of the `UnityEvent` class as follow:

```
[System.Serializable]
public class GameObjectEvent : UnityEngine.Events.UnityEvent<GameObject> {} // Leave it empty

```

And then:

```
public class GameEventListener : MonoBehaviour
{
    [Tooltip("Event to register with.")]
    public GameEvent Event;

    [Tooltip("Response to invoke when Event is raised.")]
    public GameObjectEvent Response;

    private void OnEnable()
    {
        Event.RegisterListener(this);
    }

    private void OnDisable()
    {
        Event.UnregisterListener(this);
    }

    public void OnEventRaised()
    {
        Response.Invoke( gameObject );
    }
}

```

I have never found an alternative to create a new class for every type, except using `System.Action<your_type>`, but you won't be able to use the Inspector anymore to call the function you want (unless you have a plugin to serialize the System.Action)
> 3 votes

# Answer
(Can't comment but this is expanding on what Hellium said)
Worth noting that you will need to adjust the Raised and OnEventRaised methods accordingly as well:

```
public void OnEventRaised(GameObject gameObject)
{
    Response.Invoke( gameObject );
}

```

Like this in the inspector it will show up to select a dynamic gameObject, which is the one that will be passed on from wherever you're going to be invoking the event:

`EventName?.Invoke(gameObject);`

For me this was useful for this case:
`DamageTakenEvent?.Invoke(collision.gameObject);`
> 0 votes

---
Tags: unity
---


title: Counting scores in a beat game

text:
# Question
Title: Counting scores in a beat game
I'm currently developing a beat game (similar to osu and osu!mania), in which you basically have to press keys at the right time. I would like to calculate a score (x/100), based on the accuracy of the key-press. The beats are saved in a file like this:

```
timestamp (ms) | key
1200 c
1400 a
1400 c
1650 b
...

```

At the moment, if for example the player presses the \[a\] button, the game goes through every beat with the same key and finds the closest, then calculates `beat.timestamp - press.timestamp` and saves this value in an array. The average of these array values is the average reaction time of the player.

Is there a good way of calculating a score that includes edge-cases like what should happen if the player presses a key twice or don't press it at all?

# Answer
> 3 votes
First of all, going through every beat with the same key is absolutely not efficient.

What you should do is to use an array (each member should contain a key and a timestamp which should be retrieved from your file) and look for the next value inside it, whenever the player presses the right button or the time exceeds go to the next one in the list.

And for not pressing a key you should have a `Tolerance` value (which can be used as the game's difficulty too) and if the key wasn't pressed at all, just store the tolerance inside your array.

Another thing to have in mind is that you should add `beat.timestamp - press.timestamp` only if its absolute value is less or equal to `Tolerance`

When the player presses a button (whether it's the correct button or not) you should use a `RestTime` and don't get any input from the user in that time (except for functions like stopping the game)

Finally, I would advise using just a float variable instead of a list for calculating, and after every beat add the data inside it and at the end, when you want to calculate the score use this single line:

`FinalScore = (Tolerance - (Sum / KeysList.Count)) * 100`

Hope it works for you!

# Answer
> 1 votes
Before talking about game design, one note… You say

> the game goes through every beat with the same key and finds the closest

Assuming time goes forward (and I want to come back to that), you should not have to search among the beats that are before the last you found.

---

> Is there a good way of calculating a score that includes edge-cases like what should happen if the player presses a key twice or don't press it at all?

Ern… nope. The question is how forgiving you want to make your game.

First of all, the common design is to take (the absolute value of) the difference between the press time and the target time and put it into brackets (if the difference is less than x time, you get y points, and so on - it could be only one bracket, but usually rhythm games have a few).

*I mention absolute value because the player may rush notes, and that is Ok. Well, not in every game, but in general. In a rhythm game you should not be measuring reaction time, but mastery of the track.*

Furthermore, usually rhythm games don't have an explicit penalty for skipping a note. It is simply score that the player does not get. And similarly double presses get ignored. However, you could add a penalty, which is a way to make a hard mode.

---

By the way, speaking of how you should not be measuring reaction time. There is also input and output latency. You should have a configurable offset to the time to account for that.

---

The game osu! does a great work with modifiers that can increase or decrease the difficulty and the score. You can do the same. One such modifier could be exactly what you are asking: Accepting a penalty for double presses or missed pressed in exchange for a score multiplier.

*You, of course, would mark what modifiers were used in your leader board/high score table. Or track them on a separate leader board/high score table.*

*Oh, and please have the options of half and double time. These are features players expect to have.*

---

Something I find many of these games lack is a good practice mode. I don't mean easy or forgiving mode. I mean a mode that makes delivered targeted practice easier to do.

Yet, it is not hard to conceptualize (some games do this): either mark check points in your track (or detect silences/gaps and use that as check points), then when the player misses a note, rewind time back to the last check point (I remind you I'm talking about a practice mode). *Ok, time does not always go forward, but you still know from where to search.*

If you also consider the periods between check points "sections" and allow skipping to them then players can go right to the part they are having trouble or even past it, for practice, of course. Furthermore, if you show percentage score per section, it helps the player identify area they are having trouble so they can revisit them in practice later.

---
Tags: keyboard, scoring
---