# Question
Title: How can I implement an algorithm to mix potions?
I would like to build something that allows me to obtain potions using two identical lists of ingredients.

```
ingredients = ["frog", "butterflies", "stones"]
ingredients_2 = ["frog", "butterflies", "stones"]

```

If I combine frog and stones, for example, I get frog marmelade. If I combine butterfly and butterfly I get super butterfly and so on...

But other than a terrifyingly long list of ifs, is there a better and more clever way to implement this?

I thought about a matrix:

```
row_num = 4
col_num = 4

grid = [[x for x in range(col_num)] for y in range(row_num)]

def print_grid():
    for row in grid:
        print(row)

def get_ingredient_1_index(ingredient_1):
    index = 0
    for item in grid[0]:
        if item == ingredient_1:
            return index
        index += 1
    return -1

def get_ingredient_2_index(ingredient_2):
    index = 0
    column_headers = [row[0] for row in grid]
    for item in column_headers:
        if item == ingredient_2:
            return index
        index += 1
    return -1

def mix_ingredients(ingredient_1, ingredient_2):
    coordinates_ingredient_1 = get_ingredient_1_index(ingredient_1)
    coordinates_ingredient_2 = get_ingredient_2_index(ingredient_2)
    return grid[coordinates_ingredient_2][coordinates_ingredient_1]

grid[0][1] = "frog"
grid[0][2] = "butterfly"
grid[0][3] = "stone"

grid[1][0] = "frog"
grid[2][0] = "butterfly"
grid[3][0] = "stone"

grid[1][1] = "superfrog"
grid[1][2] = "froggerfly"
grid[1][3] = "frog marmelade"

grid[1][1] = "superfrog"
grid[1][2] = "froggerfly"
grid[1][3] = "frog marmelade"

grid[2][1] = "froggerfly"
grid[2][2] = "super butterfly"
grid[2][3] = "butterfly jam"

grid[3][1] = "frog marmelade"
grid[3][2] = "butterfly jam"
grid[3][3] = "super stone"

print(mix_ingredients("frog", "butterfly"))

```

But I think it is a bit of clunky and poor solution.

Can you help in pointing me into a better direction?

# Answer
I think your matrix idea is viable. Although I would suggest a bit of improvements to make it easier to work with:

```
# step 0: define your ingredients in a list
known_ingredients = ["butterfly"      , "frog"          , "stone"]

# Step 1: reorganize your list; make it visually an actual grid.

grid[0] = [""         , "frog"          , "butterfly"      , "stone"]
grid[1] = ["frog"     , "superfrog"     , "froggerfly"     , "frog marmelade"]
grid[2] = ["butterfly", "froggerfly"    , "super butterfly", "butterfly jam"]
grid[3] = ["stone"    , "frog marmelade", "butterfly jam"  , "super stone"]

# Step 2: remove noise and some potential errors: sort the list alphabetically and
# remove the duplicates, that will be less maintenance for you:

grid[0] = [""         , "butterfly"      , "frog"          , "stone"]
grid[1] = ["butterfly", "super butterfly", "froggerfly"    , "butterfly jam"]
grid[2] = ["frog"     , ""               , "superfrog"     , "frog marmelade"]
grid[3] = ["stone"    , ""               , ""              , "super stone"]

def mix_ingredients(ingredient_1, ingredient_2):
    # the `index` function assumes the object is there, you might want to
    # add a bit of error handling here.
    coordinates_ingredient_1 = known_ingredients.index(ingredient_1) + 1
    coordinates_ingredient_2 = known_ingredients.index(ingredient_2) + 1

    if coordinates_ingredient_1 > coordinates_ingredient_2:
      # swap the indices, we sort them in alphabetical order
      tmp = coordinates_ingredient_2
      coordinates_ingredient_2 = coordinates_ingredient_1
      coordinates_ingredient_1 = tmp

    return grid[coordinates_ingredient_1][coordinates_ingredient_2]

```

Now this will work fine if you have a few ingredients, but at some point, you'll likely want to move this to something like a CSV and load it from file at game initialization.
> 1 votes

---
Tags: algorithm, python
---


# Question
Title: Intercept an accelerating object with a constant velocity projectile
I want to calculate the time that it takes to intercept a moving target "plane" with a projectile.

For example I have two 3 dimensional vectors (2 locations in 3D space).

```
Vector3 Person = {100, 0, 50};
Vector3 Plane = {200, 50, 100};

```

Now let's suppose the person has a gun that fires a projectile at `140M/s` in a straight line with no acceleration or bullet drop.

I want to hit the plane, which has an initial velocity and a constant acceleration.

```
Vector3 VelocityPlane = {-10, -10, 0};
Vector3 AccelerationPlane = {0, -10, 0};

```

**So what do I want to do:**

Using the above information, I want to calculate where I should aim to hit the Plane.

To achieve that I found the following kinematic equation:

$$\text{Future Plane Position} = \text{Position} + \text{Velocity} \cdot \text {Time} + \left(\frac 1 2 \cdot \text{Acceleration} \cdot \text{Time}^2 \right)$$

In C++ Code it would look like this:

```
Vector calculatePositionToAimAt(double time, Vector startPosition, Vector velocity, Vector accel = 0) {
    return startPosition + (velocity * time) + (0.5 * accel * pow(time, 2));
}

```

**The Problem:**

This function above is great! But there is something subtle missing. I don't have the **time** to calculate the Position where I have to aim for the function above, which happens to be the most important piece of this problem.

For many, the easiest way would probably be simple: `Time = Distance / Bulletspeed` But that wont work in my case since the Plane has Acceleration and is moving.

So for that I found the following equation:

$$ \vec p\_{\text{Plane}} + \vec v\_{\text{Plane}} \cdot t + \left(\frac 1 2 \vec a \cdot t^2\right) = \vec p\_{\text{Player}} + \vec v\_{\text{Bullet}} \cdot t$$

Together with the explanation: Because time is not a vector and is a scalar, You no longer have to use vectors in this equation. You can just input the magnitudes of the vectors instead - which would look like this:

**0.9 Seconds is the result.** So this works fine.

**Now the question is, how can I rewrite this in code so that it automatically solves such equations?**

I already have found code that should solve this which looks like so:

```
double asymetricSingleAcceleratedInterceptionTime(Vector position1, Vector position2, Vector velocity1, Vector velocity2, Vector acceleration2) {
    /*
    sqrt( (2 * a2 * x1) + (2 * a2 * x2) + v1^2 - (2 * v1 * v2) + v2^2 ) - v1 + v2
    t = ------------------------------------------------------------------------------
    a2
    */

    if (acceleration2.x == 0 && acceleration2.y == 0 && acceleration2.z == 0) {
        return asymetricInterceptionTime(position1, position2, velocity1, velocity2);
    }

    return (sqrt(
        (2 * acceleration2 * position1).Length()
        + (2 * acceleration2 * position2).Length()
        + pow(velocity1.Length(), 2)
        - (2 * velocity1 * velocity2).Length()
        + pow(velocity2.Length(), 2))
        - velocity1.Length()
        + velocity2.Length()
        ) / (acceleration2).Length();
}

```

However, this always gave me wrong results, so I rewrote it a bit and this is what it looks like now:

```
Vector3 Player = Vector3(100, 0, 50);
Vector3 Plane = Vector3(200, 50, 100);
Vector3 BulletVelocit = Vector3(140,0,0);
Vector3 PlaneVelocit = Vector3(-10,-10,0);
Vector3 PlaneAcceleration = Vector3(0, -10, 0);

float pos1 = Player.Length();
float pos2 = Plane.Length();
float vel1 = BulletVelocit.Length();
float vel2 = PlaneVelocit.Length();
float acc1 = PlaneAcceleration.Length();

float calc1 = (2 * acc1 * pos1);
float calc2 = (2 * acc1 * pos2);
float calc3 = pow(vel1, 2);
float calc4 = (2 * vel1 * vel2);
float calc5 = pow(vel2, 2);
float calc6 = vel1;
float calc7 = vel2;
float calc8 = (acc1);

float time = (sqrt(calc1 - calc2 + calc3 - calc4 + calc5) + calc6 - calc7) / calc8;

std::cout << time;

```

**This actually works but still has 2 problem:**

1. it gives me wrong results when the velocity is minus, and I already know why
2. it gives me of course only one result and not 2, like above in the picture {0.9, 26.072}

**About the first Problem:** If I change this code from this:

```
float calc1 = (2 * acc1 * pos1); //acc1(acceleration) is +10 because of magnitude
float calc2 = (2 * acc1 * pos2);

```

to this:

```
float calc1 = (2 * -10 * pos1); //manually setting acceleration to -10 like in the example
float calc2 = (2 * -10 * pos2);

```

It gives me one right result: -26.072

**So the second Problem..** I dont need the -26.072, but I need the other one which is 0.9

**So my final questions are**:

**1.** Is there other code that works better to give me the interception time based on velocity, acceleration etc like described above?

**2.** If not, how do I have to rewrite my code that it gives me the right positive result and not the negative one

**3.** How do I fix the magnitude acceleration problem which gives me wrong results.

# Answer
This is exactly equivalent to this previous Q&A: Projectile Aim Prediction with Acceleration.

The only difference is that since your projectile doesn't accelerate, your \\$\vec a\_\text{Bullet} \\$ term is \\$\vec 0\\$.

That gives us the following formula for the time-to-intercept \\$t\\$:

$$ \begin{align} 0 &= t^4 \left(\frac 1 4 \vec a \cdot \vec a \right)\\ &+ t^3 \left(\vec a \cdot \vec v \right)\\ &+ t^2 \left(\vec a \cdot \vec p + \vec v \cdot \vec v - s^2 \right)\\ &+ t^1 \left(2\vec p \cdot \vec v \right)\\ &+ 1 \left( \vec p \cdot \vec p\right)\\ \end{align}$$

Where \\$\vec v, \vec a\\$ are the velocity and acceleration of the plane, respectively, \\$\vec p = \vec p\_\text{Plane} - \vec p\_\text{Player}\\$ is the initial displacement of the plane from the player's firing position, and \\$s\\$ is the speed of your projectile.

Plug this into a quartic equation solver to get any positive time value solutions \\$t\_\*\\$, then plug each one in here to get the displacement from the firing position at the moment of interception:

$$\vec p\_\text{interecept} = \vec p + \vec v t\_\* + \frac 1 2 \vec a t\_\*^2$$

And then use that to get your bullet velocity:

$$\vec v\_\text{Bullet} = \frac 1 {t\_\*} \vec p\_\text{interecept}$$
> 0 votes

---
Tags: c++, mathematics, vector, projectile-physics, aiming
---


# Question
Title: How to interpolate angular data properly
I have been trying to interpolate raw angular data in degree (for a flow map grid) but any attempt fails because there is always two path, and I can't figure out how to interpolate on the shorter one only!

I have made a code sandbox to try different strategy in javascript:

```
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext("2d");
ctx.translate(0, canvas.height);
ctx.scale(1, -1); //flip canvas

var tau = Math.PI * 2;
var deg = tau / 360;

var min = 20; //start angle
var max = 270; //end angle
var step = 10; //space between angle

//interpolated angles visual
color('green');
for (let index = min; index % 360 < max; index += step) {
  let t = remap01(min, max, index);

  // l = lerpwrap(min*deg, max*deg, t);
  // l = lerphannah(min*deg, max*deg, t);
  let l = lerpAngle(min * deg, max * deg, t);

  createDirection(l);
}

//start angle visual
color('red');
createDirection(min * deg);

//end angle visual
color('blue');
createDirection(max * deg);

//---------------Various Lerp from google and asking
function lerpwrap(start, end, amount) {
  let short = (((((end - start) % 360) + 540) % 360) - 180);
  return start + (short * amount) % 360;
}

function lerphannah(b, a, t) {
  if (Math.abs(a - 360 - b) < (Math.abs(a) - b)) {
    a = a - 360;
  };
  return b = b + (a - b) * t;
}

function lerp(value1, value2, t) {
  return value1 + (value2 - value1) * t;
}

// Remaps angles into [0, 360) range on degrees.
function normalizeAngle(angle) {
  return angle - Math.floor(angle / 360) * 360;
}
// Returns the shortest signed angular delta
// from angle from to angle to, in degrees.
function angleDifference(from, to) {
  // Wrap difference into [0, 360) range.
  let difference = normalizeAngle(to - from);
  // Remap to range (-180, 180]
  // so that angles more than a half turn away
  // go via the shorter route.
  if (difference > 180) {
    difference -= 360
  };
  return difference;
}

// Linearly interpolates between two angles,
// using interpolation weight blend in [0, 1].
// Return is normalized into [0, 360) range.
function lerpAngle(from, to, blend) {
  let difference = angleDifference(from, to);
  return normalizeAngle(from + blend * difference);
}
// --------------utils
function createDirection(angle) {
  let angularline = createPoint(0, 1);
  angularline = rotateAngle(angularline.x, angularline.y, angle);
  angularline = scalePoint(angularline, 45);

  let midscreen = createPoint(canvas.width / 2, canvas.height / 2);
  let target = createPoint(midscreen.x + angularline.x, midscreen.y + angularline.y);
  line(midscreen.x, midscreen.y, target.x, target.y);
}

function remap01(t1, t2, x) {
  return (x - t1) / (t2 - t1);
}

function color(colour) {
  ctx.fillStyle = colour;
  ctx.strokeStyle = colour;
}

function createPoint(xp, yp) {
  return {
    x: xp,
    y: yp
  };
}

function rotateAngle(x, y, angle) {
  let x1 = x * Math.cos(angle) - y * Math.sin(angle);
  let y1 = x * Math.sin(angle) + y * Math.cos(angle);
  let result = {
    x: x1,
    y: y1
  };
  return result;
}

function scalePoint(point, scale) {
  return {
    x: point.x * scale,
    y: point.y * scale
  };
}

function line(startX, startY, endX, endY) {
  ctx.beginPath();
  ctx.moveTo(startX, startY);
  ctx.lineTo(endX, endY);
  ctx.closePath();
  ctx.stroke();
}
```

```
* {
  box-sizing: border-box;
}

body {
  background-color: #333;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-family: Arial, Helvetica, sans-serif;
  min-height: 100vh;
  margin: 0;
}

#canvas {
  background: #f0f0f0;
  /* border-radius: 5px; */
}

#source {
  display: none;
}
```

```
<canvas id="canvas" width="400" height="100"></canvas>
```

resulting image:

*0° is up*

I have been trying many implementations but none work so far

How do I interpolate angular data such as it goes by the shorter distance in the circle?

# Answer
I had to shift this

l = lerpAngle(min*deg, max*deg, t)

createDirection(l)

into

l = lerpAngle(min, max, t)

createDirection(l\*deg)
> 0 votes

# Answer
Think of two angles as two unit vectors(a,b), Calculate their Cross product. For example:

```
let min = 0;
let max = 45;
let a = (1,0);     // 0 degree Calculated by trigonometry
let b = (0.7,0.7); // 45 degree Calculated by trigonometry
let cross = a[0]*b[1] – b[0]*a[1]; //two-dimensional vector cross product formula
// when cross>0 ,a in the counterclockwise direction of b
if (cross > 0){
    //make sure degree b is greater
    min,max = max,min;
}
if (min> max){
    max += 360;
}
let step = 10;
for (let index = min; index % 360 < max; index += step) {
    let t = remap01(min, max, index);
    let l = lerpAngle(min * deg, max * deg, t);
    createDirection(l);
}

```

The principle: **The magnitude of the cross product can be interpreted as the positive area of the parallelogram having a and b as sides :**

If the result (area) is positive, This angle \< 180° ,otherwise it's \> 180°.
> 0 votes

---
Tags: mathematics, javascript, interpolation, angles
---


# Question
Title: Massive CPU Usage by WaitForTargetFPS in the Profiler
So I was checking the Standard Assets Example Projects of Unity, and they all have high FPS numbers in the Profiler.

I started a little project myself, just a simple sprite with movement via rigidbody and a plane as a floor, and suddenly this:

I searched for what exactly does WaitForTargetFPS represents, but apparently there is not a general consensus about what can cause such high CPU usage. So why exactly such a little and simple project have this performance (in contrast with the more complex Unity Example Projects)?

# Answer
> 5 votes
the reason those things happen is because Unity's is limiting your FPS and that process tells you by how much its limiting it, since regular machines can reach as high as 60 FPS anyway theres no need to use 600 FPS CPU and waste all that power for nothing.

the best you can do to solve that annoyance on the profiler is to just deselect Vsync from the profiler menu.

you can always disable Vsync from Menu: Edit \> Project Settings \> Quality, scroll all the way down and select Disable for "V Sync Count", bare in mind the first option is better for performance checks.

# Answer
> 1 votes
I saw some misunderstandings about this cropping up in recent questions, so I thought it would help to cite the documentation here too: (emphasis added)

> # WaitForTargetFPS
>
> Indicates how much time your application spent waiting for the targeted FPS that Application.targetFrameRate specifies.
>
> If the sample is a subsample of Gfx.WaitForPresentOnGfxThread, it represents the amount of time that your application spent waiting for the GPU. For example, **this could be time that the GPU spent waiting for the next VSync**, if that is configured in QualitySettings.vSyncCount, or if vSync is enforced on your target platform. However, samples with this marker are also emitted if the GPU hasn’t finished computing the frame.
>
> To determine what is causing samples with this marker to use a lot of time, switch to the Timeline view in the CPU Profiler module. In this view, you can check what happened on the render thread and how much time passed between this sample ending in the current frame and the same sample ending in surrounding frames.
>
> If the duration is larger than your application’s frame time should be (based on the targeted frame rate or vSync) your frames are taking too long to render or compute. If that’s the case, investigate the render thread and see how much time it spent on Gfx.PresentFrame over other work it did to prepare and issue commands to the GPU. If the render thread spent a large amount of time in Gfx.PresentFrame, your rendering work is GPU-bound. If the render thread’s time was spent preparing commands, your application is CPU-bound.
>
> To find out what to focus on, if your application is GPU bound, profile the GPU work with the Unity Profiler or a platform profiler. For more information, see the User manual documentation on how to optimize graphics performance.
>
> Note: **The Editor doesn’t VSync on the GPU and instead uses WaitForTargetFPS to simulate the delay for VSync**. Some platforms, in particular Android and iOS, enforce VSync or have a default frame rate cap of 30 or 60.

So: seeing high amounts of time spent in WaitForTargetFPS is not *necessarily* a problem.

If your overall framerate is still on-target, then this just means you have extra frame time headroom that the editor is burning, rather than simulating and drawing frames far faster than your display could ever keep up. It's a *good* sign that your CPU and GPU work finished so fast that you have this extra time to kill. In a build, this is time when your thread would usually be sleeping, saving power and heat.

High usage by the WaitForTargetFPS marker is only a problem if your overall framerate is dropping lower than your goal. In that case, follow the advice in the docs quoted above to identify which part of your code is taking up most of this marker time to figure out whether it's CPU or GPU work that's running behind.

In the screenshot here, the total frame time is still averaging about 10 ms, or 100 FPS, so this example is soundly in the "not a problem" category. That's why the other answer recommends just toggling off visualization of this spare time if seeing it in the graph is distracting.

---
Tags: unity, performance, profiler
---


# Question
Title: How can I make alternate fragments drop (or make them black) based on a checkerboard texture?
How can I make alternate fragments drop(or make them black) based on a checkerboard texture in a Unity fragment shader?

I am using forward path rendering in my shader passes for lighting and shadows for every object in the scene.

Now,I need a shader (or something) that drops alternate pixels from the overall screen space after everything is rendered. How can I achieve this effect?

# Answer
Generally, you can check the fragment coordinates (assuming they're integers going from (0,0) to (width, height)) and if both are even or both are odd keep the fragment, otherwise reject it. (Or the reverse if you prefer.)

In pseudocode it would look like this:

```
bool rowIsEven = (fragCoord.x % 2) == 0;
bool colIsEven = (fragCoord.y % 2) == 0;
if (rowIsEven == colIsEven)
{
    // keep the fragment
}
else
{
    // discard the fragment
}

```

If your coordinates are normalized, then you can multiply them by the width and height before checking the result. You'll need to pass the width and height in as a uniform, probably.
> 0 votes

# Answer
Writing up my 2019 comment as an answer, since the advice never got incorporated into the existing answer.

You can apply these modifications to a basic Unity shader to accomplish this:

1. Use `#pragma target 3.0` to enable the use of the `VPOS` semantic to get the pixel coordinates of the fragment being drawn inside the fragment shader.
2. Move your `SV_POSITION` out of the `v2f` structure and into an `out` parameter of your vertex shader instead. (Otherwise having both `SV_POSITION` and `VPOS` as inputs to the fragment shader causes a conflict)

```
struct v2f
{
    float2 uv : TEXCOORD0;
};

v2f vert (appdata v, out float4 outpos : SV_POSITION)
{
    v2f o;
    outpos = UnityObjectToClipPos(v.vertex);
    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
    return o;
}

```
3. Add `VPOS` to your fragment shader, and use it to `clip()` out the unwanted fragments.

```
fixed4 frag (v2f i, UNITY_VPOS_TYPE screenPos : VPOS) : SV_Target
{
    // Make a number that alternates even-odd on adjacent pixels.
    // (This is the Manhattan distance from (0, 0) to this pixel)
    float manhattan = screepPos.x + screenPos.y;

    // 0 for even, 1 for odd.
    float parity = manhattan % 2;

    // Discard all the even ones.
    clip(parity - 0.5);
    // (Or clip(-parity ) to discard odd ones.

    // Other fragment shader content here...
}

```
> 0 votes

---
Tags: unity, fragment-shader
---


title: Quaternion.LookRotation with Joystick

text:
# Question
Title: Quaternion.LookRotation with Joystick
I am having an issue i cannot seem to figure out within my code. What this code does at the moment is that it rotates the 3D Model around the z axis but i need it to rotate around the y axis. Any help would be greatly appreciated.

```
void Update ()
    {
        Vector3 moveVector = (Vector3.up * joystick.Horizontal + Vector3.left * joystick.Vertical);
        if (joystick.Horizontal != 0 || joystick.Vertical != 0)
        {
            transform.rotation = Quaternion.LookRotation(Vector3.forward, moveVector);
        }

    }

```

# Answer
It looks like the comments from three years ago solved OP's problem, so I'm posting them as an answer so we can keep this question from continuing to be bumped.

It looks like you want to do this:

```
void Update ()
{
    // Construct a direction in the horizontal plane.
    Vector3 moveVector = Vector3.forward * joystick.Horizontal
                       + Vector3.left * joystick.Vertical;

    if (moveVector != default)
    {
        // Rotate around the y axis,
        // to point our local z+ axis in that direction.
        transform.rotation = Quaternion.LookRotation(moveVector);
    }
}

```
> 1 votes

# Answer
you could also use:

```
float speed = 2f;
void Update ()
{
    Vector3 moveVector = (Vector3.up * joystick.Horizontal + Vector3.left *
    joystick.Vertical);
    if (joystick.Horizontal != 0 || joystick.Vertical != 0)
    {
        transform.eulerAngles
        += Vector3.up * Mathf.Atan(joystick.Horizontal) * Mathf.Rad2Deg * speed *
        Time.deltaTime;
        transform.eulerAngles
        += Vector3.right * Mathf.Atan(joystick.Vertical) * Mathf.Rad2Deg * speed *
        Time.deltaTime;
    }
}

```

you should also use Time.deltaTime for things like this to decouple the simulationspeed from the frametimes, i have included that in the example above.
> -1 votes

---
Tags: unity, c#, 3d, rotation
---


# Question
Title: Changing Model's rotation to keep its left side toward the pivot as it goes in a circle
I wrote a little script for my scene that allows my ship to circle an island, and it seems to work alright.

Now I am trying to get the ship model to stay broadside to a pivot point in the center of the circle, so the cannons are ready to fire on the item. I have tried `RotateAround`, but the ship spins around very fast, and not relative to the broader circle it's making.

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

public class SailAroundIsland : MonoBehaviour {

    private int radiusOfShipCircle = 100;
    private float currentTheta = 0; //start at 0 degrees
    private int speed = 1;
    private GameObject pivotPoint;

    // Start is called before the first frame update
    void Start()
    {
        pivotPoint = GameObject.Find("MainItem");
        //StartCoroutine(MovePositionAlongCircle());
    }

    // should give the new vector
    // now you just need to change theta accordingly
    Vector3 getNextPointOnCircle(int radius, float theta, Vector3 currentPoint)
    {
        float rad = theta * Mathf.Deg2Rad;
        return new Vector3(radius * Mathf.Cos(rad), 0, radius * Mathf.Sin(rad));
    }

    private void Update()
    {
        Vector3 nextPos = getNextPointOnCircle(radiusOfShipCircle, currentTheta, gameObject.transform.position);
        nextPos.y = gameObject.transform.position.y;
        gameObject.transform.position = nextPos;
        currentTheta += Time.deltaTime;

        //Finally if the angle is greater than 360 reset it to zero
        //as we have gone all the way around the circle
        if (currentTheta >= 360)
        {
            currentTheta = 0;
        }
    }
}

```

# Answer
Check Quaternion.

Quaternions are used to represent rotations. It's usually the easiest way to do the rotation.

Try to use Quaternion.AngleAxis to *Creates a rotation which rotates angle degrees around axis.*

like:

```
gameObject.transform.rotation = Quaternion.AngleAxis(currentTheta, Vector3.up);

```
> 0 votes

# Answer
You can do this more simply, using the same calculation to give both the facing direction and the offset from the circle center.

```
private void Update()
{
    // Compute our rotation first, yawing counter-clockwise.
    Quaternion orientation = Quaternion.Euler(0, -angleDegrees, 0);

    // Our offset from the center of the circle is then just
    // some distance "rightward" according to that orientation.
    Vector3 displacement = orientation * Vector3.right * radius;

    // Apply these values to our transform.
    transform.position = circleCenter + displacement;
    transform.rotation = rotation;

    // Increment our angle,
    angleDegrees += (speed / radius) * Time.deltaTime * Mathf.Rad2Deg;
    if (angleDegrees >= 360)
    {
        angleDegrees -= 360.0f; // Subtract, don't set to zero.
    }
}

```
> 0 votes

---
Tags: unity, rotation, geometry, transformation
---


# Question
Title: Optimizing overlapping units vision calculations in RTS using PyGame
Currently I'm developing a RTS game using Python/PyGame and I got some problems with fps drops when there are many units on the screen.

Using Snakeviz profiling I found out that the function `update_vision()` takes up a big majority of the processing.

This is because the function is checking every tile inside a radius of each unit (depending on the units defined vision range). When there are many units there are a lot of calculations that need to happen.

I'd like to optimize this somehow. Currently it's checking the same tiles over and over if the units vision ranges are overlapping. However I'm not sure how to go about this and would appreciate any help!

```

    #-----Update vision & explored matrixes-----
    def update_vision(self):

        for i, group in enumerate(all_p_unit_sprite_list):
            if i+1 != self.player:
                continue

            for unit in group:
                rel_x, rel_y = unit.get_coord()

                for row in range(-unit.vision_range, unit.vision_range + 1):
                    for col in range(-unit.vision_range, unit.vision_range + 1):
                        loc_x = rel_x + row
                        loc_y = rel_y + col
                        if 0 <= loc_x < matrix_width and 0 <= loc_y < matrix_height:
                            if abs(row) + abs(col) <= unit.vision_range:
                                map_vision_matrix[loc_y][loc_x] = 1
                                map_explored_matrix[loc_y][loc_x] = 1

```

```

    #-----Get grid coordinates-----
    def get_coord(self):
        col = self.rect.centerx  // tile_size
        row = self.rect.centery // tile_size
        return (col, row)

```

# Answer
Here is a suggestion:

Manage a unit number matrix like map\_unit\_num\_matrix, The number of units on each tile is recorded. And manage a dirty mark list recording the tiles that change the number of units each frame.

Fake code for example:

```
#--- unit.py
class Unit:
    def __init__(self) -> None:
        pass  // your unit variables
        self.tilePos = [0,0]

    def move(self):
        pass  // your unit moving logic
        self.onMoving()

    def onMoving():
        newTilePos = self.get_coord()
        if newTilePos[0] == self.tilePos[0] and newTilePos[1] == self.tilePos[1]:
            return
        GameMapManager.instance.unit_move(self.tilePos,newTilePos) //name is just for example
        self.tilePos = newTilePos

#--- map.py
class GameMapManager: //it may not exist
    def __init__(self) -> None:
        self.map_vision_matrix = []
        self.map_explored_matrix = []
        self.map_unit_num_matrix = []
        self.map_dirty_mark_list = []

    def unit_move(self,tileFrom,tileTo):
        self.map_unit_num_matrix[tileFrom[0]][tileFrom[1]] -= 1
        self.map_unit_num_matrix[tileTo[0]][tileTo[1]] += 1
        self.map_dirty_mark_list.append(tileFrom)
        self.map_dirty_mark_list.append(tileTo)

    def update_vision(self):
        if not self.map_dirty_mark_list:
            return
        for tilePos in self.map_dirty_mark_list:
            hasUnit = self.map_unit_num_matrix[tilePos[0]][tilePos[1]] > 0
            pass // your vision/fog of war logic
        self.map_dirty_mark_list = []

```

If the units have different field of view, you can record a field of view list or a unit list rather than unit number in the matrix.
> 0 votes

---
Tags: python, pygame
---


# Question
Title: Unity Update() Function causing a NullReferenceException that isn't there if I manually call the function
I have a pretty "basic" combat class here. It has a Player and an Enemy. They are inherrited from a Character class and have values such as health, armor and ar (attack rating (damage)). I am trying to set the combat up in a way so that once you press a button (in this case, e), you attack the enemy and the enemy attacks you. I think this is most easily done by having a method in Update() which constantly checks whether or not my desired key is pushed, and if it is, to execute said method which has 2 attacks. I have rearranged the program so that the Player and Enemy are saved seperately in the methods "savePlayer" and "saveEnemy".

Relevant global objects:

```
   public Player Player;
   public EnemyCharacterCreator Enemy;

   public Player savedPlayer;
    public EnemyCharacterCreator savedEnemy;
    public Text[] savedArray;

```

My constructor:

```
public Combat(Player Player, EnemyCharacterCreator Enemy, Text[] texxtArray)
    {
        savePlayer(Player);
        saveEnemy(Enemy);
        saveTextArray(texxtArray);
        textChanges();
     // FightLoop();
}

```

Aforementioned methods:

```
 public void savePlayer(Player Player)
    {
       savedPlayer = Player;
    }

    public void saveEnemy(EnemyCharacterCreator Enemy)
    {
      savedEnemy = Enemy;
    }

```

Combat-related code:

```
public void attackButton()
    {
        if (Input.GetKeyDown("e") == true)
        {
            FightLoop();
        }
    }
    public void FightLoop()
    {
            PlayerAttack();
            EnemyAttack();
            textChanges();
    }

    public void PlayerAttack()
    {
        savedEnemy.health = savedEnemy.health - savedPlayer.ar;
    }

    public void EnemyAttack()
    {
        savedPlayer.health = savedPlayer.health - savedEnemy.ar;
    }

```

Conceptually this should work fine, except it doesn't. When I "manually" execute FightLoop() in the constructor (commented out in the first code block) it works and the enemies health is reduced by 45 (which is my players' ar value), yet when I put attackButton() into the Update() function I get a NullReferenceException whenever I press e.  The error leads to line 74, which is the only line within the PlayerAttack() method:

```
savedEnemy.health = savedEnemy.health - savedPlayer.ar;

```

I put a breakpoint there and the savedEnemy object was null. I have no idea why, it is a global object and it works perfectly when I do it "manually", without Update(). Help would be appreciated.

A Minimal Complete Verifiable Example as requested in the comments:

There are 4 Scripts.

Combat:

```

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Combat : MonoBehaviour
{
    bool playerTurn = true;
    bool invActive = false;

    public Player Player;
    public Enemy Enemy;
    public Text[] textArray = new Text[6];

    public Player savedPlayer;
    public Enemy savedEnemy;
    public Text[] savedArray;

    public Combat(Player Player, Enemy Enemy, Text[] textArrayPass)
    {

        savePlayer(Player);
        saveEnemy(Enemy);
        saveTextArray(textArrayPass);

        //textChanges();
        // FightLoop();
        textChanges();

    }

    public void saveTextArray(Text[] textArray)
    {
        savedArray = new Text[6];
        savedArray = textArray;
        //Debug.Log(savedArray[0].text);
    }
    public void savePlayer(Player Player)
    {
        savedPlayer = Player;
    }

    public void saveEnemy(Enemy Enemy)
    {
        savedEnemy = Enemy;
    }

    public void attackButton()
    {
        if (Input.GetKeyDown("e") == true)
        {
            Debug.Log(Player.health);
            FightLoop();
            Debug.Log(Player.health);
        }
    }
    public void FightLoop()
    {
        PlayerAttack();
        EnemyAttack();
        textChanges();
    }

    public void PlayerAttack()
    {
        savedEnemy.health = savedEnemy.health - savedPlayer.ar;
    }

    public void EnemyAttack()
    {
        savedPlayer.health = savedPlayer.health - savedEnemy.ar;
    }

    public void textChanges()
    {
        savedArray[0].text = savedPlayer.health.ToString();
        savedArray[1].text = savedPlayer.armor.ToString();
        savedArray[2].text = savedPlayer.ar.ToString();

        savedArray[3].text = savedEnemy.health.ToString();
        savedArray[4].text = savedEnemy.armor.ToString();
        savedArray[5].text = savedEnemy.ar.ToString();

    }

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        attackButton();
    }

    private void Awake()
    {
        Combat fight = new Combat(Player, Enemy, textArray);
    }
}

```

Character:

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

public class Inventory
{

    public int[] inventory;
    public Inventory(int inventorySlots)
    {

        inventory = new int[inventorySlots];
        Debug.Log("Your Inventory has " + inventorySlots + " slots.");
    }
}

public class Character : MonoBehaviour
{
    public Inventory charInventory;
    public int health = 125;
    public int armor = 10;
    public int cash = 100;
    public int ar = 45;

    public bool weaponEquipped;
    public Character()
    {
        Inventory charInventory = new Inventory(20);
    }
    //HaheaghehAEH
    public void attack(Character enemy)
    {
        int oldHealth = enemy.health;
        enemy.health = enemy.health - ar;
        int damage = oldHealth - enemy.health;
        Debug.Log(damage + " damage!");
    }
    public Character returnChar()
    {
        Character x = new Character();
        return x;
    }
}

```

Player:

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

public class Player : Character
{
    public Player()
    {
        health = 150;
        ar = 45;
    }

}

```

Enemy:

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

public class Enemy : Character
{

    public Enemy()
    {
        health = 87;
        ar = 15;

        Inventory enemyInventory = new Inventory(5);
    }
}

```

Error Message

Enemy object gets saved in savedEnemy

Filled

# Answer
You declared a combat local variable here:

```
Combat fight = new Combat(Player, Enemy, textArray);

```

This is not the same object you mounted on the gameobject. Maybe you don't need a constructor but an initializer function like:

```
public void CombatInit(Player Player, Enemy Enemy, Text[] textArrayPass)
{

    savePlayer(Player);
    saveEnemy(Enemy);
    saveTextArray(textArrayPass);

    //textChanges();
    // FightLoop();
    textChanges();

}
private void Awake()
{
    CombatInit(Player, Enemy, textArray);
}

```
> 1 votes

---
Tags: unity, exceptions
---


title: Parameter 'Blend' doesnt exist

text:
# Question
Title: Parameter 'Blend' doesnt exist
I want to animate my character, but i got this error: Parameter 'Blend' doesnt exist.

if i use 1d Blend Type it works fine no bug nothing.

But if i change the Blend type

in the animation panel working fine the animation but if i run the game i get this error: Parameter 'Blend' doesnt exist and my character is freeze in one position what can cause this problem ?

parameters

# Answer
I had the same problem, at first blend type on the inspector just said "blend" so I adjusted the parameters on the inspector side to match with Animator.
> 1 votes

---
Tags: unity, animation, animation-states
---


# Question
Title: Technique for multiple shadow casting lights in 2D
I'm trying to create shadows in a 2D game in such a way that I can have an arbitrary number of lights in a scene, all of which can cast shadows. To do this I think I have to generate a mesh for each light that models where the light can come (e.g. where there is no shadow).

In this tutorial: http://youtu.be/4BtjcH-iLR0?t=4m40s (at 4 minutes 40 seconds) Chris Molini does exactly what I want describing it as 'a polygon clipping pass' for each edge that intersects with the light. However I don't understand what kind of polygon clipping he is refering to here. I have tried to mimick his technique on my own but without success. (I get lost in corner cases and radial+distance ordering around the light).

Here's a screenshot from the video. The square is the light's mesh (basically an AABB containing the light's sphere of influence). Which is gradually adjusted for each edge that intersects with the light's mesh.

# Answer
> 6 votes
I've implemented a similar method in the past, and it can be quite tricky to get it right. The best resource I've seen is on Amit Patel's fantastic site:

http://www.redblobgames.com/articles/visibility/

There are quite detailed explanations of each step, lots of good demos, and some code samples.

To briefly answer your question directly, the "polygon clipping" seems to refer to casting rays from the light source through each end of the shadow-casting edge. If the rays hit the border of the light's mesh AFTER passing the edge, then the section of the border between the hit points must be edited. Remove any vertices of the border that are between the endpoints. Add the first hit point, then the endpoint of the shadow-casting edge that corresponds to that point, then the other endpoint of the shadow-casting edge, then the second hit point.

Hope this helps.

# Answer
> 0 votes
isn't there a more "raster"-like method for 2d shadows ?

like a shadow map, except it would only be a 1D texture. The difficult part would be to render proper distances because of sprites being rectangles of pixels, there would be some pixel perfect collision detection to make, using grid marching for example. Not trivial. (but your geometrical solution also requires that anyway)

but then with a shader the presence of shadows would just be determined by a bit of projective maths and a lookup.

the scaling for multiple lights would work like any 3d engine, either using classic forward (all for all) shader, or defered (multi pass) shading.

# Answer
> 0 votes
Here's a possible answer that doesn't involve clipping polygons, but requires two light textures:

Render each light on texture #3 then draw it additively onto your light texture. It works best if your lights are extremely fuzzy. That will make shadows wash out near your light centers, but still be present on the periphery.

---
Tags: 2d, lighting, shadows
---


# Question
Title: How to handle multiple facial expressions in Unity 2D?
I want the character in my Unity 2D game to be able to change between many facial expressions (normal, happy, angry etc.), but I don't know the best way to do this. My character will be split into parts (Head, body, left & right arm and left & right leg) for animation purposes mainly. Should I make the head have no facial expression at first and then add another object with transparent background over it with the face and change the sprite or delete that object and instantiate another one? And also should all of these images be in the same large picture or should there be one face in every image file?

This image below is how the basic shapes looks at the moment (the graphics are not finished yet). And every shape has its own color. So the goal is to put a face (sprite) on the yellow head and be able to change that while the game story progresses.

Thanks in advance.

# Answer
Your proposal to make transparent sprites for facial expressions is a good one. You can have a sprite renderer for the face (or for each part of the face), and swap which sprite it displays using an animation timeline or a script.

It doesn't matter whether the different faces are all in separate images or all in one. Unity can automatically pack individual sprites together into a sprite atlas texture for efficiency as part of its build process, so that's an optimization you can always apply later, without needing to re-do your sprite work.

Or, if you're building your character as an animated 3D mesh rather than sprites, you can use the techniques the Asteroid Base devs demonstrate in this blog post / dev video.
> 1 votes

---
Tags: unity, 2d
---


# Question
Title: “undefined reference to” error when compiling for MinGW
I tried to move to MinGW to compile my program, since I am trying to use a more recent OpenMP version than the 2.0 one used in Visual Studio.

I was planning on using `#pragma omp target{}` to pass the function for the GPU since it is a rendering part of the code, but now that I am using MinGW, I can't compile my program anymore. I downloaded mingw-17.1 to get the needed headers and libs for sdl2.

Here is the GitHub page for the engine.

The error I got:

> GNU C++14 (MinGW.org GCC-6.3.0-1) version 6.3.0 (mingw32) compiled by GNU C version 6.3.0, GMP version 6.1.2, MPFR version 3
> warning: MPC header version 1.0.2 differs from library version 1.0.3. Compiler executable checksum: af09a87986453bf79da3565f33c7648f COLLECT\_GCC\_OPTIONS='-v' '-g' '-o''C:\Users\samsung\source\repos\forespend\forespend\forespend.exe' '-shared-libgcc' '-mtune=generic' '-march=i586'
> c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/as.exe -v -o C:\Users\samsung\AppData\Local\Temp\ccdGkN4k.o
> C:\Users\samsung\AppData\Local\Temp\cc6DG7xs.s
> GNU assembler version 2.28 (mingw32) using BFD version (GNU Binutils) 2.28 COMPILER\_PATH=c:/mingw/bin/../libexec/gcc/mingw32/6.3.0/;c:/mingw/bin/../libexec/gcc/;c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/ LIBRARY\_PATH=c:/mingw/bin/../lib/gcc/mingw32/6.3.0/;c:/mingw/bin/../lib/gcc/;c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/lib/;c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../ COLLECT\_GCC\_OPTIONS='-v' '-g' '-o'
> 'C:\Users\samsung\source\repos\forespend\forespend\forespend.exe' '-shared-libgcc' '-mtune=generic' '-march=i586'
> c:/mingw/bin/../libexec/gcc/mingw32/6.3.0/collect2.exe -plugin
> c:/mingw/bin/../libexec/gcc/mingw32/6.3.0/liblto\_plugin-0.dll -plugin-opt=c:/mingw/bin/../libexec/gcc/mingw32/6.3.0/lto-wrapper.exe -plugin-opt=-fresolution=C:\Users\samsung\AppData\Local\Temp\ccxKCd8F.res -plugin-opt=-pass-through=-lmingw32 -plugin-opt=-pass-through=-lgcc\_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lmoldname -plugin-opt=-pass-through=-lmingwex -plugin-opt=-pass-through=-lmsvcrt -plugin-opt=-pass-through=-ladvapi32 -plugin-opt=-pass-through=-lshell32 -plugin-opt=-pass-through=-luser32 -plugin-opt=-pass-through=-lkernel32 -plugin-opt=-pass-through=-lmingw32 -plugin-opt=-pass-through=-lgcc\_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lmoldname -plugin-opt=-pass-through=-lmingwex -plugin-opt=-pass-through=-lmsvcrt -Bdynamic -u \___register\_frame\_info -u \___deregister\_frame\_info -o
> C:\Users\samsung\source\repos\forespend\forespend\forespend.exe
> c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../crt2.o
> c:/mingw/bin/../lib/gcc/mingw32/6.3.0/crtbegin.o -L
> c:/mingw/bin/../lib/gcc/mingw32/6.3.0 -Lc:/mingw/bin/../lib/gcc -L
> c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/lib -L
> c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../..
> C:\Users\samsung\AppData\Local\Temp\ccdGkN4k.o -lstdc++ -lmingw32 -lgcc\_s -lgcc -lmoldname -lmingwex -lmsvcrt -ladvapi32 -lshell32 -luser32 -lkernel32 -lmingw32 -lgcc\_s -lgcc -lmoldname -lmingwex -lmsvcrt c:/mingw/bin/../lib/gcc/mingw32/6.3.0/crtend.o
> C:\Users\samsung\AppData\Local\Temp\ccdGkN4k.o: In function 'ZN4Game5resetEv':
> C:/Users/samsung/source/repos/forespend/forespend/main.cpp:235: undefined reference to 'al::raycasting::Raycaster::createGrids(int, int, int, int)'
> C:/Users/samsung/source/repos/forespend/forespend/main.cpp:236: undefined reference to \`g\_map' ...

# Answer
> 2 votes
SDL2 has specific binaries for compiling with MinGW. On the downloads page, (https://www.libsdl.org/download-2.0.php) download the SDL2-devel-2.0.20-mingw.tar.gz.

---
Tags: c++, sdl, raycasting, visual-studio-code, mingw
---


# Question
Title: Why lookat is working but when using slerp to rotate smooth to look at the same target is not working?
This is the part when i'm trying to rotate the objectToThrow smooth slowly.

```
objectToThrow.LookAt(playerHead);
                //objectToThrow.rotation = Quaternion.Slerp(objectToThrow.rotation, playerHead.rotation, 3f * Time.deltaTime);

```

When i'm using the LookAt(playerHead) it does make the rotation but at once fast. When i'm using:

```
objectToThrow.rotation = Quaternion.Slerp(objectToThrow.rotation, playerHead.rotation, 3f *
 Time.deltaTime);

```

It's not rotating at all and when using the Slerp in runtime and try to rotate the objectToThrow in the editor there is some force that not let me rotate it. I can't figure out why the LookAt is working but the Quaternion.Slerp is not ?

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

public class ThrowObject : MonoBehaviour
{
    public Transform objectToThrow;
    public Transform target;
    public Transform playerHead;
    public Transform objectToThrowParent;
    public Animator objectToThrowAnimator;
    public float throwingSpeed;
    public float waitAtTargetTime;
    public float distanceToStopFromTarget;
    public bool go = false;
    public AnimationCurve animationCurve;
    public Hovl_DemoLasers laser;

    private Animator anim;
    private bool startThrowAnimationOnce = true;
    private bool reParent = false;
    private bool startMovingBack = false;
    private bool startRot = false;

    private void Start()
    {
        anim = GetComponent<Animator>();
    }

    private void Update()
    {
        if (anim != null && startThrowAnimationOnce)
        {
            anim.SetTrigger("Throw");

            startThrowAnimationOnce = false;
        }

        if (go)
        {
            objectToThrow.parent = null;
            StartCoroutine(Throw());
            var objtothrow = objectToThrow.GetComponent<InteractableItem>();
            objtothrow.enabledInteraction = true;
            objtothrow.distance = 100;
            target.GetComponent<InteractableItem>().enabledInteraction = false;
            objectToThrow.LookAt(target);
            go = false;
        }

        if (reParent)
        {
            objectToThrow.position = objectToThrowParent.position;
        }

        if (startMovingBack)
        {
            if (Vector3.Distance(objectToThrow.position, playerHead.position) >= 1f)//0.1f)
            {
                float step = 5 * Time.deltaTime;
                objectToThrow.position = Vector3.MoveTowards(objectToThrow.position, playerHead.position, step);

                startRot = true;
            }
        }

        if(startRot)
        {
            objectToThrow.LookAt(playerHead);
            //objectToThrow.rotation = Quaternion.Slerp(objectToThrow.rotation, playerHead.rotation, 3f * Time.deltaTime);
        }
    }

    public void ThrowEvent()
    {
        go = true;
    }

    IEnumerator Throw()
    {
        while(Vector3.Distance(objectToThrow.position, target.position) >= distanceToStopFromTarget)
        {
            objectToThrow.position = Vector3.MoveTowards(
                  objectToThrow.position,
                  target.position,
                  throwingSpeed * Time.deltaTime
             );

            yield return null;
        }

        laser.startLaser = true;

        yield return new WaitForSeconds(waitAtTargetTime);

        target.parent = objectToThrow;
        laser.hovl_laserDemo.MaxLength = Vector3.Distance(objectToThrow.position, target.position);
        objectToThrowAnimator.enabled = false;

        startMovingBack = true;
    }
}

```

# Answer
Looks like you meant to write:

```
var lookDirection = playerHead.position - objectToThrow.position;

var lookOrientation = Quaternion.LookRotation(lookDirection);

objectToThrow.rotation = Quaternion.Lerp(objectToThrow.rotation, lookOrientation, 3f *

```

Time.deltaTime);

`playerHead.rotation` is the quaternion describing the way the head is facing, not the way another object would need to rotate to face the head. So we need to calculate that orientation quaternion ourselves.

Also, since you're already using a non-linear blending factor anyway, there's no real benefit to using the more expensive `Slerp` over the cheaper `Lerp`. If you want an exactly linear rotation rate, use `RotateTowards` insteadz which will allow you to enforce a particular speed in degrees per second.
> 1 votes

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


# Question
Title: How to destroy just the specific powerup I hit, not all of them?
Creating a game for a computer science class - basically I have a player (cop) who will collide with donuts. When the player collides with a Donut, I want the speed to increase by 0.5 each time. Here is the current code involving the collision (applied to the player object):

```
 private void OnCollisionEnter(Collision collision)
{
    if(collision.gameObject.CompareTag("Landmine"))
    {
        speed = speed - 0.5f;

    }
    if(collision.gameObject.CompareTag("Donut"))
    {
        speed = speed + 0.5f;
        Destroy(GameObject.FindWithTag("Donut"));

    }

```

The speed is working, but when the player collides with the Prefab tagged with "Donut", all the other donut objects also get destroyed. I just want to be able to individually destroy each Donut object, is there a way I can do this? I tried making the Donut game object into a prefab but it doesn't change anything since the collision script relies on the tag of the gameobject and not the gameobject itself. The donuts are duplicated objects of the first prefab.

# Answer
> 0 votes
This line: `Destroy(GameObject.FindWithTag("Donut"));` says "search the entire scene (slow) for the first object that has the tag 'Donut', and destroy that".

But in this collision handler, you don't want to destroy just *any* old donut, and usually not specifically the *first* donut in scene search order. You want to destroy *the specific donut you hit*. Fortunately, that one's already stored in a variable - you used it to check if you hit a donut in the first place!

```
if(collision.gameObject.CompareTag("Donut"))
{
    speed = speed + 0.5f;
    Destroy(collision.gameObject);
}

```

Also, you'll probably want to use trigger collider for the donuts, and detect collisions with `OnTriggerEnter(Collider other)` instead - that way you won't get any collision resolution impulses modifying the movement of your car. Trigger colliders *detect* and *report* overlaps, without pushing the colliders apart or acting like a solid barrier.

In fact, I'd rewrite this without two tag checks, and use the same script for both donuts and landmines:

```
public class SpeedChangePowerup : MonoBehaviour {

    public float speedChange;
    public bool destroyOnCollect;
    public Transform destructionEffectPrefab;

    void OnTriggerEnter(Collider other) {
        if (!other.TryGetComponent(out PlayerCar car)) return;

        car.speed += speedChange;

        if (destroyOnCollect) {
            Instantiate(destructionEffectPrefab,
                        transform.position,
                        Quaternion.identity);
            Destroy(gameObject);
        }
    }
}

```

Your donut is then just a prefab with a `SpeedChangePowerup` component that has `speedChange = 0.5` set in the inspector. Your landmine is one with `speedChange = -0.5`. And the car script doesn't need a collision handler with branches for each type of powerup, improving modularity and reducing bloat as you add other types of powerups and effects.

---
Tags: unity, c#, physics, collider
---


title: Unity MLAPI Instance server

text:
# Question
Title: Unity MLAPI Instance server
I am currently developing a multiplayer game with unity using MLAPI sdk. Right now i have an API Gateway for everything that is not directly gameplay and theirs also Zone servers AKA Gameplay servers. Right now the zone server can handle around 250 players within a single instance of the zone. What i am wondering about is how can i have a dungeons server. So lets say players in groups of 5 will zone into a dungeon, i cannot have 1 instance of the server running for only 1 group of 5 players. I need to be able to handle multiple groups of 5 entering the dungeons without them seeing each other since they arent in the same group. How would i go about doing this ??

# Answer
> 0 votes
One way to do this is how Vaillancourt was saying, which is to only send updates to the players who are in the same group, but not the rest of them.

Another way to do it is to use a service like Edgegap. Basically, you will create a really small instance that's only for a specific number of players and they will deploy it in the best location for all your players. So, instead of having one big server that hosts all the players and runs 24/7, you create small container servers and you only run them for the time that the dungeon lasts. That can help with latency and also save costs in the long run.

---
Tags: unity, multiplayer, unity-networking
---


# Question
Title: Applying incremental rotation with quaternions: flickering or hesitating
I'm having a couple of problems while rotating an object every frame with GLM.

**First problem**
I'm trying to rotate the object with a small increase using quaternion multiplication.

```
glm::quat deltaQuat = glm::qua(0.001f, glm::vec3(0.0f, 1.0f, 0.0f));
object.SetWorldRotation(object.GetWorldRotation() * deltaQuat);

```

The result of this code is that the rotation switches back and forward with its inverse each frame, plus the small delta.

Full framerate video here, and the logs I get:

```
Object world rotation: quat(1.000000, {0.000000, 0.000000, 0.000000})
Object world rotation: quat(0.001000, {0.000000, 1.000000, 0.000000})
Object world rotation: quat(-0.999999, {0.000000, 0.002000, 0.000000})
Object world rotation: quat(-0.003000, {0.000000, -0.999997, 0.000000})
Object world rotation: quat(0.999994, {0.000000, -0.004000, 0.000000})
Object world rotation: quat(0.005000, {0.000000, 0.999990, 0.000000})
Object world rotation: quat(-0.999985, {0.000000, 0.006000, 0.000000})
Object world rotation: quat(-0.007000, {0.000000, -0.999979, 0.000000})
Object world rotation: quat(0.999972, {0.000000, -0.008000, 0.000000})
Object world rotation: quat(0.009000, {0.000000, 0.999964, 0.000000})
Object world rotation: quat(-0.999955, {0.000000, 0.010000, 0.000000})
Object world rotation: quat(-0.011000, {0.000000, -0.999945, 0.000000})
Object world rotation: quat(0.999934, {0.000000, -0.012000, 0.000000})
Object world rotation: quat(0.013000, {0.000000, 0.999922, 0.000000})
Object world rotation: quat(-0.999909, {0.000000, 0.014000, 0.000000})
Object world rotation: quat(-0.015000, {0.000000, -0.999895, 0.000000})
Object world rotation: quat(0.999880, {0.000000, -0.015999, 0.000000})
Object world rotation: quat(0.016999, {0.000000, 0.999864, 0.000000})
Object world rotation: quat(-0.999847, {0.000000, 0.017999, 0.000000})
Object world rotation: quat(-0.018999, {0.000000, -0.999829, 0.000000})
Object world rotation: quat(0.999810, {0.000000, -0.019999, 0.000000})

```

**Second problem**
Similarly to the first one, I'm trying to rotate the object with a small increase, this time using euler angles.

```
object.SetWorldEulerRotation(object.GetWorldEulerRotation() + glm::vec3(0.0f, 0.1f, 0.0f));

// where:

void SetWorldEulerRotation(glm::vec3 const& eulerRotation)
{
    SetWorldRotation(glm::quat(eulerRotation));
}

// and

glm::vec3 GetWorldEulerRotation() const
{
    return glm::eulerAngles(m_rotation); // m_rotation is a world quaternion
}

```

The result of this code is that the object's rotation does not go beyond 180º in either direction. It jitters between a little over that rotation and a little under it.

Video here, and the logs I get:

```
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})
Object world rotation: quat(0.707403, {0.000000, 0.706810, 0.000000})
Object world rotation: quat(0.703863, {-0.000000, 0.710336, -0.000000})

```

Is there something I'm misunderstanding about quaternions/Euler angles, rotations in general or the GLM library?

# Answer
As discussed in the comments (special thanks to @DMGregory):

**Problem 1:**
The GLM API is a bit misleading and the constructor I was using actually sets the quaternion's x,y,z,w values instead of it being an "angle along this vector"-constructor.
Using the euler angles constructor works: `glm::quat deltaQuat = glm::quat(glm::vec3(0.0f, 0.001f, 0.0f));`.

**Problem 2:**
I've fallen to a common trap by rotating in euler angles when internally using quaternions. Basically, there are no guarantees in the continuity of the euler angles you get when converting from a quaternion. So adding a euler angle rotation on top of those will likely result in this type of behaviour. More info in this question.
I'd suggest simply sticking to quaternions for incremental rotations or, as Gregory said, you can store the euler angles internally as well instead of converting them from the quaternion.
> 0 votes

---
Tags: rotation, quaternion, glm, euler-angles
---


# Question
Title: Unity 2021 Silicon Build Performs Poorly with DynamicGI.UpdateEnvironment()
I recently upgraded my large-scale RPG world project from 2019 LTS version to 2021 for the native Silicon support. I have a Silicon based Mac and even though the game seems to have smoother FPS in the 2021 builds, the lag spikes are extreme.

These lag spikes, after profiling, come from the method DynamicGI.UpdateEnvironment() which is called a few times a second. Even when I increase this interval the lag spikes just make the game jittery despite the overall smooth FPS.

Why is it that Unity 2021 handles this method so poorly? In my 2019 build I was getting slightly less FPS overall but it was extremely consistent and no lag spikes (Intel build played through Rosetta 2). I checked a 2021 Intel build and same problem, it was smoother overall (less so than the native Silicon build) but had lag spikes.

# Answer
Dynamic GI would be dynamic global illumination. Unity's been working on replacing the previous Enlighten GI system, so this may be a new feature in Unity 2021 which comes with new demands on performance. Try adjusting the GI settings in the Lighting window.
> 0 votes

---
Tags: unity, graphics, performance, macos, lag
---


# Question
Title: Rendering top down water on a 2D surface (OpenGL)
i'm looking for suggestions on how i could use shaders to create a water effect on the surface in the picture (below):

I am using noise to create heightmap and normalmap textures that is uploaded to GPU. I am the rendering a plane of vertices using Triangle strips. Each vertex then samples the those textures to get normals and Y-value (height). The Y value (0-1) is just used to sample a "palette" texture (with the color shown in the picture), the vertex Y value remains 0 across the entire terrain. So it has a 3D look but it's just a flat plane.

Now, if it were 3D i could render a quad at Y = 0 (water level), and use this to create a water effect like this tutorial: OpenGL Water Tutorial

But i am unsure how to do something simular in 2D. All vertices are mixed in the same mesh. Before i have used tiles. And then i could single out and render the "water-tiles" to an fbo and do some effects.

So does anyone have any suggestions on how to identify the water, and only do the effect on the "blue" and not the rest of the terrain? I'm not sure if the question is any good, but i can provide more details if needed.

(The picture shows below 0 terrain as blue, ideally it would be something like brown with a semi-transparent "water layer" on top of it)

Maybe i could render a quad and discard all the fragments above the water level or something like that?

**EDIT** After applying a shader: (The colors are not final, and i need to blend the shorelines. But a good start :))

shader: shadertoy

# Answer
The solution to my problem was to pass the height value sampled from the heightmap texture in the vertex-shader, on to the fragment-shader. Then query that height per-fragment to see if it's below "water-level" or not. If it is then I do water-effect calculation on it.

It's kind of obvious when I think of it. But in my mind I had to do water calculations in a separate shader-program. :)

If you are here about HOW you could do the calculations. @DmGregory mentioned these past Q&A: here , here and here
> 1 votes

# Answer
2D can be implemented as 3D from a fixed view & projection, so you could still use the approach in the tutorial. If you like how the tutorial effect looks, I'd start with that.

The angle will be different than shown in the video, so you may need to tweak the parameters. With respect to that, keep in mind that it's your game and how it looks can take precedence over the 'simulation truth' (that is to say, things like where the light source is located, camera angle & so forth). Often times shadows in 2D games aren't realistic, but still provide useful visual cues about depth. You can do the same thing with your water effect - if it looks watery, it is doing its job.
> 0 votes

---
Tags: opengl, glsl, water, top-down
---


# Question
Title: How can I use IntelliJ to make Minecraft mods?
I'm starting out creating Minecraft mods with my son.

I've seen one YouTube tutorial which sets up project with Eclipse.

Since I don't like Eclipse much, I ask: how would I setup IntelliJ or Android Studio(if feasible) to develop Minecraft mods?

My son specifically want to create roller coaster mods.

# Answer
> 3 votes
1. Download IntelliJ
2. Download Minecraft Forge from https://files.minecraftforge.net/, you'll want the MDK
    * Depending on your needs, the recommended version is fine, but as changes are being made regularly, downloading the most current might be beneficial.
3. Extract the zip into a new folder, I use a nested structure where I have one folder called "Minecraft Mods" and inside that a folder for each version of Forge (e.g. "Forge 1.12.1-2462" and "Forge 1.14.4-39"). Inside each of those is another folder that contains the zip archive contents (I used to skip this inner folder, but the project setup changed and Eclipse didn't like things; not sure how IntelliJ plays). I use this structure so that when I update from one version to another, I have an old workspace that still runs.
4. Open the readme and follow the directions:

> If you prefer to use IntelliJ:
>
> 1. Open IDEA, and import project.
> 2. Select your build.gradle file and have it import.
> 3. Run the following command: "gradlew genIntellijRuns" (./gradlew genIntellijRuns if you are on Mac/Linux)
> 4. Refresh the Gradle Project in IDEA if required.

There may be additional issues if you are on a Mac (because of the auto-generated .DS\_Store files that us Windows folk hate cleaning up; Minecraft will attempt to parse these as resources, and I can't find a posted solution atm) and you might run into an issue with assets (solution linked).

# Answer
> 1 votes
A plugin on IntelliJ is available for mods and plugins development (here).

I didn't make mods yet, but the plugin development is

---
Tags: minecraft-modding
---


# Question
Title: Is there a good practice for defining names programmatically?
In my use of Unity so far, I've been defining element names programmatically with classes like this:

```
public class MyClass : MonoBehaviour
{
    public const string Name = "MyName";

    public void Awake()
    {
        name = Name;
    }
}

```

My hope with this is to avoid magic strings in my project. Any other object that wants this object can run `GameObject.Find` with this constant and if I ever want to change the name for whatever reason, I only have to change one place and everything should just work.

```
public void Awake()
{
    GameObject x = GameObject.Find(MyClass.Name);
}

```

The issue that I'm seeing is Unity sometimes failing to find the object, instead just giving me `null`. I'm sure the problem is the order of different objects getting ran by Unity, but I'm not sure what the best practice would be here.

One option would be to use `Awake` for naming and `Start` for finding other objects, but this seems to be the opposite of what the documentation recommends for these functions. Would doing this prove to have negative consequences in the future? Is there another approach developers take to avoiding magic strings akin to this?

# Answer
> 2 votes
> Is there another approach developers take to avoiding magic strings akin to this?

Yes, they don't use `Find(name)`. It's slow, it's error-prone and it's fragile. The only reason why you name objects in Unity should be so you can tell them apart when you look at the scene tree in the editor. If you need objects to communicate with each other, then there are several better ways to do that than by linking them with Find:

* Use tags and `FindWithTag` (which also has problems, but less so than Find)
* Set up relationships via drag-and-drop inspector fields.
* Have objects communicate via UnityEvents
* When you are 100% sure there will only ever be one of a certain object in the scene, find it via the Singleton pattern.
* Find objects at runtime by a specific component they are supposed to have, like via `FindObjectOfType` or `GetComponentInChildren`. When you have no fitting component for your particular use-case, then don't hesitate to create pure "tag components" which contain no methods or variables and only exist so you can tell an object apart from others.
* Have objects instantiate each other from prefabs, and then keep the reference returned by Instantiate (`myMinions.Add(Instantiate(minionPrefab));`).
* When you are interested in objects not just because of *what* they are but based on *where* they are in the game, detect them using trigger colliders or spatial detection with the `Physics`.Overlap*Whatever* methods, and then use `GetComponent` on the returned objects to filter them down to those you are actually interested in.
* Use "Manager" behaviours which use any of the above patterns to keep track of references to certain objects and are able to provide them to other behaviors on request (like an `EnemyManager` with a method `IEnumerable<Enemy> GetEnemiesWhichCanSee(Player p)`).

---
Tags: unity, c#, software-engineering
---


# Question
Title: How to create IOS style rubber scrollbar in unity?
I'm looking to create a scroll bare similar to IOS scroll when you load page or something when it lets you pull all the way down but the tension gets higher like it is on spring. How would I approach this.

# Answer
> 1 votes
The ScrollRect component does this by default.

ScrollRect has a property called **MovementType**. If you set it to *Elastic*, you'll achieve the same effect you're looking for (the spring effect).

From the documentation:

> **Movement Type** Unrestricted, Elastic or Clamped. Use Elastic or Clamped to force the content to remain within the bounds of the Scroll Rect. Elastic mode bounces the content when it reaches the edge of the Scroll Rect

> **Elasticity** This is the amount of bounce used in the elasticity mode.

Just right click in your hierarchy and go to UI-\>ScrollRect

Here's a good video that goes more in detail.

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


# Question
Title: How do I resume the rotation where it last rotates when it got pause?
```
public class PlayerControl : MonoBehaviour
{
    float Speed = 125f;
    void FixedUpdate()
    {
        transform.Rotate(0, 0, Speed * Time.deltaTime);
    }

    public void ChangeDirection()
    {
        Speed = -Speed;
    }

    public void PauseMovement() <---- Pointer Down
    {
        Speed = 0f;
    }

    public void Boost()
    {
        Speed = 330f * Mathf.Sign(Speed);
    }

    public void NormalSpeed()   <----- Pointer Up
    {
        Speed = 125f * Mathf.Sign(Speed);
    }

}

```

I press a button on a trigger event as pointer down, my player stops moving and when i release the button, it resumes as per normal. This works but not as how i intended, when i want my player to resume, i want it to resume the direction it last went. Like if it rotates to the left, it will continue on the left. Right now, it last rotates on the left, it continues on the right. Please advice?

# Answer
First I will define a bool:

```
private bool IsClockwise; // set it to true or false depending on your need

```

And then making the `Speed` variable non-negative:

```
    float Speed = 125f;
    void FixedUpdate()
    {
        transform.Rotate(0, 0, Speed * Time.deltaTime);
    }

    public void ChangeDirection()
    {
        // We don't change the value of Speed here!
    }

    public void PauseMovement() <---- Pointer Down
    {
        Speed = 0f;
    }

    public void Boost()
    {
        Speed = 330f;
    }

    public void NormalSpeed()   <----- Pointer Up
    {
        Speed = 125f;
    }

```

And finally, let's define the new `ChangeDirection` method:

```
public void ChangeDirection()
{
    IsClockwise = !IsClockwise;
}

```

But it won't affect anything before we tweak the rotation part:

```
void FixedUpdate()
{
    if (IsClockwise)
        transform.Rotate(0, 0, Speed * Time.fixedDeltaTime);
    else
        transform.Rotate(0, 0, -Speed * Time.fixedDeltaTime);
}

```

Note that as you want to do this in `FixedUpdate`, you will need to use `fixedDeltaTime` instead of `deltaTime` (see Unity's documentation)
> 1 votes

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


# Question
Title: Speed up Reaction-Diffusion simulation calculations in Unity
I'm trying to use Unity Job system to speed up some calculation related to Reaction-Diffusion simulation. The calculations requires 2 matrixes, `current` and `next` and the `current` will be used to calculated `next`, then `next` will become `current`. I wanted each job to handle a single row of the matrix.

The problem lies in the `Laplace()` function, which when inputed a coordination, return a value based on that cell and 8 other cells around it:

```
private float laplaceA(int x, int y)
{
    float sum = 0f;
    for (int idx = -1; idx <= 1; idx++)
    {
        for (int j = -1; j <= 1; j++)
        {
            int newX = x + idx, newY = y + j;
            if (withinBorder(newX, newY))
            {
                float val = cur[newX*height + newY].x;

                if (idx == 0 && j == 0) { sum += val * -1f;} //center
                else if (Absy(idx) == 1 && Absy(j) == 1) {sum += val * 0.05f;} //diagonal
                else { sum += val * 0.2f;} //adjacent
            }
        }
    }
    return sum;
    //NOTE: Absy() is just Mathf.Abs() rewrite for using jobs
}

```

I tried some ways to make it works:

1. `IJobParallel` seems promising at first, but then I realize `Laplace()` can't access what it need, as I need the previous and next row, not just the current row (hence this post).
2. Tried `NativeArray<NativeArray<float2>>` to pass in each array one of a time, but failed as Unity doesn't support this yet. `List<NativeArray<float2>>` to try and sneak in failed as well.
3. Tried using just `IJob` and creating a `NativeArray<>` each row and a job with it, but I haven't figured out a way to store each array to dispose of it later.

Any idea to fix this problem, or other methods for speeding up calculations?

# Answer
> 1 votes
After some experiements I figured out what you need to do. The key appears to be to use an **`IJobParallelFor`** and to mark the array you only want to read from with the `[ReadOnly]` attribute. This `IJobParallelFor` interface is specifically designed for operating on arrays. The `[ReadOnly]` attribute allows you to access cells at other indices than the one currently being iterated.

1. Flatten the 2d array into a 1d array. This is important because IJobParallelFor isn't designed to work with 2d arrays.
2. Keep two copies of the whole matrix as persistent `NativeArray`s within the MonoBehaviour / System from which you intend to spawn the jobs. The reason why we want two persistent copies is because we don't want to constantly allocate and deallocate memory. What we are going to do is implement **double buffering**. One copy is being created while the other one serves as a template. And then for the next iteration we simply switch them, so that the new buffer becomes the template and the old buffer gets overwritten by the next version.
3. Create your job as an `IJobParallelFor`. You do not want to create copies of the persistent arrays, so the job should take its data as `NativeSlice`s. One for the current array which should be declared with the `[ReadOnly]` attribute. This is important, because otherwise you get "ReadWriteBuffers are restricted to only read & write the element at the job index." errors as soon as you try to access another cell than the one being iterated. The other is for the next array which it is going to overwrite. We are going to tag this with the `[WriteOnly]` attribute. It does not appear *strictly necessary* to do that and it doesn't really seem to affect performance in my particular test-case. But who knows, perhaps it allows some under-the-hood optimizations.
4. Schedule the `IJobParallelFor` from Update (or where else you want to schedule it)
5. When the job is completed, switch which NativeArray is "current" and which one is the "next" array.

Here is an example:

```
public class LaplaceVisualisation : MonoBehaviour {
    // some constants to avoid magic numbers
    private static int WIDTH = 256;
    private static int HEIGHT = 256;
    private static int NUM_CELLS = WIDTH * HEIGHT;

    // the two persistent data buffers
    private NativeArray<float2> bufferA;
    private NativeArray<float2> bufferB;

    // the double buffering implementation
    private bool buffersFlipped;
    private NativeSlice<float2> frontBuffer{ get => buffersFlipped ? bufferB : bufferA; }
    private NativeSlice<float2> backBuffer { get => buffersFlipped ? bufferA : bufferB; }

    void Start() {
        // create the two persistent buffers
        bufferA = new NativeArray<float2>(NUM_CELLS, Allocator.Persistent);
        bufferB = new NativeArray<float2>(NUM_CELLS, Allocator.Persistent);

        // TODO: Initialize bufferA with the initial configuration
        // You don't need to initialize bufferB, because it will get overwritten anyway
    }

    // the parallel job
    struct LaplaceJob : IJobParallelFor {
        [ReadOnly] public NativeSlice<vector2> current;
        [WriteOnly] public NativeSlice<vector2> next;

        public void Execute(int i) {

            var x = i % WIDTH;
            var y = i / WIDTH;

            // TODO: your logic here
            // read ONLY from current
            // write ONLY to next[i]
        }
    }

    void Update() {
        // create the job.
        // note that frontBuffer and backBuffer are implemented as
        // properties which return a slice of whatever buffer
        // has the respective role at the moment
        var laplaceJob = new LaplaceJob {
            current = frontBuffer,
            next = backBuffer
        };

        // run it
        var laplaceHandle = laplaceJob.Schedule(NUM_CELLS, 256);
        laplaceHandle.Complete();

        // flip frontBuffer and backBuffer
        buffersFlipped = !buffersFlipped;

        // visualise the data
        var data = frontBuffer;
        // TODO: Your visualisation code here
        // Do that by reading from data
    }

    private void OnDestroy() {
        // and don't forget to dispose the two NativeArray's when
        // Unity quits, so we don't get an ugly error message
        bufferA.Dispose();
        bufferB.Dispose();
    }
}

```

---
Tags: unity, c#, matrix, unity-job-system
---


# Question
Title: How to generate boards for a game like GamePigeon's Word Hunt?
Naively, I would assume that there's an even probability of any of the 26 given letters appearing in a tile and that each tile is generated independently. After playing around a hundred times, though, I have some doubt; the number of times I've seen three or four of the same letter, as well as uncommon letters like 'z' or 'w' feels too small, but I could absolutely be wrong.

Does anyone know how I can generate boards for this game? Should I generate each tile independently, or are there rules for how many of the same letters should appear?

# Answer
> 3 votes
If I had to create a board like that that has to have a certain amount of valid words, I would first create an algorith that can find words given a wordlist within that matrix. This has the following benefits:

* You can see how hard a board is to solve. The more words your algorith finds, the easier the board gets.
* If your game has a fixed level layout (means lvl XYZ should return always the same board), you can calculate the total points a level can give and reward accordingly stars for a level

Now that you can test a level, you can actually pick multiple ways how to generate a board. The laziest version would be to use a random letter for each field. Since you can test it, if you do not get enough words, simply recreate a new board.

A slightly better result would be to use a scrabble list for the language you target. They usually are a distribution of how often a letter is used. Now instead of randomly using a letter, you pick one by random from the list. Since some letters are more often in there, you will pick them up more often. (Might be better to pick and remove the letter from the list to not have the rare choosing of 4x Z and 3xY)

---
Tags: algorithm, procedural-generation, statistics, probability, word-games
---


title: How to simplify the code below

text:
# Question
Title: How to simplify the code below
I want to create 9 resistor and each resistor have 4 color code. I use a single array with size 36 to create the color code as below

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

public class AdvanceWayPoint : MonoBehaviour
   {

public Transform player;
public bool CreateResistor;
int RandNum;
public GameObject myprefab;
public GameObject FloatingText;
public GameObject[] Resistor;
public GameObject[] way1;
Vector3[] ExactResistorSpawnPoint;
public int[] ResistorBand;
public float[] ResistorValue;
public float ChoosenResistorValue;
public int Ammo;

void Start()
{
    ResistorBand = new int[36];
    ResistorValue = new float[9];
    Random.InitState(System.DateTime.Now.Millisecond);
    CreateResistor = true;
    player = new GameObject().transform;
    ExactResistorSpawnPoint = new Vector3[9];
}

void Update()
{

    if (CreateResistor == true)
    {
        RandNum = 1;
        CreateResistor = false;
        Waypoint();
    }

}

public void Waypoint()
{
    Vector3 SpawnPosition = player.transform.position;
    Vector3 ExactSpawnPoint = new Vector3(SpawnPosition.x + Random.Range(1, 4), 0, SpawnPosition.z + Random.Range(1, 4));

    if (RandNum == 1)
    {
        int i = 0;
        int y = 0;
        while (i < 35)
        {
            ExactResistorSpawnPoint[y] = new Vector3(ExactSpawnPoint.x + Random.Range(1, 10), ExactSpawnPoint.y + 7, ExactSpawnPoint.z + Random.Range(1, 10));
            ResistorBand[i] = Random.Range(1, 10);
            ResistorBand[i+1] = Random.Range(1, 10);
            while(ResistorBand[i+1]==ResistorBand[i])
            {
                ResistorBand[i + 1] = Random.Range(1, 10);
            }
            ResistorBand[i+2] = Random.Range(1, 5);
            while(ResistorBand[i + 2]==ResistorBand[i+1]||ResistorBand[i+2]==ResistorBand[i])
            {
                ResistorBand[i + 2] = Random.Range(1,5);
            }
            ResistorBand[i + 3] = Random.Range(1, 3);
            ResistorValue[y] = ((ResistorBand[i] * 10 + ResistorBand[i+1]) * Mathf.Pow(10, ResistorBand[i+2]) / 1000);
            i = i + 4;
            y = y + 1;
        }
        way1 = GameObject.FindGameObjectsWithTag("1K ohm");
        if (way1.Length == 0)
        {
            for (y = 0; y < 9; y++)
            {
                Instantiate(Resistor[y], ExactResistorSpawnPoint[y], Quaternion.identity);
            }

        }
        int RandomChooseWayPointValue = Random.Range(0, 9);
        ChoosenResistorValue = ResistorValue[RandomChooseWayPointValue];
        Instantiate(myprefab, ExactSpawnPoint, Quaternion.identity);
        GameObject go = Instantiate(FloatingText, ExactSpawnPoint, Quaternion.identity);
        go.GetComponent<TextMesh>().text = ResistorValue[RandomChooseWayPointValue].ToString() + " K ohm +/-" + ResistorBand[((RandomChooseWayPointValue+1)*4)-1].ToString() + "%";
    }
}

```

}

In game, I would need to pick up a resistor to a waypoint and each resistor is attached a script "ReadResistor" to retrieve the value of "ResistorValue".

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

public class ReadResistor1 : MonoBehaviour
{
public GameObject ReadValue;
public float value;
public GameObject ResistorPosition;

void Awake()
{
    ReadValue = GameObject.Find("Cube");
    AdvanceWayPoint way = ReadValue.GetComponent<AdvanceWayPoint>();
    value = way.ResistorValue[1];
}

private void OnMouseDrag()
{

    Vector3 result = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1f));
    transform.position = result;
}

```

}

Since each resistor have to retrieve respective stored value in ResistorValue in "AdvanceWaypoint" script, the current ineffective way I figured out is to create 9 ReadResistor script and attach a script to each of the resistor starting from ReadResistor to ReadResistor8. Since on the awake method, each resistor need to retrieve different array location.

As an example, the 1st resistor would refer to ResistorValue\[0\] in the awake method,

```
void Awake()
{
  ReadValue = GameObject.Find("Cube");
  AdvanceWayPoint way = ReadValue.GetComponent<AdvanceWayPoint>();
  value = way.ResistorValue[0];
}

```

the second would refer to ResistorValue\[1\] and so on

```
void Awake()
  {
    ReadValue = GameObject.Find("Cube");
    AdvanceWayPoint way = ReadValue.GetComponent<AdvanceWayPoint>();
    value = way.ResistorValue[1];
  }

```

Is there a way to create a single script for all the 9 resistor but each of them able to retrieve value in different array number?

# Answer
Simply create a public variable (say `Num` for instance) and then set it via inspector for each resistor:

```
public int Num;

void Awake()
  {
    ReadValue = GameObject.Find("Cube");
    AdvanceWayPoint way = ReadValue.GetComponent<AdvanceWayPoint>();
    value = way.ResistorValue[Num];
  }

```

some notes:

* I would recommend using `Start` for this, but this depends on your need (awake runs even if the game object is disabled which may not be desirable for you)
* If you don't have any other uses for `way` then you can combine it with the next line:

```
value = ReadValue.GetComponent<AdvanceWayPoint>().ResistorValue[Num];

```
* You can make `Num` private like this: `[Serializable] private int Num`
* Instead of an array with size 36 you can create a struct and then create an array from it:

```
public List<ResistorInfo> ResistorBand;

// ...

struct ResistorInfo
{
    public int a;
    public int b;
    public int c;
    public int d;
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: In SDL2 what is the fastest / most efficient way to draw pixels onto the screen? Using SDL_RenderDrawPoint or SDL_RenderCopy with a Texture?
I want to add pixel splatters and particle effects to a game. For this my options were to have a bunch of pre-made animations in the form of textures, OR create a particle engine.

For the particle engine approach, my options as far as I know are to create pixels and render them either using:

1. SDL\_RenderDrawPoint(s) (Using SDL\_SetRenderDrawColor)
2. SDL\_RenderCopy (Using Textures with SDL\_SetTextureColorMod)

I'm not sure what's a better approach. #2 is probably easier as I have a whole system built around fast texture rendering (not necessarily faster than 1., but seemingly easier to implement with my current system.) #1 seems ideal because it's in the SDL2 library for a reason I'd think, but really I'm unsure which approach I should go with.

# Answer
> 2 votes
So I ran both Functions 100,000 times (ran it a few times just to make sure), and timed it using time.h . I rendered a simple 1x1 pixel at 0,0 and a texture of a 1x1 pixel at 0,0. Below is basically a single trial I found.

SDL\_RenderDrawPoint: Time taken 9 milliseconds

SDL\_RenderCopy: Time taken 266 milliseconds

Not surprisingly the RenderDrawPoint is much faster than RenderCopy. My trial wasn't super perfect as I might have been able to use a more optimized Texture, and had to use some variables with values for SDL\_RenderCopy, but I doubt it added much time to make RenderCopy come even close to RenderDrawPoint.

Edit (Here's essentially the code I used, `renderer` is the window renderer, `texture` is a 1x1 bitmap surface in a texture loaded using RLE optimization):

```
#include <time.h>
#include <SDL2/SDL.h>

SDL_Rect clip;
clip.x = 0;
clip.y = 0;
clip.w = 1;
clip.h = 1;

int msec, i;
clock_t start, diff;

i = 100000;
start = clock()
while(i-- > 0)
{
    SDL_RenderDrawPoint(renderer, 0, 0);
}
diff = clock() - start;

msec = diff * 1000 / CLOCKS_PER_SEC;
fprintf(stdout, "Time taken %d seconds %d milliseconds", msec/1000, msec%1000);

i = 100000;
start = clock()
while(i-- > 0)
{
    SDL_RenderCopy(renderer, texture, &clip, &clip);
}
diff = clock() - start;

msec = diff * 1000 / CLOCKS_PER_SEC;
fprintf(stdout, "Time taken %d seconds %d milliseconds", msec/1000, msec%1000);

```

# Answer
> 1 votes
Neither of those: use SDL\_LockSurface to directly access directly the surface data. Then changing pixels is changing values in an array, which is fastest.

---
Tags: rendering, particles, sdl2, pixel
---


# Question
Title: Camera follows object and has a target object on the y-axis
I have two capsule objects in a split screen shooter. At this moment, the first camera follows player one, and has the target player two. The second camera follows player two, and has the target player one.

It feels a bit strange to play, because the game has different platforms with different height. How can I only follow the target along the y-axis?

The followed object shouldn't change at all. It should only look at the target. This is what I have, so far:

```
using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour
{
    [SerializeField]
    private float distanceAway;
    [SerializeField]
    private float distanceUp;
    [SerializeField]
    private float smooth;
    [SerializeField]
    private Transform followedObject;
    [SerializeField]
    private Transform target;
    private Vector3 toPosition;

    void LateUpdate()
    {
        toPosition = followedObject.transform.position - target.transform.position;

        GetComponent<Camera>().transform.position
            = followedObject.transform.position + toPosition.normalized *distanceAway;

        transform.LookAt(followedObject);
    }
}

```

# Answer
You may want to try locking the other two positions and see if that works as a simple solution. So just set the X and Z axis = 0 at the same time you are updating where the Y axis would change and that should effectively stop it from changing those values which would make the Y be the focus.

```
Transform.LookAt(0,followedObject.position.y,0);

```

May look something like that if it's working.

There are some good Q/A and forums on unity's site that may help more if you need it. http://answers.unity3d.com/questions/458219/how-do-i-let-a-camera-follow-on-one-axis.html
> 0 votes

# Answer
It looks like this old question meant "on the y-axis" as "Rotating only around the y axis (ie. yawing left and right), not rotating around the x axis (pitching up and down)".

That can be accomplished like this:

```
void LateUpdate()
{
    toPosition = followedObject.transform.position - target.transform.position;

    GetComponent<Camera>().transform.position
        = followedObject.transform.position + toPosition.normalized *distanceAway;

    // Look toward the target.
    var lookDirection = -toPosition;
    // Flatten this direction into the horizontal plane.
    lookDirection.y = 0;

    // Make a rotation that points straight out to the horizon in this direction.
    var yaw = Quaternion.LookRotation(lookDirection);

    // Set up a constant pitch if you want to look slightly downward.
    var pitch = Quaternion.Euler(pitchAngle, 0, 0);

    transform.rotation = yaw * pitch;
}

```

Here you can set `pitchAngle` in the inspector, or cache it in Start based on the initial camera pose.
> 0 votes

---
Tags: unity, camera, multiplayer
---


# Question
Title: How does one calculate the surface normal, in 2D collisions?
I have a ball, which should bounce when it collides with a surface. I know the formula for reflections;

$$ v\_1 - 2n(v\_1 \cdot n) $$

---

However, I cannot obtain the required information. I know:

* the ball position,
* the ball velocity,
* the ball radius,
* the polygon center
* the polgygon width and height
* the polgyon corner coordinates

---

How does one calculate the surface normal, in 2D collisions?

# Answer
> 5 votes
I think the following may help. You have the sphere center, box center and hopefully the details of the rectangle. Since the rectangle may be rotated we need the rectangle extents, and the orthogonal unit vectors, e.g.

Now we need the closest point on the rectangle to the point c.

```
vector d = c - r;

// project d onto ux to get distance along ux from c
float dx = dot(d,ux)
if(dx > ex)    dx = ex;
if(dx < -ex)   dx = -ex;

// project d onto uy to get distance along uy from c
float dy = dot(d,uy)
if(dy > ey)    dy = ey;
if(dy < -ey)   dy = -ey;

// calculate closest point p on box to c
vector p = r + dx*ux + dy*uy;

vector collision_norm = norm(c - p);

```

Now this should hopefully give you the required collision normal.

# Answer
> 0 votes
Based on the answer posted by Biggy Smith - See engine specific CPP code below.

```
CVector Helper::GetNormal(CSprite* collisionSource, CSprite* collisiontarget)
{
    // Work out the displacement vector
    auto d = collisionSource->GetPos() - collisiontarget->GetPos();

    // Find the extants of the rectangle
    auto ex = collisiontarget->GetWidth() / 2.0f;
    auto ey = collisiontarget->GetHeight() / 2.0f;

    // Find the bottom right point of the rectangle
    CVector bottomRight = CVector(collisiontarget->GetRight(), collisiontarget->GetBottom());

    // Find the bottom left point of the rectangle
    CVector bottomLeft = collisiontarget->GetBottomLeft();

    // Find the top left point of the rectangle
    CVector topLeft = CVector(collisiontarget->GetLeft(), collisiontarget->GetTop());

    // Find orthonomal unit vectors (I think? These are normalised anyway...)
    // In this instance I just took the displacement of the two appropriate corner points.
    CVector ux = Normalise(bottomRight - bottomLeft);
    CVector uy = Normalise(topLeft - bottomLeft);

    // Project d onto ux to get distance along ux from c
    float dx = Dot(d, ux);

    if (dx > ex)
    {
        dx = ex;
    }
    else if (dx < -ex)
    {
        dx = -ex;
    }

    // Project d onto uy to get distance along uy from c
    float dy = Dot(d, uy);

    if (dy > ey)
    {
        dy = ey;
    }
    else if (dy < -ey)
    {
        dy = -ey;
    }

    // calculate closest point p on box to c
    CVector contactPoint = collisiontarget->GetPosition() + dx*ux + dy*uy;

    // Calculate the normal at this point
    CVector surfaceNormal = Normalise(collisionSource->GetPosition() - contactPoint);

    return CVector(round(surfaceNormal.X()), round(surfaceNormal.Y()));
}

```

# Answer
> 0 votes
Created a Javascript solution based on Biggy Smith's answer.

Uses no external libraries. All input arguments are numbers.

```
// cX = circle center x
// cY = circle center y
// rX = rectangle top left x
// rY = rectangle top left y
// rW = rectangle width
// rH = rectangle height
// rA = rectangle rotation amount around center (in radians)

function getCollisionNormal(cX, cY, rX, rY, rW, rH, rA) {
  const eX = rW / 2;
  const eY = rH / 2;

  const rCX = rX + eX;
  const rCY = rY + eY;

  const uxX = Math.cos(rA);
  const uxY = Math.sin(rA);

  const uyX = Math.cos(rA - 1.571)
  const uyY = Math.sin(rA - 1.571);

  const distanceX = cX - rCX;
  const distanceY = cY - rCY;

  let dx = distanceX * uxX + distanceY * uxY;
  let dy = distanceX * uyX + distanceY * uyY;

  if (dx > eX)  { dx = eX; }
  if (dx < -eX) { dx = -eX; }
  if (dy > eY)  { dy = eY; }
  if (dy < -eY) { dy = -eY; }

  const pX = rCX + dx * uxX + dy * uyX;
  const pY = rCY + dx * uxY + dy * uyY;

  const deltaX = cX - pX;
  const deltaY = cY - pY;

  const magnitude = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

  if (magnitude === 0) {
    return { x: 0, y: 0, xDir: 0, yDir: 0 };
  } else {
    return { x: pX, y: pY, xDir: deltaX / magnitude, yDir: deltaY / magnitude };
  }
}

```

---
Tags: 2d, physics, mathematics, geometry, normals
---