# Question
Title: Implementing Linear Diagonal Movement Relative to Camera Rotation
So far I've implemented horizontal (X-axis) and vertical (Z-axis) linear movement for the player in a 3D game. Using the code shown below, the player is able to move relative to the camera's Y-axis rotation.

`rotationOffset` represents the direction:

* 0.f = Forward
* 90.f = Right
* 180.f = Backwards
* -90.f = Left

```
velocity.x = glm::sin(cameraYRotation + rotationOffset) * speed;
velocity.z = glm::cos(cameraYRotation + rotationOffset) * speed;

```

I use key press & release events to set the velocity using the code above.

However, I'm not sure how I can implement diagonal movement, such as when the player is moving Forward + Right.

If the player is initially moving Forward, but then starts moving to the right as well to move diagonally, how would can I apply that change to the velocity?

Should I create more variables to keep track of the keys being pressed?

Furthermore, how do I deal with key releases (e.g. Player initially moves diagonally Forward + Right, but then releases the Right key, thus only moves Forward)?

# Answer
I tend to develop in 2D, but your question seems more functional-based so I might be able to help, hopefully.

Maybe this approach is a little naïve, but perhaps try post-incrementing the movement of your player-character by an incremental amount when you change direction on the Keypress/D-Pad. This will smoothly move your player character in the scene, rather than snap them to one, set direction.

You'll need to make sure that you are applying the incremental change with every Update() as long as the Key-Press is being held. For Key-Releases, simply post-decrement the axis-value with every Update() until it reaches '0'. Blending 'Forward' and 'Right' movement should then result in "diagonal" movement more naturally.

So it might function like this pseudo code:

```
Vector3 movement;
double x;
double y;
double z;

public SomeConstructor()
{
    movement = new Vector3(x, y, z);
}

....

private void On_KeyPressUp()
{
    if (z < 1)
    z += 1;
}

private void On_KeyPressRight()
{
    if (x < 1)
    x += 0.1;
}

private void On_KeyReleaseUp()
{
    if (z > 0)
    z -= 0.1;
}

private void On_KeyReleaseRight()
{
    if (x > 0)
    x -= 0.1;
}

private void Update()
{
    MovePlayer(movement);
}

```

Also maybe look into 'Linear Interpolation'. It may help shed some light on helpful smoothing-techniques. Hope this may have helped.

Helpful Research: Game Engine Architecture By Jason Gregory · 2017 (p.181) https://www.google.co.uk/books/edition/Game\_Engine\_Architecture/LlLSBQAAQBAJ?hl=en&gbpv=0
> 0 votes

---
Tags: physics, movement
---


# Question
Title: How to make a code-generated mesh interact with a rigidbody?
I'm using a sphere and an empty game object that generates a mesh upon playing/starting.

On the mesh, I place a `Mesh Collider` component with `None` for the "Material" and "Mesh" fields and a `RigidBody` with "kinematic" checked. Then when I place a `Rigidbody` on the sphere, it just falls through it.

I'm not sure what I'm missing so that the sphere will fall and land on the mesh and treat it like another object like a plane for example.

# Answer
> 2 votes
To use your code created `Mesh` with the collider you need to assign it to be used by the `MeshCollider` and `MeshFilter` component. Then turn `MeshCollider.convex` to `false` in the `FixedUpdate()` function.

You may have `convex` set to `false` in the `MeshCollider` component but when I tried to collide my mesh with a physics object (Sphere) then it would not work. I'm not sure why but when I flipped `convex` between true and false before the collision occurs it would work. The only way to avoid doing this is to do it as I explain above and show below.

I hope someone who knows Unity better than I can explain what is going on exactly but this is how I made it work.

Example of the assignments in your `Start()` function, in this case I'll call it `mesh` and will have this:

```
MeshCollider collider;
void Start()
{
        mesh = new Mesh();
        // do your mesh setup here or call a method that does it

        GetComponent<MeshFilter>().mesh = mesh;
        collider = GetComponent<MeshCollider>();
        collider.sharedMesh = mesh;
}

void FixedUpdate() {
        collider.convex = false;
}

```

---
Tags: unity, physics, procedural-generation, mesh, rigidbody
---


# Question
Title: Turn based game in HTML/JS/CSS - new joiner messes with state of game while animations are still running for other players
I developed a playing cards web app using HTML/JS/CSS. Communication with the server is performed using WebSocket. The server is developed in Java Spring.

The game proposes to join one of the many available tables where you can immediately perform an action.

The players who are already in the table are perfectly in sync with each other, as when they receive a message from the server, I show a screen overlay preventing them from clicking on any element on the table while an animation is running. After the animation is terminated, the game becomes available and runs normally.

My problem is that if a new player joins the table after a message has been sent by the server, then he can perform an action while the animation is still running for the other players, thus starting a new animation for them at the same time and the game becomes messy.

Is there a way to either prevent the new joiner from performing an action before the animation has ended for the rest of the players ? Do you have any other idea how I can solve this issue ?

Thanks for your help

# Answer
> 1 votes
I would invert the logic from "You are allowed to do anything **unless** the server told you there is an ongoing animation" to "You are **only** allowed to do something when the server tells you that it is your turn".

The result would be that any new player joins in a state where they can't do anything (because they didn't receive the "It's your turn" message yet). Their UI would not become active until the server tells them that it's their turn. Which it would do immediately when there is no ongoing animation, but would delay if there is an ongoing animation.

# Answer
> 0 votes
Thanks to @DMGregory insights, I think the best solution is to put the server in a paused state for a fixed duration allowing the animation to be completed before starting to accept new requests from other players.

The drawback is that there might be an overlap of animations due to the latency between players having slow/fast connection speeds. But this would happen very rarely as the new joiner has to perform an action quicker than the latency of the slower player.

I guess this is the best approach to my problem.

---
Tags: animation, server, turn-based, css, spring
---


# Question
Title: Is there an algorithm for a Joystick class that happens to be engine/framework independent?
I need to be able to get the given input's distance inside the joystick, bounded within -100% and 100% and an unbounded version of it, get the position of where the mouse's position projects to the joystick's ring and get the angle from the joystick to the given input that also wouldn't need unit conversion since all of the inputs would always be in within terms of a given unit.

# Answer
I happen to have written an algorithm that does exactly that!

```
import kotlin.math.*

/**
 * As long as all your input is in X units, you shouldn't need any kind of conversion
 *
 * If you don't want the joystick to gravitate towards its origin position after some time,
 * use the UI viewport's units instead of game viewport's units (as the UI viewport's camera doesnt move/gravitate)
 */
data class Joystick (var initialX: Float, var initialY: Float, var radius: Float = 1f){
    var active = false
    var x = 0f; var y = 0f; var degree = 0f; var stickDistPercentageX = 0f; var stickDistPercentageY = 0f
    var distanceX = 0f; var distanceY = 0f; var realStickDistPercentageX = 0f; var realStickDistPercentageY = 0f
    var cachedValues = Array(9){1f}.apply {
        this[0] = x
        this[1] = y
        this[2] = degree
        this[3] = stickDistPercentageX
        this[4] = stickDistPercentageY
        this[5] = distanceX
        this[6] = distanceY
        this[7] = realStickDistPercentageX
        this[8] = realStickDistPercentageY
    }

    fun updateValues(mouseX: Float, mouseY: Float) : Array<Float>
    {
        var distanceY = mouseY - initialY
        var distanceX = mouseX - initialX
        if(distanceX == 0f || distanceY == 0f) return cachedValues
        // not sure if I should keep this check, the atan2 function seems to function normally despite such inputs anyway.
        var degree = atan2(distanceY,distanceX)

        var outerCircleHalfR = sqrt(distanceX*distanceX+distanceY*distanceY)

        var realStickDistPercentageX = cos(degree) *  abs(outerCircleHalfR/radius)
        var realStickDistPercentageY = sin(degree) *  abs(outerCircleHalfR/radius)
        var stickDistPercentageX = cos(degree) *  abs(outerCircleHalfR/radius).coerceIn(-1f, 1f)
        var stickDistPercentageY = sin(degree) *  abs(outerCircleHalfR/radius).coerceIn(-1f, 1f)

        var x = cos(degree) * radius
        var y = sin(degree) * radius

        this.x = x
        this.y = y
        this.degree = degree
        this.stickDistPercentageX = stickDistPercentageX
        this.stickDistPercentageY = stickDistPercentageY
        this.distanceX = distanceX
        this.distanceY = distanceY
        this.realStickDistPercentageX = realStickDistPercentageX
        this.realStickDistPercentageY = realStickDistPercentageY

        return cachedValues
    }
}

```

and an example usage:

```
if(joystick.active) {
    run joy@
    {
        joystick.updateValues(unProjectMouse.x, unProjectMouse.y)
        viewport.camera.position.add(
            joystick.stickDistPercentageX * delta * IMV * 10,
            joystick.stickDistPercentageY * delta * IMV * 10, 0f)
        if(!DEBUG) return@joy
        uiDebug.begin(ShapeRenderer.ShapeType.Line)
        uiDebug.color = Color.YELLOW
        uiDebug.circle(joystick.initialX, joystick.initialY, joystick.radius, 50)
        uiDebug.end();uiDebug.begin(ShapeRenderer.ShapeType.Filled)
        uiDebug.color = Color.WHITE
        uiDebug.circle(joystick.initialX + (joystick.stickDistPercentageX * joystick.radius),
                       joystick.initialY + (joystick.stickDistPercentageY * joystick.radius), joystick.radius/3, 50)
        uiDebug.color = Color.CYAN
        uiDebug.circle(joystick.initialX + joystick.x, joystick.initialY + joystick.y, joystick.radius/5, 50)
    }
}

override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
    centralScreen.joystick.initialX = centralScreen.unProjectMouse.x
    centralScreen.joystick.initialY = centralScreen.unProjectMouse.y
    centralScreen.joystick.active = true
    return false
}

override fun touchUp(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
    centralScreen.joystick.active = false
    return false
}

```

A screenshot of an illustration of the algorithm:

Also if you input a negative number for the radius, luckily, nothing breaks, and the only side effect (as far as I observed) is that the stick and the dot of the joystick happens to be in the direction opposite to the direction of the mouse

Now I'm sure that a lot of this code needs some explanation, so there we go.

First of all we call the `updateValues` function with the unprojected positions of the mouse to the viewport (The units of the `InitialX`, `InitialY`, `radius`, and the arguments of the `updateValues` function need to be consistent).

For those that don't know what Unproject is, (Non-LibGDX users I mean) | If you know it, skip this part.

Say the "screen" is 100PX wide and 100 PX tall and the camera in the program has a `worldWidth` of 5, which means that 1 unit equals 20 Pixels on the screen. and say, the camera is at the position, x,y: 5,5, the unproject function first converts the mouse positions into the internal units of the camera (the viewport), then adds the camera offset (how far away from the origin is it, AKA the position) and there you have your unprojected value!

The `stickDistPercentage` value of the joystick is how far away it is from the radius in percentages, the value ranges from -1 (-100%) to +1 (100%). Since it is within -1 to +1, you can directly use it in multiplicative operations without any further conversion of it. The `realStickDistPercentage` is the same as this, just that it is not in the bounds of -100% to 100%

The IMV stands for InverseMouseMovement (just realized that I named it mouse movement); either -1 or 1, pull or push basically.

Line 11 draws the maximum bounds of the joystick. 50 stands for how circle-y it should look, it is outside our topic.

Line 14 draws the "stick" of the joystick that has a radius of `Joystick.radius/3`

Line 17 draws the dot on the ring itself.

The `x, y` is the dot in the ring of the circle, it isn't necessarily mandatory for a joystick but I kept it here because it might be useful in different cases.

The `degree` variable is the degree between the initial position and the given input position basically, don't know how to further describe it.

The `distance` is the distance between the initial position and the given input position
> 0 votes

---
Tags: libgdx, trigonometry, joystick, kotlin
---


title: Unity ECS: Issues with rotation

text:
# Question
Title: Unity ECS: Issues with rotation
Posting this here because I spent several days trying to figure out why I couldn't rotate my entities the way I wanted to in Unity.

For a little bit of background, I'm creating a flight dynamics model using Unity's Entities package. Part of this project involves providing keyboard input to a system in order to manipulate the motion of an aircraft--a very basic simulator.

I encountered an issue when I tried rotating my aircraft entity using the Rotation.Euler() method. In fact, just about every approach I saw on every forum I visited could not provide the answer I was looking for. My keyboard input logic manipulated the bank angle (roll), alpha (pitch), and yaw, and I was trying to set an absolute angle for my entity based on those values. It seemed that I was unable to set the rotation values the way I would in the inspector panel, since rotating the entity one direction would make rotating it along another axis unpredictable.

Such is the nature of quaternions.

Thus, I found a solution to my issue, involving a simple helper function that converts a float3 array of rotation values (one for each axis) to a quaternion. I'll be posting the code and explanation in the answer below.

EDIT: In the previous iteration of my code, this is what I had tried in order to update my entity's rotation:

```
Vector3 temp = transform.rotation.eulerAngles;
temp.x = -90.0f + state.bank;
temp.y = 0.0f;
temp.z = state.alpha;

Entities.ForEach((ref Translation translation, ref Rotation rotation, ref AircraftData aircraftData) => {
            translation.Value = position;
            rotation.Value = Quaternion.Euler(temp);
        }).Schedule();

```

All other code within the answer below was the same (minus the new quaternion calculations).

# Answer
> 0 votes
So how *does* one manipulate the axis angles of an entity without all of the headache?

Here's the function:

```
public void update_entity(ref State state)
    {
        // velocity information
        float vx = state.q0;
        float vy = state.q4;
        float vz = state.q2;
        // position information
        float x = state.q1;
        float y = state.q5;
        float z = state.q3;

        float3 position = new float3(x, y, z);
        float bank = -90.0f + state.bank;
        float alpha = state.alpha;

        // calculate new quaternion value for rotation
        float roll = bank * Mathf.Deg2Rad;
        float pitch = 0.0f;
        float yaw = alpha * Mathf.Deg2Rad;

        float croll = Mathf.Cos(roll * 0.5f);
        float cpitch = Mathf.Cos(pitch * 0.5f);
        float cyaw = Mathf.Cos(yaw * 0.5f);

        float sroll = Mathf.Sin(roll * 0.5f);
        float spitch = Mathf.Sin(pitch * 0.5f);
        float syaw = Mathf.Sin(yaw * 0.5f);

        float cyawcpitch = cyaw * cpitch;
        float syawspitch = syaw * spitch;
        float cyawspitch = cyaw * spitch;
        float syawcpitch = syaw * cpitch;

        Quaternion newRot = new Quaternion((cyawcpitch * sroll - syawspitch * croll),
            (cyawspitch * croll + syawcpitch * sroll),
            (syawcpitch * croll - cyawspitch * sroll),
            (cyawcpitch * croll + syawspitch * sroll));

        Entities.ForEach((ref Translation translation, ref Rotation rotation, ref AircraftData aircraftData) => {
            translation.Value = position;
            rotation.Value = newRot;
        }).Schedule();

    }

```

My state struct contains the location, velocity, bank, alpha, and flap projection of the aircraft (The values not used in this function are used later for the instruments UI panel). Using the bank and alpha angles (with a 90 degree offset because of how the aircraft model was spawned), I was able to calculate the appropriate quaternion values (x, y, z, and w) to provide the necessary rotation to my aircraft entity.

Hope this helps someone else out there who struggled to find a solution as bad as I did! :)

# Answer
> 0 votes
With Unity ECS:

1. you should use the (new) Unity.Mathematics.quaternion instead of the (old) UnityEngine.Quaternion
2. you should use quaternion.EulerZXY() which is exactly Quaternion.Euler() Indeed, the order of axis rotations is key and the old Quaternion.Euler() has an order Z, then X, then Y (as per the documentation).
3. BUT x, y and z are radians while they were degrees

Example: Quaternion.Euler(10,20,30) becomes quaternion.EulerZXY(math.PI / 180 * 10, math.PI / 180 * 20, math.PI / 180 * 30)

Voila

---
Tags: unity, unity-dots
---


# Question
Title: Automatically create capsule colliders from bones?
I have tried to automatically generate capsule colliders from bones by temporarily creating a mesh collider and using raycast to find the distance to it from the bone, but when I create the capsule collider there seems to be some rounding errors that makes them very big for bones far down in hierarchy. I am doing this to make cloth physics work.

Any suggestions what might be wrong? I have tried to convert to from global and local space to the best of my knowledge, so am wondering if the only solution is to flatten the bone hierarchy.

Code example (needs Editor Coroutines installed):

```
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Unity.EditorCoroutines.Editor;

public class AutomaticColliderFitting : ScriptableWizard
{
    [field: SerializeField]
    public SkinnedMeshRenderer SkinnedMeshRenderer { get; set; }

    [field: SerializeField]
    public Cloth[] Clothes { get; set; }

    [MenuItem("Tools/Fit Colliders To Bones")]
    static void CreateWizard()
    {
        CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
        CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
        DisplayWizard<AutomaticColliderFitting>("Automatic Collider Fitting", "Fit");
    }

    IEnumerator ProcessBones()
    {
        var queriesHitBackfaces = Physics.queriesHitBackfaces;

        List<CapsuleCollider> colliders = new List<CapsuleCollider>();

        var meshCollider = this.SkinnedMeshRenderer.transform.root.gameObject.AddComponent<MeshCollider>();
        try
        {
            Physics.queriesHitBackfaces = true;

            meshCollider.sharedMesh = this.SkinnedMeshRenderer.sharedMesh;

            var maxDistance = this.SkinnedMeshRenderer.bounds.size.magnitude;

            foreach(var bone in this.SkinnedMeshRenderer.bones)
            {
                if(bone == null) continue;

                List<Vector3> X = new List<Vector3> { Vector3.left, Vector3.right };
                List<Vector3> Y = new List<Vector3> { Vector3.up, Vector3.down };
                List<Vector3> Z = new List<Vector3> { Vector3.forward, Vector3.back };

                var resultX = RayCast(meshCollider, maxDistance, bone, X).ToList();
                var resultY = RayCast(meshCollider, maxDistance, bone, Y).ToList();
                var resultZ = RayCast(meshCollider, maxDistance, bone, Z).ToList();

                var closestToBoneX = resultX.Where(x => x.hit.collider != null).Select(x => (x.hit.distance, x)).DefaultIfEmpty().Min().x;
                var closestToBoneY = resultY.Where(x => x.hit.collider != null).Select(x => (x.hit.distance, x)).DefaultIfEmpty().Min().x;
                var closestToBoneZ = resultZ.Where(x => x.hit.collider != null).Select(x => (x.hit.distance, x)).DefaultIfEmpty().Min().x;

                var tentative = new List<(Vector3 direction, Ray ray, RaycastHit hit)> { closestToBoneX, closestToBoneY, closestToBoneZ }.Where(x => x.direction != default).ToList();
                if(tentative.Count < 2) { continue; }

                var closest = tentative.Select(x => (x.hit.distance, x)).Min().x;
                tentative.Remove(closest);
                var furthest = tentative.Select(x => (x.hit.distance, x)).Max().x;

                var collider = Undo.AddComponent<CapsuleCollider>(bone.gameObject);
                collider.center = Vector3.zero;
                collider.radius = collider.transform.InverseTransformPoint(closest.hit.point).magnitude;
                collider.height = collider.transform.InverseTransformPoint(furthest.hit.point).magnitude;
                if(furthest.direction == Vector3.left || furthest.direction == Vector3.right) { collider.direction = 0; }
                if(furthest.direction == Vector3.up || furthest.direction == Vector3.down) { collider.direction = 1; }
                if(furthest.direction == Vector3.forward || furthest.direction == Vector3.back) { collider.direction = 2; }

                bool overlapped = Physics.ComputePenetration(
                    collider, collider.transform.position, collider.transform.rotation,
                    meshCollider, meshCollider.transform.position, meshCollider.transform.rotation,
                    out Vector3 direction, out float distance
                );

                if(overlapped)
                {
                    Selection.objects = default;
                    Selection.activeObject = collider;
                    SceneView.lastActiveSceneView.LookAtDirect(collider.transform.position, SceneView.lastActiveSceneView.rotation);
                    SceneView.RepaintAll();
                    yield return null;

                    if(EditorUtility.DisplayDialog("CapsuleCollider overlaps MeshCollider.", "Action for CapsuleCollider?", "Add", "Remove"))
                    {
                        colliders.Add(collider);
                    }
                    else
                    {
                        DestroyImmediate(collider);
                    }
                }
                else
                {
                    colliders.Add(collider);
                }
            }
        }
        finally
        {
            DestroyImmediate(meshCollider);
            // Restore setting
            Physics.queriesHitBackfaces = queriesHitBackfaces;
        }

        if(this.Clothes != null)
        {
            foreach(var cloth in this.Clothes)
            {
                cloth.capsuleColliders = colliders.ToArray();
            }
        }

        static IEnumerable<(Vector3 direction, Ray ray, RaycastHit hit)> RayCast(MeshCollider meshCollider, float maxDistance, Transform bone, List<Vector3> X)
        {
            foreach(var direction in X)
            {
                var ray = new Ray(bone.position, bone.TransformDirection(direction));
                meshCollider.Raycast(ray, out RaycastHit raycastHit, maxDistance);
                yield return (direction, ray, raycastHit);
            }
        }
    }

    /// <summary>
    /// Fit
    /// </summary>
    void OnWizardCreate()
    {
        Undo.RegisterCompleteObjectUndo(this.SkinnedMeshRenderer, "Automatic Collider Fitting");
        Debug.Log("Automatic Collider Fitting.", this.SkinnedMeshRenderer);

        co = EditorCoroutineUtility.StartCoroutineOwnerless(this.ProcessBones());
    }

    private EditorCoroutine co;

    void OnWizardUpdate()
    {
        this.helpString = "Fits colliders to mesh.";
    }
}

```

Made a super simple character with a Basic Human metarig in Blender:

As you can see the capsule gets a really weird size and it gets super big.

I get equally bad results when measuring distance to closest vertex. Will need to try to measure distance to each triangle as well.

# Answer
> 0 votes
I will just post the code that seems to work good enough for me at the moment. There were several things that went wrong in my initial answer (for example the MeshCollider was not aligned with the SkinnedMesh). There are probably ways to improve this but for others interested this seems to kind-of work:

```
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Unity.EditorCoroutines.Editor;
using System;
using System.Reflection;

public static class ColliderExtensions
{
    internal static int GetDirection(this CapsuleCollider collider, Vector3 worldVertex)
    {
        float x = Math.Min(Vector3.Angle(collider.transform.right, worldVertex - collider.transform.position), Vector3.Angle(-collider.transform.right, worldVertex - collider.transform.position));
        float y = Math.Min(Vector3.Angle(collider.transform.up, worldVertex - collider.transform.position), Vector3.Angle(-collider.transform.up, worldVertex - collider.transform.position));
        float z = Math.Min(Vector3.Angle(collider.transform.forward, worldVertex - collider.transform.position), Vector3.Angle(-collider.transform.forward, worldVertex - collider.transform.position));
        if (x <= Math.Min(y, z))
        {
            return 0;
        }
        else if (y <= Math.Min(x, z))
        {
            return 1;
        }
        else if (z <= Math.Min(x, y))
        {
            return 2;
        }
        else
        {
            return 0;
        }
    }

    internal static void UpdateRadius(this CapsuleCollider collider, Vector3 worldVertex)
    {
        Debug.Log($"Using radius {collider.transform.position} -> {worldVertex} with distance {(worldVertex - collider.transform.position).magnitude}.", collider.gameObject);
        Debug.DrawRay(collider.transform.position, worldVertex - collider.transform.position, Color.magenta, 60);
        collider.radius = collider.transform.InverseTransformPoint(worldVertex).magnitude;
    }
    internal static void UpdateHeight(this CapsuleCollider collider, Vector3 worldVertex)
    {
        Debug.Log($"Using height {collider.transform.position} -> {worldVertex} with distance {(worldVertex - collider.transform.position).magnitude}.", collider.gameObject);
        Debug.DrawRay(collider.transform.position, worldVertex - collider.transform.position, Color.cyan, 60);
        collider.height = collider.transform.InverseTransformPoint(worldVertex).magnitude;
    }
    internal static void ReflectionRestoreToBindPose(this GameObject gameObject)
    {
        if (gameObject == null)
            return;
        Type type = Type.GetType("UnityEditor.AvatarSetupTool, UnityEditor");
        if (type != null)
        {
            MethodInfo info = type.GetMethod("SampleBindPose", BindingFlags.Static | BindingFlags.Public);
            if (info != null)
            {
                info.Invoke(null, new object[] { gameObject });
            }
        }
    }
}

public class AutomaticColliderFitting : ScriptableWizard
{
    [field: SerializeField]
    public SkinnedMeshRenderer SkinnedMeshRenderer { get; set; }

    [field: SerializeField]
    public Cloth[] Clothes { get; set; }

    [MenuItem("Tools/Fit Colliders To Bones")]
    static void CreateWizard()
    {
        CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
        CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
        DisplayWizard<AutomaticColliderFitting>("Automatic Collider Fitting", "Fit");
    }

    IEnumerator ProcessBones()
    {
        var queriesHitBackfaces = Physics.queriesHitBackfaces;

        List<CapsuleCollider> colliders = new List<CapsuleCollider>();

        this.SkinnedMeshRenderer.gameObject.ReflectionRestoreToBindPose();

        var meshCollider = this.SkinnedMeshRenderer.transform.root.gameObject.AddComponent<MeshCollider>();
        try
        {
            Physics.queriesHitBackfaces = true;

            Mesh colliderMesh = new Mesh();
            this.SkinnedMeshRenderer.BakeMesh(colliderMesh);
            meshCollider.sharedMesh = null;
            meshCollider.sharedMesh = colliderMesh;

            foreach (var bone in this.SkinnedMeshRenderer.bones)
            {
                if (bone == null) continue;
                var collider = Undo.AddComponent<CapsuleCollider>(bone.gameObject);

                if (UpdateCollider(meshCollider, collider))
                {
                    bool overlapped = Physics.ComputePenetration(
                        collider, collider.transform.position, collider.transform.rotation,
                        meshCollider, meshCollider.transform.position, meshCollider.transform.rotation,
                        out Vector3 _, out float _
                    );

                    if (overlapped)
                    {
                        Debug.Log($"Overlapping {collider.radius} {collider.height}.", collider.gameObject);
                        Selection.objects = default;
                        Selection.activeObject = collider;
                        SceneView.lastActiveSceneView.LookAtDirect(collider.transform.position, SceneView.lastActiveSceneView.rotation);
                        SceneView.RepaintAll();
                        yield return null;

                        if (EditorUtility.DisplayDialog("CapsuleCollider overlaps MeshCollider.", "Action for CapsuleCollider?", "Add", "Remove"))
                        {
                            colliders.Add(collider);
                            continue;
                        }
                        else
                        {
                            DestroyImmediate(collider);
                            continue;
                        }
                    }
                }
                else
                {
                    DestroyImmediate(collider);
                    continue;
                }
            }
        }
        finally
        {
            DestroyImmediate(meshCollider);
            // Restore setting
            Physics.queriesHitBackfaces = queriesHitBackfaces;
        }

        if (this.Clothes != null)
        {
            foreach (var cloth in this.Clothes)
            {
                cloth.capsuleColliders = colliders.ToArray();
            }
        }
    }

    private static bool UpdateCollider(MeshCollider meshCollider, CapsuleCollider collider)
    {
        List<RaycastHit> raycastHits = GetRayCastHits(meshCollider, collider);
        if (raycastHits.Any())
        {
            var firstDirectionClosest = raycastHits.OrderBy(x => x.distance).FirstOrDefault();
            collider.UpdateRadius(firstDirectionClosest.point);
            int firstIgnoreDirection = collider.GetDirection(firstDirectionClosest.point);
            raycastHits.RemoveAll(x => collider.GetDirection(x.point) == firstIgnoreDirection);
            if (raycastHits.Any())
            {
                var secondDirectionClosest = raycastHits.OrderBy(x => x.distance).FirstOrDefault();
                int secondIgnoreDirection = collider.GetDirection(secondDirectionClosest.point);
                raycastHits.RemoveAll(x => collider.GetDirection(x.point) == secondIgnoreDirection);
                if (raycastHits.Any())
                {
                    var thirdDirectionClosest = raycastHits.OrderBy(x => x.distance).FirstOrDefault();
                    collider.UpdateHeight(thirdDirectionClosest.point);
                    collider.direction = collider.GetDirection(thirdDirectionClosest.point);
                    return true;
                }
            }
        }
        return false;
    }

    private static List<RaycastHit> GetRayCastHits(MeshCollider meshCollider, CapsuleCollider collider)
    {
        List<RaycastHit> raycastHits = new List<RaycastHit>();
        foreach (var direction in new[] { collider.transform.up, collider.transform.right, collider.transform.forward, -collider.transform.up, -collider.transform.right, -collider.transform.forward })
        {
            if (meshCollider.Raycast(new Ray(collider.transform.position, collider.transform.TransformDirection(direction)), out RaycastHit hit, meshCollider.bounds.size.magnitude))
            {
                raycastHits.Add(hit);
            }
        }

        return raycastHits;
    }

    /// <summary>
    /// Fit
    /// </summary>
    void OnWizardCreate()
    {
        Undo.RegisterCompleteObjectUndo(this.SkinnedMeshRenderer, "Automatic Collider Fitting");
        Debug.Log("Automatic Collider Fitting.", this.SkinnedMeshRenderer);

        co = EditorCoroutineUtility.StartCoroutineOwnerless(this.ProcessBones());
    }

    private EditorCoroutine co;

    void OnWizardUpdate()
    {
        this.helpString = "Fits colliders to mesh.";
    }
}

```

---
Tags: unity, raycasting, collider, cloth
---


# Question
Title: Unity does not kill everything on application quit
I'm finding out that unity does not fully destroy all game objects on application quit. The result is that I have a number of async/await functionality that eventually runs and I can see output stream into the console long after the editor has been stopped.

Currently I'm manually disposing / destroying objects in `OnApplicationQuit` but this seems a bit silly.

Is there a more proper way to make sure all objects in the editor are fully destroyed on application quit ?

\** EDIT \**

How I'm using async code

```
public static async Task<Texture2D> DownloadTexture(string uri)
{
    using (
        UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(uri, true)
    )
    {
        var asyncOp = uwr.SendWebRequest();

        if (WeatherTracker.instance == null)
        {
            uwr.Abort(); // todo: something related to this is crashing the editor while textures are still being download @jkr
            return null;
        }
        while (asyncOp.isDone == false)
        await Task.Delay(1000 / MainCamera.instance.MaxFrameRate);

        // return this.uwr.SendWebRequest();
        // Debug.Log($"download tex {z}/{x}/{y}");
        if (uwr.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError($"{uwr.error}: {uri}");
            return null;
        }
        else
        {
            return DownloadHandlerTexture.GetContent(uwr);
        }
    }
}

```

# Answer
The `async` / `await` construct is problematic in Unity. While coroutines are bound to the object which started them, async method executions are not. That means destroying objects won't stop them. They will still return to the method of the destroyed object and try to do stuff there, which will run into NullReferenceExceptions if you are lucky or cause all kinds of weird bugs if you are not. They will even survive leaving play mode and will then continue their work back in edit mode with potentially disastrous consequences for the scene you are editing.

It's therefore usually better to avoid them.

* When performance doesn't matter enough to warrant multithreading, use Coroutines instead. A coroutine is always bound to a GameObject, and will be stopped automatically when that object gets destroyed.
* When you want to parallelize complex calculations on multiple threads for performance reasons, use Jobs. While the job system is designed for entities, it can still be useful in projects which use classic game objects.

But if you really want to use an `await` for a long-running operation which might outlive the lifetime of the calling object, then you might want to put a check `if (this == null) return;` behind the async call to detect if the current object was destroyed in the meantime.

```
GameObject prefab = await LoadPrefabFromNetwork();
if (this == null) return; // Thanks for the effort, but I don't care anymore.
Instantiate(prefab);

```

When the asynchronous method itself does things with game objects internally, you might also want to use null-checks to confirm that none of those objects were destroyed in the meantime.

```
async void PutHatOn(GameObject target) {
    GameObject hat = await LoadHatPrefab();
    if (target != null) { // target might have been destroyed while loading
         Instantiate(hat, target.transform);
    }
}

```
> 1 votes

# Answer
I use a utility class for my async/await conditionals. I have slightly modified it for your use case (untested):

```
public static class TaskUtility
{
    private static readonly int DeltaTime;

    static TaskUtility()
    {
        DeltaTime = 1000 / MainCamera.instance.MaxFrameRate;
    }

    /// <summary>
    /// Whiles while the function is true
    /// </summary>
    /// <param name="condition">The function to check</param>
    public static async Task WaitWhile(Func<bool> condition)
    {
        while (condition() && Application.isPlaying)
        {
            await Task.Delay(DeltaTime);
        }
    }

    /// <summary>
    /// Waits until the function is true
    /// </summary>
    /// <param name="condition">The function to wait on</param>
    public static async Task WaitUntil(Func<bool> condition)
    {
        while (!condition() && Application.isPlaying)
        {
            await Task.Delay(DeltaTime);
        }
    }
}

```

Which would change your code to:

```
public static async Task<Texture2D> DownloadTexture(string uri)
{
    using (
        UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(uri, true)
    )
    {
        var asyncOp = uwr.SendWebRequest();

        if (WeatherTracker.instance == null)
        {
            uwr.Abort(); // todo: something related to this is crashing the editor while textures are still being download @jkr
            return null;
        }

        await TaskUtility.WaitUntil(() => asyncOp.isDone);

        // return this.uwr.SendWebRequest();
        // Debug.Log($"download tex {z}/{x}/{y}");
        if (uwr.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError($"{uwr.error}: {uri}");
            return null;
        }
        else
        {
            return DownloadHandlerTexture.GetContent(uwr);
        }
    }
}

```

This should effectively do the same thing as your code, except it pretends the condition is complete (which is a lie) if you press stop in the editor. (Note: It may behave differently on build.)

It is slightly hacky. Using cancellation tokens as commented by @DMGregory is probably the better way to go. But I have been using this method for a few years without issue. (But I think I will probably dehackify it, and update this answer when I do.)
> 1 votes

---
Tags: unity
---


# Question
Title: Do not cast shadows when transparent in unity
I am developing a game for WebGL and I have a shader that makes parts of an object in specific ranges of coordinates transparent, like so:

This shader makes all parts of an object with an absolute Y-coordinate of more than 1.7 transparent. But these parts still cast a shadow:

How do I stop them from casting a shadow?

# Answer
This may be a bit sideways – there may well be a shader keyword you can define that does the same — but what about simply waiting for the object to complete it's animation/movement then setting Cast Shadows -\> Off on the Mesh Renderer?

The main issue I see is, from a shader perspective, I believe your shadows will be all or nothing. And maybe you can drive shadow casting from the shader, toggling it on and off at the appropriate time, but there may be a simpler solution here.
> -1 votes

---
Tags: unity, unity-shader-graph, unity-webgl
---


# Question
Title: How Do You Change A Button's Background Color in an EditorWindow in Unity?
I'm trying to change a button's background color in an EditorWindow. I can change tint using GUI.backgroundColor which seems to AND the color with grey, but I want to change it to an exact color. This is what I'm seeing:

Here's the code:

EditorWindowButtonBackgroundColor.cs

```
using UnityEngine;
using UnityEditor;

public class EditorWindowButtonBackgroundColor : EditorWindow
{
  [MenuItem("Tools/Button Background Color Editor Window")]
  private static void OpenWindow()
  {
    GetWindow<EditorWindowButtonBackgroundColor>("Button Background Color");
  }

  public void OnGUI()
  {
    GUIStyle yellowBackgroundStyle = new GUIStyle(GUI.skin.button);

    yellowBackgroundStyle.normal.background = MakeBackgroundTexture(10, 10, Color.yellow);

    if (GUILayout.Button("GUIStyle Button", yellowBackgroundStyle))
    {
      Debug.Log("GUIStyle Button");
    }

    Color originalBackgroundColor = GUI.backgroundColor;

    GUI.backgroundColor = Color.yellow;

    if (GUILayout.Button("GUI.backgroundColor Button", yellowBackgroundStyle))
    {
      Debug.Log("GUI.backgroundColor Button");
    }

    GUI.backgroundColor = originalBackgroundColor;
  }

  private Texture2D MakeBackgroundTexture(int width, int height, Color color)
  {
    Color[] pixels = new Color[width * height];

    for (int i = 0; i < pixels.Length; i++)
    {
      pixels[i] = color;
    }

    Texture2D backgroundTexture = new Texture2D(width, height);

    backgroundTexture.SetPixels(pixels);
    backgroundTexture.Apply();

    return backgroundTexture;
  }
}

```

I got the code for `MakeBackgroundTexture` here: https://forum.unity.com/threads/giving-unitygui-elements-a-background-color.20510/

As you can see, modifying and applying a GUIStyle is not working for me. Any idea what I'm doing wrong?

# Answer
The reason why you are getting those results is that the algorithm for coloring UI elements (or any other sprite using the default sprite shader) is to take the image (in this case the button background) and multiply the color values of each pixel with your chosen color. That means only those pixels which are pure white (RGB value 255, 255, 255) become that color, while all darker shades become darker variants of it.

And the default button image is not very bright. So the results of coloring is often a much darker tint than you would expect.

If you want brighter buttons, then you have to create your own button background image and use that for your buttons. You can change the background graphic of an IMGui button with a gui style. Either a button-specific one you pass to `GUI.Button`, or a general one for all buttons as part of a global gui skin.

There are five different images you need to set in that style:

* normal.background
* onActive.background
* onFocused.background
* onHover.background
* onNormal.background

You might also want to adjust the border of the gui style to match the borders of your button image and ensure that it tiles correctly.
> 2 votes

# Answer
Could it be your version? I'm running Unity 2020.3.19f1, and using your code this is what I see:

What version are you currently running?

You may also want to try:

```
yellowBackgroundStyle.onNormal.background = MakeBackgroundTexture(10, 10, Color.yellow);

```

The onNormal property also allows you to set specific styling when a GUI element is in the Normal state.
> 1 votes

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


title: Is clothing/armor design copyrighted?

text:
# Question
Title: Is clothing/armor design copyrighted?
If I google ''fantasy armor drawings'' or maybe look them on pinterest, and use those drawings of random people to model 3D meshes of armors, is this a copyright violation or can I put them inside my games ?

I mean, I modelled/animated/colored those armors, but they were drawn by someone else.

Why this question? I need to dish out lot's of models, no time to waste designing clothing, I'm not a deisgner.

# Answer
Firstly: I am not a lawyer and this is not legal advice. To get legal counsel, consult a lawyer, not a game development Q&A site.

**Yes**, *ANY* and *EVERY* creative work is subject to copyright, and this is automatic in many jurisdictions of interest.

There is no special carve-out that makes fashion designs, or fantasy-themed fashion designs, exempt from this rule that applies to all creative works.

Even if I go and make a new model or otherwise transpose the work to a different format, that does not give me ownership of the original design. The original creator could object to my unauthorized use of their design, even taking legal action against me.

If you want to use a creative work in your game, you should do one of the following:

* Create your own original work
* Combine, remix, and adapt inspirations you've drawn on in a transformative way, so that what you produce is not just a copy in another format (hoping to use a "Fair Use" defense if legal action were taken against you, though this is not as strong a protection as just making your own work to begin with)
* Seek out creative works that are explicitly offered under a permissive licence (like Creative Commons attribution or public domain licences) and follow the licence terms in your use of the work
* Pay a creator for a licence to use their work in your game
* Hire a creator to produce original works specifically for your game
> 2 votes

---
Tags: copyright
---


# Question
Title: Torque orientation when changing the coordinate system
I have some Unity application, where the user can input a torque that will be apply to a given *rigidbody*. Nonetheless, the sophistication comes from the fact that the input from the user is in a given coordinate system (`(x,y,z)` becomes `(y,-z,x)` in unity) which follow the right-hand rule and that it'll be converted to the unity coordinate system which unfortunately follow the left-hand rule...

Let's summarize, the user input his torque in his coordinate system which will be converted to the coordinate system of unity and finally the torque is apply using AddTorque.

The problem is that when for example the user enter a torque of `(0,0,-1000)` it'll assume that the *rigidbody* will turn on his **left**, but as unity coordinate system use left hand rule the *rigidbody* will turn on his **right**.

How can I convert the torque from one system to the other but I want to keep the orientation of the torque ? Or in an equivalent way : How can I make sure that the user does not know that there has been a change of coordinate system and that everything is transparent for him ?

Sorry if it's a bit confusing, please let met know if you need some further details.

Edit : I made a typing error, I wanted to write `(0,0,1000)` for the torque example. To match with the answer, I will just reverse the direction in which it turns.

# Answer
> 1 votes
When you change handedness, all angles are negated. So all you have to do is negate the torque.

If I'm reading your question correctly, your source coordinate system is:

* x+ forward
* y+ right
* z+ down

In that coordinate system, a torque of (0, 0, -1000) should rotate *left* (counter-clockwise if we're looking down on the plane of rotation). To see this, point your right thumb upward (away from z+ "down" because our torque has a negative z component). Your fingers curl to the left, in the direction of rotation.

Converting this to Unity's coordinates using the swizzle you provided (y, -z, x) gives (0, 1000, 0), which rotates *right* (clockwise when looking down on the plane of rotation). (This time we point our left thumb upward, toward y+ since the torque has a positive y component, and our fingers curl to the right).

So all you have to do to get back to leftward rotation is negate it to produce (0, -1000, 0).

Distributing the negation through your swizzle gives you (-y, z, -x).

---
Tags: unity, physics, linear-algebra, torque
---


# Question
Title: Calculating time taken for projectile to reach height (y) and position (xz) at that time in 3D space
I am trying to calculate, given a `Rigidbody` and a `float` height, at what time will the `Rigidbody` reach that height. Given my maths career was given up around 20 years ago, I am trying to convert some equations I found to accommodate this. Namely,

$$t=\frac{V\_y+\sqrt{V^2\_y+2\cdot g \cdot h}}{g}$$

I have the following function:

```
private void CalculateTimeToHeightAndPosition(Rigidbody rb, float targetHeight, ref float timeToHeight, ref Vector3 positionAtHeight)
{
    float ySpeed = rb.velocity.y;

    timeToHeight  = (ySpeed + Mathf.Sqrt((ySpeed * ySpeed) + (2 * -Physics.gravity.y * rb.transform.position.y)) / -Physics.gravity.y);

    if (!float.IsNaN(timeToHeight))
    {
        Vector3 v = rb.position + (rb.velocity * timeToHeight);

        positionAtHeight = new Vector3(v.x, targetHeight, v.z);
    }
    else
    {
        timeToHeight = 0f;
        positionAtHeight = Vector3.zero;
    }
}

```

I think the problem is this is not taking into account the `targetHeight`, and therefore calculates the time to ground, but I don't know how it fits into this equation. Anyone able to help in how to amend the function?

# Answer
I re-factored the function to (mainly to keep track of the `a,b,c` variables) and it seems to have done the job. Simply taking the target position away from initial position seems to have been the answer. Rubber ducking at its finest.

```
private void CalculateTimeToHeightAndPosition(Rigidbody rb, float targetHeight, ref float timeToHeight, ref Vector3 positionAtHeight)
{
    float yTargetPos = targetHeight;
    float ySpeed = rb.velocity.y;
    float a = -Physics.gravity.y;
    float b = ySpeed;
    float c = rb.position.y - yTargetPos;

    timeToHeight = (b + Mathf.Sqrt(Mathf.Pow(b, 2) + (2 * a * c))) / (2 * a);

    if (!float.IsNaN(timeToHeight))
    {
        Vector3 v = rb.position + (rb.velocity * timeToHeight);

        positionAtHeight = new Vector3(v.x, catchTargetHeight, v.z);
    }
    else
    {
        timeToHeight = 0f;
        positionAtHeight = Vector3.zero;
    }
}

```
> 1 votes

---
Tags: unity, projectile-physics
---


title: GLSL Convert YUV to RGB

text:
# Question
Title: GLSL Convert YUV to RGB
I have a problem where I have YUV, but UV texture is embedded into one texture.. How would I convert Y-UV into RGB ?

```
const char* pFragmentShaderSource = "\
    precision highp float;\
    uniform sampler2D gsuTexture0;\
    uniform sampler2D gsuTexture1;\
    uniform sampler2D gsuTexture2;\
    varying vec2 gsvTexCoordLuma;\
    varying vec2 gsvTexCoordChroma;\
    \
    void main()\
    {\
        float y = texture2D(gsuTexture0, gsvTexCoordLuma).r;\
        float u = texture2D(gsuTexture1, gsvTexCoordChroma).r;\
        float v = texture2D(gsuTexture2, gsvTexCoordChroma).r;\
        u = u - 0.5;\
        v = v - 0.5;\
        vec3 rgb;\
        rgb.r = y + (1.403 * v);\
        rgb.g = y - (0.344 * u) - (0.714 * v);\
        rgb.b = y + (1.770 * u);\
        gl_FragColor = vec4(rgb, 1.0);\
    }";

// TODO: optimization in Shader
int32_t sx = bitmap_.dx() / bitmap_uv.dx();
int32_t sy = bitmap_.dy() / bitmap_uv.dy();

unsigned int textures[2];
glGenTextures(2, &textures[0]);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glBindTexture(GL_TEXTURE_2D, textures[1]);

// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);    // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, bitmap_.dx(), bitmap_.dy(), 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, bitmap_.ptr());
glGenerateMipmap(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]);

glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, bitmap_uv.dx(), bitmap_uv.dy(), 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, bitmap_uv.ptr());
glGenerateMipmap(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textures[1]);

setBitmapVertices(a, ab, ad, m_bitmapVBO);

udi::BitmapShader *shader = m_bitmapShaderNV12;
if (m_shaderPtr != shader) {
    glUseProgram(shader->getShaderProgram());
    m_shaderPtr = shader;
}
glEnableVertexAttribArray(shader->posAttrib);
glVertexAttribPointer(shader->posAttrib, NUM_VERTEX_COMPONENTS, GL_FLOAT, GL_FALSE, (NUM_VERTEX_COMPONENTS + NUM_TEX_COMPONENTS) * sizeof(GLfloat), 0);
glEnableVertexAttribArray(shader->  );
glVertexAttribPointer(shader->texAttrib, NUM_TEX_COMPONENTS, GL_FLOAT, GL_FALSE, (NUM_TEX_COMPONENTS + NUM_VERTEX_COMPONENTS) * sizeof(GLfloat), (void*)(NUM_VERTEX_COMPONENTS * sizeof(GLfloat)));
glUniformMatrix4fv(shader->matrixLocation, 1, GL_FALSE, m_transformationMatrix);
glUniform1i(glGetAttribLocation(shader->getShaderProgram(), "textureY"), 0);
glUniform1i(glGetAttribLocation(shader->getShaderProgram(), "textureUV"), 1);

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glDeleteTextures(2, &textures[0]);

```

# Answer
> 0 votes
Just delete one unused `sampler2D`, sample both red and green channels from the chroma texture, and unpack them to your u and v variables.

```
const char* pFragmentShaderSource = "\
    precision highp float;\
    uniform sampler2D lumaTexture;\
    uniform sampler2D chromaTexture;\
    varying vec2 gsvTexCoordLuma;\
    varying vec2 gsvTexCoordChroma;\
    \
    void main()\
    {\
        float y = texture2D(lumaTexture, gsvTexCoordLuma).r;\
        float2 chroma = texture2D(chromaTexture, gsvTexCoordChroma).rg;\
        float u = chroma.r - 0.5;\
        float v = chroma.g - 0.5;\
        vec3 rgb;\
        rgb.r = y + (1.403 * v);\
        rgb.g = y - (0.344 * u) - (0.714 * v);\
        rgb.b = y + (1.770 * u);\
        gl_FragColor = vec4(rgb, 1.0);\
    }";

```

---
Tags: glsl
---


# Question
Title: Difference in definitions of "Minkowski difference"
I'm trying to understand Minkwoski difference, as it relates to collision detection.

It seems, to me, that there are two definitions of Minkowski difference floating around. One, as defined by wikipedia and the other as defined for example here. My question is, am I wrong? Are those two definitions equivalent?

My intuition says no, because according to the Wikipedia definition, if `B` contains the origin then `B+c` contains `c`, and that means that every such `c` must be contained in `A`. However, according to the other definition, `A-B` might contain points not in `A`.

# Answer
I've found that there is a bit of confusion surrounding the use of the terms minkowski sum/difference. The Wikipedia definition gives the sum/difference definitions in the context of morphological operations, where the sum refers to dilation and the difference refers to erosion, which are mathematical duals of each other. see here and here for some info.

Using minkowski sums for collision detection originates from robot motion planning (amongst other things see page 6 here for more) and involves the minkowski sum of a set and a set reflection (i.e. A+(-B)). I have seen it referred to as the minkowski subtraction before, but most papers often comment on the irregularity of the term minkowski difference and go on to explicitly define what they exactly mean when they use the term.

The definition in the second link you gave should be the one you need for applying the 'minkowski difference' for collision detection.
> 3 votes

# Answer
You are both correct, there are two different definitions and it is confusing.

In computational geometry and collision detection, the second one is more common: $$A\ominus B \equiv A \oplus(-B)$$

The first definition indeed can be motivated by erosion operations and can be written using complements.
> 0 votes

---
Tags: collision-detection, mathematics, terminology
---


# Question
Title: Why does my code intended to stop Rigidbody from sliding prevent player from jumping?
I have the following code which gives a Rigidbody capsule the ability to move and jump (if on layer `Ground`).

After Player stops input, the Rigidbody slides. I wanted to massively reduce sliding by adding `GroundStopSlide()` which is intended to set Rigidbody velocity to zero if it detects sliding greater than a certain magnitude when Player lets hand off keyboard.

I am finding that this works mostly as intended, BUT: If player jumps while standing still, the jump does not reach its normal height. It is a stunted jump.

Why might this be happening? Thank you.

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

public class Move1 : MonoBehaviour
{
    public Rigidbody r;

    //Base Movement
    public float horizontalInput;
    public float verticalInput;
    public Vector3 movDirection;
    public float speed = 20f;

    //Ground Check
    public bool isGrounded = true;
    public Transform groundCheckTransform;
    public float groundCheckRadius = 0.25f;
    public LayerMask groundLayerMask;

    //Jump
    public float jumpForce = 10f;
    public bool isJumping;
    public float stopSlideSpeed = 1f;

    void Awake()
    {
        groundLayerMask = LayerMask.GetMask("Ground");
        r = this.GetComponent<Rigidbody>();
    }

    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
        movDirection = new Vector3(horizontalInput, 0.0f, verticalInput).normalized;

        if (!isGrounded)
        {
            print("Not Grounded");
            this.GetComponent<Renderer>().material.SetColor("_Color", Color.cyan);
        }
        else
        {
            this.GetComponent<Renderer>().material.SetColor("_Color", Color.white);
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            isJumping = true;
        }
    }

    public void FixedUpdate()
    {
        if (isGrounded)
        {
            GroundStopSlide();
        }

        r.AddForce(movDirection * (speed + 10f), ForceMode.Force);

        if (isJumping == true)
        {
            Jump();
        }

        GroundCheck();
    }

    public void GroundCheck()
    {
        isGrounded = Physics.CheckSphere(groundCheckTransform.position, groundCheckRadius, groundLayerMask);
    }

    void Jump()
    {
        if (isGrounded)
        {
            r.AddForce(new Vector3(0f, jumpForce, 0f), ForceMode.Impulse);
        }
        isJumping = false;
    }

    void GroundStopSlide()
    {
        if (r.velocity.magnitude >= stopSlideSpeed && movDirection == Vector3.zero)
            r.velocity = Vector3.zero;
    }

}

```

# Answer
> 1 votes
I don't have the reputation yet to comment, so will have to put this as an answer.

I think the problem is due to the GroundCheck staying set to true after you've started your jump. The impulse to the rigidbody from the jump will probably set the y velocity to some positive value, but the groundcheck is still triggering (maybe something to do with the radius of the sphere you're using) before Unity does the vertical movement. The next fixed update frame will see that the isGrounded is still true and set the y velocity to 0 in the GroundStopSlide method, thus stunting the jump.

You can probably avoid this by testing whether you have zero or negative y velocity in the groundcheck method (if you're moving up, you don't really need to check if you're grounded still).

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


# Question
Title: How do I integrate Unity and CodeCov (Using GitHub Actions)?
GitHub actions attempt to upload my coverage reports to CodeCov, but I get an error. Below is my most recent GitHub Action code, and the error I'm receiving from CodeCov. Please let me know if there is any more information I can provide.

**Error**

```
Run codecov/codecov-action@v2
  with:
    name: CodeCov
    flags: automated
    token: ***
    files: coverage-results/**/*.xml
  env:
    UNITY_LICENSE: ***
==> linux OS detected
https://uploader.codecov.io/latest/linux/codecov.SHA256SUM
==> SHASUM file signed by key id 806bb28aed779869
==> Uploader SHASUM verified (330066ecce62f2cdcfd2fe1845095475f51bbad9649dce81ac7b663dc884bbef  codecov)
==> Running version latest
==> Running version v0.1.15
/home/runner/work/_actions/codecov/codecov-action/v2/dist/codecov -n CodeCov -Q github-action-2.1.0 -f coverage-results/**/*.xml -F automated -C 9d9656791bb5e390945821f1ecaae8a226b15aba
[2022-01-27T20:19:24.095Z] ['info']
     _____          _
    / ____|        | |
   | |     ___   __| | ___  ___ _____   __
   | |    / _ \ / _` |/ _ \/ __/ _ \ \ / /
   | |___| (_) | (_| |  __/ (_| (_) \ V /
    \_____\___/ \__,_|\___|\___\___/ \_/

  Codecov report uploader 0.1.15
[2022-01-27T20:19:24.108Z] ['info'] => Project root located at: /home/runner/work/Time-Bubble/Time-Bubble
[2022-01-27T20:19:24.108Z] ['info'] ->  Token found by environment variables
[2022-01-27T20:19:24.119Z] ['info'] Searching for coverage files...
[2022-01-27T20:19:24.133Z] ['error'] There was an error running the uploader: Error while cleaning paths. No paths matched existing files!

```

**GitHub Action**

```
name: Test with coverage
on:
  pull_request:
    branches: [master]

env:
  UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }}

jobs:

  testRunner:
    name: Test in ${{ matrix.testMode }}
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        testMode:
          - EditMode
          - PlayMode
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Create LFS file list
        run: git lfs ls-files -l | cut -d' ' -f1 | sort > .lfs-assets-id

      - name: Restore LFS cache
        uses: actions/cache@v2
        id: lfs-cache
        with:
          path: .git/lfs
          key: ${{ runner.os }}-lfs-${{ hashFiles('.lfs-assets-id') }}

      - name: Git LFS Pull
        run: |
          git lfs pull
          git add .
          git reset --hard

      - name: Restore Library cache
        uses: actions/cache@v2
        with:
          path: Library
          key: Library-test-project-${{ matrix.targetPlatform }}
          restore-keys: |
            Library-test-project-
            Library-

      - uses: game-ci/unity-test-runner@v2.0-alpha-5
        id: testRunner
        with:
          testMode: ${{ matrix.testMode }}
          checkName: ${{ matrix.testMode }} test results
          githubToken: ${{ secrets.GITHUB_TOKEN }}
          customParameters: -debugCodeOptimization -enableCodeCoverage -coverageResultsPath ./coverage-results -coverageOptions generateAdditionalMetrics

      - uses: actions/upload-artifact@v2
        with:
          name: Test results (${{ matrix.testMode }})
          path: ${{ steps.testRunner.outputs.artifactsPath }}

  codeCov:
    needs: testRunner
    name: Submit to CodeCov
    runs-on: ubuntu-latest
    steps:
      - name: Upload XML report to Codecov
        uses: codecov/codecov-action@v2
        with:
          name: CodeCov
          flags: automated
          token: ${{ secrets.CODECOV_TOKEN }}
          files: coverage-results/**/*.xml

      - name: Check for failure
        if: steps.CodeCov.outcome != 'success'
        run: exit 1

```

# Answer
The error that you're seeing

> \[2022-01-27T20:19:24.133Z\] \['error'\] There was an error running the uploader: Error while cleaning paths. No paths matched existing files!

implies that either (1) the coverage file doesn't exist or that (2) it's not at the right location. Given that you seem to have a lot of control as to where that file is located, I'm going to assume that it's likely the first problem.

Taking a look at your `codeCov` job, it looks like it is only trying to upload coverage reports to Codecov. However, the job doesn't have access to that file because it isn't persisted across jobs.

**You can solve this by either combining the two jobs into one or using an artifact strategy presented here and adding a `download-artifact` step.**

One note, if you do end up doing `download-artifact` as the solution, I think you will still need to do an `actions/checkout@v2` step.
> 1 votes

---
Tags: unity, testing, unit-testing, test-driven-development
---


title: Snake game made in processing

text:
# Question
Title: Snake game made in processing
I have been working on this snake game for a few days, and I have the basics down, but I was wondering if anyone could help me figure out the tail. I need it to follow the body, as it does in the original game. I have read through a lot of really helpful forums, but as I am still new to code and the processing language, I would like a more specific idea as to how I can go about making the tail work.

This is what I have so far:

```
PImage snake;
PImage arrow1;
PImage arrow2;
PImage arrow3;
PImage arrow4;
PFont font;

boolean state = false;

int snakeSize = 1;
int maxLength = 25;
int x [] = new int [maxLength];
int y [] = new int [maxLength];
int j;

int foodX = (round(random(49)+1*10));
int foodY = (round(random(49)+1*10));

int speed = 1;
int xspeed = 0;
int yspeed = 0;

int foodCount = 0;

int page = 0;

void setup() {
  size(1280, 800);
  x[0] = 250;
  y[0] = 250;
  snake = loadImage ("snake.png");
  arrow1 = loadImage ("arrow_up.png");
  arrow2 = loadImage ("arrow_down.png");
  arrow3 = loadImage ("arrow_left.png");
  arrow4 = loadImage ("arrow_right.png");
  font = createFont ("Arial Rounded MT Bold", 40);
}
void draw() {
  background(200);

  //PLAYING FIELD
  stroke(100);
  fill(225);
  rect(10, 10, 900, 780);

  //BUTTON
  stroke(255);
  fill (#0EEB52);
  rect(990, 690, 200, 52, 25);

  //Page 1--------------------------------------------
  //MENU
  if (page == 0) {
    textFont(font);
    textAlign(CENTER);
    fill(255);
    textSize(12);
    text ("Made by Brya Patterson", 1090, 775);
    textSize(40);
    text ("Play!", 1090, 730);
    textSize(50);
    text ("SNAKE", 1090, 85);
    image (snake, 930, 15);
  }

  //Page 2--------------------------------------------
  //GAME
  else if (page == 1) {
    stroke(100);
    fill(255);
    textSize(12);
    text ("Made by Brya Patterson", 1090, 775);
    textSize(40);
    text ("Home", 1090, 730);
    textSize(50);
    text ("SNAKE", 1090, 85);
    image (snake, 930, 15);
    text ("Score:"+foodCount, 1080, 310);
    textSize(17);
    text ("To begin, press any key in the key pad\n
        or use arrow keys to move.", 1085, 653);

    //KEY PAD
    image (arrow1, 1055, 375, 80, 80);
    image (arrow2, 1055, 525, 80, 80);
    image (arrow3, 975, 450, 80, 80);
    image (arrow4, 1130, 450, 80, 80);

    //SNAKE---------------------------------------------
    //BODY
    for (int i = 0; i < snakeSize; i++) {
      fill (#ACE235);
      rect (x[i], y[i], 10, 10);

      x [i] = x[i]+xspeed;
      y [i] = y[i]+yspeed;

      if (x[i]< 10 || x[i] > 910 || y[i] < 15 || y[i] > 790) {
        page = 2;
      }
    }

    //FOOD----------------------------------------------
    fill (#F0ACBD);
    rect(foodX, foodY, 12, 12);
    if (snakeSize < y.length) {
      if (x[0] >= foodX-10 && x[0] <= foodX+10 && y[0] >= foodY-10 && y[0] <= foodY+10) {
        foodX = (round(random(50))+1)*10;
        foodY = (round(random(50))+1)*10;
        snakeSize++;

        if (j!=1) {
          x[snakeSize-1] = x[snakeSize-2]-0;
          y[snakeSize-1] = y[snakeSize-2]-10;
        }
        //SCORE---------------------------------------------
        foodCount++;
      }
    }
  }

  //Page 3--------------------------------------------
  //END/RESTART
  else if (page == 2) {
    fill(255);
    rect(0, 0, 1280, 800);
    stroke(255);
    fill (#0EEB52);
    rect(990, 690, 200, 52, 25);
    fill(200);
    textAlign(CENTER);
    textFont(font);
    textSize(103);
    text ("SNAKE", width/2, 180);
    image (snake, 581, 169, 254, 250);
    textSize (60);
    text("You Died! \nPress 'Home' \nto restart.", width/2, height/2);
    fill(255);
    textSize(40);
    text ("Home", 1090, 730);
  }
}

//CONTROL MOVEMENT and BUTTON STUFF
void keyPressed() {
  if (keyCode == UP) {
    xspeed = 0;
    yspeed = -2;
  }
  if (keyCode == DOWN) {
    xspeed = 0;
    yspeed = 2;
  }
  if (keyCode == LEFT) {
    xspeed = -2;
    yspeed = 0;
  }
  if (keyCode == RIGHT) {
    xspeed = 2;
    yspeed = 0;
  }
}
void mousePressed() {
  if (mouseX > 955 && mouseX < 955+200 && mouseY > 690 && mouseY < 690+52) {
    page++;
    if (page == 3) {
      x[0] = 300;
      y[0] = 300;
      x[1] = 300;
      y[1] = 300;
      page = 0;
    }
  }
  //arrow1-UP
  if (mouseX > 1055 && mouseX < 1055+80 && mouseY > 375 && mouseY < 375+80) {
    xspeed = 0;
    yspeed = -2;
  }
  //arrow2-DOWN
  if (mouseX > 1055 && mouseX < 1055+80 && mouseY > 525 && mouseY < 525+80) {
    xspeed = 0;
    yspeed = 2;
  }
  //arrow3-LEFT
  if (mouseX > 975 && mouseX < 975+80 && mouseY > 450 && mouseY < 450+80) {
    xspeed = -2;
    yspeed = 0;
  }
  //arrow4-RIGHT
  if (mouseX > 1130 && mouseX < 1130+80 && mouseY > 450 && mouseY < 450+80) {
    xspeed = 2;
    yspeed = 0;
  }
}

```

# Answer
I'm not familiar with processing, only with java, but that shouldn't matter.

How I'd do it is to have an infinite array (in java an ArrayList) of vectors, each marking a position of a snake tile. When the snake wants to move, you first create a new vector in the heads new position, add it to the array, then check if it collides with any of the other snake tiles. If it does, then it's game over, otherwise check if it collides with the fruit.

As @wondra pointed out, a Deque is a better solution than an ArrayList, because it's easier to insert and remove elements from and to the ends of the list.

If it didn't collide with the fruit, remove the first piece (the last tail), this will make the snake win and lose a tile, thus it appears as it moved forward. You'll probably need to shift the other tiles back to make the snake occupy the beginning of the array.

If it collided with the fruit, then don't di anything, this will make the snake get a new tile.
> 1 votes

# Answer
You can remove the last piece of the tail and put on the head
> 0 votes

---
Tags: animation, software-engineering, processing, snake
---


# Question
Title: How can I make my Unity 2d scene pitch black, except for manually added lighting?
I have tried modifying all the settings suggested that I can find, but the lighting of objects in my Scene remains unchanged. I've used the "Generate" button, I've set "Intensity Multiple" to 0, I've enabled/disable Scene lighting, I've set the Environment Lighting to black, there are no lights in the Light Explorer, etc.

I want everything but the Canvas HUD to be completely black, except anything illuminated by manually added lights. Is there some way to do this in the latest Unity that I'm somehow missing?

**Edit 2:** I have changed the material of my sprites, and now there is total darkness, except when I place lights. I changed the Rendering Mode of the material to Fade to fix the HUD being blocked from viewing by the tiles, and now the problem is that a light placed as a child of the player is causing the player to appear as a purely black version of his sprite.

# Answer
The default rendering material (formally called a Material, set in the Sprite Renderer component) for sprites is automatically fully visible regardless of other lights in the scene. In order to have a sprite affected by light (or the lack thereof), one must change the material to a different one. Setting to a newly created Material with all default settings suffices to make sprites respond to light. One should set "Intensity Multiple" to 0 and the Environment Lighting color to black, then press the "Generate" button, in order to actually remove the ambient light.

The Z position of the light, and the particular settings of the material, may affect how things actually end up getting lit, assuming one is using the default renderer with 3D Lights (just called Lights in the menus). The Rendering Mode of the material affects the results, with Fade being the option that solved some of my problems.
> 0 votes

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


# Question
Title: Collision prediction and RTS group movement
I am making a simple group selection and movement system in Unity and so far it is great. However, when I move a group of units to a location, they all bunch up on top of each other.

So I instead picked a point around the location and moved all of the units to their own location at an offset from the position they were told to move to. This also works okay and I'm happy enough with this approach.

However, on their way to the destination, my sprites will overlap and crossover each other. I would instead prefer they respect each others colliders and move around each other in order to reach their destination.

I'm sure there's some better approaches to this (to which I'm all ears if you have any suggestions), however my initial thought was to first try to predict a collision and make a unit stop moving until the coast was clear.

My issues are that I can't seem to properly predict when a collision *might* occur. Here is the general approach I have taken:

```
private void Update() {
    if (moving) {
        // stop moving if we're close
        if (Vector3.Distance(moveDestination, transform.position) < 0.05f) {
            moveDirection = Vector3.zero;
            moving = false;
        }

        var moveDelta = moveDirection * moveSpeed * Time.deltaTime;
        var newPosition = transform.position + moveDelta;

        // only move if we're not going to collide with something
        if (!HitTest(newPosition)) {
            transform.position = newPosition;
        }
    }
}

private bool HitTest(Vector3 newPosition) {
    // Find any colliders close by that aren't MY collider
    var colliders = Physics2D.OverlapBoxAll(newPosition, boxCollider.size, 0f).Where(x => x != boxCollider).ToList();
    Debug.Log(colliders.Count());
    return colliders.Count() > 0;
}

```

The result is that the units seem to stop in completely random ways. They will stop moving .. even when moving *away* from a collider thats in the other direction. I am unable to figure out why the collider API's for overlapping aren't producing the results I desire. Even if I use one of the others (like Ray Casting in a direction) it still seems to return colliders that *aren't* in that direction.

Is there something obvious I am misunderstanding about these collision APIs? Can my idea be improved? I am open to any and all suggestions.

# Answer
Here are some general tips and advice on how to troubleshoot this problem yourself:

* Using Physics functions like `OverlapBoxAll()` is not the best way to predict collisions. OverlapBoxAll() tells you where obstacles are *now*, not where they'll be at some point in the future. Depending on how far into the future you predict, this can give you wildly inaccurate results. True prediction involves estimating where other obstacles will be at that point in the future.
* It looks like you're predicting one frame in the future, every frame. This can give jittery, unrealistic looking results. In my experience, it's usually better to predict at least a few frames into the future; the exact window depends on how close together your units are.
* When you're having trouble understanding what's going on with collision prediction code, use visualizations to help. For example:

```
private bool HitTest(Vector3 newPosition) {
    // Find any colliders close by that aren't MY collider
    var colliders = Physics2D.OverlapBoxAll(newPosition, boxCollider.size, 0f);
    //draw a red line from me to any predicted obstacles. make sure gizmos are enabled
    if (drawDebugLines) { //new serialized field
        for (int i = 0; i < colliders.Length; i++) {
            var other = colliders[i];
            if (other != myCollider) {
                Debug.DrawLine(transform.position, other.transform.position, Color.red, .1f);
            }
        }
    }

    Debug.Log(colliders.Length);
    //much more efficient way to check the colliders:
    if (colliders.Length > 1) return true;
    if (colliders.Length == 0) return false;
    return colliders[0] != myCollider;
}

```

By the way, the method you're using to check collisions is terribly inefficient:

`var colliders = Physics2D.OverlapBoxAll(newPosition, boxCollider.size, 0f).Where(x => x != boxCollider).ToList();`

* `OverlapBoxAll()` allocates an array. You should generally use `OverlapBoxNonAlloc()` instead
* The Linq `Where()` extension method will most likely allocate some type of object (see the source code) and probably isn't optimal for maximum performance.
* `ToList()` allocates yet another object. All of these allocations generate memory garbage which in turn means that expensive garbage collection occurs more frequently.

If you know that OverlapBoxAll() will always include your own collider, you can just subtract 1 from the count. Even if you're not sure, it's easy to check without using Linq. See my modified `HitTest()` function above.
> 1 votes

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


# Question
Title: How can I keep a node in-place while I re-parent it?
I have an object that needs to follow various `Path2D` paths in my scene. To do this, when it needs to follow a path, I re-parent it to a `PathFollow2D` that will traverse the relevant path. The code to do this looks like this:

```
# Remove from the current parent first, otherwise we can't set new parent
character.get_parent().remove_child(character)
slide_follow.add_child(character)

# ...set PathFollow2D in motion, etc...

```

Functionally, this works, and it's perfectly fine 90% of the time. However, because I have to remove the node from it's current/prior parent in order to add it, it briefly loses it's location and then comes back. Sometimes, this happens inside an `Area2D` that has collision detection on for the character, which results in `body_exited` and `body_entered` signals firing incorrectly unnecessarily, which can have adverse side effects.

I've tried temporarily disabling collision on the character to prevent this:

```
character.get_node("CollisionShape2D").disable = true
print("#1 removing from old parent")
character.get_parent().remove_child(character)
print("#2 parentless node")
slide_follow.add_child(character)
print("#3 on to new parent")
character.get_node("CollisionShape2D").disable = false

```

but the signals still fire:

```
#1 removing from old parent
exit signal fired!
#2 parentless node
enter signal fired!
#3 on to new parent

```

Is there a way to either keep the node in place or temporarily disable relevant collision so that the enter/exit signals don't fire during the reparenting process?

# Answer
> 1 votes
The node should keep its global position while it is out of the scene tree. The problem is not that it lost its position, the problem is that it is out of the scene tree. And there is no way to change the parent node without removing it from the scene tree and adding it back.

---

Shy of suggesting to write the path following code yourself so that it does not require to change parent nodes…

For non physics objects, I suggest to use a `RemoteTransform2D` to push the transform from the `PathFollow2D` to it (By making the `RemoteTransform2D` a child of the `PathFollow2D`, and setting its `remote_path` to the `Node2D` you want to control).

For a physics objects, however, I'd suggest to write code to follow the `PathFollow2D`. For example, a `KinematicBody2D` could do something like this:

```
func _physics_process(delta:float) -> void:
    # …
    if is_instance_valid(follow):
        global_rotation = follow.global_rotation
        move_and_slide((follow.global_position - global_position) / delta)

```

Where `follow` is a reference to the node currently being followed (e.g. the `PathFollow2D`).

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


# Question
Title: Convert a dot product scalar for a triangle's slope, into a translation ratio?
Struggling with accurate terminology; I've got a 3D app with triangulated terrain, where it looks like a checkerboard from the top view, where every cell is two tris, and every cell is equal size (1 sq unit). I'm storing the "unit circle" slope/scalar (?) for every triangle, two for each cell, so that I can index into a cell during runtime and lookup its slope, to see if the tri I'm over is flat enough to walk on, or if I should start sliding down the slope instead. For example, a triangle with a perfect 45 degree slope, has "0.707106" saved for the "slope" value, which was calculated via dot product of the tri's normal and a World Up vector.

What I need, is to somehow convert that slope scalar to a different scalar value which needs to represent a ratio of *how much to slide forward if we hypothetically fell straight down into the ground because of gravity*, based on that slope value. That's hard to explain, but for example:

* 0.707106 "slope" cell: 1 unit across, 1 units down... Needs to somehow convert to "1.0" (this first case is the perfect 45 degree slope. A value of "1.0" would mean, we translate downwards by the same exact amount we should translate forward, hence "1.0" ratio)
* 0.447213 "slope" cell: 1 unit across, 2 units down... Needs to somehow convert to "0.5" (this second case is a steeper slope, so assuming we are still falling down at the same speed, I only need to translate forward only half as much as I fell into the floor, hence 0.5)
* 0.316227 "slope" cell: 1 unit across, 3 units down... Needs to somehow convert to "0.3333"

Those were simplified examples, whereas the actual terrain is more randomized. The examples are also 2D, whereas the app is 3D. So, can I derive the ratio/scalar I'm looking for, from my "slope" dot product scalar? I've got the sliding/translating logic completed, but I'm just translating forward at the wrong rate, so I only need to understand how to properly find that missing ratio/scalar. Thank you

# Answer
> 3 votes
I don't understand your setup. However, `0.707106` looks familiar to me. It is approximately this:

$$\frac{1}{\sqrt{2}}$$

And you say that is a 45º slope, right? So, my hypotheses is that you have the inverse of the hypotenuse (with one side being of unit length).

If this is true, fro your case 1 unit across 2 units down, you should have:

$$\frac{1}{\sqrt{1^2+2^2}} = \frac{1}{\sqrt{1+4}} = \frac{1}{\sqrt{5}} = \frac{1}{2.2360679...} = 0.447213...$$

Yep.

The final case is 1 unit across and 3 units down:

$$\frac{1}{\sqrt{1^2+3^2}} = \frac{1}{\sqrt{1+9}} = \frac{1}{\sqrt{10}} = \frac{1}{3.162277...} = 0.316227...$$

And yep.

---

The number you have is the cosine of the angle. This makes sense, because the dot product has a a trigonometric identity with the cosine of the angle between the vectors: $$\vec{a}·\vec{b} = |a||b|cos(θ)$$ Where θ is the angle between the vectors.

---

Now, if we are always talking of one unit across, we have this equation:

$$n = \frac{1}{\sqrt{1 + x^2}}$$

And we solve for x:

$$n = \frac{1}{\sqrt{1 + x^2}}$$

$$\implies$$

$$\frac{1}{n} = \sqrt{1 + x^2}$$

$$\implies$$

$$\left(\frac{1}{n}\right)^2 = \left(\sqrt{1 + x^2}\right)^2$$

$$\implies$$

$$\frac{1}{n^2} = \left(\sqrt{1 + x^2}\right)^2$$

$$\implies$$

$$\frac{1}{n^2} = |1 + x^2|$$

$$\implies$$

$$\frac{1}{n^2} = 1 + |x^2|$$

$$\implies$$

$$\frac{1}{n^2} = 1 + x^2$$

$$\implies$$

$$\frac{1}{n^2} - 1 = 1 + x^2 - 1$$

$$\implies$$

$$\frac{1}{n^2} - 1 = x^2$$

$$\implies$$

$$\sqrt{\frac{1}{n^2} - 1} = |x|$$

---

Let us try it out.

For `0.707106`:

$$|x| = \sqrt{\frac{1}{n^2} - 1} = \sqrt{\frac{1}{0.707106^2} - 1} = \sqrt{\frac{1}{0.499998} - 1} = \sqrt{2.000008 - 1} = \sqrt{1.000008} = 1.000004$$

For `0.447213`

$$|x| = \sqrt{\frac{1}{n^2} - 1} = \sqrt{\frac{1}{0.447213^2} - 1} = \sqrt{\frac{1}{0.199999} - 1} = \sqrt{5.000025 - 1} = \sqrt{4.000025} = 2.000006$$

For `0.316227`

$$|x| = \sqrt{\frac{1}{n^2} - 1} = \sqrt{\frac{1}{0.316227^2} - 1} = \sqrt{\frac{1}{0.099999} - 1} = \sqrt{10.000100 - 1} = \sqrt{9.000100} = 3.000017$$

Ok, we run into rounding problems. The good news is that we are consistently overshooting, so you can go ahead an floor the result. And of course, you want the multiplicative inverse.

The code would be something like this:

```
float compute_slope(float n)
{
    return 1.0/floor(sqrt((1.0/(n * n)) - 1.0));
}

```

This is what I get trying it out:

* For `0.707106`: `1.0`
* For `0.447213`: `0.5`
* For `0.316227`: `0.333333`

---

If I follow the trigonometric approach, then what you are looking for (the slope) is the cosine over the sine of the angle. And we have the cosine, we could do this:

```
float compute_slope(float n)
{
    return n/sin(acos(n));
}

```

However, this gave me worst precision when trying it out:

* For `0.707106`: `0.999997`
* For `0.447213`: `0.499999`
* For `0.316227`: `0.333332`

---

**Addendum** Sometimes ideas arrive when I step away from a problem. If I have the cosine and I need the sine, I can do it with this identity:

$$sin(x)^2 + cos(x)^2 = 1$$

Which gives me this code:

```
float compute_slope(float n)
{
    return n/(sqrt(1.0 - (n * n)));
}

```

And I get… The same:

* For `0.707106`: `0.999997`
* For `0.447213`: `0.499999`
* For `0.316227`: `0.333332`

I was worth trying.

# Answer
> 1 votes
An alternative to the method described by Theraot would be to calculate the sliding vector of the triangle. You have already calculated the normal vector, so:

```
LeftVec = worldUpVec X normalVec
SlidingVec = LeftVec X normalVec
Normalize(SlidingVec)

```

You can now multiply the `SlidingVec` by speed and delta time to create movement along the sliding plane of the triangle, perhaps projecting the gravity vector onto the sliding vector via the dot product to get the right speed.

---
Tags: c++, transformation, terrain, normals
---


# Question
Title: Proper way to build sensible object graphs?
**The Context**

I'm currently working on a game and its engine using C# and MonoGame. The engine is data-driven and I want people to be able to mod the game or make their own using my engine. All the assets and data are processed using the MonoGame Content Pipeline.

Currently, I'm loading the game data and passing it into a sort behavior object (I guess this could be seen as a business model?) like so:

```
// Data object, in the real world it's less like a DTO and more like an anemic model.
// Almost always originally a *.json compiled to *.xnb by the content pipeline.
public class CharacterData
{
    public string Name { get; set; }
    public string TexturePath { get; set; }
    public string WeaponPath { get; set; }
    public string RivalPath { get; set; }
}

// Actual behavior object the game interacts with. May be serialized in a savegame file.
public class Character
{
    public Character(CharacterData data, ContentManager content)
    {
        Level = 1,
        Hp = 234,
        Name = data.Name;
        Texture = content.Load<Texture2D>(data.TexturePath):
        Weapon = new Weapon(content.Load<WeaponData>(data.WeaponPath));

        // Possible circular reference leading to a StackOverflowException if it points
        // to the same data object on disk or if two Characters are each other's rival.
        Rival = new Character(content.Load<CharacterData>(data.RivalPath));
    }
}

```

**The Problem**

The problem I'm facing right now seems to be an architectural one that leads to large object graphs, circular references and StackOverflowExceptions.

The above example is relatively simple but I know if I keep doing this I'll run into a much worse scenario. For example:

A Map that has a list of Characters which themselves have a list of Spells or Items which themselves point to yet another data object and so on and so forth.

In the end, I'm going to load almost the entirety of the game assets because of that, which I obviously don't need and don't want most of the time. That's not even mentioning the poor design and likelihood of infinite recursion as I mentioned above, let alone serializing this graph.

What am I missing here? What sort of architecture is best suited for what I want to achieve? I'm sure I need to refactor this but I'm unsure how. Any tips would be greatly appreciated.

**A Few Notes**

* Somewhat relevant to my current architecture, I also have an editor (WPF + MVVM). The data objects are created there and passed to ViewModels in a similar fashion to what I'm doing with the behavior objects.
* The editor doesn't care about the game's behavior, only the data that it will use.
* This whole thing is extensible, people can create their own libraries with their own data types, meaning that I can't control everything.

Thanks!

# Answer
> 1 votes
Separate your contentloading from the class that holds your object data.

```
public static class Art
{
    private static Dictionary<string, Texture2D> _textures;
    private ContentManager _cm;

    public static Init(ContentManager cm)
    {
        _cm = cm;

        //add each texture to the dictionary of textures with the path- you were sure to load anyway.
    }

    public static void LoadAsset(string path)
    {
        if(_textures.KeyExists(path))
          return;

        _textures.Add(path,_cm.Load<Texture2D>(path)); // add your checks for the existence of file etc.
    }

    public Texture2D Sprite(string path)
    {
        return _textures(path); // ofcourse do some checking if a path exists in the dictionary etc.
    }
}

```

Now your paths are no longer causing duplicate content to load because you decoupled that so:

```
// Actual behavior object the game interacts with. May be serialized in a savegame file.
public class Character
{
    public Character(CharacterData data)
    {
        Level = 1,
        Hp = 234,
        Name = data.Name;
        Texturepath = data.TexturePath;
        Art.LoadAsset(Texturepath);
    }
}

```

Now in your draw function you can point to the Art.Sprite() to pick up the texture;

Next to solve the rivals circular references- you shouldn't declare "new" characters in each character you create. Create a pool of characters first. And then appoint rivals afterwards.

Weapons can be a mixed bag. Let's say you have a weapon like "excalibur"- one exists, but any character could own it- so you may want to create it outside of the character. On the other hand, each weapon could be unique in the sense that it has its own durability stat- in that way you can create one when needed (when a character is created, a chest is opened etc).

---
Tags: c#, xna, architecture, monogame, xna-content-pipeline
---


# Question
Title: Designing database schema for multiplayer game inventory
I want to create an inventory system for an online multiplayer game, so I was thinking about database.

My research led me to this form:

* id (user, bigint, unsigned + index, foreign key for user's id in users table)
* itemid (item\_id, int, unsigned)
* amount (amount of the items, int)

I know there will be a lot of rows with duplicated user IDs - are there any improvements I can make to this design to work with that?

# Answer
Yes, this is a properly by-the-book normalized database design. It allows operations like checking the quantity of a specific item with a single database query returning just that one number and it allows analytic queries like getting statistics about how much of what item is in the game.

If you make use of those abilities, then that's fine.

However, in many multiplayer online games, there are only two database operations which ever happen on characters. And those are:

1. Save the character completely
2. Load the character completely

If that's your usage pattern, then database normalization into lots of rows in lots of tables gives you no benefit, but is a lot of work and a lot of additional performance cost. You can just as well serialize the whole data of the player to a BLOB and store that in a single field of a single table row.

If you still want analytics, then you can have a properly normalized copy of the player data in a separate data-warehouse database.
> 1 votes

# Answer
A lot of rows is not a problem per se, even more so since you do not neet to ask for the whole inventory all the time - it should be enough to get the full inventory once at the start of the game and keep it locally at your player and just do another check on the server once the player actually uses an item (to prevent client side manipulation of item amount).

Before you encounter an actual bottleneck (which is unlikely to be the database), your approach seems to be ok.
> 0 votes

---
Tags: databases, inventory
---


# Question
Title: How to fix exception:Resource not found: testdata/alphamap.png?
I keep getting this exception:Resource not found: testdata/alphamap.png when trying to use Slick in my program. How can I resolve this error?

# Answer
Google turned up with a fork of slick (not available anymore) here: Slick Fork. When you go to the folder located under `testdata/alphamap.png` you will find it or directLink.

You can resolve the error with simply placing it at the location it expects the file to be.
> 1 votes

---
Tags: java, maps, slick, alpha, exceptions
---


# Question
Title: How to restrict player movement without jitters
I am currently making top-down space shooter and would like to hear some suggestions on how to restrict player movement without causing jitters. Everything works fine except one thing: the player (spaceship) jitters back and forth when trying to move beyond the game bounds. Here is a short video to show you what I mean: https://drive.google.com/file/d/1ZsBHnSakQYh0J5srJC\_KUbB00OSSQFA9/view?usp=sharing And here is a script:

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

public class Starship : MonoBehaviour
{
    private float moveX, moveY;
    private float boundsY = 450f, boundsX = 850f;

    [SerializeField]
    private float moveSpeed;

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        moveX = Input.GetAxis("Horizontal");
        moveY = Input.GetAxis("Vertical");
        Vector3 currentPosition = transform.localPosition;
        transform.localPosition += new Vector3(moveX, moveY) * moveSpeed * Time.deltaTime;
        if (currentPosition.y < -boundsY)
            transform.localPosition = new Vector3(currentPosition.x, -boundsY);
        else if (currentPosition.y > boundsY)
            transform.localPosition = new Vector3(currentPosition.x, boundsY);
        else if (currentPosition.x < -boundsX)
            transform.localPosition = new Vector3(-boundsX, currentPosition.y);
        else if (currentPosition.x > boundsX)
            transform.localPosition = new Vector3(boundsX, currentPosition.y);
    }
}

```

# Answer
> 1 votes
So I decided to use rigidbody and some box colliders to restrict player movement. Overall I think it's the best solution for this case. I used Box colliders 2D as bounds and to detect a ship of a player. I also set Rigidbody2D for a ship. It's also important setting continuous collision detection in Rigidbody properties for the ship of a player, so the ship doesn't bounce off the bounds.

```
private Rigidbody2D playerRB;

void Start()
    {
        playerRB = GetComponent<Rigidbody2D>();
    }

void Update()
    {
        moveX = Input.GetAxis("Horizontal");
        moveY = Input.GetAxis("Vertical");
        playerRB.MovePosition(playerRB.position + new Vector2(moveX, moveY) *
        Time.deltaTime * moveSpeed);
    }

```

# Answer
> 0 votes
The fastest fix would be to first check if your new position is out of bounds before clipping it to the bound in case it is bigger.

```
void Update() {
    moveX = Input.GetAxis("Horizontal");
    moveY = Input.GetAxis("Vertical");
    Vector3 currentPosition = transform.localPosition;
    Vector3 futurePosition = currentPosition + new Vector3(moveX, moveY) * moveSpeed * Time.deltaTime;
    if (futurePosition.y < -boundsY)
        futurePosition = new Vector3(futurePosition.x, -boundsY);
    else if (futurePosition.y > boundsY)
        futurePosition = new Vector3(futurePosition.x, boundsY);
    if (futurePosition.x < -boundsX)
        futurePosition = new Vector3(-boundsX, futurePosition.y);
    else if (futurePosition.x > boundsX)
        futurePosition = new Vector3(boundsX, futurePosition.y);
    transform.localPosition = futurePosition;
}

```

Keep in mind that setting the position directly ignores physics. If you moved your ship with a rigidbody and had some borders (invisible or not), it would not jitter against them.

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


title: How to go back to the old input system?

text:
# Question
Title: How to go back to the old input system?
I have tried using Unity's new input system, but it's incredibly hard to learn, the documentation is poor, and the old system is much easier to work with. I would like to revert my project back to the old system, but I am unsure how to do that. How do i disable the package and reconfigure my project so it will accept code using the old system?

# Answer
> 1 votes
If you write the old input system, in code, then unity's code checker will automatically update it for you. If unity doesn't automatically then in the menus up top press Assets-\>Run API Updater. Hope this helps.

# Answer
> 1 votes
In order to revert back Go to **player** settings and select **Active input handling** dropdown.

**Watch 43 Second Tutorial**

---
Tags: unity, input
---


# Question
Title: How to make Player rotation driven by mixture of camera rotation *and* keyboard rotation?
Currently I have these lines of code driving Player rotation:

```
    horizontalInput = Input.GetAxis("Horizontal");
    verticalInput = Input.GetAxis("Vertical");
    moveDirection = new Vector3(horizontalInput, 0.0f, verticalInput).normalized;

    if (moveDirection != Vector3.zero)
    {
        Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
        targetRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotDegPerSecond * Time.deltaTime);
        rigidBody.MoveRotation(targetRotation);
    }

```

This works well to rotate the Player with the keyboard input.

However, I would like my Camera to be able to influence player rotation as well.

How can I add code to make Player rotation determined from both Keyboard Input *and* Camera rotation together?

# Answer
> 0 votes
I solved this through a YouTube tutorial that implements Cinemachine. The core important lines are:

```
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");

moveDirection = new Vector3(horizontalInput, 0.0f, verticalInput).normalized;
moveDirection = (Quaternion.AngleAxis(cameraTransform.rotation.eulerAngles.y, Vector3.up) * moveDirection).normalized;

```

where `cameraTransform` is declared at the top (`public Transform cameraTransform;`) and is a reference to your camera. In this case, it is my Cinemachine camera, implemented with the settings shown here:

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

Good luck all!

---
Tags: unity
---