# Question
Title: 2-Color Fonts in Unity? (so maybe called 3-Color including transparent alpha?)
I have been trying to make my game title screen look better. I realised it was because all my fonts have just one colour.

I read some very old threads about a Editor Scripts to extract the font to png format. I then see there is now a way to do it in the 'hamburger' menu of the Font in Inspector.

I had to change my font to be not 'Dynamic' then it allowed me to extract a copy to PNG. I opened this in GIMP and added my white inside the outlines of each character (it had been alpha before this, giving a horrible see-thru effect on the letters).

I put this back into Unity (the new PNG) and used it as the source texture for my Text Shader. However it is still not handling both colours. (Screenshot below). So what can I do using Unity 2020 to achieve better looking text? I've read this: (https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/StyledText.html) and many other pages on Unity site but I am now going around in circles not achieving anything.

Thanks for any help.

EDIT: Since DMGregorys comment. I am posting picture of my import settings on the modified (coloured-in) font PNG file:

EDIT 2: The 3rd screenshot shows the 'Text' objects settings. Note I have changed Material to be my extracted one. 4th screenshot shows that Material's settings

enter image description here

# Answer
> 1 votes
I'm unable to reproduce this problem. Here are the steps I took, following an earlier answer on this topic:

1. Drag a .otf font file into my project folder, and select the font asset this creates.
2. Set its font size to my desired value, and change the "Character" field from "Dynamic" to "ASCII default set"
3. Click the ⋮ at the top-right of the font inspector and select "Create Editable Copy". To make it easier to sort out what was the new versus the old, I named the new font asset, material, and texture "Custom Font Asset" / "Custom Font Material" / "Custom Font Texture".
4. Edit the "Custom Font Texture" in a paint program to have the 2-colour look I wanted.
5. Change the "Custom Font Texture" import settings to use Automatic format (not Alpha-8), Alpha Is Transparency, Alpha Source = Input Texture Alpha, Generate Mip Maps.
6. Create a new Text component in my scene.
7. Set the Text component's Font field to point at my "Custom Font Asset". I left the Material section saying "None".
8. My two-colour font appears in the scene and game view as desired.

---
Tags: unity, fonts
---


# Question
Title: Multithreading vs Asynchronous game loop for multiplayer online game?
I'm trying to create a turn based multiplayer online game where players can be grouped in a room/lobby and play (similar to Ludo but number of players can be more than 4). There can be multiple such rooms at a time.

**Here is brief overview of the game:** The game is not resource heavy. Each player gets his turn to perform some actions for some time (~90 seconds) and meanwhile other players just communicates with server to get the actions performed by the player. There can be multiple game rounds and a winner is declared at the end.

The game state of each room would be different at a given time. Therefore, to manage the game states for all the rooms, I could think of two approaches:

1. **Multithreading approach:** Spawn a new thread for each room and run/manage the game loop and corresponding game states in room specific threads. But if there are too many rooms, the number of threads would be very large and this approach is not feasible as per this answer's comment. However this approach is preferable for mass multiplayer games online games (MMO) as per this answer. I also think this should work for considerable number of rooms because most of the time, threads are waiting for player's actions.
2. **Asynchronous approach:** Here, the game states of all the rooms would be stored in server's memory and whenever any requests is received from any player, the game state object will be retrieved using player's room ID and based on the state, the server will command players in that room. The state will then be updated. There will be only one main thread here.

So my question is what would be the better approach for this type of games, considering the future scaling requirements? Also suggest any better alternatives which I couldn't think of.

# Answer
> 1 votes
You can get the best of both worlds by creating as many threads as you have CPU cores of the server (you might want to make this number configurable in case you have other unrelated threads running at the same time which also require non-negligible CPU load). Then make each thread responsible for managing a set of currently active rooms in sequential order.

To get started you might want to just distribute your game rooms in a round-robin manner. But depending on the usage patterns of the game you might add a more complex load-balancing logic, like assign each room to the thread with the least rooms, or actually measure how much idle time each thread has so you can distribute rooms more evenly.

---
Tags: architecture, multiplayer, game-loop, multithreading
---


# Question
Title: How to best select a texture pair to use in height blending when using a splatmap shader
In my project, I'm implementing a shader to combine up to 4 textures in a terrain using a splatmap texture (https://en.wikipedia.org/wiki/Texture\_splatting).

I want to combine the splatmap blending with the height blending technique, described in: http://untitledgam.es/2017/01/height-blending-shader/. This technique basically defines a function to interpolate between two textures more realistically based on height information.

The problem is, in order to use height blending, I need to know which pair of textures I'll be interpolating, while in the splatmap I actually have four different texture sets (channels, R G B and A).

So what I want to achieve is a shader that will select the pair of textures for which the splatmap channel information is strongest, and interpolate between the two while discarding others. My "naïve" attempt was something along the lines of (simplified version, pseudo-code and only for illustrative purposes):

```
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform sampler2D splat;

void fragment_shader() {
    sampler2D sampler;
    if (splat.r > splat.g) {
      sampler = tex1;
    } else {
      sampler = tex2;
    }
}

```

The problem, I realized, is that I can't store samplers inside a variable like this due to limitations in GLSL. So I'm looking for a soultion that would be similar to this. Particularly, I would want to avoid a solution where I'm sampling all four textures for every texture lookup. That is because I will be using some expensive techniques inside the shader which require several texture lookups, and I don't want to increase the computation cost 2x.

*EDIT* My current attempt to do this consists of computing two vectors to select the maximum and "second maximum" channels. A channel vector would be something like `(1.0, 0.0, 0.0, 0.0)` to indicate the red channel should be used. The implementation is currently looking something like this:

```
vec4 c1, c2;
  float m = max(max(max(splat_val.r, splat_val.g), splat_val.b), splat_val.a);
  if (m == 0.0) {
      c1 = vec4(0.0);
      c2 = vec4(0.0);
  } else {
      c1 = vec4(float(splat_val.x == m), float(splat_val.y == m), float(splat_val.z == m), float(splat_val.a == m));
      vec4 splat_val_2 = splat_val * (vec4(1.0) - c1);
      float m2 = max(max(max(splat_val_2.r, splat_val_2.g), splat_val_2.b), splat_val_2.a);
      c2 = vec4(float(splat_val_2.x == m2), float(splat_val_2.y == m2), float(splat_val_2.z == m2), float(splat_val_2.a == m2));
  }

```

Where `c1` and `c2` end up being the channel vectors for the largest and second largest splatmap channels. I'm still facing some issues when there are multiple elements with the same value though, and I keep thinking there should be a better way to do this.

After I compute the channel vectors, I'd still need a nasty static if structure like the following, so all in all I'm not sure my current attempted solution is a very good one:

```
if (dot(c1, red_constant) == 1.0) {
  if (dot c2, green_constant) == 1.0) {
    do_shader(tex_sampler_R, tex_sampler_G);
  }
  else if (dot c2, blue_constant) == 1.0) {
    do_shader(tex_sampler_R, tex_sampler_B);
  }
} else if (dot(c2, green_constant) == 1.0) {
  // ...
}
// ...

```

# Answer
> 2 votes
We can actually extend the height blending function to compute weights for all four terrain types at once.

We'll take as input a packed 4-vector, whose RGBA channels are the 0-1 height values of each of our four maps, and use it to modify the 4-vector of terrain type weights we read from our splat map.

(I've written this in Unity hlsl syntax, since that's what I used to test the shader, but it should be straightforward to translate to glsl equivalents)

```
void applyHeightsToWeights(float4 heights, inout float4 weights) {

    // Scale the height influence of a type toward 0 as we move away from its zone.
    heights *= weights;

    // Compute the lowest height that could have a non-zero blending weight.
    float height_start = max(max(heights.r, heights.g), max(heights.b, heights.a))
                       - _Height_Blend_Range;

    // Measure only heights above this cut-off.
    heights = max(heights - height_start, 0.0f);

    // Turn these heights into weights, balanced so all four channels sum to 1.0
    weights.rgba = heights/dot(heights, 1.0f);
}

```

The way I used this was to make one texture with my four height maps packed into it as the four channels. That way I could read all four heights with one tap, read the splat map with a second tap, and run them through the weighting function above after only these two texture samples.

This is convenient because you can defer your samples of the four albedo/normal/etc. textures and potentially modify them based on the blended result. Like if you were applying some per-pixel displacement based on height, and needed to shift the colour sampling point accordingly.

Or, if some weights come out "close enough" to zero, you could even skip reading those terrain types' albedo/normal/etc. textures entirely. This can save quite a lot of texture bandwidth, so it may be worth the branches to take advantage of it.

The downside is that all 4 terrain types need to have the same tiling frequency if you want to use this trick.

If you really want to pick just two textures to blend though, you can process this weight 4-vector like so:

```
// Find the greatest weight.
float top = max(max(weights.x, weights.y), max(weights.z, weights.w));

// Zero-out the greatest element.
float4 thresh = (weights < top);
float4 bottom = weights * thresh;

// Find the second-highest weight.
float second = max(max(bottom.x, bottom.y), max(bottom.z, bottom.w));

// Zero-out any elements below second-place.
weights *= (weights >= second);

// Re-balance so the remaining elements sum to 1.0
weights /= dot(weights, 1);

```

Technically this would give incorrect results if two weights tied at exactly the same value, but I haven't observed that occurring in practice.

In the animation above, you can see that limiting the blending to just the top two textures causes a harsher and more speckly-looking cut-off where the sand feathers out into the blending zone between grass and dirt/rock.

The areas where 3+ textures are all blending together at once tend to be quite small though, so you could get away with 2-texture blending most of the time, with a branch for the rare 3-4-way case.

Visualization of the number of textures contributing more than 1% to the result:

* Dark green: 1
* Bright green: 2
* Yellow: 3
* Red: all 4

---
Tags: shaders, textures, terrain-rendering
---


# Question
Title: Intentionally using "worse machines" to develop a game?
I am developing a game intended for desktop computers.

I am afraid of developing a game that will be too costly in aspects of performance, so I am wary of using a machine that might be better than the target devices.

However, I don't know yet what the target devices will look like when my game is finished in 5 years.

How do Indy developers choose a device for developing their game in order not to get carried away with its performance?

Just an example to make it more clear:

If a developer had access to a quantum computer, I guess they shouldn't use it. Else they would lose their ability to estimate the performance on the target devices.

Or is the "developer machine selection approach" not how it's done, and instead, there is simply a certain tri count limit for everything? (I remember that for RE4, there was simply a hard limit for tri count for meshes)

# Answer
Intentionally doing everything on a weak PC when a stronger one is available to you is just masochism. Developers run lots of tools in parallel to the game which require resources, and also do various amounts of offline processing. Game engine editors, IDEs, compilers, graphic and modeling programs, audio processing etc. can take far more resources than the game itself. Even just 30 seconds of additional loading time each time you run the game can be a huge time waster when you do that a hundred times each day. So intentionally using suboptimal hardware is just hampering your work experience and productivity.

Nevertheless, continually testing the game on multiple configurations is part of the Quality Assurance (QA) process of every well-organized game project.

Larger studios can afford to have whole QA labs stacked with dozens of PCs in all imaginable configurations. They hire a couple highly paid QA engineers who create automated test suits, and an army of lowly paid QA testers to play the game manually. That QA department then tests the game over and over during development and reports any new performance or compatibility problems to the development team. When the developers can not reproduce the problems on their development machines, then they occasionally have to borrow one of those test machines to reproduce and fix the problem.

Smaller development teams or solo developer of course don't have the resources to afford such rigorous QA. Nevertheless, it can still be a good idea to have an older/weaker PC around to check from time to time if the game still runs on it. Even just having a single other PC available for testing can catch a lot of those "works on my machine" problems.

Also keep in mind that technology marches on while you are developing your game. When your game is planned for release in 5 years, then the high-end gaming PC you are sitting at right now will be an outdated model on release day. So developing your game for your current specs will give you a pretty wide audience in 5 years. That means if you are going to treat yourself with a new Intel Core i11-14900 with an RTX 5090 GPU in a couple years, don't eBay the old one right away.
> 58 votes

# Answer
What you're trying to do is called "premature optimization" and it's considered a great evil (1st google link https://stackify.com/premature-optimization-evil/)

In short, performance optimization should only be done:

* when it's factually measured to be a real problem (may never happen)
* by measuring performance with dedicated tools and improving only what harms it (usually a very localised part of your code and not the one you would have expected)

You're putting your project in danger at the moment. Instead, you should focus on a MVP and get market feedback as soon as possible (in ~3 month, not 5 years)

Also if your game really takes 5 years to be developed, the machines in 5 years will be much more powerful or maybe a different form factor or architecture.

Not your question but: "indie game 5 years of development" is a red flag. I'd recommend reading https://gamesfromwithin.com/sometimes-you-have-to-let-go Also remember that creating = 50% building 50% marketing.
> 8 votes

# Answer
As an indy developer, I use whatever I have available. In my case, the desktop machine is a couple years old, so I'm not much afraid I'll overwhelm my players.

There are two easy things you can do:

1. Use an engine that allows you easy access to quality settings so that players can change them to match their device.
2. Use a few different machines (friends, etc.) **for testing** \- not for development, but from time to time run the game on those machines to check if it runs smoothly.

Don't overdo it, though and don't wreck your brain too much - see the other comment about premature optimisation.
> 5 votes

# Answer
The following answer talks in general terms. It is definitely possible to purposely make a game that uses 100% of available resources, but in general terms, you shouldn't worry about it.

Modern computers are ridiculously powerful. Unless your game is doing very specialized computations that you know will use all available resources, I think that as an indie developer you are very unlikely to even come close to the limits of modern computers.

The main bottleneck for game development pipelines today is content. Modern GPUs can draw millions upon millions of triangles per second. To get close to the hardware limitations, you need very high definition 3D models that are very expensive to create. We're talking about tens of millions of dollars of budget to make a game with consistently high quality art assets to naturally reach the limits of modern hardware.

On the other hand, a powerful computer lets you do many things at the same time: coding, debugging, graphics editing, audio editing, project management, and so on. Not using a powerful machine for game making is setting up yourself for a world of pain.
> 2 votes

---
Tags: performance, hardware
---


# Question
Title: How to compute the points of a CollisionPolygon2D?
`Godot v3.3.1.stable.mono.official`

---

I am trying to draw a CollisionPolygon2D programmatically but I cannot resize or write the `PoolVector2Array` property called `polygon`:

```
extends CollisionPolygon2D

func _ready() -> void:
    polygon.resize(1)
    print(polygon.size())
    polygon[0] = Vector2.ZERO

```

---

This code prints `0` and throws an error: `Invalid set index '0' (on base: 'PoolVector2Array') with value of type 'Vector2'`.

# Answer
The type `PoolVector2Array` is a value type, and reading `polygon` gives you copy. Use another variable to hold it and edit it:

```
func _ready() -> void:
    var points = polygon
    points.resize(1)
    points[0] = Vector2.ZERO
    polygon = points
    print(polygon.size())

```

If you are going to build it over time, I suggest to add another field, and do the modifications to that field:

```
var _points := PoolVector2Array()

func _ready() -> void:
    _points.resize(1)
    _points[0] = Vector2.ZERO
    polygon = _points
    print(polygon.size())

```

And you would be doing `polygon = _points` every time you need to commit the changes.
> 1 votes

---
Tags: collision-detection, godot, gdscript
---


# Question
Title: Calculate how many degrees a physical device is off centre (offset) given X, Y, Z
Let's say I have a physical device that I can rotate with my hands and receive X Y Z coordinates of that device. What I need to calculate is the offset - how far is the pendulum of gravity straight down. Basically how many degrees I am off centre. Is there a way of doing so? I've googled a lot of questions but so far I'm struggling.

Thanks.

**Updated:**

There is a physical device (sensor) which I can rotate. The device sends its X Y Z coordinates and a calculated acceleration vector in mg (mill mg). I can read this data from this device using BLE. The device should lie flat while transportation, so I need to calculate how many degrees the device is off centre (which is the laying flat on table).

**Updated x2:**

I need to calculate the angle between the device's centre vector and a gravity pendulum (the blue angle) on the photo.

# Answer
First, note that accelerometer sensors tend to be noisy — giving rapidly varying values that jitter around the true measure, even when the device is at rest. So you'll likely want to gather up several measurements into a windowed average to smooth out this noise and get a more consistent orientation estimate.

Next you'll want to measure what value the device reports when lying stationary and flat. This will probably correspond to a vector along one of the axes of the sensor, whose magnitude corresponds to 1 g of acceleration. Something like (0, 1000, 0) if your sensor uses units of 1/1000th of 9.8 m/s².

Discard the magnitude to make a unit vector, like (0, 1, 0) in the example above, but keep the sign (ie. if we had (0, 0, -1234) we'd normalize it to (0, 0, -1)). Store this in your program as your "reference direction"

Now you can compute a degree offset from it like so:

```
direction = averageAccel
                * 1/Sqrt(Dot(averageAccel, averageAccel))

cosine = Dot(direction, referenceDirection)

degreeError = Acos(cosine) * 180/PI

```

Here we're using the fact that the dot product between two unit vectors gives the cosine of the angle between them. So we can use the inverse cosine function to turn that into an angle in radians, then rescale that to change the units into degrees.
> 0 votes

---
Tags: 3d, rotation, coordinates, angles
---


# Question
Title: How to maximize enclosed area and minimize perimeter on a grid with obstacles?
Developing an RTS game, I have a tile-based terrain (grid) filled with obstacles. It looks like this (red shapes are obstacles):

Now I need to plan an enclosed area on the terrain with some restrictions:

* tile marked with a "star" must be included (it is a seed)
* area needs to be at least 20 tiles (for this example)
* farthest area tile from the seed needs to be no more than 7 steps away (for this example)
* area needs to traversable by moving in 4 directions
* area should be bound by existing obstacles and by new fences
* new fences building takes time and resources, it is beneficial to use existing obstacles as much as possible and have the smallest number of fences placed.
* there are cases where terrain could be free of any obstacles, or contrary to that - be a maze-like labyrinth)
* it is okay to fail (e.g. there's not enough walkable tiles around the seed), or the area/fences ratio is too low.
* processing is done on CPU (if that matters)

So, here are some "manual" attempts at outlining an area of required size using the least fences:

As you can see, there are 3 enclosed areas (green, blue, orange) with very similar perimeters, yet different areas. Best one in this case would be "green" one - it has the least fences added (just 10) and has the sufficient area (21).

## **What is the algorithm to allow to plan area of given size (~20) while minimizing the amount of additional fences required?**

---

So far I have tried to take the larger area and try to clip it - using BFS to get the area within possible reach (7 steps), clipped the last step (since it is touching the unexplored and has no neighbor info) and clipped the obvious protruding buds - leaves plenty of tiles to work with. I'm out of good ideas on how to improve from that:

* yellow tile is the seed
* red tiles are walkable (saturation shows distance from the seed)
* dark grey tiles are obstacles
* light grey tiles are obstacles that also need fences
* purple tiles got clipped by existing incomplete algo
* black tiles are unexplored
* yellow dashes are required fences

As you can see, it looks quite sub-optimal, but I'm at loss as to how to proceed.

# Answer
> 0 votes
An idea that came to me while typing the question and preparing the pictures:

1. Take existing results (BFS to get the area within reach (7+1 steps)/
2. Clip the last step (since it is touching the unexplored and has no neighbor info)
3. Clip the obvious protruding buds (3 fences around 1 tile)
4. *We could "blow up" all the corners - if 2 fences are to be placed in a zig-zag pattern, we can always flip them to include one more tile while keeping the perimeter the same.*

*however I'm leaving this step for later evaluation, since that would include the yet unexplored tiles into the mix.*
5. Now we can repeatedly scan the resulting area across (horizontal and vertical) and evaluate the side edges to see how many fences would get removed or added if that line was to be clipped:

* white dashes show the sorted candidates for clipping (the more fences we remove and the less area we remove is better).

This gives a quite good result, with a typical 2/1 factor of area/fences.

---
Tags: algorithm, tiles, space-partitioning
---


# Question
Title: Why is is so hard to develop a game console emulator?
I have always found emulators rather fascinating. I would seriously like to create an emulator for an older ganeration console or handheld. It would help me gain a greater appreciation of the hardware and the games which were created for that hardware. However, people are always saying how hard it is and that I should not even try. I would like to know why that is.

Also, I would like some suggestions on a good place to start and where can I find the information I need?

# Answer
SO Question

This seems to be a popular resource about how they work.

TL;DR - The architecture is totally different, and this takes a lot of parallel resources to achieve the original architecture.

> The CPU architecture for game consoles is often somewhat exotic compared with your average desktop machine. Emulation means to perform in software everything that the original hardware did. That is, while the original console may have had dedicated graphics, audio, etc. chips as well as a CPU with a different instruction set, the emulator must perform all the functions of these parallel resources at speed.
>
> Unless the console's GPU is old, it almost certainly must be emulated on the GPU of the host machine, as modern graphics cards, even cheap ones, have many times the throughput (for graphics workloads) of even the most expensive multicore CPUs. Compounding this difficulty is the fact that communication between CPU, GPU, any other onboard DSPs, and memory was probably highly optimized on the console to take advantage of the specifics of the hardware configuration, and therefore these resources must be rate-matched as well.
>
> Compounding all these difficulties, usually little is known about the specifics of the console's hardware, as this is kept very much under wraps by design. Reverse engineering is getting less and less feasible for hobbyists to do.
>
> To put things into perspective, an architectural simulator (a program which can run, for example, a PowerPC program on an x86 machine and collect all sorts of statistics about it) might run between 1000x and 100000x slower than real-time. An RTL simulation (a simulation of all the gates and flip-flops that make up a chip) of a modern CPU can usually only run between 10Hz and a few hundred Hz. Even very optimized emulation is likely to be between 10 and 100 times slower than native code, thus limiting what can be emulated convincingly today (particularly given the real-time interactivity implied by a game console emulator).
> 15 votes

# Answer
A major difficulty with trying to develop emulators for older machines is that on such older platforms, there are aspects of behavior which weren't intentionally designed to fit together in any particular way, but nonetheless happened to fit together in ways that some game designers have exploited. Sometimes these aspects of design may be documented, individually, in a way that would imply their interactions, but in other situations they might not.

For example, on the Atari 2600, storing a value to HMP0, storing a value to HMOVE on the first cycle of a horizontal blanking, and then waiting awhile before writing to either HMP0 or HMOVE, will cause the player 0 sprite to be moved to the left by a signed 4-bit number of pixels specified in the upper bits of HMP0, i.e. anywhere between 7 pixels left and 8 pixels right. As a side effect, the first 8 pixels of the next scan line will be blanked. If the store to HMOVE happens two cycles before the start of horizontal blanking, however, the start of the next scan line won't be blanked but all sprites will be moved to positions 8 pixels to the left of where they would otherwise have gone. Some programs exploit this to avoid having to the system blank the leftmost eight pixels of the line after the HMOVE.

If the designer of an emulator is aware of this behavior, it may not be particularly difficult to emulate, but the designer of an emulator isn't aware that the HMOVE circuitry works this way, programs that rely upon it would not be emulated correctly. Emulation of older systems is difficult because it's impossible to know about all the behavioral quirks that programs might be expecting. While one could take the attitude that any game which performs an HMOVE two cycles before the specified time is "broken", such an attitude would imply that all games must forego the use of the leftmost 8 pixels on the line after any sprite is moved. Code which uses cycle-74 HMOVEs may be able to achieve a cleaner looking display, and will work either on original vintage hardware or on emulators that support that behavior. Accurate emulation of all games would require knowing all of the aspects of hardware upon which those games would rely, which would be impossible on any system for which unreleased prototype games might exist.
> 1 votes

---
Tags: c++, architecture, hardware
---


# Question
Title: Unity LookAt function. Only looking at 'Root' of object, even if set to look at child transform
I made a small routine to make the camera zoom in to the players face when they finish a level.

It mostly worked, until I tried to make it focus on the players head rather than feet. This time I did read the Unity docs for `Transform.LookAt` but it just says it will point at the `target`.

My player object has its root on the floor. But one of the child objects is `sunglasses` which I would like the camera to `LookAt`.

How I've done this is created a script called `SunGlasses` (purely to add it as a Component on the `Sunglasses` object). Then in my code (below) I find use `GetComponentInChildren` to find the sunglasses of the player and look at that instead. However it still aims at the player's feet.

```
switch (camMode)
        {
            case CAM_MODE.FOLLOW:
                transform.localEulerAngles = camera_eulers;
                transform.position = player.transform.position + camera_position_offset;
                break;
            case CAM_MODE.CELEBRATION:
                Transform sunglasses = player.GetComponentInChildren<SunGlasses>().transform;
                transform.LookAt(sunglasses);
                if (transform.position.y > sunglasses.position.y)
                    transform.Translate(0, -zoomSpeed * Time.deltaTime, 0, Space.Self);
                if (Vector3.Distance(transform.position, sunglasses.position) > MIN_CELEBRATION_DISTANCE)
                    transform.Translate(transform.TransformDirection(transform.forward) * zoomSpeed * Time.deltaTime);
                break;
        }

```

So, the result/problem is that it zooms in to his feet, no matter if I use `player.transform` or `sunglasses` as the argument in my `LookAt` function call.

# Answer
Very simple solution to this (after I spent too much time trying to change my code!). The problem was actually where the pivot to my sunglasses model was located (which is defined during the modelling process in Maya in my case).

The pivot for the sunglasses was on the floor at 0,0,0. This was an error on my part.

To fix, I could have gone into Maya and changed it, reexported the model etc. But actually for my specific scenario, I can just use this same technique with the 'head' object in the players rig.

Thank you to the site admin who is super helpful. A credit to Stack Exchange.
> 0 votes

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


# Question
Title: Should I include 3rd party libraries in my Plugin?
I'm using Firebase services in a custom plugin that will be released later, Should I include all 3rd party libraries like Firebase on the final plugin package or is there another way to handle this in unity ?

# Answer
> 2 votes
There are several reasons why I don't like it when third-party DLLs are included in plugins:

1. There may be copyright/legal issues; does the 3rd-party library (Firebase in this case) *allow* you to include their DLLs in your plugin?
2. If the 3rd-party library is updated after you release your plugin, the DLL files in your plugin will be out of date until you update your plugin.
3. End users may encounter conflicts if they import multiple plugins which use conflicting versions of the 3rd-party library (e.g. your plugin embeds Firebase 7.2.0 and some other plugin embeds Firebase 6.9.0).
4. If the DLLs are large, they may bloat the plugin (increase the download size).

As with most things, there are exceptions. For example, if the third party library was no longer maintained and updated, you wouldn't need to worry about the embedded version becoming out of date. However, Firebase is updated regularly, so that exception doesn't apply here.

The downsides to not including the third-party library are more minor:

* There will be a little extra setup for users who install your plugin
* Major changes to the 3rd-party library may break your plugin, causing headaches for your users. This can be partially mitigated by including a disclaimer in your installation notes, e.g.:

> We officially support Firebase versions up to x.y.z. Newer versions of the Firebase plugin may still be compatible, but please test them thoroughly before shipping your game. If you discover a compatibility issue with a new version of Firebase, please contact us at (email address).

---
Tags: unity, plugin
---


# Question
Title: What data structure do I use to store Archetypes in ECS?
I am implementing an ECS with "archetypes" similar to how they are defined in Unity:

> A unique combination of component types is called an Archetype. For example, a 3D object might have a component for its world transform, one for its linear movement, one for rotation, and one for its visual representation. Each instance of one of these 3D objects corresponds to a single entity, but because they share the same set of components, they can be classified as a single archetype:
>
> In this diagram, entities A and B share archetype M, while entity C has archetype N.
>
> You can fluidly change the archetype of an entity by adding or removing components at runtime. For example, if you remove the Renderer component from entity B, then B moves to archetype N.

I know that an archetype is a group of entities with a specific set of components. However, I am confused as to how to actually store the different archetypes. The tutorials I've found online are all quite vague or opaque. I'm using JS.

My first instinct was to use a hash table using a bit array denoting the set of components as the key and the archetype data structure as the value. However, this doesn't seem to work well in JS because TypedArrays use reference equality.

Another approach I tried was using the bit array as an array of integers which index nested hash tables, but this approach is convoluted and introduces several unnecessary layers of indirection.

A third approach I tried was indexing a hash table using the string representation of the bit array but I'm not sure about the performance implications of this approach. (Strings are slow)

What is the ideal data structure (eg array, hash table, set, etc.) to store archetypes or references to archetypes?

To be clearer, I'm looking for a way to determine which archetype an entity belongs to upon addition/removal of components. I'm also looking for a data structure in which to store that component data such that it is friendly to iteration.

An example is Unity, however, other approaches that work are fine as well.

I'm not looking for specific implementations or code, but if they help explain then that's ok, but rather general ideas or guidelines.

# Answer
**Avoiding conditionals**

I assume some leeway here, as you've asked for a general approach. The point here is to eliminate the main potential bottlenecks. Unless you are creating very large numbers entities per frame (as in e.g. a particle system), it seems unlikely you will ever need such code - but you asked ;)

First we set up our constants:

```
//component type (enum)
const LIFE = 1;
const WEAPON = 2;
const JUMP = 3;
const JETPACK = 4;
const GRAPPLE = 5;
const SLIME = 6;
const TELEPORT = 7;
const COMMANDER = 8;

//entity type (enum)
const GRUNT = 0;
const SCOUT = 1;

//bitfields by entity type (archetypes) - faked as arrays, should have minimal impact on performance.
const bitfieldsByEntityType = {}; //or []
bitfieldsByEntityType[GRUNT] = [1,1,1,0,0,0,0,0]; //has life, weapon, and jump abilities
bitfieldsByEntityType[SCOUT] = [1,0,0,1,0,0,0,1];

```

Then we set up the component creator functions:

```
function creatorFuncNull()
{
    //return undefined; //don't even need to write this, as this is exactly what empty JS functions do.
}

function creatorFuncLife()
{
    //various setup steps here if required
    let component = new LifeComponent(100); //see caveat, below.

    return component;
}
//all your creatorFuncs will return a component this way.
//...TODO define rest of your creator funcs...

```

Next we map the creator functions into an array by unique index, with null creator at `[0]`:

```
const componentCreators = [];
//indices here need to match the above constants
componentCreators[0] = creatorFuncNull; //special at [0], take note
componentCreators[1] = creatorFuncLife;
componentCreators[2] = creatorFuncWeapon;
componentCreators[3] = creatorFuncJump;
componentCreators[4] = creatorFuncJetpack;
componentCreators[5] = creatorFuncGrapple;
componentCreators[6] = creatorFuncSlime;
componentCreators[7] = creatorFuncTeleport;
componentCreators[8] = creatorFuncCommander;

```

The core function that does the work of creation:

```
function createEntity(bitfield)
{
    let i, bit, componentIndex;
    for (i = 0; i < 8, i++) //fixed length loop will be unrolled by the compiler, eliminating loop conditional checks.
    {
        bit = bitfield[i];

        //create and assign to component slot
        entity.components[i] = componentCreators[bit * (i+1)];
    }
}

```

Lastly, make use of what we've created:

```
let bitfield = bitfieldsByEntityType[GRUNT];
let entity = createEntity(bitfield);

```

e.g. if `i == 5`, and the bit is set i.e. `bit == 1`, then we will call into `componentCreators[1*5=5]`, but if the bit is not set, we call `[0*5=0]`, the null creator function. Using multiplication here avoids any conditionals like `if (bit == 0)` or `if (bit == 1)`. Any unset bit will return `undefined` at that component slot for that entity - as it should.

`(i+1)` is used as `bitfieldsByEntityType` assumes LIFE is 0, WEAPON is 1 etc. - whereas `componentCreators` assumes LIFE is 1, WEAPON is 2 - to avoid the null creator function at `[0]`.

Trivial to convert to a true bitfield once comfortable with the approach. For greater understanding, see Strategy Pattern \- including the null strategy pattern, and Builder Pattern.

**Avoiding allocations**

Notice that we call `new LifeEntity()` in the above. This is a massive DON'T, even more so than avoiding conditionals. What you actually need here is to pre-allocate some fixed number of entities before gameplay begins (say 10k) and then assign those into a pool structure (can be just an array or queue if you like) for retrieval (whereupon they are removed from the pool) and immediate re-use; when entities are destroyed, they are returned into this pool for later reuse. So instead of

`let entity = new LifeComponent(100);`

we would have something like

```
let args = {lifeValue: 100}; //flexible args object that can be passed regardless of components on this or that entity
let entity = LifeComponentPool.retrieve(args);

```

But this is a whole other topic. See Object Pool Pattern for more.
> 1 votes

# Answer
You're on the right track, but, oddly enough, Unity's reference documentation doesn't offer the most robust definition of the term Archetype. Granted, I won't be doing that either in this answer but, in the interest of clarity, I'll attempt to further flesh out what the documentation touches on.

An Archetype defines the specific set of components processed by a **System**. All entities with those components will get processed by said System. That distinction might seem trivial but this concept will shape the architecture of your ECS moving forward.

Also note that an entity's component composition may satisfy multiple Archetypes (and therefore be processed by multiple systems). So in that diagram you referenced, Entities A and B are also valid candidates for Archetype N.

So how does one implement Archetypes in a language like JavaScript? Well, its far from trivial, but you can start by creating a manager class, which some implementations label as the **Engine** (some implementations refer to it as the **World** class). This Engine class/object stores your lists of Components and Systems and contains logic to register Entities with Systems when they have the requisite components attached.

With respect to the inner workings of an ECS Engine, they run the gamut, from linked-lists, to bitfields to sparse sets and probably all manner of combinations in-between.

I can't point you to anything Javascript-specific but here are a few resources in other languages that you can check out to see what you can glean from them:

* Richard Lord's Ash Entity Component System \- its a classic linked-list implementation written in AS3 (scripting language for the now defunct Flash browser runtime and plugin). The github repo also has links to his blog where his discusses ECS architecture in more depth.
* Retinazer \- A bit-field lookup driven implementation written in Java (and indirectly based on Ash). One of the more interesting implementations I've come across.
* EnTT \- A C++ implementation that leverages Sparse Sets. Check out the author's series of blog articles ECS Back and Forth, he (Michele "skypjack" Caini) goes to great lengths to explain how his ECS works. Very insightful stuff, the entry about Archetypes should be especially useful.
> 0 votes

---
Tags: javascript, architecture, software-engineering, data-structure, entity-component-system
---


title: Add inertia to Pawn movement

text:
# Question
Title: Add inertia to Pawn movement
I've just started to learn Unreal Engine 4.26.2 while developing an Atari Pong clone.

This is how I have implemented the Paddle's movement (but this implementation doesn't accelerate or has inertia):

```
// Called to bind functionality to input
void APaddle::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
    Super::SetupPlayerInputComponent(PlayerInputComponent);

    // Respond every frame to the values of our movement.
    InputComponent->BindAxis(TEXT("MovePaddle"), this, &APaddle::Move_ZAxis);
}

void APaddle::Move_ZAxis(float AxisValue)
{
    CurrentVelocity.Z = FMath::Clamp(AxisValue, -1.0f, 1.0f) * 100.0f;
}

```

But I want to do two things:

1. While the user is pressing the key the paddle movement will accelerate.
2. When the user release the key the Paddle won't stop immediately; instead, it will slowing down until it stops.

Is there anything done with Physics that I can use here or do I have to implement it by myself?

By the way, I'm not English and I don't know if inertia is the right word here.

# Answer
> 1 votes
You could do this with physics though I'm thinking that for what you're trying to achieve, it will be a very complicated solution.

The simplest will be to calculate how long you want it to take for the paddle to get up to full speed, multiply this time by the Delta Time (Tick) of the paddle, then divide the top speed by this value.

```
float ChangeThisTick = PaddleTopSpeed / (TimeToTopSpeed * GetWorld()->GetDeltaSeconds());

```

You'll need a second, global variable to keep track of the current multiplier to be added or subtracted depending on whether the AxisValue is positive or negative.

When the AxisValue is zero, you can then check whether the current value of the global variable is positive or negative so you can then reduce or increase the value of this accordingly to slow the paddle down, using a multiplier if you want it to slow down faster than it speeds up.

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


# Question
Title: Event type and SDL_QUIT are incompatible
I'm following the Lazy Foo SDL2 tutorials, and I've run into a problem when trying to poll for events. While I'm polling for the events, the event type and `SDL_QUIT` throw an error saying the operand types are incompatible when trying to see if they're equal.

```
SDL_Event e;

while (!quit)
{
    // Handle vents on queue
    while (SDL_PollEvent(&e) > 0)
    {
        // User requests quit
        if (e.type == SDL_Quit)
        {
            quit = true;
        }
    }
}

```

I double-checked and everything is linked correctly, and I've tried other scenarios and it always says the same thing. Does anyone have any ideas about what could be going wrong?

# Answer
SDL\_Quit with lowercase letters u, i, and t is a function, not an enumeration constant or type.

It looks like you want SDL\_QUIT with all uppercase letters, as shown in the documentation.
> 2 votes

---
Tags: c++, sdl2
---


# Question
Title: Unity DontDestroyOnLoad not always working after Android build
I've been using this small script as a component to any object I want to not be destroyed at scene loading.

```
public class DontDestroy : MonoBehaviour
{
    void Start()
    {
        DontDestroyOnLoad(gameObject);
    }
}

```

It has been working fine. It works for my GameOver canvas which I've been using for a long time whilst making the game.

Today I added the same script to a new AndroidControls Canvas I made. In the Editor it worked fine. Then I built it for Android to run on my physical phone (Galaxy S10). It gave me a Null exception.

It turned out to be caused by the AndroidControls Canvas being destroyed between scene loading (even though as I say, I tested in Editor for a few runs and it didnt get destroyed). And it gets a little weirder because after the attempted build to APK, and fail on physical device, it then failed to work in the editor. It continues to not work in each test after this in Editor, however if I remove the component and add it again, the entire process then repeats.

Please help as I don't have a clue how to start fixing this. The only thing I can imagine it being wrong is it started as soon as I used this script on two canvas's simultaneously. (I highly doubt I am correct but it's the only thing I could notice at all that might be causing this).

This picture actually shows my DontDestroy component is attached to Canvas\_AndroidControls, but in the Hierarchy you can already see that it is not in the DontDestroyOnLoad section (excuse the pink overlay for play-mode):

Maybe relevant, here are some of my specs:

```
Win 10
Unity 2020.3.5f1 (Just downloaded NDK/SDK for Android today via Unity Modules)
Android 11 (Samsung Galaxy S10)

```

# Answer
EDIT: Since writing this answer, the problem has reappeared. Extremely odd how it worked for a few builds. Then all I did was change the music from one file to another, build again and suddenly the exact same problem process has resurfaced.

(If somebody did wish to see the project, pending me adding it to Github. I zipped it in it's current state, 2 part download: https://file.io/j9ofNLrj4Pp6 , https://file.io/tNkot6Yd6gPx) The problem is evident as soon as you open the project in Unity.

As I stated in the comments above. I can fix the problem by ditching my 'DontDestroy' component completely and just adding the lines to not destroy each object in my GameManager.cs Start() instead.

Seems Unity 2020.3.5f1 LTS is a version of Unity to be avoided. There was no Error or Warning regarding this issue and I had to mess about a while debugging to even find why the original Null Error was thrown.

Until now I was under the impression that Unity builds with LTS tag where very stable and tested builds: https://unity3d.com/unity/qa/lts-releases?version=2020.3

I can confirm that installing 2020.3.9f1 LTS fixes the issue. I removed my workaround code line (as mentioned in comments on question), and re-added my original 'DontDestroy' component to the objects. Now they all remain and are never destroyed upon Scene change.
> 1 votes

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


# Question
Title: How can I spin a child capsule of a cube parent?
I have a parent cube and to make it like a surface I had to change the rotation of the cube on the X to 90. and as a child, I added a capsule, and to make the capsule-like standing I had to change the capsule X also to 90. The result is :

The reason I put the capsule child of the cube is that I want the capsule to move with the cube.

The capsule rotation on the X is also 90 :

Then in a script at the top, I added speed and index variables for the rotation :

```
private int index = 0;
private int rotationIndex = 0;

```

In the Update :

```
RotateTo();

```

And the method : curvedLinePoints is a List

```
private void RotateTo()
    {
        var distance = Vector3.Distance(capsule.position, curvedLinePoints[rotationIndex].transform.position);
        if(distance < 0.1f)
        {
            rotationIndex++;
        }

        // Determine which direction to rotate towards
        Vector3 targetDirection = curvedLinePoints[rotationIndex].transform.position -capsule.position;

        // The step size is equal to speed times frame time.
        float singleStep = rotationSpeed * Time.deltaTime;

        // Rotate the forward vector towards the target direction by one step
        Vector3 newDirection = Vector3.RotateTowards(capsule.forward, targetDirection, singleStep, 0.0f);

        // Draw a ray pointing at our target in
        Debug.DrawRay(capsule.position, newDirection, Color.red);

        // Calculate a rotation a step closer to the target and applies rotation to this object
        capsule.rotation = Quaternion.LookRotation(newDirection);
    }

```

The problem is that because the capsule is a child when I rotate the capsule it looks like the capsule changes its shape and not spinning around itself. If I remove ut the capsule from the prefab and will rotate it on its own it will spin fine but when it's a child of the cube the result is :

I tried before running the game to play with the capsule rotation in the editor in the inspector changing the Y and Z values and the result is like in this screenshot. but I want to spin it around itself but because it's a child of the cube it's not spinning but looks like it's changing its shape.

The workaround I found is to create an empty GameObject at 0,0,0 and put both Platform and Capsule as a child of it.

Then I added this part to the script above :

```
private void LateUpdate()
    {
        capsule.localPosition = transform.localPosition + new Vector3(0, 1.4f, 0);
    }

```

This way the Capsule is following the Platform. The empty GameObject is just to put them both together.

and for testing I just did in the Update :

```
capsule.Rotate(0, 10, 0);

```

and it's working fine. Now I have to figure out how to make this rotation with the code in the RotateTo method.

# Answer
> 0 votes
You can avoid this distortion by keeping the scale - especially any non-uniform scale - at the leaf nodes of your transformation hierarchy.

So your hierachy could look like this:

* Platform Root: local rotation = (0, 0, 0) / local scale = (1, 1, 1)
    + Cube Child: local rotation = (0, 0, 0) / local scale = (4.3, 1, 4.3)
    + Capsule Child: local rotation = (0, 0, 0) / local scale = (1, 1, 1)

Because the root has only uniform scale, rotating it and objects inside it won't cause an distortion.

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


# Question
Title: Best way to handle events for a turn base game?
I'm looking for the best way to handle events for a tactic game in Unity. Every unit may need to react to different events (turn start, end, on damage to self, on damage to other, on kill, etc...).

At the moment I'm just cycling all units for any event from a central manager class, but I'm looking for a more elegant and easy-to-extend solution. I'm not worried about performance since the involved number of units will be low.

Any advice?

# Answer
> 1 votes
One of the best ways to handle events in Unity is... using UnityEvents!

In this example, we have a singleton called `TurnManager` with functions we can call when a turn starts or ends. Units subscribe to the relevant event so they are notified when a turn starts or ends.

```
public class TurnManager : MonoBehavior {
    //singleton pattern for convenience
    private static TurnManager instance;
    public static TurnManager Instance => instance;

    [SerializeField] private UnityEvent onTurnStart;
    public UnityEvent OnTurnStart => onTurnStart;

    [SerializeField] private UnityEvent onTurnEnd;
    public UnityEvent OnTurnEnd => onTurnEnd;

    void Awake() {
        Assert.IsNull(instance);
        instance = this;
    }
    void OnDestroy() {
        instance = null;
    }

    public void StartTurn() {
        onTurnStart.Invoke();
    }
    public void EndTurn() {
        onTurnEnd.Invoke();
    }
}

public class SelfHealingUnit : Unit {
    [SerializeField] private int hpPerTurn = 10;

    void OnEnable() {
        TurnManager.Instance.OnTurnStart.AddListener(TurnStartHandler);
    }
    void OnDisable() {
        TurnManager.Instance.OnTurnStart.RemoveListener(TurnStartHandler);
    }
    void TurnStartHandler() {
        HP += hpPerTurn;
    }
}

public class SuicideUnit : Unit {
    [SerializeField] private int lifespan = 3;
    [SerializeField] private UnityEvent onExplode;
    public UnityEvent OnExplode => onExplode;

    int turnsAlive = 0;

    void OnEnable() {
        TurnManager.Instance.OnTurnEnd.AddListener(TurnEndHandler);
    }
    void OnDisable() {
        TurnManager.Instance.OnTurnEnd.RemoveListener(TurnEndHandler);
    }
    void TurnEndHandler() {
        turnsAlive++;
        if (turnsAlive >= lifespan) {
            Explode();
        }
    }
    public void Explode() {
       //do stuff here
       //...
       onExplode.Invoke();
    }
}

```

This way we don't have to notify every single unit every time the turn starts or ends; we only notify the units that *care* when the turn starts or ends. You can easily extend this example with other types of events.

---
Tags: unity, c#, architecture, events
---


# Question
Title: How can I get the Text component from TextMeshPro ? I'm getting null exception
At the top of the screen :

```
public GameObject uiSceneText;
private TextMeshPro textMeshPro;

```

Then in the script at some point :

```
uiSceneText.SetActive(true);

if (textMeshPro.text != "")
    textMeshPro.text = "";

```

The exception error null is on the textMeshPro on the line :

```
if (textMeshPro.text != "")

```

textMeshPro is null.

This screenshot shows the TextMeshPro in the Hierarchy :

and I see that the Scene Image object and its child Scene Text both are enabled true.

I want to get the text and add replace a new text with the text already in the Text but the textMeshPro is null.

The complete script :

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

public class PlayerSpaceshipAreaColliding : MonoBehaviour
{
    public float rotationSpeed;
    public float movingSpeed;
    public float secondsToRotate;
    public GameObject uiSceneText;

    private float timeElapsed = 0;
    private float lerpDuration = 3;
    private float startValue = 1;
    private float endValue = 0;
    private float valueToLerp = 0;
    private Animator playerAnimator;
    private bool exitSpaceShipSurroundingArea = false;
    private bool slowd = true;
    private TextMeshPro textMeshPro;

    // Start is called before the first frame update
    void Start()
    {
        textMeshPro = uiSceneText.GetComponent<TextMeshPro>();

        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (exitSpaceShipSurroundingArea)
        {
            if (slowd)
                SlowDown();

            if (playerAnimator.GetFloat("Forward") == 0)
            {
                slowd = false;

                LockController.PlayerLockState(false);

                uiSceneText.SetActive(true);

                if (textMeshPro.text != "")
                    textMeshPro.text = "";

                textMeshPro.text = "Here I will add the new text.";

            }

            if (slowd == false)
            {

            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = false;
            Debug.Log("Entered Spaceship Area !");
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = true;
            Debug.Log("Exited Spaceship Area !");
        }
    }

    private void SlowDown()
    {
        if (timeElapsed < lerpDuration)
        {
            valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
            playerAnimator.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;
        }

        playerAnimator.SetFloat("Forward", valueToLerp);
        valueToLerp = 0;
    }
}

```

# Answer
First problem: I tried to get the TextMeshPro component in the Start(), but the uiSceneText object was not yet enabled true. That's why I got the null exception error.

Second problem: It's not TextMeshPro but TextMeshProUGUI.

Solution: Instead of trying to get the TextMeshProUGUI component in the Start() I added a new variable for the TextMeshProUGUI and assigned the TextMeshProUGUI in the editor it's working fine now.

The complete working script :

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

public class PlayerSpaceshipAreaColliding : MonoBehaviour
{
    public float rotationSpeed;
    public float movingSpeed;
    public float secondsToRotate;
    public GameObject uiSceneText;
    public TextMeshProUGUI textMeshProUGUI;

    private float timeElapsed = 0;
    private float lerpDuration = 3;
    private float startValue = 1;
    private float endValue = 0;
    private float valueToLerp = 0;
    private Animator playerAnimator;
    private bool exitSpaceShipSurroundingArea = false;
    private bool slowd = true;

    // Start is called before the first frame update
    void Start()
    {
        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (exitSpaceShipSurroundingArea)
        {
            if (slowd)
                SlowDown();

            if (playerAnimator.GetFloat("Forward") == 0)
            {
                slowd = false;

                LockController.PlayerLockState(false);

                uiSceneText.SetActive(true);

                if (textMeshProUGUI.text != "")
                    textMeshProUGUI.text = "";

                textMeshProUGUI.text = "Some new text will be added here soon.";

            }

            if (slowd == false)
            {

            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = false;
            Debug.Log("Entered Spaceship Area !");
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = true;
            Debug.Log("Exited Spaceship Area !");
        }
    }

    private void SlowDown()
    {
        if (timeElapsed < lerpDuration)
        {
            valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
            playerAnimator.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;
        }

        playerAnimator.SetFloat("Forward", valueToLerp);
        valueToLerp = 0;
    }
}

```
> 0 votes

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


# Question
Title: How to add zombie arms to enemies in HTML canvas
I'm making a game with HTML canvas (not WEBGL). I have zombies that go to the center of the screen, but for now they are just circles. I want to give them two arms, like the arms players have in surviv.io. I have looked at this question: Moving an object in a circular path. I don't know what trigonometry to use to calculate the angle. Here is my code:

```
var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');

function Enemy(x, y) {
  this.x = x;
  this.y = y;
  this.r = 5;
  this.color = `hsl(${Math.floor(Math.random() * 360)},50%,50%)`;
  this.vx = 0;
  this.vy = 0;
  this.draw = () => {
    this.x += this.vx;
    this.y += this.vy;
    context.beginPath();
    context.fillStyle = this.color;
    context.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    context.fill();
  }
}
var enemy = new Enemy(0, 0);

function loop() {
  requestAnimationFrame(loop);
  context.fillStyle = 'rgba(0,0,0,0.2)';
  context.fillRect(0, 0, canvas.width, canvas.height);
  var angle = Math.atan2(canvas.height / 2 - enemy.y, canvas.width / 2 - enemy.x);
  enemy.vx = Math.cos(angle);
  enemy.vy = Math.sin(angle);
  enemy.draw();
}
requestAnimationFrame(loop)
```

```
<canvas id='canvas'>
```

I want the arms facing the center, and I want them to move when the enemy changes direction.

# Answer
I'm not familiar with the game you mention, but on a quick image search it looks like the entity arms are represented by circles, either holding a gun or in resting positions when not holding anything. Regardless, the basic approach is pretty much the same:

```
const angle = Math.atan2(this.vy, this.vx);
ctx.beginPath();
ctx.arc(
  this.x + Math.cos(angle + armOffsetRadians) * armDistance,
  this.y + Math.sin(angle + armOffsetRadians) * armDistance,
  this.r / 2,
  0, Math.PI * 2
);
ctx.stroke();

```

An alternative approach is to use something like

```
ctx.save();
ctx.transform(entity.x, entity.y);
ctx.rotate(entityAngle);
// draw the entity facing a neutral direction -- rotation is already handled
ctx.restore();

```

Here's a naive example of the top approach running:

```
var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');

function Enemy(x, y) {
  this.x = x;
  this.y = y;
  this.r = 5;
  this.color = `hsl(${Math.floor(Math.random() * 360)},50%,50%)`;
  this.vx = 0;
  this.vy = 0;
  this.move = () => {
    this.x += this.vx;
    this.y += this.vy;
  };
  this.draw = ctx => {
    const armOffsetRadians = 0.5;
    const armDistance = 8;
    const angle = Math.atan2(this.vy, this.vx);
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    ctx.fill();
    ctx.beginPath();
    ctx.arc(
      this.x + Math.cos(angle + armOffsetRadians) * armDistance,
      this.y + Math.sin(angle + armOffsetRadians) * armDistance,
      this.r / 2,
      0, Math.PI * 2
    );
    ctx.fill();
    ctx.beginPath();
    ctx.arc(
      this.x + Math.cos(angle - armOffsetRadians) * armDistance,
      this.y + Math.sin(angle - armOffsetRadians) * armDistance,
      this.r / 2,
      0, Math.PI * 2
    );
    ctx.fill();
  };
}
var enemy = new Enemy(0, 0);
var mouseX = canvas.width / 2;
var mouseY = canvas.height / 2;
var canRect = canvas.getBoundingClientRect();
canvas.addEventListener("mousemove", e => {
  mouseX = e.clientX - canRect.left;
  mouseY = e.clientY - canRect.top;
});

function loop() {
  requestAnimationFrame(loop);
  context.fillStyle = 'rgba(0,0,0,0.2)';
  context.fillRect(0, 0, canvas.width, canvas.height);
  var angle = Math.atan2(
    mouseY - enemy.y,
    mouseX - enemy.x
  );
  enemy.vx = Math.cos(angle);
  enemy.vy = Math.sin(angle);
  enemy.move();
  enemy.draw(context);
}
requestAnimationFrame(loop);
```

```
<canvas id='canvas'>
```

I couldn't resist passing the context in as a parameter to `Enemy.draw` -- if you rely on globals, the function breaks if the name or scope changes.

I also separated `move` and `draw` functions. This is good engineering practice in general, since functions should only do one thing, but it's even more important in an animation, because rendering is a totally distinct step from updating positions, computing collision, etc. The typical approach is to loop over all entities and update their positions, handle collisions and complete a full logical update on the game, then loop over the game state in a separate pass and render everything by z-index.

You can see 4 arms when the enemy stops. That's because it's moving back and forth really fast on the destination coordinates. You'll probably want to add a condition not to move if the entity's distance to the destination is below a certain threshold to avoid this "spazzing out" effect.

Beyond that, you can see a lot of repeated work happening here. I'm not sure how you ultimately want to design your game, but adding a setter for an enemy's angle would avoid multiple calls to `Math.atan2`. Setting `enemy.vx` and `enemy.vy` should probably be internal to the enemy and occur when `setAngle` is called.

I'll leave this design suggestion as an exercise since your primary question is a trigonometric one and I don't want to assume too much.
> 1 votes

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


# Question
Title: Isometric ball moving in unity 3d. Ball moving in opposite direction
I am making a game in unity 3d. It is a 2.5d game which mean it is in isometric. The game is quite simple. Player drags mouse and a trajectory will be shown just like in angry bird and when player release the mouse the ball will move to the direction. However I am having issue here that once mouse is released the ball moves in exact opposite direction. I am not able to understand what the real issue is. My code is as follows:

For Ball:

```
public class BallScript : MonoBehaviour

{
    public Rigidbody2D rbg;
    public CircleCollider2D col;

    public Vector3 BallPos{
        get {return transform.position;}
    }

    void Awake(){
        rbg = GetComponent<Rigidbody2D>();
        col = GetComponent<CircleCollider2D>();
    }

    public void PushBall(Vector2 force){
        rbg.AddForce(force,ForceMode2D.Impulse);
    }

    //to enable rigidbody so we can use projectile again
    public void ActivateRb(){
        rbg.isKinematic = false;
    }

    public void DeActivateRb(){
        rbg.velocity = Vector3.zero;
        rbg.angularVelocity = 0f;
        rbg.isKinematic = true;
    }
}

```

The code for my game manager is as follows:

```
public class Trajectory : MonoBehaviour
{
    [SerializeField] int dotsNumbers;
    [SerializeField] GameObject dotsParent;

    [SerializeField] GameObject DotsPrefab;
    [SerializeField] float dotSpacing;
    Vector2 pos;
    float timeStamp;
    Transform[] dotsList;

    void Start(){
        //hide trajectory in the start
        Hide();

        PrepareDots();
    }

    void PrepareDots(){
        dotsList = new Transform[dotsNumbers];
        for(int i=0;i<dotsNumbers;i++){
            dotsList[i] = Instantiate(DotsPrefab,null).transform;
            dotsList[i].parent = dotsParent.transform;
        }
    }
    public void UpdateDots(Vector3 ballPos,Vector2 forceApplied){
        timeStamp = dotSpacing;
        for(int i=0;i<dotsNumbers;i++){
            pos.x = (ballPos.x + forceApplied.x * timeStamp);
            pos.y = (ballPos.y + forceApplied.y * timeStamp)-(Physics2D.gravity.magnitude * timeStamp * timeStamp)/2f;
            dotsList[i].position = pos;
            timeStamp += dotSpacing;
        }
    }

    public void Show(){
        dotsParent.SetActive(true);
    }
    public void Hide(){
        dotsParent.SetActive(false);
    }
}

```

Here is the code for gamemanager

```
// using singleton pattern
Camera cam;
public BallScript ball;
public Trajectory trajectory;
public static GameManagerScript Instance;
void Awake(){
    if(Instance==null){
        Instance = this;
    }
}

[SerializeField] float pushForce = 4f;
bool isDragging = false;

Vector2 startPoint;
Vector2 endPoint;
Vector2 direction;
 Vector2 force;
float distance;

void Start(){
    cam = Camera.main;
    ball.DeActivateRb();
}

void Update(){
    if(Input.GetMouseButtonDown(0)){
        isDragging = true;
        OnDragStart();
    }
    if(Input.GetMouseButtonUp(0)){
        isDragging = false;
        OnDragEnd();
    }
    if(isDragging){
        OnDrag();
    }
}

void OnDragStart(){
    ball.DeActivateRb();
    startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
    trajectory.Show();
}

void OnDrag(){
    endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
    distance = Vector2.Distance(startPoint,endPoint);
    direction = (endPoint-startPoint).normalized;
    force = direction* distance * pushForce;

    trajectory.UpdateDots(ball.BallPos,force);

}

void OnDragEnd(){
    ball.ActivateRb();
    ball.PushBall(force);
    trajectory.Hide();
}

```

The ball moves in exact opposite direction where I wish to send it by dragging. Is it because of the isometric issue or I am missing something?P.S: have applied negative force as well as in case and have also made change in direction formula

```
rbg.AddForce(-force,ForceMode2D.Impulse);
direction = (startPoint-endPoint).normalized;

```

# Answer
Some suggestions:

When you call `ScreenToWorldPoint()`, you generally should not pass in the mouse position directly. You need to set the z-position first. For example,

```
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = cam.nearClipPlane;
endPoint = cam.ScreenToWorldPoint(mousePosition);

```

This part of your `OnDrag()` is pointlessly complicated:

```
distance = Vector2.Distance(startPoint,endPoint);
direction = (endPoint-startPoint).normalized;
force = direction* distance * pushForce;

```

Let's analyze what you're doing here:

1. Calculate the scalar distance.
2. Get the Vector3 from `startPoint` to `endPoint`
3. Normalize the Vector3 from step 2 to get a direction.
4. Multiply the distance from step 1 and direction from step 3 to get the Vector3 from `startPoint` to `endPoint`.

Hold on a minute - the value you end up with in step 4 is the same value you got in step 2. You don't need the other steps! This can be simplified to

```
force = (endPoint - startPoint) * pushForce;

```
> 1 votes

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


# Question
Title: Problem trying to lock framerate at 60 FPS
I've written a simple class to limit the framerate of my current project. But it does not work as it should. Here is the code:

```
void FpsCounter::Process()
{
    deltaTime = static_cast<double>(frameTimer.GetMsecs());
    waitTime = 1000.0/fpsLimit - deltaTime;
    frameTimer.Reset();

    if(waitTime <= 0)
    {
        std::cout << "error, waittime: " << waitTime << std::endl;
    }
    else
    {
        SDL_Delay(static_cast<Uint32>(waitTime));
    }

    if(deltaTime == 0)
    {
        currFps = -1;
    }
    else
    {
        currFps = 1000/deltaTime;
    }

    std::cout << "--Timings--" << std::endl;
    std::cout << "Delta: \t" << deltaTime << std::endl;
    std::cout << "Delay: \t" << waitTime << std::endl;
    std::cout << "FPS: \t" << currFps << std::endl;
    std::cout << "--       --" << std::endl;
}

Timer::Timer()
{
    startMsecs = 0;
}

Timer::~Timer()
{
    // TODO Auto-generated destructor stub
}

void Timer::Start()
{
    started = true;
    paused = false;
    Reset();
}

void Timer::Pause()
{
    if(started && !paused)
    {
        paused = true;

        pausedMsecs = SDL_GetTicks() - startMsecs;
    }
}

void Timer::Resume()
{
    if(paused)
    {
        paused = false;

        startMsecs = SDL_GetTicks() - pausedMsecs;

        pausedMsecs = 0;
    }
}

int Timer::GetMsecs()
{
    if(started)
    {
        if(paused)
        {
            return pausedMsecs;
        }
        else
        {
            return SDL_GetTicks() - startMsecs;
        }
    }
    return 0;
}

void Timer::Reset()
{
    startMsecs = SDL_GetTicks();
}

```

The "FpsCounter::Process()" Method is called everytime at the end of my gameloop.

I've got the problem that the loop is correctly delayed only every second frame, so it runs one frame delayed at 60 FPS and the next without delay at over 1000 fps.

I am searching the error quite a while now, but I do not find it.

I hope somebody can point me in the right direction.

# Answer
> 3 votes
You need to reset the timer **after** you have waited. Otherwise, the wait time will be part of the duration of the next frame and the algorithm will think it is running slowly.

# Answer
> 2 votes
This wrong on many levels. The code behaves like it does because you reset the timer before you have finished waiting for the correct time for the current frame to come. If you moved the reset to after the wait block it should work like you have planned.

This is however still a very poor and inexact time control as it does not correct slight lapses of one frame in the next. What you really need is to have game logic running at a fixed rate and rendering running as fast as possible, though possibly with v-sync on so that it is limited to the screen update rate.

Your game loop should look something like this: (Edited, pausing will probably work better in the new version.)

```
double nextFrame = static_cast<double>SDL_GetTicks();
while(true){
    while(nextFrame > static_cast<double>SDL_GetTicks()){
        render();
    }
    nextFrame += 1000.0 / logicrate;
    if(!paused)
        gameLogic();
}

```

Alternate version that caps the frame rate at the logic rate:

```
double nextFrame = static_cast<double>SDL_GetTicks();
while(true){
    if(nextFrame > static_cast<double>SDL_GetTicks()){
        render();
    }
    if(!paused)
        gameLogic();
    delay = static_cast<Uint32> (nextFrame - static_cast<double>SDL_GetTicks());
    if(delay > 0){
        SDL_Delay(delay);
    }
    nextFrame += 1000.0 / logicrate;
}

```

# Answer
> 0 votes
This problem have already been discussed here : Make the game run 60 fps in Irrlicht Engine

(initial question is for iirlicht engine but what have been said there also applied to other environments)

# Answer
> 0 votes
Mine is something like this...

```
     timer.Update();

     static float frameTime = 0.0f;
     static int frames = 0;
     frameTime += timer.DeltaTime();
     frames++;

     while(frameTime >= kTimeStep)
     {
        (object->*callback)(frameTime);
        frames = 0;
        frameTime -= kTimeStep;
     }

```

# Answer
> 0 votes
Try something such as 3 stages waiting:

```
        m_tickEnd = m_timer.Mark() * 1000.0; // converting seconds to milliseconds

    // Doing all three stages of waiting would safe CPU usage from 30% to less than 10% for a 8 cores PC
    // 1. sleep
    while (m_ticksPerFrame - m_tickEnd > 6)
    {
        // sleep until has roughly +/- 1 millisecond accuracy
        std::this_thread::sleep_until(std::chrono::steady_clock::now() + std::chrono::milliseconds{ 5 });
        m_tickEnd = m_timer.Mark() * 1000.0;
    }
    while (m_ticksPerFrame - m_tickEnd > 4)
    {
        // sleep until has roughly +/- 1 millisecond accuracy
        std::this_thread::sleep_until(std::chrono::steady_clock::now() + std::chrono::milliseconds{ 3 });
        m_tickEnd = m_timer.Mark() * 1000.0;
    }
    while (m_ticksPerFrame - m_tickEnd > 2)
    {
        // sleep until has roughly +/- 1 millisecond accuracy
        std::this_thread::sleep_until(std::chrono::steady_clock::now() + std::chrono::milliseconds{ 1 });
        m_tickEnd = m_timer.Mark() * 1000.0;
    }

    // 2. yield
    while (m_tickEnd < m_ticksPerFrame * .99)
    {
        // yield has roughly +/- 30 microsecond accuracy, it could work as a more accurate sleep function at fine grain.
        std::this_thread::yield();
        m_tickEnd = m_timer.Mark() * 1000.0; // converting seconds to milliseconds
    }

    // 3. busy wait
    do {
        m_tickEnd = m_timer.Mark() * 1000.0; // converting seconds to milliseconds
    } while (m_tickEnd < m_ticksPerFrame * .9999);

```

---
Tags: c++, sdl, frame-rate
---


# Question
Title: Detecting a mouse click While in a Trigger
Why does the following code not working? (weird, sometimes it works sometimes not )

I want to move player by touching on the screen and change the color of gameObject ***when*** detect trigger ***and*** release mouse click.

"Drag and move" script works correctly I just add following code and sometimes it works sometimes not

```
  private void OnTriggerStay2D(Collider2D colider)
  {

    if (Input.GetMouseButtonUp(0) & colider != null)
    {
      colider.gameObject.GetComponent<SpriteRenderer>().material.color = Color.blue;

    }

  }
```

There is a full script :

```
  private Camera _cam;
  private Vector3 _daragOfset;
  [SerializeField] private float _speed = 4.55f;
  private bool isEntered = false;

  void Update()
  {
    if (Input.GetMouseButtonDown(0))
    {
      _daragOfset = transform.position - GetMousePos();
    }
  }

  private void OnTriggerStay2D(Collider2D colider)
  {
    if (Input.GetMouseButtonUp(0) & colider != null)
    {
      colider.gameObject.GetComponent<SpriteRenderer>().material.color = Color.blue;
    }
  }

  void Awake()
  {
    _cam = Camera.main;
  }

  void OnMouseDrag()
  {
    transform.position = Vector3.MoveTowards(transform.position, GetMousePos() + _daragOfset,_speed * Time.deltaTime);
  }

  Vector3 GetMousePos()
  {
    var mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
    mousePos.z = 0;
    return mousePos;
  }
```

# Answer
Note that you have used only one `&` in the if statement, what you really wanted was the AND Operator (`&&`). Here is the edited code:

```
if (Input.GetMouseButtonUp(0) && colider != null)
{
  colider.gameObject.GetComponent<SpriteRenderer>().material.color = Color.blue;
}

```
> 1 votes

---
Tags: unity, collision-detection
---


# Question
Title: Best ways to navigate a single step on a hexagonal grid depending on input
**Problem**

* In my puzzle game, the player moves **one** step at a time on a hexagonal grid. (Not an action game.)
* The sequence of steps is important for the gameplay, so it is not only about getting from A to B.
* There are of course six possible move directions that I have to map my input to.
* My hexagons have a pointy tip, so I do not have a North or South adjacent cell. So the ordinal directions are NW, NE, E, W, SW and SE. See the image.
* I am particularly interested in ideas to accomplish this movement for **mouse**, **keyboard** and Xbox-like **controllers**, but feel free to post your thoughts on touch.
* The main difficulty is that I am very experienced with my very clunky controls and new players are struggling to simply move the player around. Also, the movement controls cannot be accomplished via conventional square grid controls, e.g. a dpad or WASD.

**What I have tried / Ideas**

Keyboard

* Mapping the characters around S directly to the six hexagonal directions, so W-\>NW, E-\>NE, A-\>W, D-\>E, Z-\>SW and X-\>SE. This is what I use basically.
* Idea: Use WASD only. W is a North modifier, S is a South modifier and A and D correspond to East and West. Holding down the modifier will change what A/D does. Maybe show preview of current move possible with modifiers.

Controller

* Flick controls: When you reach a certain threshold in displacement of the 2D left stick, this angle counts as as movement and will be mapped directly to a direction. You will see a small line/arrow pointing to the corresponding direction of the stick when you are not fully tilting the stick. Center stick to proceed.
* Same as before, but you have to press A to go in that direction.

Mouse

* Idea: Click on the adjacent tile to go there, maybe highlight possible moves.
* Idea: Press a button and drag from that position to mimick stick controls, e.g. flicks.

# Answer
For keyboard inputs, a simple but effective implementation is to have a set of keys that when repeatably pressed, change the player's orientation by rotating through the surrounding tiles in a clockwise or counter-wise direction.

So you could set the 'A' and left arrow keys to cycle through adjacent cells in a counter-clockwise direction and the 'D' and right arrow keys to cycle through adjacent cells in a clockwise direction. And then have the player hit enter (or some other key) to commit the move.

Cycling through orientations in a clockwise or counterclockwise direction can be mapped to a controller as well. Left on the stick or d-pad is counter-clockwise, right on the stick or d-pad is clockwise.

Clicking adjacent tiles makes the most sense for mouse input so I'd stick with that. Plus, you'll be able to use the same underlying logic for touch controls on a mobile device.
> 2 votes

---
Tags: input, user-experience, puzzle, hexagonal-grid
---


# Question
Title: How to find intersections using MapBox Unity SDK
I'm currently using MapBox's Untiy SDK, which allows me to render 3D Buildings and roads. I want to place a gameobject at each intersection in an area. But, I'm having trouble finding a good way to do that.

The roads are gameobjects attached to a "Tile" gameobect. The roads have a local position 0,0,0 with meshes on them that dictate their rendered position. A long road can cross multiple tiles, and thus the same "road" may exist as two or more gameobjects on two or more tiles. The Mesh itself is rectangular prism extruded from some line data by Mapbox.

I have tried to use colliders with no success. For one, in order to get points of intersections between two colliders, they need to have rigidbodies attached to them and it's too expensive to do that, since there are hundreds of roads. Furthermore, many of the meshes have bad verts in them, which wont allow mesh colliders to work anyway, and box colliders wont work for non-straight roads. Some road meshes are sprawling, twisting, and winding and could "collide" with a number of roads without actually touching them.

I am not above brute force looping through every mesh's vertex in every tile to detect intersections, but I am as of yet unsure of the best way to do this or if it is necessary.

I am also not sure if MapBox has some hidden feature for this the way Google Maps Unity SDK allows for access to the road lattice and intersections. If I could get some info about the line that represents the road, it would be easy to tell if roads overlap.

The best way I can figure is to loop through the verts on a road to determine if the lines between verts overlap that of the roads within the same time, but am not sure if that is the best course of action

# Answer
Okay so it's taken me some time, but I finally have a high-level solution that seems to be working.

In my quest to calculate when edges in a road segment overlap, I discovered a better way to determine where an intersection exists. This discovery was found while creating a custom `MeshModifier` class. The MapBox SDK makes extensive use of `ScriptableObject`s to modify features as they are loaded in. For instance, you can add create a `AddMonoBehavioursModifier` instance in your project and tell the SDK to apply it to roads. The instance you create can hold references to scripts you want to attach to each road.

Using this system, I set out to create my own `MeshModifier` by looking at the `LineMeshModifier` class they had created themselves. In it I discovered that we do get access to points that represent road segments in the form of Vector3s. After some playing around, I was able to place them in world space where they belong.

Finally, the way to detect intersections was found.

In any tile, each road has a series of `Vector3` points that dictate its shape. If any `Vector3` in one road is the same as a `Vector3` in another road, then they represent the location of an intersection. THIS is how I can find out where intersections are located.

There are probably additional calculations one could do to determine actual segments of road, but this part I am not interested in.

Here is the basic code I came up with. Better ways to do most of it, but this is the first pass and should work for beginners.

```
public class IntersectionModifier : MeshModifier
{

    //custom classes to make it easier to understand what information is being held
    public class TileToCheck
    {
        public bool hasBeenChecked = false;
        public GameObject tile;
        public List<RoadSegment> roads = new List<RoadSegment>();
        public TileToCheck(GameObject tile)
        {
            this.tile = tile;
        }
    }
    public class RoadSegment
    {
        public List<Vector3> points;
    }

    //our strategy is to hold a reference to each tile as it comes in so that we dont check the same tile twice
    //the string is the tile's name, which is the same as it's coordinates, so it is unique.
    public Dictionary<string, TileToCheck> roadsByTiles = new Dictionary<string, TileToCheck>();

    //MapBox's factories will call these functions and pipe in the features we want
    public override void Run(VectorFeatureUnity feature, MeshData md, float scale)
    {
        AddRoadToDictionary(feature, md);
    }
    //MapBox's factories will call these functions and pipe in the features we want
    public override void Run(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
    {
        AddRoadToDictionary(feature, md);
    }

    //Adds our data to the dictionary
    public void AddRoadToDictionary(VectorFeatureUnity feature, MeshData md)
    {
        var key = feature.Tile.gameObject.name;
        //data comes in an ordered fashion, so whenever we get a new tile, that means the last tile is finished.
        if (roadsByTiles.ContainsKey(key) == false)
        {
            //trigger calculation of intersection
            foreach (var kvp in roadsByTiles)
            {
                CalculateIntersections(kvp.Key, kvp.Value);
            }

            roadsByTiles.Add(key, new TileToCheck(feature.Tile.gameObject));

        }
        //feature.Points is a list of lists, each of those sub-lists being a road segment with points
        foreach (var roadSegment in feature.Points)
        {
            var road = new RoadSegment();
            road.points = roadSegment;

            roadsByTiles[key].roads.Add(road);
        }

    }

    public void CalculateIntersections(string name, TileToCheck tile)
    {
        //dont check the same one twice.
        //there are better ways to do this
        if (tile.hasBeenChecked == true)
            return;
        tile.hasBeenChecked = true;

        //the following isnt necessary to determine intersection points, but you will need to
        //align them to the tile eventually if you want real world space locations.
        //loop through the roads
        foreach (var road in tile.roads)
        {
            //separate roads by gameobject, to make things easier to debug.
            GameObject roadGo = new GameObject();
            //make sure the position is the same as the tile from the map or the positioning will be inaccurate
            roadGo.transform.position = tile.tile.transform.position;
            roadGo.transform.SetParent(tile.tile.transform);

            foreach (var point in road.points)
            {
                GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                go.transform.SetParent(roadGo.transform);
                //This position in world space is accurate as long as the map hasnt updated.
                //this system of setting parents isnt necessary if you use TransformPoint,
                //but its helpful to understand what the "point" actually means.
                go.transform.localPosition = point;
            }
        }

        //again, better ways to do this
        //loop through each road in the tile
        for (int i = 0; i < tile.roads.Count; i++)
        {
            //loop through each other road in the tile
            for (int j = 0; j < tile.roads.Count; j++)
            {
                //ignore yourself
                //or dont? can a road intersect with itself?
                if (j == i)
                    continue;

                //loop through the road's points
                for (int ii = 0; ii < tile.roads[i].points.Count; ii++)
                {
                    var pointA = tile.roads[i].points[ii];
                    //loop through the other road's points
                    for (int jj = 0; jj < tile.roads[j].points.Count; jj++)
                    {
                        var pointB = tile.roads[j].points[jj];
                        //if the points are the same, they are an intersection
                        if (pointB == pointA)
                        {
                            //Intersection!
                            //this point is local to the tile's position.

                        }
                    }
                }
            }
        }

    }
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Async load texture from PersistentDataPath with bytes
I have an issue with my texture loader, everything works fine but once the function runs Unity freezes until the files are loaded into memory. These two are the functions i use to load the textures and add them to an array.

```
public void LoadTextureArray(string _dirname)
    {
        var fileNames = Directory.GetFiles(Application.persistentDataPath + "/" + _dirname + "/", "*.jpg");
        source = new Texture2D[fileNames.Length];

        Array.Sort(fileNames, (s1, s2) => Path.GetFileName(s1).CompareTo(Path.GetFileName(s2)));

        int index = 0;
        foreach (var fileName in fileNames)
        {
            source[index] = LoadTextureFromPath(fileName);
            source[index].name = fileName;
            index++;
        }
    }

public Texture2D LoadTextureFromPath(string path)
    {
        if (string.IsNullOrEmpty(path))
        {
            Debug.LogError("Texture path is null or empty");
            return null;
        }

        if (!File.Exists(path))
        {
            Debug.LogError($"File not found: {path}");
            return null;
        }

        byte[] bytes = File.ReadAllBytes(path);
        Texture2D texture = new Texture2D(512, 512, TextureFormat.RGB24 , false);
        texture.LoadImage(bytes);
        Debug.Log("success");
        return texture;
    }

```

Now i understand i need to make it async in order for it to work on the background but honestly i have no idea how to proceed, i did read a bit on various forums but most of what i found used WWW and even though i did try some parts i was not successful.

Edit: Ok so for starters i cannot understand which of those two functions i need to make asynchronous. i found a thread which contained this code

```
Texture2D _content;
Material _material;

// Call this with StartCoroutine(LoadTexture(path));
IEnumerator LoadTexture(string path)
{
    // Start the asynchronous load.
    var www = new WWW("file://" + path);

    // Let the game continue running until the texture has been loaded.
    yield return www;

    // Replace current content with loaded texture.
    if (_content != null)
        Destroy(_content);
    _content = www.texture;

    // Instantiate a copy of the material,
    // and hang onto it so we can clean up when finished with it
    if (_material == null)
        _material = GetComponent<Renderer>().material;

    _material.mainTexture = www.texture;
}

void OnDestroy()
{
    // Clean up created instances
    // (these aren't immediately garbage-collected otherwise)
    if(_material != null)
         Destroy(_material);
    if(_content != null)
         Destroy(_content);
}

```

but i could not make it work by replacing it with this

```
IEnumerator LoadTexture(string _dirname)
    {
        var fileNames = Directory.GetFiles(Application.persistentDataPath + "/" + _dirname + "/", "*.jpg");
        // Start the asynchronous load.
        var www = new WWW(fileNames.ToString());

        source = new Texture2D[fileNames.Length];

        Array.Sort(fileNames, (s1, s2) => Path.GetFileName(s1).CompareTo(Path.GetFileName(s2)));

        //Debug.Log(string.Join("\n", fileNames));

        int index = 0;
        foreach (var fileName in fileNames)
        {
            // Let the game continue running until the texture has been loaded.
            yield return www;
            source[index] = LoadTextureFromPath(fileName);
            source[index].name = fileName;
            index++;
        }
    }

```

and even though this works it still freezes the game abit and it takes more time to load the textures than when the game freezes, maybe i should be making the texture into a asynchronous event but i do not know how to.

Edit: by placing the yield in the foreach loop it seems to be working but is this the way it should be done?

Edit: ok so after some trial and error i think i have gotten to a decent point. this part here works in the way that it loads everything in the background without freezing the game and it loads them as fast as i would like but is it correct?

code is this

<pre><code>    private IEnumerator GetTextureFromPath(string _dirname)
    {
        var fileNames = Directory.GetFiles(Application.persistentDataPath + "/" + _dirname + "/", "*.jpg");
        source = new Texture2D[fileNames.Length];

        Array.Sort(fileNames, (s1, s2) => Path.GetFileName(s1).CompareTo(Path.GetFileName(s2)));

        int index = 0;

        foreach (var fileName in fileNames)
        {
            UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(fileName);

            yield return webRequest.SendWebRequest();
            while (!webRequest.isDone)
            {
                yield return null;
            }

            Debug.Log("Ends server comm");
            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.Log(webRequest.error);
            }
            else
            {
                source[index] = ((DownloadHandlerTexture)webRequest.downloadHandler).texture;
                source[index].name = fileName;
                index++;
            }
        }

    }
```
</code></pre>

# Answer
> 0 votes
You don't need both

```
yield return webRequest.SendWebRequest();

```

and

```
while (!webRequest.isDone)
{
    yield return null;
}

```

You can choose one or the other. The first says "call me back when the load is 100% finished", the other says "call me back every frame, and I'll keep looping *until* it's finished" (useful if you wanted to put code inside that `while` loop that updates a progress bar or somesuch, which you're not doing here).

Otherwise, this looks fine.

---
Tags: unity
---


# Question
Title: How could I simulate projectile collision agaisnt RTS units with primitive colliders?
For example, humans are easy they are just capsules. But for cavalry, an arrow could hit the horse or the rider. Right now cavalry are also capsule colliders for unit-unit collision, but for projectiles I would need to detect hits on the rider too.

Would a compound collides be the solution? In the Total War series, it looks like arrows have full mesh collision with units. Here is a video showing arrows hitting different parts of the models accurately-- It shows how arrows can hit limbs and the head idk how that is done in such a scale.)

How is this done?

# Answer
Like DMGregory said: it's very unlikely Total War is actually *simulating* physics for all those arrows. There's probably a big separation from the battle simulation and the actual animations in game.

Here's a GDC talk about "predictable projectiles" which could be used for the animation side of things.
> 2 votes

---
Tags: collision-detection, rts, projectile-physics, collider
---