# Question
Title: Unity - call Start in another script's class
#### What I have:

1. A scene with only a cube (player), directional light and main camera.
2. A `Player` script containing functionality for movement and button press
3. A `Bullet` script that has two private members, GameObject and Material. They are loaded and set in the `Start()` function.

#### What I want:

I want to create a `Bullet` object (doing for example `Bullet bullet;`) when I press space. Inside the bullet `Start()` function the bullets mesh is created and position initialised. Thus the bullet should appear in the scene. It does not.

#### The issue:

There is no bullet that is created. Furthermore, I am unable to create a new bullet doing `Bullet bullet = new Bullet();` because `Bullet` is a class that inherits from `MonoBehaviour`.

#### Question:

How do I fix this? How do I execute another script's class's start function from my original script? I have tried to create an init class that is public and only calls Start of bullet but it does not work either!

Example of my bullet class:

```
public class Bullet : MonoBehaviour {
private GameObject sphere;
private Material mat;

void Start() {
    this.transform.position = new Vector3(1.0f, 1.0f, 1.0f);
    mat = Resources.Load("Materials/bullet", typeof(Material)) as Material;
    sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
    sphere.GetComponent<Renderer>().material = mat;
  }
}

```

The above code is by no means complete and it may contain grammatical errors because the actual code is on another computer. I do not want feedback about how to transfer code from one computer to another nor do I want feedback on whether the example is the most efficient way to initialize the bullet object. If the initialization is wrong, however, for example, it should be in another function or perhaps be made with a special function, then I'd be more than happy to receive your guidance!

Thanks in advance!

# Answer
It looks like what you really want here is a factory method. Something like...

```
public class Bullet : MonoBehaviour {
     static Material _mat;

     public static Bullet Create() {
         var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
         sphere.transform.position = Vector3.one;
         if (_mat == null) {
              mat = Resources.Load<Material>("Materials/bullet");
         }
         sphere.GetComponent<Renderer>().sharedMaterial = mat;

         return sphere.AddComponent<Bullet>();
     }
}

```

Now your code can say `Bullet myBullet = Bullet.Create();` to instantiate a new bullet.

However, a much more conventional way to achieve this behaviour is to simply create a game object in a scene that has the mesh/material/script configurations you want, then drag it from the Hierarchy window into the Project window — placing it somewhere in or nested under your game's Assets folder. This creates what's called a "prefab". Other code can expose a serialized `Bullet bulletPrefab` field that you assign to point at that prefab. (Assuming the prefab has a `Bullet` component attached — change the type accordingly if you want to refer to a different component on the prefab, or `GameObject`/`Transform` if you don't care what components the prefab has)

Then you can spawn instances (copies) of that prefab with `Bullet myBullet = Instantiate(bulletPrefab);` and Unity's deserializer handles creating and initializing the object according to the saved configuration, no special factory method needed.

---

The reason what you were trying originally didn't work is that `MonoBehaviour` scripts expect to be attached to `GameObject` instances. You can get this attachment if you spawn one from a prefab as described above, or attach one to an existing `GameObject` with `AddComponent`, or construct a new `GameObject` with a custom list of components like:

```
var go = new GameObject("newbie", typeof(MyComponent), typeof(MyOtherComponent);

```

But trying to use `Bullet myBullet` or `new Bullet()` will not on its own create a `GameObject`. The former creates a *slot* to store a `Bullet` (initially containing just `null`), and the latter just creates a free-floating `MonoBehaviour` instance, and throws a warning in your console reminding you that this is *not* the way to do it.

`MonoBehaviour` message functions are called only on `MonoBehaviour` scripts attached to `GameObject` instances in the scene. So no `GameObject` in the scene, no `Start()` call.

When you tried calling `Start()` manually, the first line it hit was:

```
this.transform.position = new Vector3(1.0f, 1.0f, 1.0f);

```

...which tries to access the `Transform` component attached to "this" `Bullet` instance's `GameObject`. But since it's not attached to any `GameObject`, this throws a null reference exception and aborts the method.
> 2 votes

---
Tags: unity
---


# Question
Title: Characters not applying avatars correctly
I am trying to get different models to go through animation cycles in Unity. The first four models are from Mixamo. Does anyone know why my characters end up like this (lodged into the ground) when I press play? Each model is set as humanoid animation. I set the avatar definition for each to be created from their own model, and they have their own avatars and animator controllers. When I play, the model in the middle animates fine (idle animation) but the other two do not go into the idle state I am trying to send them into.

# Answer
This may be due to a misconfiguration on the animations.

Honestly, you should check out this post made on Unity Forums: How To: Getting Mixamo and Unity to work, it's one of the most complete guides I've seen.

You've said that the models are set to Humanoid, but what about the animations?

In the post that I just mentioned, the following is said:

> 7. ...Okay, so click on the animation that you just imported into your project folder. In the inspector window, click on Rig, now change that from Generic to Humanoid and click apply. If you followed the steps correctly, no red or yellow errors here.

Oh, and another thing, you didn't mention if you're using the same Idle animation for each character, so I'm assuming you're not. Still, even if it's not the case, there may be a misconfiguration somewhere else.

I doubt that the problem is something else, since it's usually not the case, so try the above first.
> 0 votes

---
Tags: unity, animation, models, controllers, rigging
---


# Question
Title: Find out (general) orientation of cube faces with rotated and translated camera
I have the following problem. I have a camera that is initially looking at a cube. The cube is with center at (0, 0, 0). The camera that is initially on (0, 0, 60). The camera can rotate and translate freely around the world while the cube stays fixed. I want for a given position of the camera, to determine which side of cube is oriented to "up", "left", "right", "down", "front" and "back". For example on the given picture we see thaht we are looking at left side of cube and on right side is the front.

I know how to solve the problem if the camera is fixed, but the cube rotates(apply the inverse of the transformation matrix, of the cube, to the normal of face, in which we are interested in(for example (-1, 0, 0) for left) than find face with normal with smallest angle to this vector). But I cant design an algorithm for the camera moving case.

Also I should probably add that the camera stays looking at (0, 0, 0) the whole time. I think that might be relevant...

# Answer
> 1 votes
Take the normal vector of the face you care about, and multiply it by the cube's transformation matrix (not its inverse, unless you mean the inverse-transpose which you'd use to transform normals in the presence of non-uniform scale) to get it into world space.

Next, multiply it by the camera's view matrix (the inverse of the camera's world transformation matrix) to get it into view space.

Now it's in a space where +1 x means it's facing "right" from the camera's point of view, +1 y means it's facing "up", +1 z means it's facing "toward" the camera, and -1 z means it's facing "away". (If you're using an OpenGL right-handed coordinate system - adjust as needed for your coordinate conventions)

So, you can find which component of your vector is farthest from zero (greatest in absolute value), and label the face as facing that corresponding direction from the camera's point of view.

---
Tags: mathematics, camera, matrix, geometry, transformation
---


# Question
Title: How to slide along a wall at full speed?
I was reading this answer, and while it works for that use-case, mine is slightly different (simpler?), but I can't figure out how to do it.

What I'm looking for is a way for the player to retain their speed. That is, if they are running into a wall at 5 meters per second, then when they collide with the wall, regardless of the angle they hit the wall, they will slide along that wall at 5 meters per second.

I've illustrated an example of what I mean in the following picture:

The green arrows are the player velocities, the orange arrow is what I want the resulting velocity to look like, and the white lines are the rectangles the player is colliding with.

Is there a way to do this? If so, how? Also, does it require the dot product? My intuition is that it shouldn't, because we want to maintain the player's speed, but I'm not sure.

# Answer
> 2 votes
---

## Using the Dot Product

To begin, we reject the vector from the normal. I mean to subtract from the vector its projection over the normal. The vector projection looks like this:

```
Vector project(Vector a, Vector b)
{
    return b * (dotProduct(a, b)) / (dotProduct(b, b));
}

```

However, if we know we are projecting on a vector of already `1`, then `dotProduct(b, b)` is `1`. So we are left with:

```
Vector projectOnUnitVector(Vector a, Vector b)
{
    return b * (dotProduct(a, b));
}

```

So we are going to do this:

```
Vector undesiredMotion = normal * (dotProduct(input, normal))

```

Then we subtract, which leads us to the accepted answer of the linked question:

```
Vector undesiredMotion = normal * (dotProduct(input, normal));
Vector desiredMotion = input - undesiredMotion;

```

---

And then we can normalize the result and scale it to the length we want, like this:

```
Vector undesiredMotion = normal * (dotProduct(input, normal));
Vector desiredMotion = input - undesiredMotion;
Vector output = normalize(desiredMotion) * length(input);

```

---

## Using the Cross Product

I want to reiterate that I describe above is the general solution. **If you are working in 2D**, you have some advantages. First of all: You know all your vectors are coplanar.

So, we know that the result will be the normal, rotated a quarter turn (either clockwise or counterclockwise, we don't know yet) and scaled up to the length of the input.

And the second advantage is that doing the quarter turn rotation is trivial:

```
Vector2D rotateQuarterTurnCounterClockwise(Vector2D v)
{
    return Vector2D(-v.y, v.x);
}

```

Or:

```
Vector2D rotateQuarterTurnClockwise(Vector2D v)
{
    return Vector2D(v.y, -v.x);
}

```

But, what way do you want to turn it? Well, you want the result to turn from the input to the same side as the normal turns from the input. In other words, you the output have the same sign curl as the normal. I mean, you want the wedge product to have the sign. I mean, the length of the cross product. *The cross product has different sign if the vectors are turning to one side or the other.*

I mean:

```
sign(length(cross(input, normal))) == sign(length(cross(input, output)))

```

*The cross product here would expand the vectors with `0` on the third axis. I remind you that we are working in 2D. So this is an external product (the result is outside the space of the inputs).*

Now, as you know, if we multiply one tentative output by `-1`, we get the other one. *To reiterate, we either want the direction of the normal rotated a quarter turn clockwise or counterclockwise.*

So if we do this:

```
Vector2D direction = rotateQuarterTurnCounterClockwise(normal);
direction = direction * sign(length(cross(input, direction)));

```

We are always getting a direction that turns to the same side no matter what (if the direction was turning the other side, the product flips it). And then we do this:

```
Vector2D direction = rotateQuarterTurnCounterClockwise(normal);
direction = direction * sign(length(cross(input, direction)));
direction = direction * sign(length(cross(input, normal)));

```

So we get a direction that turns from the input to the same side as the normal turns from the input.

Then you can scale it:

```
Vector2D direction = rotateQuarterTurnCounterClockwise(normal);
direction = direction * sign(length(cross(input, direction)));
direction = direction * sign(length(cross(input, normal)));
Vector2D output = direction * length(input);

```

Actually, it will be like this when we are done with it, I explain what is going on below:

```
Vector2D direction = rotateQuarterTurnCounterClockwise(normal);
direction = direction * sign(wedge(input, direction));
direction = direction * sign(wedge(input, normal));
Vector2D output = direction * length(input);

```

**I want to reiterate that the approach I'm describing is for 2D only.**

*Although, you could take arbitrary input and normal vectors in 3D, find a plane that contains both, project, do the approach in this answer, and un-project the result… That extra work would decrease precision, decrease performance, and be error prone. Thus I would advice against it.*

---

Alright, let us unpack this:

```
sign(length(cross(a, b)))

```

The cross product is like this:

```
Vector3D crossProduct(Vector3D a, Vector3D b)
{
    return Vector3D(
        a.y * b.z - a.z * b.y,
        a.z * b.x - a.x * b.z,
        a.x * b.y - a.y * b.x
    );
}

```

We are, however, defining one that works on 2D vectors. And this happens:

```
Vector3D cross(Vector2D a, Vector2D b)
{
    return Vector3D(
        a.y * 0.0 - 0.0 * b.y,
        0.0 * b.x - a.x * 0.0,
        a.x * b.y - a.y * b.x
    );
}

```

In other words:

```
Vector3D cross(Vector2D a, Vector2D b)
{
    return Vector3D(
        0.0,
        0.0,
        a.x * b.y - a.y * b.x
    );
}

```

Only the z axis of the result has value (after all, it has to be perpendicular to the inputs, and the inputs are in the XY plane). Consequently, the length is the value of the z axis. Let me define a function for that:

```
float wedge(Vector2D a, Vector2D b)
{
    return a.x * b.y - a.y * b.x;
}

```

Therefore, instead of writing this:

```
sign(length(cross(a, b)))

```

We write this:

```
sign(wedge(a, b))

```

*And nobody has to complain that you can't make a cross product of 2D vectors.*

---

For contrast, this is dot product:

```
float dotProduct(Vector2D a, Vector2D b)
{
    return a.x * b.x + a.y * b.y;
}

```

Wait a minute… This:

```
float wedge(Vector2D a, Vector2D b)
{
    return a.x * b.y - a.y * b.x;
}

```

Is this:

```
float wedge(Vector2D a, Vector2D b)
{
    return dotProduct(a, Vector2D(b.y, -b.x))
}

```

**A dot product with a vector rotated a quarter turn clockwise!**

---

## Using Trigonometry

I suppose we can go about it yet another way: trigonometry. The idea is that we want to rotate the input vector. And we need to find out by what angle.

First we need to find the angle between the input and the normal… And that could be done with the dot product or the cross product, but since we want to do something else… Good old atan2:

```
float inputAngle = atan2(input.y, input.x);
float normalAngle = atan2(normal.y, normal.x);

```

**To be clear: this is also a 2D only solution.** *Project and un-project shenanigans apply.*

To find out if it is a positive or negative turn:

```
float inputAngle = atan2(input.y, input.x);
float normalAngle = atan2(normal.y, normal.x);
float turnSign = sign(normalAngle - inputAngle);

```

And the output angle will be:

```
float inputAngle = atan2(input.y, input.x);
float normalAngle = atan2(normal.y, normal.x);
float turnSign = sign(normalAngle - inputAngle);
float outputAngle = normalAngle + quarterTurn * turnSign;

```

*Here `quarterTurn` is the angle that represents a quarter turn. That is `90º`, or `TAU/4` radians, I mean… `PI/2`.*

And thus we need a turn of:

```
float inputAngle = atan2(input.y, input.x);
float normalAngle = atan2(normal.y, normal.x);
float turnSign = sign(normalAngle - inputAngle);
float outputAngle = normalAngle + quarterTurn * turnSign;
float turn = outputAngle - inputAngle;

```

We can rotate the input vector with a rotation matrix:

```
Vector output = RotationMatrix(turn) * input

```

Which is something like this:

```
         +-                        -+   +-         -+
         |  cos(turn)   -sin(turn)  |   |  input.x  |
output = |                          | * |           |
         |  sin(turn)   cos(turn)   |   |  input.y  |
         +-                        -+   +-         -+

```

Which is the same as:

```
         +-                                           -+
         |  input.x * cos(turn) - input.y * sin(turn)  |
output = |                                             |
         |  input.x * sin(turn) + input.y * cos(turn)  |
         +-                                           -+

```

In other words:

```
float c = cos(turn);
float s = sin(turn);
Vector2D output = Vector2D(input.x * c - input.y * s, input.x * s + input.y * c);

```

Wait, wait, I can rewrite that as two dot products:

```
float c = cos(turn);
float s = sin(turn);
Vector2D xRot = Vector2D(c, -s);
Vector2D yRot = Vector2D(s, c);
Vector2D output = Vector2D(dotProduct(input, xRot), dotProduct(input, yRot));

```

**Muahahahaha!**

*Embrace the dot product.*

---
Tags: physics, mathematics, vector, linear-algebra
---


# Question
Title: Attach images via script into array unity
I have 3 objects of `Image` type in game scene. So I need to attach this 3 objects via script into `Image` array inside of this script. How can I do this? I tried to use `GetComponent` but they all have different names and actually I don't know how to attach them.

# Answer
The first way is Using `GameObject.Find(name)` which works fine as long as you know the name of objects but a more easy-to-manage way, which I prefer to use, is getting help from Unity's inspector: just make your array serializable and then just a simple drag and drop in the inspector! the only thing you need to do is add `[Serializable]` before `private` to tell the unity that "I want you to serialize this!" and then add game objects into the array in the inspector.

But of course, there are other ways, such as giving all of them the same tag (like `UIImages`) and then finding them by `GameObject.FindWithTag()`. But my advice is that if you know which objects you want in your array and it never changes then use the inspector's abilities, otherwise using tags is a good way to go.

Final note: you can group them all in the hierarchy (make them all children of an empty parent) and then find that one and use `transform` to access its children
> 0 votes

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


# Question
Title: Is it possible to project a vector on another vector to calculate the distance without raycasting
I have the following game scenario:

Player is P and there are 2 enemies E1 and E2

I want to calculate the distance between the ennemies and **the player base** which is anywhere in that green line, and not the actual player character.

Currently if if I try to calculate the distance between enemies and players I get something like this:

But what i really want is this:

Now i could've just raycast from the enemies forward to hit the "base collider" but this is what am trying to avoid.

My question is:

If the green line is always going to be a "longer version" of the player Transform.Right vector, is there a way to project the Enemies Transform.forward vector, and now where it intersects with the player vector like this:

If you're curious about the reason behind this, then this image should clarify it:

Basically I need to create a "high threat zone" in front of the player, and based on the enemy distance to the "player base", i will give different feedback.

Thank you!

# Answer
> 1 votes
Solved it with **Vector3.Project()**

So basically what i needed to do is to project the enemies normal (in this case the forward) on the distance vector.

And then use the projection result's magnitude to determine the distance.

# Answer
> 0 votes
1. Defines the face direction(vfront) of the base.
2. v1 = e1 - p; v2= e2 - p
3. Obtain the dot product of v1 and v2 to vfront. If the result \< 0, the point is behind the "line".

Dot Product

---
Tags: unity, mathematics, vector
---


# Question
Title: Get index of chunk in flattened 2d array from world position
I have a world which is divided in chunks and saved in a flattened 2d array. The world is currently 80 units wide and high, and each chunk represent a 20x20 unit area.

This gives that in my flattened chunk array I have the following chunks:

```
Index 0 x: -40, y: -40
Index 1 x: -40, y: -20
Index 2 x: -40, y: 0
Index 3 x: -40, y: 20
Index 4 x: -20, y: -40
...
Index 10 x: 0, y: 0

```

Etc. It can be visualized like this (chunk index)

```
3, 7, 11, 15
2, 6, 10, 14
1, 5, 9,  13
0, 4, 8,  12

```

The flattening is done column first.

I now want to find the chunk index of a given world position, say x:4 and y:2, or x:-15 and y:5.

I know that I can loop through each row and column and find the first chunk which area covers the given position, but I would like to know if there's a mathematical function to solve this so I can compare it's performance to looping. My solution might fall apart as I scale up the world, as this calculation could be done very often (multiplayer game).

I know I can get the index of a position in a flattened array of positions given the formula (y * width) + x, but this is not applicable here since each index represents a range of positions.

# Answer
This is just basic division.

```
int column = floorToInt((x - minX) / 20f)
int row = floorToInt((y - minY) / 20f)

int chunkIndex = rowCount * column + row

```

`minX` and `minY` are the coordinates of the bottom-left chunk in your grid, so -40 each in this example.
> 0 votes

---
Tags: mathematics, open-world, position, array
---


# Question
Title: What's the best way of transforming a 2D vector into the closest 8-way compass direction?
If you have a 2D vector expressed as x and y, what's a good way of transforming that into the closest compass direction?

e.g.

```
x:+1,  y:+1 => NE
x:0,   y:+3 => N
x:+10, y:-2 => E   // closest compass direction

```

# Answer
> 29 votes
The simplest way is probably to get the angle of the vector using `atan2()`, as Tetrad suggests in the comments, and then scale and round it, e.g. (pseudocode):

```
// enumerated counterclockwise, starting from east = 0:
enum compassDir {
    E = 0, NE = 1,
    N = 2, NW = 3,
    W = 4, SW = 5,
    S = 6, SE = 7
};

// for string conversion, if you can't just do e.g. dir.toString():
const string[8] headings = { "E", "NE", "N", "NW", "W", "SW", "S", "SE" };

// actual conversion code:
float angle = atan2( vector.y, vector.x );
int octant = round( 8 * angle / (2*PI) + 8 ) % 8;

compassDir dir = (compassDir) octant;  // typecast to enum: 0 -> E etc.
string dirStr = headings[octant];

```

The `octant = round( 8 * angle / (2*PI) + 8 ) % 8` line might need some explanation. In pretty much all languages that I know of that have it, the `atan2()` function returns the angle in radians. Dividing it by 2*π* converts it from radians to fractions of a full circle, and multiplying by 8 then converts it to eighths of a circle, which we then round to the nearest integer. Finally, we reduce it modulo 8 to take care of the wrap-around, so that both 0 and 8 are correctly mapped to east.

The reason for the `+ 8`, which I skipped past above, is that in some languages `atan2()` may return negative results (i.e. from −*π* to +*π* rather than from 0 to 2*π*) and the modulo operator (`%`) may be defined to return negative values for negative arguments (or its behavior for negative arguments may be undefined). Adding `8` (i.e. one full turn) to the input before reduction ensures that the arguments are always positive, without affecting the result in any other way.

If your language doesn't happen to provide a convenient round-to-nearest function, you can use a truncating integer conversion instead and just add 0.5 to the argument, like this:

```
int octant = int( 8 * angle / (2*PI) + 8.5 ) % 8;  // int() rounds down

```

Note that, in some languages, the default float-to-integer conversion rounds negative inputs up towards zero rather than down, which is another reason to make sure that the input is always positive.

Of course, you can replace all occurrences of `8` on that line with some other number (e.g. 4 or 16, or even 6 or 12 if you're on a hex map) to divide the circle into that many directions. Just adjust the enum/array accordingly.

# Answer
> 10 votes
You have 8 options (or 16 or more if you want even finer precision).

Use `atan2(y,x)` to get the angle for your vector.

`atan2()` works in the following way:

So x=1, y=0 will result in 0, and it's discontinuous at x=-1, y=0, containing both π and -π.

Now we just need to map the output of `atan2()` to match that of the compass we have above.

Likely the simplest to implement is a incrementing check of angles. Here's some pseudo code that easily be modified for increased precision:

```
//start direction from the lowest value, in this case it's west with -π
enum direction {
west,
south,
east,
north
}

increment = (2PI)/direction.count
angle = atan2(y,x);
testangle = -PI + increment/2
index = 0

while angle > testangle
    index++
    if(index > direction.count - 1)
        return direction[0] //roll over
    testangle += increment

return direction[index]

```

Now to add more precision, simply add the values to the direction enum.

The algorithm works by checking increasing values around the compass to see if our angle lays somewhere between where we last checked and the new position. That's why we start at -PI + increment/2. We want to offset our checks to include equal space around each direction. Something like this:

West is broken in two because of the return values of `atan2()` at West are discontinuous.

# Answer
> 8 votes
Whenever you're dealing with vectors, consider fundamental vector operations instead of converting to angles in some particular frame.

Given a query vector `v` and a set of unit vectors `s`, the most-aligned vector is the vector `s_i` that maximizes `dot(v,s_i)`. This is due to that the dot product given fixed lengths for the parameters has a maximum for vectors with the same direction and a minimum for vectors with opposing directions, changing smoothly inbetween.

This generalizes trivially into more dimensions than two, is extensible with arbitrary directions and doesn't suffer frame-specific problems like infinite gradients.

Implementation-wise, this would boil down to associating from a vector in each cardinal direction with an identifier (enum, string, whatever you need) representing that direction. You would then loop over your set of directions, finding the one with the highest dot product.

```
map<float2,Direction> candidates;
candidates[float2(1,0)] = E; candidates[float2(0,1)] = N; // etc.

for each (float2 dir in candidates)
{
    float goodness = dot(dir, v);
    if (goodness > bestResult)
    {
        bestResult = goodness;
        bestDir = candidates[dir];
    }
}

```

# Answer
> 3 votes
One way that hasn't been mentioned here is treating the vectors as complex numbers. They don't require trigonometry and can be pretty intuitive for adding, multiplying or rounding rotations, especially since you're already have your headings represented as pairs of numbers.

In case you're not familiar with them, the directions are expressed in the form of a + b(i) with a being the real component and b(i) is the imaginary. If you imagine the cartesian plane with the X being real and Y being imaginary, 1 would be east (right), i would be north.

Here is the key part: **The 8 cardinal directions are represented exclusively with the numbers 1, -1 or 0 for their real and imaginary components.** So all you have to do is reduce your X, Y coordinates as a ratio and round both to the closest whole number to get the direction.

```
NW (-1 + i)       N (i)        NE (1 + i)
W  (-1)          Origin        E  (1)
SW (-1 - i)      S (-i)        SE (1 - i)

```

For heading-to-nearest diagonal conversion, reduce both X and Y proportionally so the larger value is exactly 1 or -1. Set

```
// Some pseudocode

enum xDir { West = -1, Center = 0, East = 1 }
enum yDir { South = -1, Center = 0, North = 1 }

xDir GetXdirection(Vector2 heading)
{
    return round(heading.x / Max(heading.x, heading.y));
}

yDir GetYdirection(Vector2 heading)
{
    return round(heading.y / Max(heading.x, heading.y));
}

```

Rounding both components of what was originally (10, -2) gives you 1 + 0(i) or 1. So the closest direction is east.

The above doesn't actually require the use of a complex number structure, but thinking of them as such makes it quicker to find the 8 cardinal directions. You can do vector math the usual way if you want to get the net heading of two or more vectors. (As complex numbers, you don't add, but multiply for the result)

# Answer
> 0 votes
Wonder, why so complicated? (not sure what language, so keep it general)

If you want the 8 direction from a Vector2, just normalize it and then round it. Maybe something like:

```
var length = Math.sqrt(x * x + y * y);
x /= length;
y /= length;

```

Then round:

```
rX = Math.round(x);
rY = Math.round(y);

```

Then you could still convert to String, like Philipp explained:

```
string result = "";
if (rY < 0.1)
    result.Append("N");
else if (rY > 0.1)
    result.Append("S");
if (rX < 0.1)
    result.Append("W");
else if (rX > 0.1)
    result.Append("E");

```

0.1 is just in case if floating point precision issues, except you rounded to int, then you are safe with 0. Or do I miss something?

# Answer
> -2 votes
this seems to work:

```
public class So49290 {
    int piece(int x,int y) {
        double angle=Math.atan2(y,x);
        if(angle<0) angle+=2*Math.PI;
        int piece=(int)Math.round(n*angle/(2*Math.PI));
        if(piece==n)
            piece=0;
        return piece;
    }
    void run(int x,int y) {
        System.out.println("("+x+","+y+") is "+s[piece(x,y)]);
    }
    public static void main(String[] args) {
        So49290 so=new So49290();
        so.run(1,0);
        so.run(1,1);
        so.run(0,1);
        so.run(-1,1);
        so.run(-1,0);
        so.run(-1,-1);
        so.run(0,-1);
        so.run(1,-1);
    }
    int n=8;
    static final String[] s=new String[] {"e","ne","n","nw","w","sw","s","se"};
}

```

# Answer
> -2 votes
E=0,NE=1,N=2,NW=3,W=4,SW=5,S=6,SE=7

f(x,y)=mod((4-2\*(1+sign(x))\* (1-sign(y^2))-(2+sign(x))\*sign(y)

```
    -(1+sign(abs(sign(x*y)*atan((abs(x)-abs(y))/(abs(x)+abs(y))))

    -pi()/(8+10^-15)))/2*sign((x^2-y^2)*(x*y))),8)

```

# Answer
> -4 votes
When you want a string:

```
h_axis = ""
v_axis = ""

if (x > 0) h_axis = "E"
if (x < 0) h_axis = "W"
if (y > 0) v_axis = "S"
if (y < 0) v_axis = "N"

return v_axis.append_string(h_axis)

```

This gives you constants by utilizing bitfields:

```
// main direction constants
DIR_E = 0x1
DIR_W = 0x2
DIR_S = 0x4
DIR_N = 0x8
// mixed direction constants
DIR_NW = DIR_N | DIR_W
DIR_SW = DIR_S | DIR_W
DIR_NE = DIR_N | DIR_E
DIR_SE = DIR_S | DIR_E

// calculating the direction
dir = 0x0

if (x > 0) dir |= DIR_E
if (x < 0) dir |= DIR_W
if (y > 0) dir |= DIR_S
if (y < 0) dir |= DIR_N

return dir

```

A slight performance improvement would be to put the `<`-checks into the else-branch of the corresponding `>`-checks, but I refrained from doing that because it harms readability.

---
Tags: algorithm, sprites, vector
---


# Question
Title: Is there an alternative to Update for continuously spawning an object?
What I did here works, but it looks messy and funny to me.

```
void Update()
{
    rb = GetComponent<Rigidbody2D>();

    if(BossHP <= 2)
    {
        PhaseTwo.Invoke();
    }
}

private void OnTriggerEnter2D(Collider2D collision)
{
    if(collision.gameObject.CompareTag("Circle"))
    {
        BossHP--;
        Debug.Log(BossHP);
    }
}

```

When I put `if(BossHP <= 2) { PhaseTwo.Invoke(); }` under `void OnTriggerEnter2D`, it only spawns once. So that's why I put under Update. But ...is this the right way? It looks funny to me.

# Answer
> 0 votes
The reason it's only invoking `PhaseTwo` once is likely because the circle continues overlapping this script's object. `OnTriggerEnter2D` won't get called again for this pair of colliders until the colliders separate and then overlap again.

If you want to continuously invoke this event every frame after reaching this threshold health, an alternative would be to start a coroutine:

```
const int LOW_HEALTH_THRESHOLD = 2;
Coroutine _lowHealthLoop;

private IEnumerator LowHealth() {
    while (BossHP < LOW_HEALTH_THRESHOLD) {
        PhaseTwo.Invoke();
        yield return null;
    }
    _lowHealthLoop = null;
}

private void OnTriggerEnter2D(Collider2D collision)
{
    if(collision.gameObject.CompareTag("Circle"))
    {
        BossHP--;
        Debug.Log(BossHP);

        if (BossHP < LOW_HEALTH_THRESHOLD && _lowHealthLoop == null) {
            _lowHealthLoop = StartCoroutine(LowHealth());
        }
    }
}

```

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


# Question
Title: Calculate the angle of rotation between two vectors relative to the first vector
I'm trying to get the angle between two 2D vectors relative to the first vector input. Every method I've tried has given me a value between 0-180 degrees but doesn't tell me whether it was a clockwise or counter-clockwise rotation.

For example: If I hold my forward vector in a variable and then turn counter-clockwise 45 degrees and use that as my second forward vector, I'm looking for -45 or 315 degrees as the output, not 45.

# Answer
```
float AngleBetween(Vector2 a, Vector2 b) {
    // Get a vector rotated 90 degrees from a.
    Vector2 perpendicular = new Vector2(a.y, -a.x);

    // Compute a scaled projection of b onto the original and rotated version.
    float x = Vector2.Dot(a, b);
    float y = Vector2.Dot(perpendicular, b);

    // Treat these as a point in a coordinate system where a is the x axis,
    // and perpendicular is the y axis, and get the polar angle of that point.
    return Mathf.Atan2(y, x);
}

```
> 0 votes

# Answer
There is a solution for unity (Maybe there is a better solution, but it works):

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

public class NewBehaviourScript : MonoBehaviour
{
    void Start()
    {
        var v1 = new Vector3(1, 1, 0);//45
        var v2 = new Vector3(1, 0, 0);//0

        Debug.Log(GetDegree(v1, v2));
        Debug.Log(GetDegree(v2, v1));
    }

    private float GetDegree(Vector3 from, Vector3 to)
    {
        var rot = Quaternion.FromToRotation(from, to);
        var angle = 0.0f;
        var axis = Vector3.zero;
        rot.ToAngleAxis(out angle, out axis);

        if (Vector3.forward == axis)
        {
            return angle;
        }
        else
        {
            return angle - 360f;
        }
    }
}

```

Output:

```
-315
44.99999

```
> 0 votes

---
Tags: rotation, vector, linear-algebra, angles
---


# Question
Title: How to use pingpong in the waypoints script?
I tried this : And the pingPong is working but after some times changing the pingpong flag true false many times i'm getting index out of bound exception :

The pingpong line that give the exception :

```
transform.position = Vector3.Lerp(pos[index + 30], pos[index], Mathf.PingPong(Time.time, 1));

```

And how i tried to use the pingPong :

```
void Move()
    {
        if (pingPong)
        {
            transform.position = Vector3.Lerp(pos[index + 30], pos[index], Mathf.PingPong(Time.time, 1));
        }
        else
        {
            Vector3 newPos = transform.position;
            float distanceToTravel = speed * Time.deltaTime;

            bool stillTraveling = true;
            while (stillTraveling)
            {
                if (changeDir && goForward)
                {
                    goForward = false;
                }
                if (changeDir == false && goForward == false)
                {
                    goForward = true;
                }

                Vector3 oldPos = newPos;

                newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);

                distanceToTravel -= Vector3.Distance(newPos, oldPos);
                if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
                {
                    // when you hit a waypoint:
                    if (goForward)
                    {
                        atLastOne = index >= pos.Length - 1;
                        if (!atLastOne)
                        {
                            index++;
                            counter++;
                            if (counter == numofposbetweenpoints)
                            {
                                c++;

                                counter = 0;
                            }
                            if (c == curvedLinePoints.Count - 1)
                            {
                                c = 0;
                            }
                        }
                        else
                        {
                            if (stop && index == pos.Length - 1)
                            {
                                break;
                            }
                            else
                            {
                                if (loop)
                                {
                                    index = 0;
                                }
                                else
                                {
                                    index--;
                                    goForward = false;
                                }
                            }
                        }
                    }
                    else
                    { // going backwards:
                        bool atFirstOne = index <= 0;
                        if (!atFirstOne)
                        {
                            index--;

                            counter++;
                            if (counter == numofposbetweenpoints)
                            {
                                c++;

                                counter = 0;
                            }
                            if (c == curvedLinePoints.Count - 1)
                            {
                                c = 0;
                            }
                        }
                        else
                        {
                            if (stop && index == 0)
                            {
                                break;
                            }
                            else
                            {
                                if (loop)
                                {
                                    index = pos.Length - 1;
                                }
                                else
                                {
                                    index++;
                                    goForward = true;
                                }
                            }
                        }
                    }
                }
                else
                {
                    stillTraveling = false;
                }
            }

            transform.position = newPos;
        }
    }

```

The full script :

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

public class MoveOnCurvedLines : MonoBehaviour
{
    public LineRenderer lineRenderer;
    public float speed;
    public bool go = false;
    public bool moveToFirstPositionOnStart = false;
    public float rotSpeed;
    public bool loop = false;
    public bool changeDir = false;
    public bool pingPong = false;
    public bool stop = false;
    public bool random = false;
    public int currentCurvedLinePointIndex;
    public TextMeshProUGUI lastWaypointText;
    public TextMeshProUGUI countWaypointText;

    private Vector3[] positions;
    private Vector3[] pos;
    private int index = 0;
    private bool goForward = true;
    private List<GameObject> curvedLinePoints = new List<GameObject>();
    private int numofposbetweenpoints;
    private bool getPositions = false;
    int randomIndex;
    int curvedPointsIndex;
    private bool atLastOne = false;

    // Start is called before the first frame update
    void Start()
    {
        curvedLinePoints = GameObject.FindGameObjectsWithTag("Curved Line Point").ToList();

        if (curvedLinePoints != null && curvedLinePoints.Count > 0)
        {
            transform.rotation = curvedLinePoints[1].transform.rotation;
        }

        if (random)
            GetNewRandomIndex();

        if (lastWaypointText != null)
        {
            lastWaypointText.text = "Last Waypoint : " + (curvedPointsIndex + 1).ToString();
        }

        if (countWaypointText != null)
        {
            countWaypointText.text = "Waypoints Count : " + curvedLinePoints.Count.ToString();
        }
    }

    Vector3[] GetLinePointsInWorldSpace()
    {
        if (lineRenderer != null)
        {
            positions = new Vector3[lineRenderer.positionCount];
            //Get the positions which are shown in the inspector
            lineRenderer.GetPositions(positions);

        }

        //the points returned are in world space
        return positions;
    }

    // Update is called once per frame
    void Update()
    {
        if (lineRenderer != null)
        {
            if (curvedLinePoints.Count > 0)
            {
                for (int i = 0; i < curvedLinePoints.Count; i++)
                {
                    if (curvedLinePoints[i].transform.hasChanged)
                    {
                        getPositions = false;
                    }
                }
            }

            if (lineRenderer.positionCount > 0 && getPositions == false)
            {
                pos = GetLinePointsInWorldSpace();

                numofposbetweenpoints = pos.Length / curvedLinePoints.Count;

                if (moveToFirstPositionOnStart == true)
                {
                    transform.position = pos[index];
                }

                getPositions = true;
            }

            if (go == true && lineRenderer.positionCount > 0)
            {
                Move();

                Vector3 targetDirection = (curvedLinePoints[c].transform.position - transform.position).normalized;
                curvedLinePoints[c].transform.localRotation = Quaternion.LookRotation(targetDirection);
                transform.localRotation = Quaternion.RotateTowards(transform.localRotation, curvedLinePoints[c].transform.localRotation, Time.deltaTime * rotSpeed);
            }

            if (curvedLinePoints.Count > 1)
            {
                var dist = Vector3.Distance(transform.position, curvedLinePoints[curvedPointsIndex].transform.position);
                if (dist < 0.1f)
                {
                    if (curvedPointsIndex < curvedLinePoints.Count - 1)
                    {
                        curvedPointsIndex++;

                        if (lastWaypointText != null)
                        {
                            lastWaypointText.text = "Last Waypoint : " + curvedPointsIndex.ToString();
                        }
                    }
                    else
                    {
                        if (lastWaypointText != null)
                        {
                            lastWaypointText.text = "Last Waypoint : " + (curvedPointsIndex + 1).ToString();
                        }

                        curvedPointsIndex = 0;
                    }

                    currentCurvedLinePointIndex = curvedPointsIndex;
                }
            }
        }
    }

    int counter = 0;
    int c = 1;
    void Move()
    {
        Vector3 newPos = transform.position;
        float distanceToTravel = speed * Time.deltaTime;

        bool stillTraveling = true;
        while (stillTraveling)
        {
            if(changeDir && goForward)
            {
                goForward = false;
            }
            if(changeDir == false && goForward == false)
            {
                goForward = true;
            }

            if(pingPong)
            {
                if(goForward)
                {
                    transform.position = Vector3.Lerp(pos[index + 1], pos[index], Mathf.PingPong(Time.time, 1));
                }
            }

            Vector3 oldPos = newPos;

            newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);

            distanceToTravel -= Vector3.Distance(newPos, oldPos);
            if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
            {
                // when you hit a waypoint:
                if (goForward)
                {
                    atLastOne = index >= pos.Length - 1;
                    if (!atLastOne)
                    {
                        index++;
                        counter++;
                        if (counter == numofposbetweenpoints)
                        {
                            c++;

                            counter = 0;
                        }
                        if (c == curvedLinePoints.Count - 1)
                        {
                            c = 0;
                        }
                    }
                    else
                    {
                        if (stop && index == pos.Length - 1)
                        {
                            break;
                        }
                        else
                        {
                            if (loop)
                            {
                                index = 0;
                            }
                            else
                            {
                                index--;
                                goForward = false;
                            }
                        }
                    }
                }
                else
                { // going backwards:
                    bool atFirstOne = index <= 0;
                    if (!atFirstOne)
                    {
                        index--;

                        counter++;
                        if (counter == numofposbetweenpoints)
                        {
                            c++;

                            counter = 0;
                        }
                        if (c == curvedLinePoints.Count - 1)
                        {
                            c = 0;
                        }
                    }
                    else
                    {
                        if (stop && index == 0)
                        {
                            break;
                        }
                        else
                        {
                            if (loop)
                            {
                                index = pos.Length - 1;
                            }
                            else
                            {
                                index++;
                                goForward = true;
                            }
                        }
                    }
                }
            }
            else
            {
                stillTraveling = false;
            }
        }

        transform.position = newPos;
    }

    void GetNewRandomIndex()
    {
        randomIndex = UnityEngine.Random.Range(0, curvedLinePoints.Count);
    }
}

```

# Answer
Here's a debug suggestion:

Given that there are so many places to set the value of `index`,You can do an interception like:

Replce: `private int index = 0;` with:

```
private int _index = 0;
private int index
{
    get
    {
        return _index;
    }
    set
    {
        if (value < 0 || value > pos.Length - 1 || value + 30 < 0 || value + 30 > pos.Length - 1)
        {
            Debug.Log($"{value},{pos.Length}");
            Debug.Log(System.Environment.StackTrace);
        }
        _index = value;
    }
}

```

Or if the debugger is working, simply set a conditional breakpoint here.
> 0 votes

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


# Question
Title: How to mathematically define a 'balance budget'?
I have three classes: A, B and C. Each has a burst spell that have a pre-delay before the damage is dealt. Class A *also* has a burst spell that deals the damage instantly and then has a post-delay before it can be cast again. Post-delay spells are more desirable for the players because they provide easier opportunity for safer hit-run tactics that don't require standing around being hit while your spells prepare to go off.

Class A has no healing and no natural damage mitigation although they can somewhat improve their mitigation with armour.

Class B has an excellent amount of natural damage mitigation but can only improve it a limited amount through additional armour.

Class C can heal itself and has reasonable damage mitigation which can be greatly improved through additional armour.

Class A spell x:

* pre-cast delay 2 rounds
* avg damage per round of: 24.3614
* avg sp cost per round of: 24.2243
* avg damage taken per round: 11.014

spell y:

* post cast delay of 2 rounds
* avg damage per round of: 15.4851
* avg sp cost per round of: 19.1129
* avg damage taken per round: 11.45

Class B spell w:

* pre-cast delay of 3 rounds
* avg damage per round of: 18.487
* avg sp cost per round of: 8.333
* avg damage taken per round: 6.326

So a slower cast time lowers the damage per round even though the actual burst is decent, plus very efficient to cast.

Class C spell z:

* pre-cast delay of 2 rounds
* avg damage per round of: 25.1447
* avg sp cost per round of: 32.7974
* avg damage taken per round: 8.6371 (base defence, no armour)

So a decent chunk of damage but nearly as efficient to cast.

My question is how can I create some kind of balance calculation for determining the relative values of things? For example my argument is that spell y is significantly under powered, even though it has a post delay, but I don't know how to calculate what might be an appropriate improvement for it. I lack the mathematical vocabulary to describe what I need, but what I *think* I need is some way to describe a 'balance budget' - "If I add x damage here I have to tweak this" but I don't know how to begin planning it out. Does this make sense? Should I try and get more information? Am I missing something fundamental, which is why I can't untangle my own brain?

# Answer
*This answer does not solve the problem. You have been warned.*

---

If you are thinking what I think you are thinking, it might not be possible. I'll describe why. However, I would also argue that if it is possible in you case, you might not want it to be.

The issue is that once you have multidimensional numbers (think vectors, or imaginary numbers, or matrices), there is no total ordering. And by that I mean that regardless of how you decide to compare elements, you may find elements that are different but neither one is greater than the other. Or you may find that if one element X is greater than another element Y, and that other element Y is greater than a third element Z, it does not imply that X is greater than Z.

In your case, we can describe the spells as points in higher dimensional space, where each coordinate is one of its attributes (delay, damage, etc…). And that means there might not necessarily be a way to sort them.

However, there could be a way to sort them. That happens if the attributes are correlated. I mean, they are not independent variables. In which case we could be able to find some hidden variable that can be used as an input parameter to predict the attributes. Then we can sort them by that hidden variable.

And, to be fair, such parameter can be useful in game design. For instance, if we have parameter that controls how difficult the enemies are, we can set it to increase steadily to make a difficulty curve. However, I would encourage to have at least some other parameter to add variety. And then we are back at multidimensional numbers.

In fact, I would like to encourage to go for a rotating meta. To illustrate, consider if A is perceived as the strong class and many player pick it, but B has an edge over A, then there will a growing population of player that pick B as response to players that pick A. In response the players that pick A may move to C to counter the player that pick B, decreasing the number of player that pick A, and eventually the players that pick B would look for a way to counter player picking C... and the counter to picking C can be picking A, making a loop. So the meta game rotates from picking A, to B to C and back to A. Duck season, Rabbit season, Duck season, Rabbit season, you get the idea.

We find this kind of design often. It can be referred as Rock-Paper-Scissors or Water-Plant-Fire or Infantry-Archery-Chivalry. Of course, it does not have to be a loop of three things, it just that those are common and easy to spot. *You may also be interested in Intransitive dice. See also the concept of Strange Loop.*

So I would encourage you to go for a design like that. So that all your classes are viable. None is evidently the best or the worst. And they all see play. *And if that isn't balance, it is a good substitute.*

---

Alright, but is you current design like that or not? And if not, what values should you tweak? And by how much? I HAVE NO IDEA.

I can infer some things from what you say, which I might be getting wrong. Since balance is important between these classes, I'm assuming competitive multiplayer. Since you say hit and run, I know there is movement. But I don't know if these classes all move the same, or if there is some kind of terrain advantage. Also, you say rounds, so I'm guessing this is turn based.

Consider that the difference between a 10 damage and 15 damage is not that relevant when the opponent can only take 3 damage, so they are both one hit death. And the difference between 5, 6, and 7 damage is not that large if the enemy can take 15 damage, so they all kill in three hits. So you don't see result grow linearly with the attributes.

And I don't know how much damage they can take, how their healing and damage mitigation works etc. And... Is there randomness? Critical hits, and stuff like that?

And even if I knew, it would not make the task of figuring out to balance them easier, since there are tons and tons of variables. In fact, that means the "None is evidently the best or the worst" part of our "balance" is covered, which is good. If you don't know if a little tweak here or a little tweak there makes a difference, it means you are getting there.

---

But your code does know. I presume you have expended some time encoding all the rules in software. So, I will suggest to add to them some autonomous agents that can use them, have them fight and find out who wins over who. And use that as test bed for your possible tweaks.

Of course, that won't account for any clever tactics your player may come up with, but it should give you a base line. Furthermore, once you bring play testers, you might incorporate their feedback. And yes, none of that guarantees you would not have to re-balance after launch.

To future proof the design, you need to find where it breaks. Instead of looking for the perfect balance, look for the edge cases. How much is too much or too little for your attributes. So you can carve an space where you can add new classes with relative confidence that you will not break the balance… *too much*.

---

And yes, that means some will be slightly better than others. Let people do their analysis, and come up with their tier lists.

In fact, have your own tier list. If you have statistics of which classes get more play, you can start by re-balancing those that see less play, which are likely those that are lagging behind. *Just, don't rush to do it. It might be just Duck season.* That way you are less likely to nerf in ways players don't like, because you are buffing the stragglers instead. And you minimize the number of annoyed players because you changed their class, because you are changing the less played classes anyway.

A corollary to that is that you probably want to introduce new classes slightly under-powered, so you have room to buff them if you need to. The new class will see play out of curiosity, which will dwindle after a while. From that initial spike you can gather information on how people use it. Yet, you might want to wait to see if the new class join the rotating meta or not before revisiting it.
> 2 votes

---
Tags: balance
---


# Question
Title: With GGPO rollback netcode, how many times might I need to update my game engine in one frame?
I'm working on a game that's going to use GGPO for rollback netcode. I understand the need for a deterministic engine whose state can be saved, restored, advanced from user inputs, etc. I understand that I may need to do this several times in a frame, and that therefore, from a performance point of view, updating the game engine needs to be fast enough to be called more than once in a frame.

My question is.... how many updates in a frame do I realistically need to budget for? If I can identify a realistic worst case, I'll simply run my game engine that many times a frame while I'm developing it.

# Answer
Your assumption that you can find a realistic worst case is correct, but you need concrete connection data to know with certainty. Without concrete data, lets approximate one. *Caveat: It's been years since I've done GGPO, might be wrong.*

---

## NetCode Vars:

* Simulation rate: 60hz (16.67ms)
* Forced, always-on input latency: 3 frames (~50ms)
* Sending 4 previous inputs per packet.
* Assuming no other input buffering on client/server.

---

## Estimated Worst-Case Network:

* Worst playable ping: 300±50ms = 350ms (175ms each way)
* Assume "1 dropped packet" as a common occurrence.
* Assume "2 or more dropped packets" as rare enough to be excluded.
* I.e. If we drop 2 packets in a row, we'll probably drop for an extended period of time (1s or more), which will *always* max out simulation frames during catch-up.

---

## "Catch-up" pro tips:

* Turn off prediction (and even rendering) during this catch-up as the game is unplayable anyway. If you're already catching up 20 frames in a single frame, adding another 20 for prediction is obviously silly.
* Rate-limit catch up too to ensure frame rate is stable.

---

## Worst delta between our predicted vs verified state:

* **SUB** 3 frames (-50ms) for forced input latency. Nice.
* **ADD** 0 to 16ms for input registering.
* **ADD** 175ms for attackers input packet delay to server.
* **ADD** 1 frame for a dropped packet (which, as assumed, is common).
* **ADD** 0 to 16ms for server packet processing.
* **ADD** 175ms for victims packet delay from server.
* **ADD** 0 to 16ms for packet processing, then triggering rollback.

## Total: 350ms

= ~22 frames worst case = Realistically jumping around from 12 to 22 frames almost randomly.

Essentially the 3 frames of forced input latency cancels out the 3 processing times, leaving only the ping + jitter.

---

## 22 is obviously a lot, so you can reduce it via:

* Lower the worst allowed ping. 350ms is extremely bad these days. I.e. Most connections should be far better than this, especially if we've got per-region game servers. You'll need to gather data on this and see what % of the player-base you're excluding by lowering this cap.
* Increase forced input latency, especially in these cases. E.g. 6 frames (100ms) on connections this poor. Keep this as stable as possible.
* Lower simulation tick rate.

---

## **Side Note on "Forced Input Latency"**

It's OP. Because it's fixed, it's consistent, so it just feels like part of the game. Players get used to it much more than a variable latency. Also, it means that on fantastic connections, you predict **0** frames on average. I.e. Both players see ***exactly*** the same thing.
> 3 votes

# Answer
I haven't used GGPO but reading through the documentation, it looks like you would just use the amount of updates that your engine needs. I think that's 1 per frame. Looking at the diagram:

It looks like the prediction serves as the remote update for the most part. You would track player input locally, update with predictions, validate with real remote data, rollback when appropriate.

From the docs:

> GGPO checks the quality of its prediction for previous frames every time it receives a remote input. As mentioned earlier, GGPO doesn't receive the inputs for player 2's first frame until player 1's fourth. At frame 4, GGPO notices that the inputs received from the network do not match the predicted inputs sent earlier. To resynchronize the two games, GGPO needs to undo the damage caused by running the game with incorrect inputs for 3 frames. It does this by asking the game engine to go back in time to a frame before the erroneously speculated inputs were sent (i.e. to "rollback" to a previous state). Once the previous state has been restored, GGPO asks the engine to move forward one frame at a time with the corrected input stream. These frames are shown in light blue. Your game engine should advance through these frames as quickly as possible with no visible effect to the user. For example, your video renderer should not draw these frames to the screen. Your audio renderer should ideally continue to generate audio, but it should not be rendered until after the rollback, at which point samples should start playing n frames in, where n is the current frame minus the frame where the sample was generated. Once your engine reaches the frame it was on before GGPO discovered the error, GGPO drops out of rollback mode and allows the game to proceed as normal. Frames 5 and 6 in the diagram show what happens when GGPO predicts correctly. Since the game state is correct, there's no reason to rollback.

I would see no reason to update more than once per frame, every frame.
> 1 votes

---
Tags: networking, performance, peer-to-peer
---


# Question
Title: Would programming a feature similar to another game be copying?
I've been, *very slowly*, working on a game similar to Minecraft and Hytale, and when I am at the point, include features similar to these mods:

As I was thinking about the workflow of this project, I wondered if I would have to have some sort of credit towards the creators of the mods, or have to not implement the features / change it in a way where it is not as similar.

I've read up on this question, but I feel as though it is questionable as some mod creators require credit when creating a modpack.

In simple terms, if I made these into features for my game, ***from scratch, not as in taking their code***, how similar could it be or would I have to credit the original creator of the mod?

# Answer
It's possible for one party to infringe on other works of another even if they didn't use the other party's code. In fact, that's typically the situation - most infringement suits are based on similarity & likeness. There are some cases that allege code theft, but those seem to be the exception rather than the norm.

The relevant legal system determines what is "too similar". In the US, cases are argued based on prior case law and the evidence at hand including but not limited to how similar the products appear, similarity of other uncontested products & evidence of intent. As already covered in the accepted answer to the linked question, game mechanics are not protected by copyright. However, it does protect the particular manner of an author’s expression in literary, artistic, or musical form.

Certain aspects of a games fall under scène à faire. These are elements that are considered necessary for the genre in question. While you cannot copy these elements directly from another game, the use of said elements do not constitute infringement. For instance, the use of a speedometer in a racing game would almost certainly be deemed fair whereas replicating the speedometer from an existing vehicle or game would not fall under scène à faire & could be grounds for an infringement suit.

You should consult a legal professional if you want to know how likely it is that a particular product infringes on another.

Regarding attribution, legally that depends on whether or not you benefited from material that was released to you under a license. I don't know if there are any prior cases that clearly spell out what is & what is not a derivative work. I have read of projects that try to avoid the problem all together by not even looking at the code of similar projects if the other projects are under an incompatible license.

That said, even if you don't have a legal obligation to give credit to others, it's generally considerate to do so.
> 0 votes

---
Tags: game-design, game-mechanics
---


title: Rotating an Icon On MiniMap

text:
# Question
Title: Rotating an Icon On MiniMap
I'm creating a minimap for my game. There is a mission where the player has to escort an NPC to an area. The minimap shows the player, the NPC and the location. The NPC icon sends an arrow from it's icon on the minimap to the destination location.

The minimap is zoomed in around the player and the location may be farther away then the minimap area, in this case, I put it on the edge of the minimap to make it still visible.

I'm using the dot product to calculate the angle between the NPC and the destination location, using a up vector (0,1). This works until the NPC is on the edge of the minimap. The angle is slightly off and the arrow icon is turned to the side.

I've confirmed both positions on the minimap are correct and the angle between them should be relatively small, but the calculation is too large. I'm unable to post a picture of the minimap here for NDA reasons, but I included a picture of the blueprint.

The arrow icon is facing down, which means it needs to be offset by some degrees depending on the quadrant, thus the addition at the end of the blueprint.

# Answer
I fixed the bug. The dot product calculation was using cos instead of acos. Changing this fixed the problem.
> 1 votes

---
Tags: 2d, mathematics, rotation, unreal-4, minimap
---


# Question
Title: Can't add script behaviour Interactable. The script class can't be abstract!
I'm building a Raycast setup where game objects run code on click / touch.

```
if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, maxDistance, interactableLayers))
     {

         if  (Input.GetButtonDown("Fire1"))
         {
             if (hit.collider != null)
             {

             currentInteractable = hit.collider.GetComponent<Interactable>();

             Debug.Log(hit.collider.name);

             }
         }

```

I'm following a tutorial where I must use an Interface to configure OnClick Actions for each game object:

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

 // public class Interactable : MonoBehaviour

 // {

   public interface Interactable
   {

     void onClickAction();

   }
```

However, I'm receiving a bunch of errors! I can't add this Interactable script to my game object and receive the error: "Can't add script behaviour Interactable. The script class can't be abstract!"

I also see in the console: "'Interactable' is missing the class attribute 'ExtensionOfNativeClass'!"

Why is this happening?

# Answer
> 1 votes
An interface is not a script.

An interface describes what public methods certain scripts (or more accurately, classes) are supposed to have. This code here:

```
public interface Interactable
{
    void OnClickAction();
}

```

says, is that any script which is an "Interactible" should have a method `void OnClickAction()`. How it implements that method is up to the script, but when it wants to be an "Interactible", it needs that method.

OK, but how do you say that a certain script is supposed to be an interactible? Like this:

```
public class SomeScript: MonoBehaviour, Interactible
{

```

What this code says is "This class here is a Unity MonoBehaviour (so it can be added as a component to a GameObject), and it is *also* an Interactible". When you write this, you will notice that there is an error stating that SomeScript says that it implements the "Interactible" interface, but does not have the method `void OnClickAction()` like an "Interactible" is supposed to. So you need to implement it.

```
public class SomeScript: MonoBehaviour, Interactible
{
     public void OnClickAction() {
         Debug.Log($"OnClickAction called on { name }");
     }
}

```

OK, but what's the purpose of all this? Because it allows you to write code like this:

```
Interactible currentInteractable = hit.collider.GetComponent<Interactable>();
currentInteractible.OnClickAction();

```

The method `GetComponent<Interactable>()` returns the first script on an object which implements Interactible, regardless of what type it is. Note that the return value of this method is of type `Interactible`. Which means that you can only call methods on it which are part of the interactible interface. Which in this case is only one method: `OnClickAction()`. What this allows you to do is to have many scripts on different kinds of gameObjects which all do different things, but all implement the interface `Interactible` with an `OnClickAction()` method. So you can call that method on those scripts regardless of what class they actually have.

---
Tags: unity, raycasting
---


# Question
Title: How do I pick tiles from an isometric map with slopes?
I'm looking for a way to convert mouse/screen coordinates to isometric map coordinates, with the addition that the world has slopes and cliffs, and I have to be able to tell which quadrant of the tile is being pointed at by the mouse. The textures are handled by OpenGL, so I can't (easily) pick directly based on the tile sprite.

I've found several similar solutions, (e.g. Isometric Tiles Math, XNA Resources & Mouse Maps for Isometric Height Maps with the latter looking most promising) but none of them seem to quite fit my requirements.

My tiles look like this:

What algorithm or technique could I use here?

# Answer
It's not immediately obvious how you're using OpenGL. If you are just sorting your tiles on the CPU and rendering them from far to near the following method won't help. If you are using an actual isometric projection matrix and a depth buffer this may help, it's how I do picking with OpenGL and perspective projection.

Use the following code to read back the depth from the frame buffer at the given mouse coordinates.

```
GLfloat depth;
glReadPixels(mouse_x, mouse_y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);

```

Next you need to convert your mouse coords into clip space.

```
glm::vec4 clip;
clip.x = (mouse_x / screen_w) * 2.0f - 1.0f;
clip.y = (mouse_y / screen_h) * 2.0f - 1.0f;
clip.z = depth * 2.0f - 1.0f;
clip.w = 1.0;

```

You then need to multiply your clip space coords by the inverse view projection matrix.

```
glm::mat4 inverse_view_proj = glm::inverse(projection_matrix * view_matrix);
glm::vec4 pre_pers_div = inverse_view_proj * clip;
glm::vec3 world_position = pre_pers_div.xyz / pre_pers_div.w;

```

The world\_position vector now contains the location of the mouse in three dimensional world coords. You can feed this into your collision detection code and see which object it is colliding with.
> 1 votes

# Answer
Summary: Make a 3d mesh exactly the size of your terrain. Then do a raytrace trough the mouse towards the terrain. This will give you the x and z coordinate of the tile. Now from the z coordinate you can calculate the y coordinate of the tile without elevation. Then you can use one of your links to calculate the tile at that position. Now some simple math will give you the quadrant.

Your terrain is probably created from a 1D or 2D array of height values. We can use this to create the 3d mesh. I am using Bullet here for some examples.

```
std::vector <unsigned char> heights; //This 1D vector contains the heights
width = 64;
height = 64;
//We make a shape for the terrain using the heights. We need to give bullet the width
//and height of the terrain, the heights, the scaling, the minimum height, the maximum
//height, the up axis (0:x,1:y,2:z), the data type and whether to flip quad edges.
btHeightfieldTerrainShape* terrainShape = new btHeightfieldTerrainShape(width, height, heights.data(), 1, 0, 255, 2, PHY_UCHAR, false);

//We make the Bullet rigidbody using the shape
body = new btRigidBody(0, new btDefaultMotionState(), terrainShape);
body->setFriction(0.8f);
body->setHitFraction(0.8f);
body->setRestitution(0.8f);

//Bullet automatically centers the body so we undo that
//Be sure to move and rotate the body in such a way that it matches your terrain
body->getWorldTransform().setOrigin(btVector3(width / 2 - 0.5f, height / 2 - 0.5f, 255/2.f));
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_STATIC_OBJECT);

//And finally we add it to the world.
physics.dynamicsWorld->addRigidBody(body);

```

So our mesh is ready and positioned. We are ready to start raytracing. Now I am not familiar with ray tracing trough a mouse so I hope you are able to do that yourself with the help of the internet.

So once we have the coordinates we can calculate which tile is under the mouse.

Suppose the arrows in the image indicate positive directions.

```
Tile column under mouse = std::floor(raycast.x);
Tile row under mouse = raycast.y - raycast.z

```

And that's about it I believe.
> 0 votes

# Answer
The setup:

1. In the map data add an extra field for the render order.
2. As you render each tile is order increment the render order by one.
3. For each tile make a AABB in view coords (the same coordinate system as the mouse is in) which is the same size as the tile and place it into a quad tree for quick access.

To retrieve:

1. Find the AAAB at the current mouse location by searching the quad tree. If multiple tiles are found sort them according to the render order.
2. Once the correct tile is known find tile in the tile map (bitmap image) and covert the mouse coordinates to the local coordinates of the tile image.
3. Sample the pixel at the final location and if it's not transparent then assume a tile has been hit.

Now you know which tile was hit and you'll need to map that to the geometry of the slopes. This is very tedious as each tile will have it's own formula how how the x and y axis maps to which z value so it's best left to figure out on your own.
> 0 votes

---
Tags: opengl, isometric, terrain, picking
---


# Question
Title: Correct camera transformation for first person camera
I am making a camera in openGl and I am having troubles with first person camera. So I had a few versions of camera transformation and all of them had their own problems. So at first, I was doing transformations in this order: I would first translate the object in the positive direction when trying to move away from it and I would translate it in the negative direction when trying to move towards it. After this translation, I would perform rotations arround X and Y axis. Now, when I try to use this camera, I found out that when I have objects in my scene, lets say a few cubes, and when I rotate, everything is fine, but when after this rotation I try translation, all of the objects converge to me or better to say, towards the "player". So after I gave this some thought I realized that because I am doing translations first, in the next frame when I try to translate the player in the direction in which the camera is looking at that moment, what happens is, objects get translated first and then rotated so I get, as a result of this, movement of the objects towards or away from the player. Code for this is here (and dont mind camUp and camRight vectors, these are just y and x axis vectors and are not transformed at all):

```
m_ViewMatrix = inverse(glm::rotate(glm::mat4(1.0f), m_Rotation, camUp))* inverse(glm::rotate(glm::mat4(1.0f), m_TiltRotation, camRight)) * glm::translate(glm::mat4(1.0f), m_Position);

```

But option to rotate and then translate is not good because then I get editor sort of camera which is actually fine but that is not what I want. So I thought about it some more and tried to make small transformations and then reset the parameters, acumulating all the transformations in this way:

```
m_ViewMatrix = inverse(glm::rotate(glm::mat4(1.0f), m_Rotation, camUp)) * glm::translate(glm::mat4(1.0f), m_Position)* inverse(glm::rotate(glm::mat4(1.0f), m_TiltRotation, camRight))*m_ViewMatrix;
        m_Position = { 0.0f, 0.0f, 0.0f };
        m_Rotation = 0.0f;
        m_TiltRotation = 0.0f;

```

But now I have a problem with rotations arround z axis which I don't want. This problem was not there before. So now I have no idea what to do, I read some answers here but couldn't apply them I don't know why. So if anyone could help me in the context of the code I just copied here, that would be great.

# Answer
> 2 votes
So i think it would be OK to answer my own question since it could help some poor soul. Actually, some answers here do help with my problem but because of terminology these were unclear to me so I had to solve the problem myself. In openGl there is actually only one coordinate system and everything is done in that coordinate system even though people tend to use phrases like "global", "world" etc....When trying to, for instance, rotate a body, lets say cube, arround its own vertical axis, but have it do that somewhere further away in your scene what you should to is, first create your body in the origin of a coordinate system, rotate there, because even though you want to rotate around cubes axis you can't because there is no such thing in opengl, there is only the axis from the coordinate sytem so only that axis is the one you actually rotate about. But, if you create the body at the origin of the coordinate system, rotations around origin are the same as the rotations around body's axis. So, first you rotate it at the origin and then you translate the body to which ever position you like. On the other hand, if you want the whole body to rotate around some observer you have to translate it first and then rotate. In this way, since rotations are always around coordinate axis, the body will rotate around origin.If you want to have first person camera you have to have this in mind. So you should first translate and then rotate and you should rotate in the oposite direction of the one in which camera is moving since moving the camera to the left is the same as moving the whole scene to the right, and since actually there is no camera, just the scene and cordinate transformations, you have to do it this way. So, you should have something like:

```
cameraTransf = rotAround(x)*rotAround(y)*tranlateIn(somedirection);

```

So this is it. In this way you get some sort of good transformations BUT if you now want to add some controls like, you want to move through the scene, you would of course connect key pressed events to some parameters in translateIn function. But, think abou what is going on. Now you want to have something like, move, rotate a bit and then move in the direction you are rotated, by means of translations again. But what you are actually doing is translate, rotate, translate again, rotate again. So in each scene you first rotate and then translate. So you are always translating objects along unrotated z axis and instead of having a feel of passing by an object when you translate again you actually have an effect of pulling the object towards the origin. So what to do about this thing? So after some thought I realized that I could make small transfomations each time I press a button or move a mouse. So I did it in this way:

```
cameraTransform = rotAround(x, someAngle)* rotAround(y, someotherAngle)*trans(someDir)*cameraTransform;
someAngle = 0;
someotherAngle = 0;
someDir = (0, 0, 0);

```

So now I had it all good and worked out but new chalenge arrived, and this was the cause for my question. All of a sudden, even though I was doing rotations around x and y I had some rotation around z axis. Now, how I solved it? I was playing aroun, changeing stuff, and then, came up with this:

```
m_ViewMatrix = glm::translate(glm::mat4(1.0f), m_Position)
            * inverse(glm::rotate(glm::mat4(1.0f), m_TiltRotation, xdir))* inverse(glm::rotate(glm::mat4(1.0f), m_Rotation, camUp)) *  m_ViewMatrix ;

        m_CameraRight = inverse(glm::rotate(glm::mat4(1.0f), m_TiltRotation, camUp))* inverse(glm::rotate(glm::mat4(1.0f), m_Rotation, camRight)) *m_CameraRight;
        m_CameraUp = inverse(glm::rotate(glm::mat4(1.0f), m_TiltRotation, xdir)) * inverse(glm::rotate(glm::mat4(1.0f), m_Rotation, camUp)) * m_CameraUp;

        m_Position = { 0.0f, 0.0f, 0.0f };
        m_Rotation = 0.0f;
        m_TiltRotation = 0.0f;

```

In this actual code you can see that I am doing my x rotation around original x axis(xdir) but my y axis rotation is around camUp axis which is vec3 version of member variable m\_CameraUp, which I am also transforming, rotating in the same manner as I am rotating the cube itself id est, view matrix in this example. The m\_CameraRight is not important here since I am not using it for anything. Hope this helps someone.

---
Tags: opengl, camera, transformation
---


# Question
Title: How can I determine which 2d entity was selected from a overlapping pile
I'm using C++ and SDL2 to learn about coding by creating a clone of a 2d tile-based game I enjoy. To setup my problem; There can be multiple items dropped on a tile by the player or other entities which can overlap and be placed at any location within the tile.

All items on screen are just sdl rects with textures rendered to them however the items usually aren't squares. If multiple items are stacked on top of each other I'm not sure how to determine which item they are actually trying to select.

I can find items easily if there is only ever one in a tile or if they stay exclusively out of each others textures but with overlapping textures im stumped.

Can someone explain a method for me to determine which item the player is trying to select?

# Answer
> 0 votes
*I can't comment, so i'll write it as an answer. I know about one way of doing it.*

It sounds like you want something like pixel-perfect mouse selection. i.e. You only select an item if you click on a opaque pixel of the items' sprite? But then, if you are just learning to code, it might not be the easiest thing to implement..

I'm not familiar with SDL2. It could provide some utilities for this?

If not, you would have to use shaders. Here is one example tutorial of how you could do it. It's OpenGL with Java. But I'm sure you could find similar videos or posts for C++ / SDL2. Either way, the video intro briefly explains the concept.

Maybe another solution would be to scroll through the items when you hover over them, switching the item that is in front.

---
Tags: c++, 2d, tilemap, sdl2
---


# Question
Title: Trunk Based Development: Prevent unreleased assets and features from being included in the build
Our team is currently working on a live service game (A game that will be updated regularly post-launch) and is using a trunk-based development strategy.

The trunk-based development strategy is great. But the only issue is that **it's incredibly hard to prevent future content (i.e. UI graphics, game assets) and features from being included in the build before its official release**. This is not ideal, as players are now decompiling the game and extracting the WIP UI assets and peeking the game code to figure out future update contents.

The issue is easier to solve on the code side, with conditional compilation flags as feature toggles. But for content, especially content that could not be self-isolated (e.g. a new UI element that lives on an existing screen), it's very easy to get accidentally included in the final build.

How do other game dev teams prevent this issue?

Is there any better branching strategy, better version control tools, or some architectural pattern that could prevent this issue from happening?

(FYI, we are using Unity + Git for development. The solution we have come up with is to put these assets in addressable and label them with a specific feature flag. In a build script, we will remove all addressable with feature flags that aren't enabled in the current build. As for content that lives on existing UIs, we have two different versions of addressables labeled with two different flags, each only differs on the modified UI elements. As you could imagine, this is very time-consuming to set up and is very error-prone.)

# Answer
> 3 votes
It appears that what you need are more branches. At least one for development and one for each released version.

The release branch for each version would diverge from the main branch whenever you make a major feature release. That release branch would then be used for hotfixes which you need to get online quickly, but which don't add any new features. Those fixes would get merged back into the development branch as soon as feasible, but priority would be to ship them quickly.

You *can* do that while keeping the "trunk" workflow for working on the development branch. While the release branch is being used for hotfixes, the development branch would be the actual "trunk" on which all the new features get developed. When you make a new feature release, you would merge any still remaining commits from the current release branch to the trunk and then create a new release branch for going through QA and deployment and which will then be used for supporting the new version post-release.

Should you transfer to a "flow"-based approach for development? That depends on how many features you are developing in parallel and how well you are able to plan and execute on your release schedule. When you usually have no problems with completing all planned features before the release deadline, great. But when you frequently have situations where just before release some features are finished and some are not and delay the release, then you might want to switch to the "flow" model where each new feature is being developed on a separate branch.

The flow model has the advantage that you are free to develop each feature in isolation, without polluting the main branch with half-finished stuff. When you want to make a new feature release, you look at each feature-branch and decide whether or not it's ready to merge it into the main branch. Those which are not can wait until the next feature release. Those which are ready can be merged into the main branch. Then you create a new release branch from the resulting main branch, and send the release branch down the QA and deployment pipeline.

The disadvantage of the flow model is that *because* you are developing each feature in isolation, it can be difficult to make sure those features actually work well with each other. When two features are fundamentally incompatible with each other, you often don't notice until you try to merge them into the main branch.

Which model is the right one for *your* project and *your* team? That's up to you to decide.

---
Tags: unity, architecture, version-control, git
---


# Question
Title: Why when changing gui box color ith a color variable in the inspector in run time the color on a gui button is not the same?
When setting the color i'm not using the alpha because then it will not change the color at all and it will be transparent. in this line :

```
currentStyle.normal.background = MakeTex(2, 2,
                        new Color(color.a, color.b, color.g));

```

The result when changing the color in the inspector in run time : The color of the PAUSE button on the left is not the same color i changed it to on the right in the inspector :

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

public class GUIExamples : MonoBehaviour
{
    public Texture btnTexture;
    public Color color;
    public string colorInf;

    private GUIStyle currentStyle = null;
    private Color oldColor;

    private void Start()
    {
        oldColor = color;
    }

    private void OnGUI()
    {
        if (!btnTexture)
        {
            Debug.LogError("Please assign a texture on the inspector");
            return;
        }

        //GUI.backgroundColor = color;
        if (GUI.Button(new Rect(10, 10, 170, 30), "LOOP"))
            Debug.Log("Clicked the button with an image");

        //GUI.backgroundColor = color;
        if (GUI.Button(new Rect(10, 50, 170, 30), "CHANGE DIRECTION"))
            Debug.Log("Clicked the button with text");

        //GUI.backgroundColor = color;
        if (GUI.Button(new Rect(10, 90, 170, 30), "PING PONG"))
            Debug.Log("Clicked the button with text");

        //GUI.backgroundColor = color;
        if (GUI.Button(new Rect(10, 130, 170, 30), "STOP"))
            Debug.Log("Clicked the button with text");

        InitStyles();
        GUI.Box(new Rect(10, 170, 170, 30), "PAUSE", currentStyle);
        if (GUI.Button(new Rect(10, 170, 170, 30), "PAUSE"))
            Debug.Log("Clicked the button with text");

    }

    private void InitStyles()
    {
            currentStyle = null;

            if (oldColor != color)
            {
                currentStyle = null;
            }

            if (currentStyle == null)
            {
                currentStyle = new GUIStyle(GUI.skin.box);
                currentStyle.normal.background = MakeTex(2, 2,
                    new Color(color.a, color.b, color.g));

                oldColor = color;
            }
    }

    private Texture2D MakeTex(int width, int height, Color col)
    {
        Color[] pix = new Color[width * height];
        for (int i = 0; i < pix.Length; ++i)
        {
            pix[i] = col;
        }
        Texture2D result = new Texture2D(width, height);
        result.SetPixels(pix);
        result.Apply();
        return result;
    }
}

```

# Answer
Here:

```
new Color(color.a, color.b, color.g)

```

Do you mean:

```
new Color(color.r, color.g, color.b)

```
> 2 votes

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


title: Unity Firebase Analytics is not working

text:
# Question
Title: Unity Firebase Analytics is not working
I have been working on a new project in Unity 2021.2.12, where we need to implement Google Analytics. I have done as follows:

1. Imported Firebase Analytics package
2. Added the services.json file to the project's directory
3. Added the fingerprints to the Firebase Dashboard

However I am not receiving any data from the users. Does anyone have a similar experience? Have I done any step or the order of steps wrong?

# Answer
> 0 votes
The issue was that I did the process in the wrong order, basically forgot to add the service JSON file after I added the fingerprints, and thus it was failing.

A good practice can be that you make an APK build and try it on your phone or emulator and watch the analytics real-time section to see if any new user gets registered; then, it is an indication that the application is working.

I hope this information helps someone else in my position.

---
Tags: unity, android, analytics, firebase
---


# Question
Title: How to reconcile collision detection with delta time?
In my simulation, if an object is inside another object, it imparts a force proportional to the distance inside the object (basically a separation force).

I am having an issue though where the simulation runs differently given different `deltaTime` values.

I think the issue is due to collisions. For example, Let's say the physics loop updated very often and the `deltaTime` as a result, was very small: if a collision occurred, then it will impart a force. And then next frame the objects will still be colliding (since not much time has passed), so it will impart *another* force to separate them. Then finally on frame 3 the objects will be separated.

This is in contrast to the game running with a very low update count (and as a result a high `deltaTime`). If two objects are colliding, a force will be imparted, but because the `deltaTime` is so high, they'll already be separated by the next frame, so another collision force won't be imparted.

As a result, different total force values will be imparted onto the intersecting objects, due to the differences in `deltaTime`. I'm struggling to think of how to resolve this. Is this indeed the issue, and if so, how does one begin to resolve this? The only thing I could think of is to enforce collision is checked, say, 60 times per second. No more, no less. But then doesn't that defeat the entire purpose of using `deltaTime`? Because then the game is locked at a 60 hz update rate.

# Answer
> 1 votes
---

## The solution

The gist of it is: **in addition to setting the velocity of the objects, you also want to move them so the next tick they are not intercepting.** *You can now stop reading this answer.*

---

## Why is that the solution?

What happens is that the objects collided at some time between the last tick to the current one. That is, the instant of collision is a fraction of your delta time. So to simulate the full span of the delta time, you can imagine that the objects were moving, collided, and then began moving according to their bounce. So at the end of the delta time the position is also wrong and you should correct it.

Now, **you need to make a trade-off between precision and performance**. Using realistic logic to figure out where the object ends up will have an impact in performance that ultimately will mean you won't be able to handle as many objects.

Thankfully, we are making games, and games don't need to be realistic. So go ahead and simply move the objects so they are no longer intercepting.

The cheap approach is to figure out the distance between the object, and at what distance they should be to not intercept, and move them accordingly. However, this approach is infamous for causing troubles by pushing objects out the wrong direction.

An slightly less cheap approach - but also one that causes less troubles - considers their velocity, and moves them in the opposite direction they came from.

---

## Other related problems

**Too many bounces**

Another issue related to delta time is too many bounces in the same tick. The issue is that when you push the object out so it is no longer intercepting, they end up intercepting something else. And then you solve that other collision, and it results in yet another collision and so on.

Have a hard cap on how many you will solve per object. It is better that at some point the physics engine gives up and leaves some objects intercepting than to kill the performance of the game.

---

**Tunneling**

Yet another issue related to delta time is tunneling. It happens when your objects are too fast (or you ticks are too long), so that they can leap from one side to the other without registering collisions.

The cheap approach for these is to enforce a maximum/terminal velocity. So that objects don't get to move so fast that they can tunnel through each other (having a maximum velocity will also help with the prior issue).

And, of course, you can increase the tick frequency.

---

## About the expensive approaches

You want to find out what is the instant when the objects would have collided. Which you can do since you have the motion equation for them. To make it easier, consider the frame of reference of one of the objects and work there. In the frame of reference of an object, itself is static, and the other object is making the combined motion of both of them… And you want to find out when the distance between their surfaces is zero. Setup the equation and solve for time (which is trivial if they just have position and velocity. No so much if they have acceleration, friction, drag, dampening, etc…).

Once you have the instant they collided, you can compute where they would have been at that time, and place them there. Then compute the speed after the bounce. And if you are so inclined, compute how much they move for the remainder of the delta time. *And that could lead to another collision…*

---

And about tunneling, you could collide the shape the objects sweep during their motion (e.g instead of colliding circles, you collide a capsule that goes from the prior position of the circle to the current one). You would have to change your approach to discard possible collision early, because, as you can imagine, you cannot simply check for collision with objects in the same area where the object ended… You need to consider their velocity, and check for collision with objects in the areas along the motion. Search for continuous collision detection and continuous physics simulations for more details.

# Answer
> 1 votes
Since I realized that physics are very hard and I wanted it to be perfectly identical on everyone's machine, I just went with a fixed physics update loop (runs at 60 hz), but with lerping every frame so the movement is smooth on high refresh rate monitors.

I based the implementation off this article and also used the `alpha` value at the bottom to interpolate movement.

That is, for each of the objects that moves, I have their current position and previous position as member variables for their class. Then when I set their new position, I set their previous position right before updating the new position.

Then in my rendering function I use the alpha value from the article:

```
const alpha = accumulator / dt;

```

And then render the position of entities based on that:

```
function lerp(a: number, b: number, t: number) {
  return (1 - t) * a + b * t;
}

const renderX = lerp(e.prevPos.x, e.pos.x, alpha);
const renderY = lerp(e.prevPos.y, e.pos.y, alpha);

renderEntity(e, renderX, renderY);

```

---
Tags: collision-detection, game-loop, collision-resolution, timestep, deltatime
---