title: Bullet Fire stuck on loop

text:
# Question
Title: Bullet Fire stuck on loop
When i shoot my bullet the unity explosion prefab keeps playing

I have a gun Script

```
using UnityEngine;
using TMPro;
public class ProjectileGunTutorial : MonoBehaviour
{
    //bullet
    public GameObject bullet;

    //bullet force
    public float shootForce, upwardForce;

    //Gun stats
    public float timeBetweenShooting, spread, reloadTime, timeBetweenShots;
    public int magazineSize, bulletsPerTap;
    public bool allowButtonHold;

    int bulletsLeft, bulletsShot;

    //Recoil
    public Rigidbody playerRb;
    public float recoilForce;

    //bools
    bool shooting, readyToShoot, reloading;

    //Reference
    public Camera fpsCam;
    public Transform attackPoint;

    //Graphics
    public GameObject muzzleFlash;
    public TextMeshProUGUI ammunitionDisplay;

    //bug fixing :D
    public bool allowInvoke = true;

    private void Awake()
    {
        //make sure magazine is full
        bulletsLeft = magazineSize;
        readyToShoot = true;
    }

    private void Update()
    {
        MyInput();

        //Set ammo display, if it exists :D
        if (ammunitionDisplay != null)
            ammunitionDisplay.SetText(bulletsLeft / bulletsPerTap + " / " + magazineSize / bulletsPerTap);
    }
    private void MyInput()
    {
        //Check if allowed to hold down button and take corresponding input
        if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
        else shooting = Input.GetKeyDown(KeyCode.Mouse0);

        //Reloading
        if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();
        //Reload automatically when trying to shoot without ammo
        if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();

        //Shooting
        if (readyToShoot && shooting && !reloading && bulletsLeft > 0)
        {
            //Set bullets shot to 0
            bulletsShot = 0;

            Shoot();
        }
    }

    private void Shoot()
    {
        readyToShoot = false;

        //Find the exact hit position using a raycast
        Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); //Just a ray through the middle of your current view
        RaycastHit hit;

        //check if ray hits something
        Vector3 targetPoint;
        if (Physics.Raycast(ray, out hit))
            targetPoint = hit.point;
        else
            targetPoint = ray.GetPoint(75); //Just a point far away from the player

        //Calculate direction from attackPoint to targetPoint
        Vector3 directionWithoutSpread = targetPoint - attackPoint.position;

        //Calculate spread
        float x = Random.Range(-spread, spread);
        float y = Random.Range(-spread, spread);

        //Calculate new direction with spread
        Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0); //Just add spread to last direction

        //Instantiate bullet/projectile
        GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity); //store instantiated bullet in currentBullet
        //Rotate bullet to shoot direction
        currentBullet.transform.forward = directionWithSpread.normalized;

        //Add forces to bullet
        currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
        currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);

        //Instantiate muzzle flash, if you have one
        if (muzzleFlash != null)
            Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);

        bulletsLeft--;
        bulletsShot++;

        //Invoke resetShot function (if not already invoked), with your timeBetweenShooting
        if (allowInvoke)
        {
            Invoke("ResetShot", timeBetweenShooting);
            allowInvoke = false;

            //Add recoil to player (should only be called once)
            playerRb.AddForce(-directionWithSpread.normalized * recoilForce, ForceMode.Impulse);
        }

        //if more than one bulletsPerTap make sure to repeat shoot function
        if (bulletsShot < bulletsPerTap && bulletsLeft > 0)
            Invoke("Shoot", timeBetweenShots);
    }
    private void ResetShot()
    {
        //Allow shooting and invoking again
        readyToShoot = true;
        allowInvoke = true;
    }

    private void Reload()
    {
        reloading = true;
        Invoke("ReloadFinished", reloadTime); //Invoke ReloadFinished function with your reloadTime as delay
    }
    private void ReloadFinished()
    {
        //Fill magazine
        bulletsLeft = magazineSize;
        reloading = false;
    }
}

```

And a Bullet Script

```
using UnityEngine;

public class CustomBullet : MonoBehaviour
{
    //Assignables
    public Rigidbody rb;
    public GameObject explosion;
    public LayerMask whatIsEnemies;

    //Stats
    [Range(0f,1f)]
    public float bounciness;
    public bool useGravity;

    //Damage
    public int explosionDamage;
    public float explosionRange;
    public float explosionForce;

    //Lifetime
    public int maxCollisions;
    public float maxLifetime;
    public bool explodeOnTouch = true;

    int collisions;
    PhysicMaterial physics_mat;

    private void Start()
    {
        Setup();
    }

    private void Update()
    {
        //When to explode:
        if (collisions > maxCollisions) Explode();

        //Count down lifetime
        maxLifetime -= Time.deltaTime;
        if (maxLifetime <= 0) Explode();
    }

    private void Explode()
    {
        //Instantiate explosion
        if (explosion != null) Instantiate(explosion, transform.position, Quaternion.identity);

        //Check for enemies
        Collider[] enemies = Physics.OverlapSphere(transform.position, explosionRange, whatIsEnemies);
        for (int i = 0; i < enemies.Length; i++)
        {
            //Get component of enemy and call Take Damage

            //Just an example!
            ///enemies[i].GetComponent<ShootingAi>().TakeDamage(explosionDamage);

            //Add explosion force (if enemy has a rigidbody)
            if (enemies[i].GetComponent<Rigidbody>())
                enemies[i].GetComponent<Rigidbody>().AddExplosionForce(explosionForce, transform.position, explosionRange);
        }

        //Add a little delay, just to make sure everything works fine
        Invoke("Delay", 0.05f);
    }
    private void Delay()
    {
        Destroy(gameObject);
    }

    private void OnCollisionEnter(Collision collision)
    {
        //Don't count collisions with other bullets
        if (collision.collider.CompareTag("Bullet")) return;

        //Count up collisions
        collisions++;

        //Explode if bullet hits an enemy directly and explodeOnTouch is activated
        if (collision.collider.CompareTag("Enemy") && explodeOnTouch) Explode();
    }

    private void Setup()
    {
        //Create a new Physic material
        physics_mat = new PhysicMaterial();
        physics_mat.bounciness = bounciness;
        physics_mat.frictionCombine = PhysicMaterialCombine.Minimum;
        physics_mat.bounceCombine = PhysicMaterialCombine.Maximum;
        //Assign material to collider
        GetComponent<SphereCollider>().material = physics_mat;

        //Set gravity
        rb.useGravity = useGravity;
    }

    /// Just to visualize the explosion range
    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, explosionRange);
    }
}

```

It is not set to looping so why is it looping?

# Answer
This function runs every frame as long as the bullet object still exists / is active and the script is enabled:

```
private void Update()
{
    //When to explode:
    if (collisions > maxCollisions) Explode();

    //Count down lifetime
    maxLifetime -= Time.deltaTime;
    if (maxLifetime <= 0) Explode();
}

```

It looks like it's been written in a way that expects `Explode()` will cause the bullet to be destroyed, so it doesn't have to worry about any future frames after that. But it doesn't - not right away. You've added a 50 millisecond delay between when Explode is called and when the bullet actually gets destroyed:

```
private void Explode()
{
    //Instantiate explosion
    if (explosion != null) Instantiate(explosion, transform.position, Quaternion.identity);

    // ...(skipping over irrelevant code)

    //Add a little delay, just to make sure everything works fine
    Invoke("Delay", 0.05f);
}
private void Delay()
{
    Destroy(gameObject);
}

```

So let's say that on frame X, the `collisions > maxCollisions` test is true and we call `Explode()`. We spawn an instance of the `explosion` effect, and schedule the bullet's destruction a half-second in the future.

On frame X+1, the bullet still exists (50 ms hasn't passed yet), and it's still true that `collisions > maxCollisions`, so we call `Explode()` *again*. We spawn a *second* instance of the `explosion` effect.

The same repeats for frame X+2 and so on. If we're running at 60 FPS, we might spawn 3 copies of the `explosion` effect in the delay between the initial explosion and the destruction of the bullet, making it look like the explosion is looping when really it's just multiple copies playing in rapid succession. If you're running at a higher framerate, you might get even more copies.

The same thing can happen if the bullet reaches the end of its lifetime, or if it explodes on touch. The `OnCollisionEnter()` method can keep firing if the bullet keeps nudging against an enemy during its death throes, firing off more explosions.

One way to fix this is to add a `bool _hasExploded = false;` flag as a member variable. When you call `Explode()`, check if `_hasExploded` is true - if so, abort before you spawn a new explosion. If not, set it to true so you never spawn a second explosion after this one.

You could also destroy the bullet sooner, or use `enabled = false` to turn off the `Update()` method during the bullet's death throes. This won't stop the `OnCollisionEnter()` handler from being invoked, so you'd want to call `Explode()` there only if `enabled` is true.
> 0 votes

---
Tags: unity, first-person-shooter
---


# Question
Title: Unity WebGL Progress bar never moves but game finishes downloading and works
Not sure why but the progress bar never moves for WebGL in Chrome, but the game downloads and works?

Using Unity 2020.1.14f1 brotli WebGL builds

# Answer
> 0 votes
This is just guesswork as I'm still searching for the answer to this myself but I seem to remember that it may be a server misconfiguration causing the loader to fall back onto a non-compressed load. Somehow I think this stops the loader from having access to how much data has downloaded so far.

# Answer
> 0 votes
I found this was fixed on 2021.2.X, is a known issue, https://issuetracker.unity3d.com/issues/webgl-incorrect-loading-progress-is-shown-in-the-player-when-build-files-are-compressed-using-brotli

---
Tags: unity, webgl
---


# Question
Title: Give an opaque color to inner base of otherwise transparent cube?
This is my first time using a material in Unreal Engine. I am trying to create a transparent cube except for the inner face of the base, which I would like to be opaque white, like in this drawing:

I have created a cube with transparent sides and an opaque white top:

I am attempting to paint the top face with a semi-transparent blue, like the sides, and move the upward-facing painting of that face down to the base, but that is not going well:

How might I achieve this material? I am using the material on glTF cubes in 3dtiles. They accept materials in the same way as a static mesh does, but it is not possible to identify the vertices.

# Answer
> 2 votes
An easy fix could be creating two different material slots with two different domains. To create two different materials slots you have to go in your 3d software of choice. In this way you can have your opaque face with the default material domain:

I set the "two sided" option to true because as I understood you want to see the opaque face from every angle. For the other faces you could have the material set to translucent in this way:

Don't mind the nodes or the other stuff. In the end you should have something that look like this:

With a few tweaks you should achieve exactly what you are looking for.

---
Tags: unreal-4, materials
---


# Question
Title: How to knock animated character backward when sword strikes wall
I was wondering how to make animation and physics interact.

Specifically, I want to make it so when my character (rigidbody) plays a sword hit animation (swinging the sword in front of it), it makes the character move backward when the sword and the wall collide.

I want this to happen with physics. When the sword pushes against the wall, It pushed the player back because of the rigidbody.

I've been looking at Animation rigging in unity. Would it work to add à collider to my sword and the use Inverse kinematic to move it ? How can I achieve this?

# Answer
> 0 votes
1. Add a collider to your Sword.
2. On your Animator add a parameter \> bool swordCollider, And and add your animation.
3. Create a script with:

```
void OnTriggerEnter () {
  if (other.gameObject.CompareTag("Wall")) {
    animator.CrossFade("KnockBack", 0.2f);
  }
}

```
4. Add your script on the Sword.

Done

---
Tags: unity, physics, animation, rigidbody
---


# Question
Title: Improving performance of lighting on mobile
I'm trying to make a 3D game for mobile. When rendering a very simple scene, my performance drops from 60 fps to 30 fps when I use fragment shader lighting instead of vertex shader lighting.

I really hate the look of the vertex shader lighting, but I'm worried about whether or not I'm going to be able to run any game system and still get a reasonable framerate if I go with fragment shader lighting. I would like to seek advice as to what should I choose, or if there's any optimisation I could make to a shader to keep the good look and the framerate.

Here's my shader code (I'm using GLSLes 3.0):

vertex shader

```
#version 300 es

in mediump vec4 position;
in mediump vec2 i_UV;
in mediump vec4 i_Normal;

out mediump vec2 UV;
out mediump vec3 Position;
out mediump vec3 Normal;
out mediump vec3 CamDir;
out mediump float fogFactor;

uniform mat4 transformationMatrix;
uniform mat4 rotationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

uniform mediump float IOR;
uniform mediump float roughness;
uniform mediump float specular;

out mediump float Fresnel_O;

void main(){
    UV = i_UV;
    Position = (transformationMatrix*position).xyz;
    Normal = normalize((rotationMatrix*i_Normal).xyz);
    CamDir = normalize((inverse(viewMatrix) * vec4(0,0,0,1.0)).xyz - position.xyz);

    fogFactor = exp(-pow(distance((viewMatrix*transformationMatrix*position).xyz,vec3(0.0,0.0,0.0))*0.01,2.0));

    mat4 a = viewMatrix;

    //Fresnel
    float F_I = -1.0/IOR;
    float F_A = dot(refract(CamDir,Normal,F_I),Normal);
    float F_B = dot(Normal,CamDir);
    Fresnel_O = pow((F_B*F_I-F_A)/(F_B*F_I+F_A),2.0) * (1.0-roughness);

    vec4 finalPos = projectionMatrix*viewMatrix*transformationMatrix * position;
    gl_Position = finalPos;
}

```

fragment shader

<pre><code>#version 300 es
precision mediump float;

out highp vec4 Fragment;
in mediump vec2 UV;
in mediump vec3 Position;
in mediump vec3 Normal;
in mediump vec3 CamDir;
in mediump float fogFactor;

const lowp int NUMBER_OF_LIGHTS = 10;
in mediump float Fresnel_O;
uniform mediump vec3 LightPos[NUMBER_OF_LIGHTS];
uniform mediump vec3 LightColor[NUMBER_OF_LIGHTS];
uniform mediump float LightIntensity[NUMBER_OF_LIGHTS];

uniform mediump float roughness;
uniform mediump float Metaliness;
uniform mediump float specular;
uniform mediump sampler2D textureSampler;
uniform mediump vec3 emission;

const mediump vec3 envColor = vec3(0.0,0.1,0.1) * 0.0;

void main(){
    vec4 albedo = texture(textureSampler,UV) * color;
    if(texture(textureSampler,UV).a < 0.5){ discard; }

    vec3 diffColorMultiplier = vec3(0.0);
    vec3 specColor = vec3(0.0);

    for(int i = 0; i < NUMBER_OF_LIGHTS && LightPos[i] != vec3(0.0); i++){
        mediump float LightDist = length(LightPos[i]-Position);
        mediump vec3 LightDir = (LightPos[i] - Position)/LightDist;

        //diffuse
        float diffLightAmount = max(dot(normalize(LightDir), Normal), 0.0);
        diffColorMultiplier += LightColor[i]*((diffLightAmount/(LightDist*LightDist))*LightIntensity[i]);

        //specular
        //custom specular algorythim based on phong shading. It gives me the look I want.
        float specularAmount = ((pow(max(dot(reflect(-normalize(LightDir), Normal), CamDir), 0.0), (1.0-roughness)*(1.0-roughness)*300.0) + diffLightAmount*0.01)/(LightDist*LightDist))*Fresnel_O*(LightIntensity[i]*LightIntensity[i]) * specular;
        specularAmount = max(specularAmount, 0.0);
        specColor += LightColor[i] * specularAmount;
    }

    vec4 finalColor = vec4(mix(mix((albedo.rgb * diffColorMultiplier) + specColor,specColor,Metaliness)+envColor+emission,envColor,1.0-fogFactor),albedo.a);

    Fragment = finalColor;
}
```
</code></pre>

# Answer
> 0 votes
> Is there some code that I could easily transfer to the vertex shader?

* You're sampling your texture twice. `if(texture(textureSampler,UV).a < 0.5)` could just be `if (albedo.a < 0.5)` since you already stored the texture sample into `albedo`.
* You're normalizing your `LightDir` three times, when once is enough. It's already normalized by this line: `mediump vec3 LightDir = (LightPos[i] - Position)/LightDist;`
* You could pre-invert your roughness uniform to a smoothness to save inverting it in the shader. Similarly, any attribute that only ever appears as `(1.0 - foo)` in your fragment shader could be pre-inverted in the vertex shader before interpolation.
* This line:

```
vec4(mix(mix((albedo.rgb * diffColorMultiplier) + specColor,specColor,Metaliness)+envColor+emission,envColor,1.0-fogFactor),albedo.a);

```

Can be written more simply as...

```
vec3 surfaceColor = (1.0 - Metalness) * albedo.rgb * diffColorMultiplier
                     + specColor + emission;

vec4 finalColor = envColor + fogFactor * surfaceColor;

```

Those are all micro-optimizations though, and it's likely that the shader compiler might already fix all but the third point for you.

The most expensive thing in this shader might be the `discard` instruction. The presence of a `discard` can disable some optimizations. If you have some objects that don't need per-pixel transparency, it would be worthwhile to make a pure opaque variant of this shader that does not include this alpha testing.

That's about as much as jumps out at me from the code alone. To go further, you'll need to do some profiling to identify which parts actually make your game slow in practice.

---
Tags: shaders, performance, lighting, mobile
---


# Question
Title: Extracting cell center and corner points from rasterized Voronoi diagram
I currently have this code which I copied from Rosetta code:

```
// version 1.1.3

import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage
import java.util.Random
import javax.swing.JFrame

fun distSq(x1: Int, x2: Int, y1: Int, y2: Int): Int {
    val x = x1 - x2
    val y = y1 - y2
    return x * x + y * y
}

class Voronoi(val cells: Int, val size: Int) : JFrame("Voronoi Diagram") {
    val bi: BufferedImage

    init {
        setBounds(0, 0, size, size)
        defaultCloseOperation = EXIT_ON_CLOSE
        val r = Random()
        bi = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB)
        val px = IntArray(cells) { r.nextInt(size) }
        val py = IntArray(cells) { r.nextInt(size) }
        val cl = IntArray(cells) { r.nextInt(16777215) }
        for (x in 0 until size) {
            for (y in 0 until size) {
                var n = 0
                for (i in 0 until cells) {
                    if (distSq(px[i], x, py[i], y) < distSq(px[n], x, py[n], y)) n = i
                }
                bi.setRGB(x, y, cl[n])
            }
        }
        val g = bi.createGraphics()
        g.color = Color.BLACK
        for (i in 0 until cells) {
            g.fill(Ellipse2D.Double(px[i] - 2.5, py[i] - 2.5, 5.0, 5.0))
        }
    }

    override fun paint(g: Graphics) {
        g.drawImage(bi, 0, 0, this)
    }
}

fun main(args: Array<String>) {
    Voronoi(70, 700).isVisible = true
}

```

The problem is, this code has a `JFrame` graphical output while I want an `Array<Vector2>` one, consisting of polygon points and centre points.

I'd try to manipulate this myself, but the code is too complex for me to understand. I'd appreciate a version of this code that returns such output.

if someone could explain the code above my problem would be solved, and how i would un-rasterise it and just get an array output

# Answer
It is better to generate a Voronoi diagram as vectors first, e.g. via Fortune's Sweepline Algorithm, then rasterise.

If, however, you are dead set on using the rasterised version as a basis, then you need, per uniquely IDed (colored) Voronoi Cell, to:

1. Collect the list of pixels / texels for that cell, via flood-fill.
2. Average the centres of those pixels to get and store centre coordinates for that cell.
3. Seek all neighbour pixels of that cell, storing only unique adjacent colors / IDs in a set or dictionary to prevent duplicates. Set up a neighbours list to store those IDs for this cell.

You can now draw a graph of all centres connected to one another using these neighbour lists. This is called the Delaunay Triangulation of the Voronoi diagram (it produces triangles). However, you need the corners rather than (just) the centres of the cells.

4. Produce the graph dual of the Delaunay Triangulation, which is the Voronoi diagram. The easiest way to do this is, for each triangle in your Delaunay Triangulation, to calculate the centroid as the average of its 3 corners / vertices. You will then need to figure out that triangle's neighbours according to which *other* triangles share its edges. Then this triangle's centre will connect to their centres. This gives you the corners you seek.

Needless to say that while possible, this is not quite trivial, and very inefficient vs. just using a proper Voronoi graph generation algorithm which outputs vectors, but it does avoid your needing to find or implement such an algorithm.
> 2 votes

---
Tags: libgdx, algorithm, geometry, pixel, kotlin
---


# Question
Title: How do I calculate a matrix to render a mirror about a plane using GLM?
I've been trying to work out how to render a mirror for a while now, but a lot of resources I find either use very outdated tools I'm not familiar with, appear to be college slides referencing other material I cannot find, or simply don't seem to work correctly at all. (e.g. the answer to a previous OpenGL mirror question links to wikibooks' tutorial on portal rendering, which doesn't provide the appropriate math for reflections.)

I have all the stencil logic in place but am struggling to produce a reflection matrix which, when combined with my view matrix, creates a correct reflection. Notice that the in-game render below does not match up with a correct reflection of the same scene:

The setup for calculating the view prior to rendering the scene looks like this:

```
// Obtain the model to world-space matrix for the mirror plane
        auto N = node.getCachedWorldTransform();

        // Obtain the position and normal of the mirror plane in world-space
        auto pt = (N * glm::vec4(meshes[node.meshes[0]].firstPoint, 1.0)).xyz();
        auto norm = glm::normalize(glm::mat3(glm::transpose(glm::inverse(N))) * meshes[node.meshes[0]].firstNormal);

        // Calculate plane equation, and then reflection matrix
        auto plane = planeFromPointNormal(pt, norm);
        auto refl = glm::transpose(matrixReflect(plane));

        // Create a new view matrix combining our reflection matrix with the previously used camera matrix
        auto pCam = camView * refl;

```

The helper functions involved are:

```
glm::vec4 planeFromPointNormal(glm::vec3 pt, glm::vec3 normal) {
    auto norm = glm::normalize(normal);
    return { norm.x, norm.y, norm.z, -glm::dot(pt, norm) };
}

// The math here is ripped shamelessly from D3DX documentation, so it may have to be transposed
glm::mat4 matrixReflect(glm::vec4 plane) {
    auto P = glm::normalize(plane);

    return glm::mat4{
        -2 * P.x * P.x + 1,  -2 * P.y * P.x,      -2 * P.z * P.x,        0,
        -2 * P.x * P.y,      -2 * P.y * P.y + 1,  -2 * P.z * P.y,        0,
        -2 * P.x * P.z,      -2 * P.y * P.z,      -2 * P.z * P.z + 1,    0,
        -2 * P.x * P.w,      -2 * P.y * P.w,      -2 * P.z * P.w,        1
    };
}

```

Various attempts at fixing this (altering culling, transposing or inverting matrices, keeping regular back-face culling but applying negative scaling on some axis, swapping the multiplication order of components, etc.) do not seem to have any effect on the outcome other than making the reflection broken in dramatically different ways. My current attempt is to flip the culling face (glCullFace(GL\_FRONT)) before drawing the reflected objects. (I am also concerned that this might cause the back-face of the floor beneath the mirror to be rendered!)

What might I be doing wrong? Is there some resource I am missing that lays out clearly how to do this?

# Answer
> 1 votes
I was working out the math for a reflection matrix from first principles, and found it matches your code exactly, *except* that you normalize the plane 4-vector first.

Don't do that.

We want the first 3 components to form a unit 3-vector, which they already do thanks to the normalization in the `planeFromPointNormal` function.

---

Here's the full derivation:

Take a basis direction vector \\$\vec d = (1, 0, 0)\\$. We'd expect this to be reflected by a unit normal \\$\vec n = (n\_x, n\_y, n\_z)\\$ to:

$$\vec d - 2 \left( \vec d \cdot \vec n \right) \vec n\\ =(1, 0, 0) - 2n\_x(nx, n\_y, n\_z)\\ = (1 - 2n\_x^2, -2n\_xn\_y, -2 n\_xn\_z)$$

And so on for the other basis vectors. That gives us the first three columns of our matrix.

Next we'll take a vector on the reflection plane: \\$\vec p = -w \vec n\\$ makes a convenient choice, where \\$w\\$ is the fourth component of our plane vector. If we reflect that vector about the origin along our normal, we'd get \\$\vec p^\prime = -w \left(- \vec n\right) = w \vec n\\$, and the translation that brings it back to where it started is \\$\vec t = \vec p - \vec p^\prime = -w \vec n - w\vec n = -2w\vec n\\$, so that gives us our fourth column.

```
glm::mat4 matrixReflect(glm::vec4 plane) {

    return glm::mat4{
        1-2*plane.x*plane.x,  -2*plane.x*plane.y,  -2*plane.x*plane.z, -2*plane.x*plane.w,
         -2*plane.y*plane.x, 1-2*plane.y*plane.y,  -2*plane.y*plane.z, -2*plane.y*plane.w,
         -2*plane.z*plane.x,  -2*plane.z*plane.y, 1-2*plane.z*plane.z, -2*plane.z*plane.w,
                          0,                   0,                   0,                  1
    };
}

```

Note that I've baked-in the transpose here, so you don't need to transpose the matrix after computing it.

---
Tags: opengl, mathematics, rendering, glm, reflection-rendering
---


# Question
Title: How do I create a method that adds a new sprite to the game?
I want to have a script in my game that adds a card.

I am using a `Card` class for all my cards, so I don't have to make a prefab for each card. Instead I can do something like: `Card fire = new Card("blah blah");` to define a "fire" card type, then call `fire.Generate(position)` to create a card sprite of that type at the given position.

Somehow I need my `Generate()` method to add a new object (sprite) to the game when called. How can I do that?

CardGenerator.cs:

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

public class CardGenerator : MonoBehaviour
{
    Card makeYellow;

    private void Start()
    {
        makeYellow = new Card("Make Yellow", "This card makes the player yellow.");
        makeYellow.Generate(Vector2.zero);
    }
}

```

Card.cs:

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

public class Card
{
    public string Name;
    public string Description;
    private Sprite sprite;
    private SpriteRenderer sr;

    public Card(string name, string description)
    {
        Name = name;
        Description = description;
    }

    public void Generate(Vector2 pos)
    {
        // ...
    }

}

```

# Answer
```
public SpriteRenderer Generate(Vector2 pos)
{
    // Add a new game object named after this card to the Active Scene.
    var card = new GameObject(Name);

    // Attach a SpriteRenderer component to this object.
    var spriteRenderer = card.AddComponent<SpriteRenderer>();

    // Assign the sprite you want the card to display.
    spriteRenderer.sprite = sprite;

    // Position the card where you want it to appear.
    card.transform.position = pos;

    // Return a reference to this object in case other code wants to manipulate it.
    return spriteRenderer;
}

```
> 1 votes

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


# Question
Title: How can I "zero out" velocity in an arbitrary direction?
I'm currently running into an issue with my character controller using physics-based movement of rigidbodies in Unity.

Here's an illustration of the issue I'm facing:

Basically, after a jump, my character sticks to the ground for a split second after landing from a jump. While I have no idea, I just assumed this had something to do with the way Physics were being implemented, given that a portion of the character's velocity is heading downward, it makes sense that there would be some "impact time". I drew a bit of depenetration in the diagram, but that's mostly some creative thinking by me, I don't actually know if that has anything to do with it.

My current solution is to do this during the "landing" frame:

```
// first frame that the ground is detected
var velocity = rigidbody.velocity;
velocity.y = 0;
rigidbody.velocity = velocity;

```

This works nicely. However, I've now implemented custom gravity into the project, which allows for completely arbitrary gravity vectors (meaning I can't just set something to `0` and be done with it).

Is it possible to nullify all force in the "gravity" direction upon landing? It's also possible I've got a problem elsewhere if this reads like something that should be happening.

Here's a snippet that has the meat of my movement code:

```
        var velocity = rigidbody.velocity;
        var normal = CollisionHelper.GetFloorNormal(capsuleCollider, true);

        Vector3 xAxis = ProjectDirectionOnPlane(rightAxis, normal);
        Vector3 zAxis = ProjectDirectionOnPlane(forwardAxis, normal);
        float currentX = Vector3.Dot(velocity, xAxis);
        float currentZ = Vector3.Dot(velocity, zAxis);
        float acceleration = isGrounded ? defaultAcceleration : airAcceleration;
        float maxSpeedChange = acceleration * Time.deltaTime;

        var desiredVelocity = new Vector3(wrapped.input.move_H, 0, wrapped.input.move_V) * defaultSpeed;

        float newX = Mathf.MoveTowards(currentX, desiredVelocity.x, maxSpeedChange);
        float newZ = Mathf.MoveTowards(currentZ, desiredVelocity.z, maxSpeedChange);
        velocity += xAxis * (newX - currentX) + zAxis * (newZ - currentZ);

        rigidbody.velocity = velocity;

```

# Answer
This is pretty simple linear algebra. You can make a little helper method for it:

```
public static class VectorExtensions {

    public static Vector3 RemoveComponent(this Vector3 vector, Vector3 direction) {
        direction = direction.normalized;

        return vector - direction * Vector3.Dot(vector, direction);
    }
}

```

Then just say:

```
velocity = velocity.RemoveComponent(Physics.gravity);

```
> 15 votes

---
Tags: unity, physics, movement, vector, rigidbody
---


# Question
Title: GM files in online mobile games: what type of GM file should I keep a local copy and how does it synchronize with server?
In mobile game development there are types of data that are not user save-data but are necessary for the game, we call it GM files. In my specific case, the GM files include text data such as "item name" and "item description", as well as things like monster parameters like attack point and defense point.

A very common thing to do that are employed in a lot of real life games, based on my research, is to store a local copy of the GM file and also a server copy of the GM file. The server version of the file is prioritized but the local copy is used to speed up game rendering.

My questions are,

(1) Are text info such as names and descriptions generally considered data that need to be pulled from server every request or something that can be accessed from the local file?

(2) When the local file for game rendering become out of sync with the server, when should it be synchronized? It does not seem likely for me one has to wait until the next version upgrade to fix these type of bugs.

Some side notes:

One problem I am considering is, storing the item names locally would reduce the amount of data transfered (and hence the cost) than when pulled from server every request. However I am not even sure whether this is considered a significant factor in real life games since the amount of data is tiny when compared to other resource files. (A programmer in my team is very keen on this method but I am pretty precarious as research I made suggests the other way. The main argument he makes is actually about the data transfer cost rather than the rendering speed)

On the other hand, I can't find a very good reason to defend the method that pulls the item names from server every time, since one would never achieve the effect of cheating via modifying "names". The only thing I can think of is it's more convenient to debug for the developing process. And most real life games I have researched seem to use this method.

# Answer
> (1) Are text info such as names and descriptions generally considered data that need to be pulled from server every request or something that can be accessed from the local file?

"General practice" will not save us from making our own decisions here. Every game makes its own idiosyncratic choices based on all kinds of factors - be they well-considered responses to the game's unique needs, or historical baggage from a tumultuous development process, or compromises forced upon it by budget, time, technology, or architectural (or sometimes legal) constraints.

The real question you need to ask yourself is "is this data *in my game* something that I want to synchronize from the server?" Things you might consider here include:

* Is this data unnecessary for the initial experience of the game, and bulky? (So you might want to remove it from the initial app install to keep your download size small, and stream it later as needed - this is done for levels/maps beyond the starting area in some games)
* Will I want to *change* this data frequently or with very little notice? (Say for urgent balancing updates, without pushing a whole new app update for users to install)

> (2) When the local file for game rendering become out of sync with the server, when should it be synchronized? It does not seem likely for me one has to wait until the next version upgrade to fix these type of bugs.

One simple way you can handle this is to have a manifest file that lists these data files and their latest update version.

When the user connects to the server, they request the latest manifest file, and check the versions of all the data files it references. If they are missing a data file referenced in the manifest, or their local copy has a lower version number than what's listed in the manifest, then they request the fresh version of those needed files from the server.

That way, most connections transfer just a small manifest file, and the larger data files are sent only when needed.

That said, this approach has significant complexity: your game needs to support "hot-reloading" these data files when they change, all of the manifest transactions above, and you need a process for keeping your version numbers and server manifest correctly updated so that the whole process works. That could be a substantial investment of development time and opportunity for bugs to creep in. So, ask yourself if that complexity is truly necessary for your case.

> One problem I am considering is, storing the item names locally would reduce the amount of data transfered (and hence the cost) than when pulled from server every request. However I am not even sure whether this is considered a significant factor in real life games since the amount of data is tiny when compared to other resource files.

Again, there's no such thing as "real games" or, to put it another way, *your game* is as "real" as any. To get a precise answer here, you need to ask about *your game* and get concrete: **count the bytes** of data involved in the specific data you want to send.

You can get a ballpark idea of the size of the data to be transferred per message, and multiply it by the number of concurrent users and the rate at which you need to send them these messages. That gives you the total added bandwidth of including these bits of data in each relevant exchange, rather than keeping a local cache in sync. Compare that to the rate you pay under your server hosting plan - is it within your budget? You may well find it's cheaper to pay that overhead than it is to pay a programming team for the extra weeks to develop the file caching/synching system. Instead, they can spend that time working on gameplay updates!
> 2 votes

# Answer
When you have data which changes very rarely, like the data for common inventory items in the game, then it's usually not a bad idea to just put them in a file in your favorite markup format (XML, JSON, CSV, whatever) and ship it with the game client.

Now there is of course the questions what happens if you release an update. This should happen rarely (perhaps weekly or monthly), but when it happens there might be players who are online.

One way to do this is to just restart the server and kick all online users in the process. A server restart might be required anyway because allowing such files to be hot-loaded on the server is also a nasty can of worms with a lot of pitfalls and edge-cases to handle. So taking the server down, changing the content file, and rebooting it can be the easiest and safest solution.

Then when the clients reconnect, have the client send their version number. When the version number is outdated, reject the login attempt and tell them to download the update first. This also prevents a ton of *other* problems which can occur when players try to play the game with an outdated client.

**So if you can get away with a restart for all servers and clients for each update, you should do so.** It's the easiest and cleanest way to ensure that all clients and servers play the same version of the game.

OK, but what if your managers and players really don't like getting kicked once per week and insist on six-sigma uptime? A rather costly request, but not a completely unreasonable one. In that case you need hot-reloading on both the client and the server. Which means you need to establish a protocol which allows these things:

0. There needs to be some command on the server to reload a specific content file at runtime.
1. The server then notifies the currently connected clients that a specific content file is outdated
2. There needs to be a way to transfer the new version of the content file (incremental updates optional if you are extra-masochistic). This could happen via pull (the client does a request, via HTTPS, for example) or via push (the notification from the server already includes the new version of the file)
3. The client needs to be able to hot-reload that file at runtime without restarting.

None of these points is trivial to do, but nothing about it is technically impossible.
> 1 votes

# Answer
> the GM files include text data such as "item name" and "item description", as well as things like monster parameters like attack point and defense point

Those are potentially different categories of things.

Names and descriptions are often fine to modify. In fact, you may want to provide different versions of them for clients in different languages.

Yet, stats have a more direct impact on game play. For example, more or less attack points - presumably - means battles could last longer or shorter.

For those you are going to consider the online and multiplayer mechanics of the game. If every game is pretty much isolated from each other, there is little harm on these modifications. Yet if there are online rankings, or some other way in which players compete to each other, then you need to consider if modifying these stats can enable cheating. *It can be far removed from the actual player-player interaction, for example changing the stats leads to defeating more offline enemies that lead to more resources that are used in a player-player interaction.*

*Addendum: The server should be in charge of player-player interactions. In general, don't let the client tell the server what it has (be it stats or inventory or rewards or whatever). But some of those changes made locally, if the game is entirely offline, or other players can't see and are unaffected by them are fine.*

---

> (1) Are text info such as names and descriptions generally considered data that need to be pulled from server every request or something that can be accessed from the local file?

No, not really. Unless it is something that changes often. Usually you would download them in case of an update.

I'll elaborate further below.

---

> (2) When the local file for game rendering become out of sync with the server, when should it be synchronized? It does not seem likely for me one has to wait until the next version upgrade to fix these type of bugs.

Again, this depends on your game. On one extreme it could be that this is entirely irrelevant. On the other it could be that you need to tell the player that they have to update the game because a new version is available and they can't play with the old version.

Plus, I cannot hold it against you if you don't have a hot reload mechanism if isn't a problem, much less on an initial version. Yet, it cost you very little to publish the current version on the server, so the client can check if its version matches.

---

You seem to be worried that the players are going to see the wrong thing. And one part is to keep the data up to date. And another part is to prevent the data from being tampered with.

If the player tampered with the game in such way that they see a million times the damage or coins or whatever, but that is only local and the server register the correct value, is that really cheating? Also, are you worried they don't see the correct information when it is them who tampered with it? I don't think it is cheating, nor that you should be worried.

---

> One problem I am considering is, storing the item names locally would reduce the amount of data transfered (and hence the cost) than when pulled from server every request. However I am not even sure whether this is considered a significant factor in real life games since the amount of data is tiny when compared to other resource files. (A programmer in my team is very keen on this method but I am pretty precarious as research I made suggests the other way. The main argument he makes is actually about the data transfer cost rather than the rendering speed)

It will be important for you and your servers to save transfer data. And it will be important for those players on a measured connection. You need to consider how many players are there, and how much data transfer per unit of time they need. Having a server and connection that can handle more will have a monetary cost for you.

*If the player sees the wrong values because they tampered with them, it won't cost you.*

Let us put this in terms of information security. There are three main properties of the information we want do defend:

* Confidentiality. I believe there are no confidentiality concerns here.
* Availability. The local files are available even when there isn't a network connection, or the network connection is of poor quality.
* Integrity. The local files could be tampered with or corrupted. Also, sometimes they can become outdated.

This tells us that having local files is better. But we need some kind of integrity check and update check. *And let me reiterate that you should not worry about the integrity check.*

Thankfully, we can address both checks in a single one: when launching the game - or when you first need the data - ask the server for a checksum of the files. Compute it for the local files and compare it with the checksum from the server, and if they don't match, download them again. You may also add a timestamp so the client can bypass the check if the server is saying that it is a newer version of the files than the client has downloaded.

However, that is an extra request (one for asking for the checksum, and one to download). We can do better, let the client tell the server what it got (checksum and timestamp), so the server can simply reply "not modified" or reply with the file. *Or perhaps just a timestamp, if we don't care about the integrity.*

Ah, but that request could be faked… Look, if this is text data, this is fine. The players that tampered with it is only affecting themselves. If they got to the point when they bypassed the checksum so they can tamper with their own copy, let them.

It is when we talk about player-player interactions that you would have some concern. To prevent cheating you need to have the server decide all rewards, control the player stats and inventory, and have the server validate all interactions. The local copy is both to reduce data transfer and for performance. But your game logic should remain on the server.

---

I have been assuming we are talking only about text data. But you can imagine how you could start doing something like this for textures, models, and so on. Which have their own considerations (e.g. if the player can modify the textures, can the player make an x-ray mod?).

Also, as I was saying, stats and text are not necessarily on the same bucket. yet, that depends on how authoritative the server is.

You could also imagine how you could even have it update without closing the game. Or how you could have the server generate diff patches so the client does not have to download the whole files, only what changed. It can get quite complex. However I believe I gave an outline of something you can get working that address the issues at hand.
> 1 votes

---
Tags: client-server, mobile, data, online
---


# Question
Title: What causes Box2D revolute joints to separate?
I have created a rag doll using dynamic bodies (rectangles) and simple revolute joints (with lower and upper angles). When my rag doll hits the ground (which is a static body) the bodies seem to fidget and the joints separate.

It looks like the bodies are sticking to the ground, and the momentum of the rag doll pulls the joint apart (see screenshot below).

I'm not sure if it's related, but I'm using the Badlogic GDX Java wrapper for Box2D. Here's some snippets of what I think is the most relevant code:

```
private RevoluteJoint joinBodyParts(
    Body a, Body b, Vector2 anchor,
    float lowerAngle, float upperAngle) {

    RevoluteJointDef jointDef = new RevoluteJointDef();

    jointDef.initialize(a, b, a.getWorldPoint(anchor));

    jointDef.enableLimit = true;
    jointDef.lowerAngle = lowerAngle;
    jointDef.upperAngle = upperAngle;

    return (RevoluteJoint)world.createJoint(jointDef);
}

private Body createRectangleBodyPart(
    float x, float y, float width, float height) {

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(width, height);

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DynamicBody;
    bodyDef.position.y = y;
    bodyDef.position.x = x;

    Body body = world.createBody(bodyDef);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 10;

    fixtureDef.filter.groupIndex = -1;
    fixtureDef.filter.categoryBits = FILTER_BOY;
    fixtureDef.filter.maskBits = FILTER_STUFF | FILTER_WALL;

    body.createFixture(fixtureDef);
    shape.dispose();

    return body;
}

```

I've skipped the method for creating the head, as it's pretty much the same as the rectangle method (just using a cricle shape).

Those methods are used like so:

```
    torso = createRectangleBodyPart(x, y + 5, 0.25f, 1.5f);
    Body head = createRoundBodyPart(x, y + 7.4f, 1);

    Body leftLegTop = createRectangleBodyPart(x, y + 2.7f, 0.25f, 1);
    Body rightLegTop = createRectangleBodyPart(x, y + 2.7f, 0.25f, 1);
    Body leftLegBottom = createRectangleBodyPart(x, y + 1, 0.25f, 1);
    Body rightLegBottom = createRectangleBodyPart(x, y + 1, 0.25f, 1);

    Body leftArm = createRectangleBodyPart(x, y + 5, 0.25f, 1.2f);
    Body rightArm = createRectangleBodyPart(x, y + 5, 0.25f, 1.2f);

    joinBodyParts(torso, head, new Vector2(0, 1.6f), headAngle);

    leftLegTopJoint = joinBodyParts(torso, leftLegTop, new Vector2(0, -1.2f), 0.1f, legAngle);
    rightLegTopJoint = joinBodyParts(torso, rightLegTop, new Vector2(0, -1.2f), 0.1f, legAngle);
    leftLegBottomJoint = joinBodyParts(leftLegTop, leftLegBottom, new Vector2(0, -1), -legAngle * 1.5f, 0);
    rightLegBottomJoint = joinBodyParts(rightLegTop, rightLegBottom, new Vector2(0, -1), -legAngle * 1.5f, 0);

    leftArmJoint = joinBodyParts(torso, leftArm, new Vector2(0, 1), -armAngle * 0.7f, armAngle);
    rightArmJoint = joinBodyParts(torso, rightArm, new Vector2(0, 1), -armAngle * 0.7f, armAngle);

```

# Answer
> 6 votes
Box2D uses an iterative, rather than closed form solver. This means *all* constraints are somewhat soft. Box2D will try very hard to do what you say, but inaccuracies do occur.

To minimize this, there are several things you can do, in order of importance:

* Use fixed-size timesteps (the first argument to `Step`). This makes the solver more stable - your inaccuracies are more likely to cancel each other out, or at least behave the same each time.
* Use a smaller timestep (1/60 or 1/120 instead of 1/30). Smaller timesteps mean smaller inaccuracies.
* Use more solver iterations (the 2nd/3rd argument to `Step`). You should try to get at least 10 of each. More solver iterations means more chances each timestep to find stability and correctly satisfy constraints - roughly, less chance of inaccuracy. However, a smaller, stabler timestep is better than more iterations. Given sufficiently complicated constraints, you might never solve them 100% correctly, so try reducing the timestep before increasing the iterations.
* Use less dense shapes. Density 10 is pretty heavy. Try standardizing on something smaller - like 1 - as your default density.

# Answer
> 0 votes
I ran into this issue and it was pretty annoying. My workaround was to check to see if the joint got disconnected by comparing the positions of the two bodies, then if they got separated, destroy the body, recreate it, and create the joint again.

---
Tags: physics, box2d
---


# Question
Title: What is the best way to make firetruck outriggers push firetruck up on specific corner
Unity3d

Hello, I'm trying to recreate functionality of outriggers stabilizing a firetruck before the ladder is raised up. How would I go about making the downward force of the outriggers lift the firetruck on that corner of the truck? Most 109ft firetrucks have 4 outriggers that extend out the sides of the truck. Basically Front-Left/Right and Rear-Left/Right.

I'm using wheel colliders and a rigidbody on the main firetruck object which works fine. I then have a child object called Outriggers which holds all 4 outrigger arms and the legs of each. The legs have their own rigidbody and collider. I have the outrigger leg movement working to hit the ground, But not really sure where to go from here.

I was thinking of somehow calculated the amount of leg force hitting the ground then just apply Vector3.up force to the truck, but then my question would be; How would I make sure it lifts only that corner.

Second thought would be changing in realtime the Rigidbody Center Mass to shift to the opposite sides or something. I don't know. Any help would be appreciated.

# Answer
I would model the leg of each outrigger as a separate rigidbody connected to the main rigidbody with a Configurable Joint component. The configurable joint is a very complex component, so I recommend reading the documentation to really understand it.

But in order to get you going, you can configure it like this:

1. Set "Connected Body" to the rigidbody of the main truck
2. Set "X Motion", "Z Motion" and all "Angular * Motion" to "Locked"
3. Set "Y Motion" to "Limited"
4. Set "Linear Limit" -\> "Limit" to the maximum distance you want the leg to be able to extend (note that this limit applies in *both* directions around the initial position of the object).
5. Under "Y Drive", set "Position Spring" and "Maximum Force" high enough to lift the truck (at least 10 times its mass assuming normal gravity).
6. You can now control the extension of the leg with "Target Position" -\> "Y" (Script API: `ConfigurableJoint.targetPosition`). Don't change it too fast, or you make the truck jump :)
> 1 votes

# Answer
Real physics is seldom how to do this sort of thing; it's notoriously flaky. I recommend playing the animation of the supports coming out, and once it's done, disable movement physics on the truck.
> 0 votes

---
Tags: unity
---


# Question
Title: Why I'm getting message in the editor console window , Look rotation viewing vector is zero?
Look rotation viewing vector is zero UnityEngine.Quaternion:LookRotation (UnityEngine.Vector3) Waypoints:Update ()

Why I'm getting this message and what should I do with it ? It's not a warning and not some error.

On the Line :

```
var rotation = Quaternion.LookRotation(nextWayPoint.position - npcs[i].position);

```

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

public class Waypoints : MonoBehaviour
{
    public List<Transform> waypoints = new List<Transform>();
    public List<Transform> npcs = new List<Transform>();
    public float movementSpeed;
    public float rotationSpeed;
    public bool reverse = false;
    public bool go = false;
    public int numberOfWaypoints;
    public int nextWaypointNumber;

    private int waypointIndex = 0;
    private Transform nextWayPoint;

    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < 100; i++)
        {
            GameObject go = new GameObject();
            go.transform.position = new Vector3(Random.Range(0, 10), Random.Range(0, 10), Random.Range(0, 10));
            waypoints.Add(go.transform);
        }

        numberOfWaypoints = waypoints.Count;

        if (reverse)
        {
            waypointIndex = waypoints.Count - 1;
        }
        else
        {
            waypointIndex = 0;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (go)
        {
            if (reverse && waypointIndex == 0)
            {
                waypointIndex = waypoints.Count - 1;
            }

            if (reverse == false && waypointIndex == waypoints.Count)
            {
                waypointIndex = 0;
            }

            nextWayPoint = waypoints[waypointIndex];

            nextWaypointNumber = waypointIndex;

            for (int i = 0; i < npcs.Count; i++)
            {
                npcs[i].position = Vector3.MoveTowards(npcs[i].position,
                    waypoints[waypointIndex].position, Time.deltaTime * movementSpeed);

                var rotation = Quaternion.LookRotation(nextWayPoint.position - npcs[i].position);
                transform.rotation = Quaternion.Slerp(npcs[i].rotation, rotation, Time.deltaTime * rotationSpeed);

                float distance = Vector3.Distance(npcs[i].position, waypoints[waypointIndex].position);
                if (distance <= 0f)
                {
                    numberOfWaypoints--;

                    if (reverse)
                    {
                        waypointIndex--;
                    }
                    else
                    {
                        waypointIndex++;
                    }
                }
            }
        }
    }

    private void OnDrawGizmos()
    {
        for (int i = 0; i < waypoints.Count; i++)
        {
            Gizmos.color = Color.green;

            Gizmos.DrawSphere(waypoints[i].position, 0.1f);
        }

        if (nextWayPoint != null && npcs != null)
        {
            Gizmos.color = Color.red;

            for (int i = 0; i < npcs.Count; i++)
            {
                Gizmos.DrawLine(npcs[i].position, nextWayPoint.position);
            }
        }
    }
}

```

# Answer
The error message is telling you exactly what's wrong: "Look rotation viewing vector is zero".

When your NPC has exactly reached the next waypoint, then `nextWayPoint.position - npcs[i].position` is a zero vector (0, 0, 0).

When you pass a vector to `Quaternion.LookRotation`, you're asking it to "turn to look in this direction".

When you pass a zero vector, the "direction" you're telling it to look in is "nowhere".

How do you rotate so that you're facing nowhere? You can't. The LookRotation method cannot do anything reasonable in response to this input. So it logs an error, to let you know that you asked it to do something impossible.

You can avoid this error by doing something like this:

```
for (int i = 0; i < npcs.Count; i++)
{
    npcs[i].position = Vector3.MoveTowards(npcs[i].position,
                waypoints[waypointIndex].position, Time.deltaTime * movementSpeed);

    float distance = Vector3.Distance(npcs[i].position, waypoints[waypointIndex].position);
    if (distance > 0f) {
         // Try to rotate to face the waypoint only if we're not on top of it.
         var rotation = Quaternion.LookRotation(nextWayPoint.position - npcs[i].position);
         transform.rotation = Quaternion.Slerp(npcs[i].rotation, rotation, Time.deltaTime * rotationSpeed);
    } else {
         numberOfWaypoints--;

         if (reverse)
         {
             waypointIndex--;
         }
         else
         {
             waypointIndex++;
         }
     }
 }

```
> 0 votes

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


# Question
Title: How To Avoid GetComponent on raycasts and collisions
`GetComponent()` is suggested to not be used so frequently because it can cause a performance impact.

I'm working on a game that needs to check the components of objects that bullets hit. I was looking to get the name of the GameObject and store the component reference in a dictionary but it's very error-prone and also needs dictionary searching.

what is the best approach to achieve this?

# Answer
> 1 votes
It's very unlikely that the performance hit of using `GetComponent()` is going to matter. As they say, "premature optimization is the root of all evil," so unless you are noticing a performance problem in testing or profiling, I would go for the simplest solution: using `GetComponent()` every impact.

However, if there *is* a bottleneck here, a dictionary seems like the only other option. In theory, there is no way to do less work than `GetComponent()` (You have to fetch the references somehow either way). the only way you can optimize is by breaking up the work and doing as much of it ahead of time as possible (caching).

In some cases, you could cut down on the work by only caching the last ~10ish objects that have been hit into a dictionary. By doing this, you could search the smaller dictionary and in an average case only have to load the references once.

In general, when you cache, use an object reference as the key in the dictionary, not the GameObject's name because it uses less memory, and object references are guaranteed to be unique.

You probably would be good not caching and just using `GetComponent()` every time, though.

---
Tags: unity
---


# Question
Title: How to have unity inspector variables modify each other bidirectionally and update in real time
Trying to make some inspector controls that both modify the same thing but in different ways, and I want them to both update when the other is edited. Won't bore with the details but there's a reason. Boils down to:

float\_1 with range 0-1 float\_2 with user defined min / max

a mapping function that translates between the two, so `float_1=0` will become `float_2 min`, and 'float\_1=1' will become `float_2 max`, and the reverse will happen if float 2 is modified.

I can do it in the Unity UI using getter / setters in properties, since I can know which setter is being called and can have it modify the other variable, ie:

```
    public float min;
    public float max;

    private float float_1;
    private float float_2;

    public float Float_1
    {
        get => float_1;

        set
        {
            float_1 = value;
            float_2 = Utl.Map(value, 0f, 1f, min, max);
        }
    }

    public float Float_2
    {
        get => float_2;

        set
        {
            float_2 = value;
            float_1 = Utl.Map(value, min, max, 0f, 1f);
        }
    }

```

However in the inspector I don't know which variable is being modified so I can't separate it out, and so I can only have a one-directional relationship.

If relevant, I also want this to work in the game isn't running, using OnValidate()

# Answer
Unity has a message called `OnValidate`: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnValidate.html

It checks to see if anything in the inspector has been edited. So your new code would look something like this:

```
public float min;
public float max;

private float float_1;
private float float_2;

public float Float_1
{
    get => float_1;

    set
    {
        float_1 = value;
        float_2 = Utl.Map(value, 0f, 1f, min, max);
    }
}

public float Float_2
{
    get => float_2;

    set
    {
        float_2 = value;
        float_1 = Utl.Map(value, min, max, 0f, 1f);
    }
}

private void OnValidate()
{
    float_1 = Utl.Map(float_2, min, max, 0f, 1f);
    float_2 = Utl.Map(float_1, 0f, 1f, min, max);
}

```

(I didn't check to make sure the logic here works - just showing you `OnValidate`. So make sure this doesn't break anything.)

---

But since you only want to run code on the changed value, you can check to see if it has been changed. This feels rather dirty, but should work. It is probably worth taking a step back and seeing if your architecture has some potential improvements though.

```
public float min;
public float max;

private float float_1;
private float float_2;
private float previous_float_1;
private float previous_float_2;

private void Awake()
{
    previous_float_1 = float_1;
    previous_float_2 = float_2;
}

public float Float_1
{
    get => float_1;

    set
    {
        float_1 = value;
        float_2 = Utl.Map(value, 0f, 1f, min, max);
    }
}

public float Float_2
{
    get => float_2;

    set
    {
        float_2 = value;
        float_1 = Utl.Map(value, min, max, 0f, 1f);
    }
}

private void OnValidate()
{
    if(float_1 != previous_float_1)
    {
        float_1 = Utl.Map(float_2, min, max, 0f, 1f);
        previous_float_1 = float_1;
    }
    if(float_2 != previous_float_2)
    {
        float_2 = Utl.Map(float_1, min, max, 0f, 1f);
        previous_float_2 = float_2;
    }
}

```
> 0 votes

# Answer
Just as you hinted, OnValidate() is where you need to do some variable checking.

If you want to update `float_1` and `float_2` mutually when the user changes one's value, you can check it in this editor-only function:

```
public class Demo : MonoBehaviour
{
    public float min;
    public float max;

    public float Float_1;
    public float Float_2;

    float float_1;
    float float_2;

    void OnValidate()
    {
        Float_1 = Mathf.Clamp(Float_1, 0, 1);
        Float_2 = Mathf.Clamp(Float_2, min, max);

        if (float_1 != Float_1)
        {
            float_1 = Float_1;
            float_2 = Mathf.Lerp(min, max, float_1);
            Float_2 = float_2;
        }
        else
        {
            float_2 = Float_2;
            float_1 = Mathf.InverseLerp(min, max, float_2);
            Float_1 = float_1;
        }
    }
}

```
> 0 votes

---
Tags: unity, unity-ui
---


# Question
Title: How to not cover up the Android/iOS top status bar (eg. with time, network/wifi icons) in mobile Unity app?
I am making an Android/iOS mobile app in Unity. Currently, when I build it and install it (for example from APK to Android) it loads completely full screen covering up the top phone status bar which usually shows the time, network signal, wifi icons, etc.

For Android, I see an option in Project Settings \> Player for "Hide Navigation Bar" - unchecking this I believe lets you see the bottom on-screen navigation buttons like home, back, etc. However, I see no option to show/hide the top status bar.

In iOS, I am told there is an option for "Status Bar Hidden" which I haven't tested yet but should hopefully do in iOS.

Is there some way to do this in Android?

For example, is there some way to "sense" from inside Unity how many pixels the height of the Android status bar is and then restrict the window to not cover it?

I see it possible to get the height of the status bar here but this is not Unity specific code and I'm not sure how to use it or limit the Unity window size according to this StackOverflow question.

I also just found this sample GitHub repo which looks like it was designed for this, but I don't understand what they mean about how to build it. I usually just build with the "Build" button from the Unity editor.

Thanks.

# Answer
> 3 votes
I wrote this for a project a few years ago. It should work fine, but I no longer maintain it. It shows the status bar in the color of your choice.

Usage:

```
#if UNITY_ANDROID && !UNITY_EDITOR
    Screen.fullScreen = false; //Should be unnecessary unless you changed it
    AndroidUtility.ShowStatusBar(Color.black);
#endif

```

Code:

```
#if UNITY_ANDROID && !UNITY_EDITOR
using System;
using UnityEngine;

namespace Evorlor.Common
{
    public static class AndroidUtility
    {
        private const int MinStatusBarColorApi = 21;
        private const int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;

        private static AndroidJavaObject activity;

        /// <summary>
        /// Shows the Android Status bar
        /// </summary>
        /// <param name="color">Color of status bar to be used</param>
        public static void ShowStatusBar(Color color)
        {
            int androidColor = ConvertColorToAndroidColor(color);
            RunOnUiThread(() =>
                {
                    using (var window = Window)
                    {
                        window.Call("clearFlags", SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
                        if (GetApi() >= MinStatusBarColorApi)
                        {
                            window.Call("setStatusBarColor", androidColor);
                        }
                        else
                        {
                            Debug.LogWarning("Changing the status bar color is not supported on Android API lower than Lollipop.");
                        }
                    }
                });
        }

        private static void RunOnUiThread(Action action)
        {
            Activity.Call("runOnUiThread", new AndroidJavaRunnable(action));
        }

        private static AndroidJavaObject Activity
        {
            get
            {
                if (activity == null)
                {
                    var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
                    activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
                }
                return activity;
            }
        }

        private static AndroidJavaObject Window
        {
            get
            {
                return Activity.Call<AndroidJavaObject>("getWindow");
            }
        }

        private static int GetApi()
        {
            using (var version = new AndroidJavaClass("android.os.Build$VERSION"))
            {
                return version.GetStatic<int>("SDK_INT");
            }
        }

        private static int ConvertColorToAndroidColor(Color color)
        {
            Color32 color32 = color;
            int alpha = color32.a;
            int red = color32.r;
            int green = color32.g;
            int blue = color32.b;
            using (var colorClass = new AndroidJavaClass("android.graphics.Color"))
            {
                int androidColor = colorClass.CallStatic<int>("argb", alpha, red, green, blue);
                return androidColor;
            }
        }
    }
}
#endif

```

# Answer
> 2 votes
You are supposed to integrate Over17's UnityShowAndroidStatusBar code after exporting a Unity game project to Android Studio rather than just building it. This way, you can add new features Unity doesn't provide out of the box. The Android export process is straightforward. You select Gradle as Build System, enable the Export Project checkbox, and click the Export button.

In this forum thread, Unity Technologies' user **Yury-Habets** mentions the same Over17's Java class to toggle status bar visibility, but the related repo hasn't been updated since 2018 and may be out of date as of today.

#### No need to export the project at all

On the other hand, user **OJ3D** refers to a script that runs right inside Unity without any additional effort. It is Zeh Fernando's `ApplicationChrome.cs` from the Unity Tidbits repository, whose author also describes in their blog.

The `ApplicationChrome.cs` script contains some Java code that Unity uses to talk to the low-level Android system APIs. It includes Android-only functions you can call from other scripts in your game to configure the appearance of your application.

Although the forum message dates back to 2016 (when Unity 5.2.3 was around) and the blog post dates back to 2015, the latest repo commit occurred in November 2019. This means the source is still being maintained. I tested the `.apk` demo from the blog post on an Android 9 (Pie) mobile device, and it still works.

Since Unity doesn't provide the status bar hide feature anymore, this seems a nice, working solution that requires neither writing additional code nor using external building tools.

#### Display the Status Bar only

Include the `ApplicationChrome.cs` script in your project. Its methods will be called once by a GameObject in your scene to set up the display mode:

```
void Start()
{
    ApplicationChrome.statusBarState = ApplicationChrome.States.Visible;
    ApplicationChrome.navigationBarState = ApplicationChrome.States.Hidden;
}

```

If you can still view the navigation bar, this is due to the script forcing non-fullscreen mode (at line `149`). You can simply get away with it by adding a new line:

```
void Start()
{
    ApplicationChrome.statusBarState = ApplicationChrome.States.Visible;
    ApplicationChrome.navigationBarState = ApplicationChrome.States.Hidden;
    Screen.fullScreen = true;
}

```

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


# Question
Title: Creating custom editor fields based on presence of custom attribute
I'm creating a manager object that controls a bunch of other objects at once.

I want to be able to restrict / expose parameters in the target object to the manager via a custom attribute. I have the following working:

```
[AttributeUsage(AttributeTargets.Field)]
public class ManagableAttribute : Attribute {}

public class TargetObject : MonoBehaviour
{
    // public ObjectScript obj;

    [Managable]public float var1;
    public float var2;
}

```

Two variables in the target object, only one of which has the `[Managable]` attribute.

Based on some other posts I found, in the editor script I have it searching the fields in the target script and identifying the ones with the `[Managable]` attribute and printing them to the terminal:

```
[CustomEditor(typeof(TargetObject))]
[CanEditMultipleObjects]
public class ObjectManagerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        TargetObject targetObject =  (TargetObject)target;

        //// Manually creating the variable floatfield i need
        //o.var1 = EditorGUILayout.FloatField("var1", o.var1);

        Type targetType = targetObject.GetType();
        FieldInfo[] objectFields = targetType.GetFields(BindingFlags.Instance | BindingFlags.Public);

        foreach (var field in objectFields)
        {
            ManagableAttribute thisAttribute = (ManagableAttribute)Attribute.GetCustomAttribute(field, typeof(ManagableAttribute));
            if (thisAttribute != null)
            {
                // Debug.Log(thisAttribute);
                var f = field;
                Debug.Log(field.Name);
            }
        }
    }
}

```

Can I have it create an `EditorGUILayout.FloatField` (or whatever type) in the loop for each variable it finds with the `[Managable]` attribute?

# Answer
I have a feeling there's a better way but this seems to work

```
    public override void OnInspectorGUI()
    {
        FieldInfo[] objectFields = targetType.GetFields(BindingFlags.Instance | BindingFlags.Public);

        foreach (var field in objectFields)
        {
            ManagableAttribute thisAttribute = (ManagableAttribute)Attribute.GetCustomAttribute(field, typeof(ManagableAttribute));
            if (thisAttribute != null)
            {
                float tempValue = EditorGUILayout.FloatField(field.Name, (float) field.GetValue(targetObject));
                field.SetValue(targetObject, tempValue);
            }
        }
    }

```
> 1 votes

---
Tags: unity, code-reflection
---


# Question
Title: How to make TEXT RENDER stand facing the camera of my character and also for the camera of simulation?
**I have an actor (Minion) with a Text Render just above it mesh:**

As you have seen, I defined your rotation as absolute, so the text does not rotate along with the actor.

**In the game the rotation setting is good and acceptable at various times:**

**At other times it is very bad:**

**An example of what I want is something like the life of the champions in the League of Legends:**

**I would also like to know how to do this when I am simulating:**

I've made some attempts at the camera of my main character. And I got some of what I tried.

**Character Blueprint:**

I know I could put on the Event Begin Play because the camera does not rotate.

**Minion Blueprint:**

**I did (partially):**

Ignoring the fact that the text is inverted. I tried **Split Struct** and added 180 to each of the 3 axes (ROLL, PITCH, YAW) and I could not solve it anyway.

**Simulating nothing works:**

---

**EDIT 1 (Attempt made based on a\_rrat's answer)**

**Blueprint:**

I think I tried all the combinations and none worked the way I would. The combination defined in the image made the Text Render spin.

---

**EDIT 2 (Correction of the attempt I made wrongly)**

**Correction that I did:**

With the answer I was given I noticed a marked improvement.

**Result 1:**

Besides the value is no longer inverted.

**Result 2:**

But I still have not got what I like.

**Result I am looking for:**

I wish life would be displayed the same way anywhere on the map the character is on.

---

**EDIT 3 (Removing roll)**

**Blueprint:**

In game there was no difference.

---

**EDIT 4 (Trying to explain what I want to happen)**

I think that because I can not speak English and have to use programs to translate things for myself, I do not know the best way to explain my doubts, the best words, among other things.

I think the best way then to try to explain what I want is with images.

I want regardless of the location or angle life is seen in the same way.

**Image:**

**Image:**

**Image:**

In the LEAGUE OF LEGENDS anywhere on the screen that the champion is, the life bar appears the same way. I would like to achieve this result.

# Answer
> 1 votes
* Firstly create a Widget Blueprint with custom size.

* Remember the size you set.
* Preferably place the text size equal to that of the widget.
* Add the widget component to your actor.
* In the Space option, select screen.
* In the Widget Class option, select the widget that you created
* In the Size option, place the same one you placed in the widget.

**Results:**

# Answer
> 2 votes
What's happening here is two things :

1. You are just applying the camera rotation to the text instead of billboarding the text
2. You are rotating all the axes of your text, when you need to rotate it on one axis only

What you can do instead :

# Answer
> 2 votes
To make this work in the same way as your League of Legends example, you need to put a Text inside a Widget component which is attached to your character, not TextRender.

The reason for this is that you can set the Widget to display at the same location in world or screen space so it moves with the character and does so automatically with rotation.

Create a Widget as you normally would by going to Add New -\> User Interface -\> Widget Blueprint

Drag a Text component onto the canvas, use the font options on the right hand side to get it the size you want, set the Anchor in the middle then shrink the canvas size to match the text.

IMPORTANT! Make a note of the size X and size Y of your Text component.

Now go into your character and add a Widget component to it.

In the details tab, under User Interface, change the Draw Size to that of your text component and make the WidgetClass the name of your created Widget.

Move the widget around as necessary to get it above the character as you wish. If it's a third person character, you may also need to set the rotation to 180°.

Finally, under User Interface, change the Space setting from World to Screen. This will make the widget disappear from the blueprint (though you can always change it back if you need to make adjustments) but when you play, it will be with the character in the same location at all times.

Using this method will make the widget appear exactly behind the character. If you want to have it rotate with the character, you need to get the default Z rotation of the character (270° in the Third Person character) and the default of your widget (180° in my example) and calculate the difference per tick.

This will now always display with the front of the text, no matter the rotation of the character on screen.

# Answer
> 2 votes
This was years ago but I wanted to add in, for anyone curious and struggling like me, how I did this.

You set the world rotation of the component in question to the value of your camera's rotations as follows. Get the PlayerCameraManager, get Camera Rotation, and break out the rotator. You're going to make a rotator for your SetWorldRotation pin and input

X, Y * -1.0, Z + 180

From camera rotation.

This image shows what I mean. The blue line is mean turning this into a Quat and back to a rotator, just incase gimbal lock messes with this at all.

# Answer
> 0 votes
Most simple algorithm for understanding is just get ForwardVector, then multiply it my -1.0f and convert to Rotator. In C++ it's like `FRotator NeedRotator = (Camera->GetActorForwardVector() * -1.0f).Rotation();`

---
Tags: camera, rotation, unreal-4, text, blueprints
---


# Question
Title: Getting XR Grabbable items networked with Unity
I'm trying to get XR Grabbable objects networked in Unity, with the networking framework Mirror.

This should be a simple task as Mirror has a component called "NetworkTransform" that simply helps sync the position of an object on both the server and the client.

The issue is that the XR Interaction Manager that Unity uses switches the parent of the held object, and moves it back again. Mirror uses local positions so the server and other clients see a massive and unpredictible offset on the object. You also can't use the same parent as the XR rig is a local object and changing parent would just move the object to the other clients hand.

Has anyone managed to create a simple networked object with Mirror and Unity's XR system?

# Answer
I have currently created a workaround but to be honest I'm not sure if this will break other aspects of the grab system. I got this working by disabling the reparenting of the object (with a bool) in the `Grab()` and `Drop()` methods in the XR Grab Interactable script.

I copied the file `XRGrabInteractable.cs` from the XR Interaction Toolkit and added a new boolean called `changeTransformParent`

```
[SerializeField]
bool m_ChangeTransformParent = true;

/// <summary>
/// Whether to set the parent of this object when this object is grabbed
/// </summary>
public bool changeTransformParent
{
    get => m_ChangeTransformParent;
    set => m_ChangeTransformParent = value;
}

```

And here are the `Grab()` and `Drop()` methods after adding the bool

```
/// <summary>
/// Updates the state of the object due to being grabbed.
/// Automatically called when entering the Select state.
/// </summary>
/// <seealso cref="Drop"/>
protected void Grab()
{
    m_OriginalSceneParent = transform.parent;

    if (m_ChangeTransformParent)
        transform.SetParent(null);

    // Special case where the interactor will override this objects movement type (used for Sockets and other absolute interactors)
    m_CurrentMovementType = selectingInteractor.selectedInteractableMovementTypeOverride ?? m_MovementType;

    SetupRigidbodyGrab(m_Rigidbody);

    // Reset detach velocities
    m_DetachVelocity = Vector3.zero;
    m_DetachAngularVelocity = Vector3.zero;

    // Initialize target pose for easing and smoothing
    m_TargetWorldPosition = m_AttachPointCompatibilityMode == AttachPointCompatibilityMode.Default ? transform.position : m_Rigidbody.worldCenterOfMass;
    m_TargetWorldRotation = transform.rotation;
    m_CurrentAttachEaseTime = 0f;

    UpdateInteractorLocalPose(selectingInteractor);

    SmoothVelocityStart();
}

/// <summary>
/// Updates the state of the object due to being dropped and schedule to finish the detach during the end of the frame.
/// Automatically called when exiting the Select state.
/// </summary>
/// <seealso cref="Detach"/>
/// <seealso cref="Grab"/>
protected void Drop()
{
    if (m_RetainTransformParent && m_OriginalSceneParent != null && !m_OriginalSceneParent.gameObject.activeInHierarchy && m_ChangeTransformParent)
    {
        bool exitingPlayMode;
#if UNITY_EDITOR
            // Suppress the warning when exiting Play mode to avoid confusing the user
            exitingPlayMode = UnityEditor.EditorApplication.isPlaying && !UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode;
#else
        exitingPlayMode = false;
#endif
        if (!exitingPlayMode)
            Debug.LogWarning("Retain Transform Parent is set to true, and has a non-null Original Scene Parent. " +
                "However, the old parent is deactivated so we are choosing not to re-parent upon dropping.", this);
    }
    else if (m_RetainTransformParent && gameObject.activeInHierarchy && m_ChangeTransformParent)
        transform.SetParent(m_OriginalSceneParent);

    SetupRigidbodyDrop(m_Rigidbody);

    m_CurrentMovementType = m_MovementType;
    m_DetachInLateUpdate = true;
    SmoothVelocityEnd();
}

```

Here is the full script - please note this for the specific version: 1.0.0-pre.5

https://pastie.io/rlsfnj.cs link no longer working

Edit:

Here's a Github repository I'm making with the same scripts https://github.com/richardmuthwill/UnityMirrorXR

> **TLDR;** This is a hack of the original file `XRGrabInteractable.cs` and might break other things
> 1 votes

---
Tags: unity, virtual-reality, mirror-networking
---


# Question
Title: Snap joystick value to minimum magnitude when it falls below
I got a joystick displayed in the image below with range -1 to 1. Green area is 80% of the total circle and yellow area is 20%.

I want to get corrected values for both areas. For example:

1. If given point falls under yellow range I want to get actual input value.
2. if given point is within green area how can I get maximum value in green area ie. 80% at same direction.

# Answer
This is some pretty trivial linear algebra.

```
Vector2 SnapToMinimumLength(Vector2 input, float minimum) {
    // Most vector libraries will give you a method to do this,
    // but in case you're not using one and aren't familiar with
    // vector magnitude/normalization, I'll show all the steps.
    float squaredLength = input.x*input.x + input.y*input.y;

    if (squaredLength > 0 && squaredLength < minimum * minimum) {
        float scale = minimum / Mathf.Sqrt(squaredLength);
        input.x *= scale;
        input.y *= scale;
    }
    return input;
}

```

To snap to the outer edge of the green area at 80% of the circle radius, you'd use:

```
Vector2 snappedInput = SnapToMinimumLength(rawInput, 0.8);

```

The one exception here is when the input is (0, 0). Then it *has* no direction, so this code skips trying to snap it anywhere and returns the input unchanged. You could decide to force a direction arbitrarily (like saying `(0, 0)->(0, 0.8)`) or cache the last non-zero direction and keep using that, or fall back on some different behaviour appropriate to your application.
> 2 votes

---
Tags: mathematics, joystick
---


# Question
Title: How do I create a HeightField in pybullet?
I've been looking for documentation on PyBullet, the python implementation of Bullet, but I haven't yet found a way to implement the btHeightfieldTerrainShape collision object, which I need to make, well, terrain.

If this isn't possible, is there another way within PyBullet to turn a set of points into a collide-able object?

# Answer
> 1 votes
There are a few ways to load a heightfield based collision shape in PyBullet:

1. manually: by mathematically creating the height field array
2. from CSV: loading a csv with the height field information
3. from PNG: loading a height field from a PNG image

Excerpts from heightfield.py from the official PyBullet GitHub examples:

**Manually construction the height field array**

```
  numHeightfieldRows = 256
  numHeightfieldColumns = 256
  heightfieldData = [0]*numHeightfieldRows*numHeightfieldColumns
  for j in range (int(numHeightfieldColumns/2)):
    for i in range (int(numHeightfieldRows/2) ):
      height = random.uniform(0,heightPerturbationRange)
      heightfieldData[2*i+2*j*numHeightfieldRows]=height
      heightfieldData[2*i+1+2*j*numHeightfieldRows]=height
      heightfieldData[2*i+(2*j+1)*numHeightfieldRows]=height
      heightfieldData[2*i+1+(2*j+1)*numHeightfieldRows]=height

  terrainShape = p.createCollisionShape(shapeType = p.GEOM_HEIGHTFIELD, meshScale=[.05,.05,1], heightfieldTextureScaling=(numHeightfieldRows-1)/2, heightfieldData=heightfieldData, numHeightfieldRows=numHeightfieldRows, numHeightfieldColumns=numHeightfieldColumns)
  terrain  = p.createMultiBody(0, terrainShape)
  p.resetBasePositionAndOrientation(terrain,[0,0,0], [0,0,0,1])

```

**Loading a CSV heightfield**

```
  terrainShape = p.createCollisionShape(shapeType = p.GEOM_HEIGHTFIELD, meshScale=[.5,.5,2.5],fileName = "heightmaps/ground0.txt", heightfieldTextureScaling=128)
  terrain  = p.createMultiBody(0, terrainShape)
  p.resetBasePositionAndOrientation(terrain,[0,0,0], [0,0,0,1])

```

**Loading a PNG heightfield and applying a PNG texture**

```
  terrainShape = p.createCollisionShape(shapeType = p.GEOM_HEIGHTFIELD, meshScale=[.1,.1,24],fileName = "heightmaps/wm_height_out.png")
  textureId = p.loadTexture("heightmaps/gimp_overlay_out.png")
  terrain  = p.createMultiBody(0, terrainShape)
  p.changeVisualShape(terrain, -1, textureUniqueId = textureId)

```

Side note: If you are interested in game development, Panda3D might facilitate the process for you: it's a 3D engine that can build upon PyBullet.

---
Tags: collision-detection, python, terrain, bullet-physics
---


# Question
Title: I'm still not sure why the reverse state is not working?
The goal is to be able to change direction(reverse or forward) at runtime in real time without waiting the transform to reach the next waypoint first but at real time to change the direction/s.

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

public class Waypoints : MonoBehaviour
{
    public List<GameObject> waypoints = new List<GameObject>();
    public float movementSpeed;
    public float rotationSpeed;
    public bool reverse = false;
    public bool go = false;
    public int nextWaypointNumber;
    public int lastWaypointNumber;
    public bool stopState = false;
    public bool stopAtFirstWP = false;
    public bool loop = false;

    private int waypointIndex = 0;
    private GameObject nextWayPoint;
    private GameObject lastWayPoint;

    // Start is called before the first frame update
    void Start()
    {
        //waypoints = GameObject.FindGameObjectsWithTag("Waypoint").ToList();

        if (reverse)
        {
            waypointIndex = waypoints.Count - 1;
        }
        else
        {
            waypointIndex = 0;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (go)
        {
            ReverseState();

            if (stopState)
            {
                StopState(stopAtFirstWP);
            }

            nextWayPoint = waypoints[waypointIndex];
            nextWaypointNumber = waypointIndex;

            transform.position = Vector3.MoveTowards(transform.position,
            waypoints[waypointIndex].transform.position, Time.deltaTime * movementSpeed);

            float distance = Vector3.Distance(transform.position, waypoints[waypointIndex].transform.position);
            if (distance > 1f)
            {
                var rotation = Quaternion.LookRotation(nextWayPoint.transform.position - transform.position);
                transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationSpeed);
            }
            else
            {
                if (reverse)
                {
                    waypointIndex--;
                }
                else
                {
                    waypointIndex++;
                }
            }
        }
    }

    public void StartMovingAfterSeconds(float seconds)
    {
        StartCoroutine(MoveNpc(seconds));
    }

    private IEnumerator MoveNpc(float seconds)
    {
        yield return new WaitForSeconds(seconds);

        go = true;
    }

    private void StopState(bool stopAtFirstWP)
    {
        if (stopAtFirstWP && waypointIndex == 1)
        {
            go = false;
        }

        if (stopAtFirstWP == false && waypointIndex == waypoints.Count - 1)
        {
            go = false;
        }
    }

    private void ReverseState()
    {
        if (reverse && waypointIndex == 0)
        {
            waypointIndex = waypoints.Count - 1;
        }

        if (reverse == false && waypointIndex == waypoints.Count)
        {
            waypointIndex = 0;
        }
    }

    private void OnDrawGizmos()
    {
        if (waypoints != null)
        {
            for (int i = 0; i < waypoints.Count; i++)
            {
                Gizmos.color = Color.green;
                Gizmos.DrawSphere(waypoints[i].transform.position, 0.1f);
            }
        }

        if (nextWayPoint != null)
        {
            Gizmos.color = Color.red;
            Gizmos.DrawLine(transform.position, nextWayPoint.transform.position);
        }
    }
}

```

I have a reverse flag and this ReverseState method :

```
private void ReverseState()
    {
        if (reverse && waypointIndex == 0)
        {
            waypointIndex = waypoints.Count - 1;
        }

        if (reverse == false && waypointIndex == waypoints.Count)
        {
            waypointIndex = 0;
        }
    }

```

but when running the game and changing the reverse flag true or false many times it's not changing the direction/s and after once or two throw exception out of range at the line :

```
nextWayPoint = waypoints[waypointIndex];

```

# Answer
> 1 votes
I think you may have over-engineered this problem a little, possibly due to not knowing you can simply reverse lists of things.

Here's how I'd do it.

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

public class Patroller : MonoBehaviour
{
    public List<GameObject> WayPoints;

    private int CurrentWayPoint = 0;
    private bool IsPatrolling = false;
    private bool PingPong = false;

    private int CachedPingPongIndex;

    private void Start()
    {
        StartPatrol();
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            ReversePatrolWayPoints();
        }

        ///We need to store the CurrentWayPoint when the ping pong button is pressed (outside of the patrol loop)
        if (Input.GetKeyDown(KeyCode.P))
        {
            PingPong = !PingPong;
            CachedPingPongIndex = CurrentWayPoint;
        }
    }

    //Simple Method so you can start the patrol from anywhere while checking its not already running
    public void StartPatrol()
    {
        if (!IsPatrolling)
        {
            StartCoroutine(Patrol());
        }
    }

    //Reverse the list!
    public void ReversePatrolWayPoints()
    {
        WayPoints.Reverse();
    }

    /// <summary>
    /// Start a Patrol through the way points
    /// </summary>
    /// <returns></returns>
    private IEnumerator Patrol()
    {
        if (WayPoints == null || WayPoints.Count == 0)
        {
            Debug.Log("Waypoints list is null or empty");
            yield break;
        }

        IsPatrolling = true;

        while (CurrentWayPoint < WayPoints.Count)
        {
            int cachedWayPoint = CurrentWayPoint;
            float distanceToWayPoint = Vector3.Distance(transform.position, WayPoints[CurrentWayPoint].transform.position);
            transform.position = Vector3.MoveTowards(transform.position, WayPoints[CurrentWayPoint].transform.position, 0.1f);

            if (distanceToWayPoint <= 1f)
            {
                Debug.LogFormat("Reached Waypoint {0}", CurrentWayPoint);
                CurrentWayPoint++;

                //Check if ping pong is enabled if so, we use the value we cached when the button was pressed + 1
                //so if we press ping pong on Point 8, then we cehck if the current way point we are on is greater than cached value + 1 so 9 in this example, if the currentwaypoint is greater than this number then we reset back to the cached value and loop these two points
                if (PingPong)
                {
                    if (CurrentWayPoint > CachedPingPongIndex + 1)
                    {
                        CurrentWayPoint = CachedPingPongIndex;
                    }
                }
                else
                {
                    if (CurrentWayPoint >= WayPoints.Count)
                    {
                        CurrentWayPoint = 0;
                    }
                }

            }

            yield return null;
        }

        IsPatrolling = false;
        yield break;
    }
}

```

As you may notice, it doesn't matter to the patroller which order the list is in, it simply knows it must move to the position of the GameObject in the WayPoints list at the *current index*, if you reverse the list and therefore which point the index refers to, the patroller will start moving there.

The "Ping Pong" loop is not too different, instead what we are manipulating is *when* we decide to reset the patrol point, the main thing to take away is we needed to store the CurrentWayPoint as a seperate variable when the button is pressed, then if Ping Pong mode is enabled we check what way point we are on against the cached value + 1.

So if the button is pressed on WayPoint 8,

`CachedPingPongIndex = 8`

`CachedPingPongIndex + 1 = 9`

`if(CurrentWayPoint > 9) > Reset To 8`

Given this information we can check while patroling if we try to increase the currentway point index above our cached value + 1 we can reset the CurrentWayPoint index to what we initially cached the value at, letting us loop between these two points.

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


# Question
Title: How to get / set value of a float2 field in a custom editor script?
I wrote this code:

```
var waveOrig = element.FindPropertyRelative("origin");
waveOrig.vector2Value = EditorGUI.Vector2Field(dirRect, "Point of Origin", waveOrig.vector2Value);

```

However, Unity logs errors because of this piece of code:

> Mismatched types in SetValue UnityEditor.SerializedProperty:set\_vector2Value (UnityEngine.Vector2)

> Mismatched types in GetValue - return value is junk UnityEditor.SerializedProperty:get\_vector2Value ()

Not sure how should I fix this, any help?

PS. "origin" element is a `float2` type

# Answer
> 1 votes
If you just want to allow a user to modify the value, you can use the generic `PropertyField()` to automatically use the editor's default representation for whatever field type it happens to be:

```
EditorGUI.PropertyField(dirRect, waveOrigin, new GUIContent("Point of Origin"));

```

But if you want to extract the value they set and read / modify it, then it would be useful to give yourself a couple helper methods:

```
public static class SerializedPropertyExtensions {
    public static Vector2 GetFloat2AsVector(this SerializedProperty property) {
        Vector2 output;
        var p = property.Copy();
        p.Next(true);
        output.x = p.floatValue;
        p.Next(true);
        output.y = p.floatValue;
        return output;
    }

    public static void SetFloat2FromVector(this SerializedProperty property, Vector2 value) {
        var p = property.Copy();
        p.Next(true);
        p.floatValue = value.x;
        p.Next(true);
        p.floatValue = value.y;
    }
}

```

Then you can work with the `Vector2Field` as you were trying to do:

```
var v = waveOrigin.GetFloat2AsVector();
v = EditorGUI.Vector2Field(dirRect, "Point of Origin", v);
waveOrigin.SetFloat2FromVector(v);

```

Don't forget to call `serializedObject.ApplyModifiedProperties()` to commit the changes the user's made to the object's data.

---
Tags: unity, editors
---