# Question
Title: Calculate average of arbitrary amount of quaternions (recursion)
Simply calculate the average for 2 Quaternions should work like follows right? :

```
Quaternion.Lerp(rotationlist[0].transform.rotation, rotationlist[1].transform.rotation, 0.5f);

```

And now I tried to put this into a recursive function, like this:

```
private Quaternion calcAvg(int pos, List<GameObject> rotationlist)
{
    if (pos < rotationlist.Count)
    {
        return Quaternion.Lerp(rotationlist[pos].transform.rotation, calcAvg(++pos, rotationlist), 0.5f);
    }
    return ???;
}

```

But I'm not absolutely sure, what to put into the second return.

Edit, I added the last position into the second return but now I get an out of bounds exception:

```
private Quaternion calcAvg(int pos, List<GameObject> markerList)
{
        if (pos < markerList.Count)
        {
            return Quaternion.Lerp(markerList[pos].transform.rotation, calcAvg(++pos, markerList), 0.5f);
        }
        return markerList[pos].transform.rotation;
}

```

Edit, fixed the issue, I will test this now but it looks alright :

```
private Quaternion calcAvg(int pos, List<GameObject> markerList)
{
        if (pos < markerList.Count)
        {
            return Quaternion.Lerp(markerList[pos].transform.rotation, calcAvg(++pos, markerList), 0.5f);
        }
        return markerList[pos].transform.rotation;
}

```

# Answer
> 0 votes
In your approach, the first quat in the list gets weighted at 50%, and all the rest together will be weighted for the other 50%.

If you had 4 quats, with your approach, their relative weightings will be 0.5, 0.25, 0.125, 0.125.

You could fix this my changing the 0.5f to something computed based on list and position.

You could also make the recursion more balanced with something like:

```
calcAvg(List<quat> quats):
  if(quats.size == 0): ERROR
  if(quats.size == 1):
    return quats[0]
  List<quat> firstHalf = first half of quats list
  List<quat> secondHalf = second half of quats list
  q1 = calcAvg(firstHalf)
  q2 = calcAvg(secondHalf)
  return Lerp(q1, q2, firstHalf.size / quats.size)

```

I'm not completely certain of the geometric characteristics of this kind of Angle Averaging. Probably fine for game use...

# Answer
> 5 votes
Under the hood, `Lerp` will simply lerp each component of the quaternion, then normalise the result. A square root is hidden in there for each call to `Lerp`. It is therefore very inefficient. Also, any floating point rounding errors will accumulate.

This will be a lot faster, and also a lot more precise:

```
private Quaternion calcAvg(List<GameObject> rotationlist)
{
    if (rotationlist.Count == 0)
        throw new ArgumentException();

    float x, y, z, w;
    foreach (var go in rotationlist)
    {
        var q = go.transform.rotation;
        x += q.x; y += q.y; z += q.z; w += q.w;
    }
    float k = 1.0f / Mathf.Sqrt(x * x + y * y + z * z + w * w);
    return new Quaternion(x * k, y * k, z * k, w * k);
}

```

# Answer
> 0 votes
Sam's logic above is sound, but the code had some errors.

```
private static Quaternion CalcAvg(List<Transform> rotationlist)
{
    if (rotationlist.Count == 0)
        throw new ArgumentException();

    float x = 0, y = 0, z = 0, w = 0;
    foreach (Transform t in rotationlist)
    {
        x += t.rotation.x;
        y += t.rotation.y;
        z += t.rotation.z;
        w += t.rotation.w;
    }
    float k = 1.0f / Mathf.Sqrt(x * x + y * y + z * z + w * w);
    return new Quaternion(x * k, y * k, z * k, w * k);
}

```

# Answer
> -1 votes
1. Convert the quaternions into angle-vectors by using `Quaternion.eulerAngles`
2. Calculate the average of each of the three axis' of these vectors.
3. Convert the resulting axis-averages back to a Quaternion using `Quaternion.Euler`.

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


# Question
Title: How to create an octahedron for sphere subdivision?
I have vertices that generate the first out of two pyramids. However, I want to have the second pyramid facing downwards as to make an octahedron. What are the correct vertices to use, because I've been trying to figure this out for hours

Here is the current pyramid

Here is my desired outcome

And here are the vertices

```
    // front face
    0.0,  1.0,  0.0,
    -1.0, -1.0,  1.0,
    1.0, -1.0,  1.0,
    // right face
    0.0,  1.0,  0.0,
    1.0, -1.0,  1.0,
    1.0, -1.0, -1.0,
    // back face
    0.0,  1.0,  0.0,
    1.0, -1.0, -1.0,
    -1.0, -1.0, -1.0,
    // left face
    0.0,  1.0,  0.0,
    -1.0, -1.0, -1.0,
    -1.0, -1.0,  1.0,

```

Close but not quite

The final result due to the answer

# Answer
> I've been trying to figure this out for hours

Next time you're stuck on a problem for hours, spend 5 minutes to check if there's a Wikipedia article about it. (Which, if you're dealing with a platonic solid that's been known since the time of, well, Plato, there is). Here are the vertices you need:

> ( ±1, 0, 0 )
> ( 0, ±1, 0 )
> ( 0, 0, ±1 )

That's just the unit vector along each (positive and negative) coordinate axis, or the 6 facing directions of a cube (an octahedron's dual). You can connect 3 of these on the same side of the origin to make one triangle in each octant:

(Just being mindful of winding - here I'm matching the winding order in your question)

```
//top-north-east
 0.0,  1.0,  0.0,
 0.0,  0.0,  1.0,
 1.0,  0.0,  0.0,

//top-north-west
 0.0,  1.0,  0.0,
-1.0,  0.0,  0.0,
 0.0,  0.0,  1.0,

//top-south-west
 0.0,  1.0,  0.0,
 0.0,  0.0, -1.0,
-1.0,  0.0,  0.0,

//top-south-east
 0.0,  1.0,  0.0,
 1.0,  0.0,  0.0,
 0.0,  0.0, -1.0,

//bottom-north-east
 0.0, -1.0,  0.0,
 1.0,  0.0,  0.0,
 0.0,  0.0,  1.0,

//bottom-north-west
 0.0, -1.0,  0.0,
 0.0,  0.0,  1.0,
-1.0,  0.0,  0.0,

//bottom-south-west
 0.0, -1.0,  0.0,
-1.0,  0.0,  0.0,
 0.0,  0.0, -1.0,

//bottom-south-east
 0.0, -1.0,  0.0,
 0.0,  0.0, -1.0,
 1.0,  0.0,  0.0,

```

This approach ensures the octahedron is centered at the origin (all vertices equidistant, and the origin is their centroid), so that if you take any point on the octahedron and normalize it, you'll get a point on the unit sphere, and your subdivisions will be evenly distributed around the 8 octants. Your original pyramid was not suitable for this use, since its base was at -1, putting the origin closer to the top of the pyramid.
> 1 votes

---
Tags: opengl, 3d, mathematics, geometry, 3d-meshes
---


# Question
Title: Need a button to reset the scene in Godot
I need to make a button that restarts the scene. i tried

```
func reset():
    if Input.is_action_just_pressed('reset'):
        get_tree().reload_current_scene()

```

But this doesn't work- any advice? All i need is the button to reset the scene

# Answer
Your code seems correct, but you actually must have the code to be called for it to have any effect. Place your two lines of code within a node's (or autoload's) `_process()` function and it should work.
> 0 votes

---
Tags: godot, gdscript
---


# Question
Title: Using IK to make a cutscene in Unity 2021
I imported a character from Mixamo to Unity, and I wanted to make a quick fight cutscene.

However, I realized that it was going to take a good bit of time. I would like to know if there is a method of animating that uses Inverse Kinematics to make animations in Unity. That way, things would go much quicker. Thank You!

# Answer
The usual workflow for creating animations for Unity games is to create them in a 3rd party 3d modeling program like Blender, Maya or 3dsMax and then import the animations into Unity as animation actions by importing the model. Unity can retarget animations via the Avatar component, so you don't necessarily need to do the animations with the same model which you are going to apply them to.

But if you still want to do it in Unity, then the new 3d rigging system might be what you want. It's basically a more advanced and flexible alternative to the build-in IK system provided by Unity. Although the basic IK system might do the job if you only want IK for hands, feet and gaze. The article I linked has an example script.

In either case you would create your IK targets as invisible game objects and then create actions using the Animation System which move those IK targets around.
> 0 votes

---
Tags: unity, animation
---


# Question
Title: How to get a type other than GameObject using GameObject.Find?
I am Using Unity 2021.3.13f1.

I need to find an object in my scene and its type is TMP\_Text.

I'm trying to use the following code:

```
TMP_Text text = (TMP_Text)(GameObject.Find("TooltipTemplate"));

```

However I get the error:

```
Cannot convert type 'UnityEngine.GameObject' to 'TMPro.TMP_Text'

```

When I remove the explicit cast and add it in Instantiate() below:

```
GameObject text = (GameObject.Find("text"));
Instantiate((TMP_Text)text, ..., ...);

```

I get the same error. I conclude that the way I use GameObject.Find, it returns a GameObject type and Unity refuses to cast it to the type I need to use.

**How do I obtain the right type with a search? Be it GameObject or a better method.**

# Answer
> 3 votes
There seems to be some misconception here about how Unity works. Specifically about what's the difference between a *GameObject* and a *Component*. GameObjects in Unity are containers for multiple Components. A GameObject that shows up as a text **isn't** a `TMP_Text`. It's a GameObject that **has a** TMP\_Text *component*. This confusion might be from how the Unity editor pretends to let you create a `TMP_Text` from the context menu, but what you *actually* get when you do that is a whole GameObject that has multiple components, and among them a `TMP_Text` component.

When you want to get a reference to a specific component of a GameObject, then you call the GetComponent method of the GameObject where you expect the component to be.

```
GameObject tooltipTemplate = GameObject.Find("TooltipTemplate");
TMP_Text tooltipTemplateText = tooltipTemplate.GetComponent<TMP_Text>();

```

Other options for you might be the static methods FindObjectOfType (that gives you the first component of the first object with such a component) and FindObjectsOfType (that gives you an array with all the components of the given type in the scene). But neither method allows you to specify a name of a specific game object. They are going to search your whole scene for components of that type.

But keep in mind that all the `Find*` methods are generally very slow, because they search through the whole scene tree. If possible, you might want to use other ways to set up references between game objects. For example, by creating a `public TMP_Text text` field in your script and then assign the desired text object in the inspector.

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


# Question
Title: Create after image effect following behind character
I'm currently trying to achieve an effect like this, except wirh a 3D character:

I've tried a variety of of techniques but have fallen short, I feel like I'm on the right track but just missing something. Here's the steps I tried to take:

* Get the distance between my current player position and previous position and if its greater than some arbitrary number I call the `Render()` method on my second camera that only renders the player
* In the `OnRenderImage()` function I then use `Graphics.Blit()` to copy the contents of my render texture to my main cameras image
* Second camera then renders that view to a `RenderTexture` which is sent to a script on my Main Camera

Here is the script on my player character:

```
public class AfterImageTest : MonoBehaviour
{
    private Vector3 prevPos;

    private float Speed = 40;
    [SerializeField] private GameObject _camera;
    private float dt;
    private float a = 0;
    // Start is called before the first frame update
    void Start()
    {
        prevPos = this.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        if (dt >= 0.1f)CreateSnapShot();
        Vector3 currentPos = transform.position;

        currentPos.y += Mathf.Sin(a ) * Speed * Time.deltaTime;
        transform.position = currentPos;
        dt = Vector3.Distance(prevPos,currentPos);
        prevPos = currentPos;
        a += 0.1f;
    }

    void CreateSnapShot()
    {
        Debug.Log("Capturing screenshot");
        _camera.SetActive(true);
        _camera.GetComponent<Camera>().Render();
        _camera.SetActive(false);
    }
}

```

And here is the script on my Main Camera:

```
public class AfterImage : MonoBehaviour
{
    public RenderTexture rt1;

    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        // Blit the contents of camera2's render texture to the destination texture
         Graphics.Blit(source,rt1);
         Graphics.Blit(rt1, destination);
    }
}

```

Some other things to note:

* I have the depth value of my second Camera set to -1 and my depth value set to 0 to make sure they are rendered in the correct order
* I have made sure the render texture I'm outputting to has transparency enabled (if you look at the render texture it only contains the character and a black background)

All I see when I do this is the main camera's viewpoint and no indication the render texture has been applied to my main camera's render. Any help would be greatly appreciated!

Also it's important to note, my game is in 3D not 2D so using particle effects to copy the player sprite isn't possible.

# Answer
> 0 votes
So after trying a few different approaches I finally found one that achieved the desired effect using the `SkinnedMeshRenderer` component. Here is the code:

```
public class AfterImageTest : MonoBehaviour
{
    [SerializeField]private SkinnedMeshRenderer[] _skinnedMeshRenderers;

    void Start()
    {
        _skinnedMeshRenderers = GetComponentsInChildren<SkinnedMeshRenderer>();
        for ( int j = 0; j < _skinnedMeshRenderers.Length; j++)
            {

                    GameObject obj = new GameObject();
                    obj.transform.SetPositionAndRotation(this.transform.position, this.transform.rotation);
                    //obj.transform.Rotate(new Vector3(0,0,0));
                    MeshRenderer meshRenderer = obj.AddComponent<MeshRenderer>();
                    MeshFilter meshFilter = obj.AddComponent<MeshFilter>();
                    Mesh mesh = new Mesh();
                    _skinnedMeshRenderers[j].BakeMesh(mesh);
                    meshFilter.mesh = mesh;
                    meshRenderer.materials = _skinnedMeshRenderers[j].materials;
        }
    }

}

```

The last line `meshRenderer.materials = _skinnedMeshRenderers[j].materials;` is important if your character has more than one material applied to it! Otherwise unity will simply pick the first material on the list of materials and youll find parts of your mesh missing. If you only have one material you can do:

`meshRenderer.material = _skinnedMeshRenderers[j].material;`

Hope this helps!

---
Tags: unity, c#, graphic-effects
---


# Question
Title: How to get Update to acknowledge variable value from other method
So I'm trying to write a script in Unity where, when right clicking while the mouse is being followed (I changed it so the cursor is replaced instead, but that's off-topic), that the cursor will change again to a specific texture.

However, for this to work, I need the "color value" variable to have a specific value... but it keeps returning as null in the Update method. Any help on how to get Update to know what the current `crayonValue` is?

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

public class ColoringScript : MonoBehaviour
{
    // Variables
    public GameObject brownCrayon;
    public GameObject selectedShape;
    public Sprite uncolored;
    public Sprite colored;
    public Texture2D brownUnflipped;
    public Texture2D brownFlipped;
    public CursorMode cursorMode = CursorMode.ForceSoftware;
    private GameObject activeCrayon;
    private string crayonValue;
    private string activeTag;
    private bool isFollowingMouse = false;
    private bool isFlipped = false;
    private Vector2 startPos;
    private Vector2 pos;
    private Vector2 movePos;
    private Vector2 hotSpot = Vector2.zero;
    private Image activeImage;
    private Texture2D cursorTexture;

    void Update()
    {
        if(isFollowingMouse)
        {
            if(Input.GetMouseButtonDown(1))
            {
                Debug.Log(crayonValue);
                WasFlipped(crayonValue); // Calls the WasFlipped function to flip the crayon
            }
            if(Input.GetMouseButtonDown(0))
            {
                isFollowingMouse = false; // Sets the boolean so the object stop following the mouse
                activeImage.enabled = true; // Makes the current crayon visible again
                activeCrayon = null; // Empties the activeCrayon variable
                activeImage = null; // Empties the activeRenderer variable
                activeTag = null; // Empties the activeTag variable
                crayonValue = null; // Empties the craonValue variable
                cursorTexture = null; // Reverts the cursor texture
                Cursor.SetCursor(cursorTexture, hotSpot, cursorMode); // Returns the cursor to its default state
            }
        }
    }

    // WasClicked is called when a crayon is left-clicked
    public void WasClicked(string crayonValue)
    {
        switch(crayonValue)
        {
            case "brown":
                activeCrayon = brownCrayon; // Sets the activeCrayon variable to the brown crayon
                activeImage = activeCrayon.GetComponent<Image>(); // Sets the activeRenderer variable
                activeImage.enabled = false; // Makes the crayon invisible
                activeTag = "brown"; // Sets the variable activeTag for ease when clicking a shape
                cursorTexture = brownUnflipped; // Sets the cursorTexture value to the brown crayon default side
                break;
        }
        isFollowingMouse = true; // Sets the boolean so the code knows the cursor is being followed
        Cursor.SetCursor(cursorTexture, hotSpot, cursorMode); // Changes the cursor to simulate picking up the crayon
    }

    // WasFlipped is called when an active crayon is right-clicked
    public void WasFlipped(string crayonValue)
    {
        switch(crayonValue)
        {
            case "brown":
                if(!isFlipped)
                {
                    Debug.Log("flipped brown");
                    isFlipped = true; // States that the crayon is currently flipped
                    cursorTexture = brownFlipped; // Flips the crayon by changing the cursor
                }
                if(isFlipped)
                {
                    isFlipped = false; // States that the crayon is currently being flipped back to normal
                    cursorTexture = brownUnflipped; // Flips the crayon back to its original side
                }
                break;
        }
        Cursor.SetCursor(cursorTexture, hotSpot, cursorMode); // Changes the cursor to simulate flipping the crayon
    }

    // WasColored is called when a shape is clicked
    public void WasColored()
    {
        Debug.Log("Colored" + crayonValue);
        selectedShape.tag = activeTag; // Sets the tag of the shape to the currently active tag
        selectedShape.GetComponent<Image>().sprite = colored; // Colors the shape by changing the source image
    }
}

```

# Answer
> 0 votes
It looks like you forgot to save the value of `crayonValue` from the argument you got in `WasFlipped`/`WasClicked` into your member variable of the same name.

Despite using the same name, these are three separate variables. One is a private member variable accessible to any method in the class, and the others are temporary variables declared as method parameters — they cease to exist as soon as execution leaves those methods.

If you want to copy the value from one to the other for safe keeping between calls, write something like this:

```
public void WasClicked(string crayonValue)
{
    this.crayonValue = crayonValue;

    // ...continue with the rest of the method.

```

This takes the value from the temporary variable used as a method parameter and stores that value in the private member variable with the same name (using `this.` to disambiguate the two and say "I want the one that's a member variable that's part of `this` class instance").

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


# Question
Title: How to rotate an image on an HTML5 canvas, without rotating the whole canvas?
I want to rotate single sprites on the canvas without rotating the whole canvas.

I also don't want to create a new canvas for each object I have.

Also, it would be interesting to know which solution is then the most performant.

# Answer
> 14 votes
> It’s important to note that changing the co-ordinate system with rotate and translate do not affect anything that’s currently drawn into the canvas. **It only affects subsequent drawing actions**.

```
var TO_RADIANS = Math.PI/180;
function drawRotatedImage(image, x, y, angle)
{
    // save the current co-ordinate system
    // before we screw with it
    context.save();

    // move to the middle of where we want to draw our image
    context.translate(x, y);

    // rotate around that point, converting our
    // angle from degrees to radians
    context.rotate(angle * TO_RADIANS);

    // draw it up and to the left by half the width
    // and height of the image
    context.drawImage(image, -(image.width/2), -(image.height/2));

    // and restore the co-ords to how they were when we began
    context.restore();
}

```

Source: http://creativejs.com/2012/01/day-10-drawing-rotated-images-into-canvas/

# Answer
> 1 votes
Based on Luis Estada's answer, I created `rotateContext` function to rotate images and other shapes:

const TO_RADIANS = Math.PI / 180;

const rotateContext = (context, origin, angle, callback) => {
    // save the current co-ordinate system
    context.save();

    // move to the origin of our element
    context.translate(origin.x, origin.y);

    // rotate around that point, converting our
    // angle from degrees to radians
    context.rotate(angle * TO_RADIANS);

    // restore context to initial position
    context.translate(-origin.x, -origin.y);

    // draw rotated elements
    callback(context);

    // and restore the coords system
    context.restore();
}

// ... more code

// draw rotated image
rotateContext(context, rotation.origin, rotation.angle, () => {
    context.drawImage(this.sprite, 0, 0, 225, 225, position.x, position.y, width, height);
});

// ... or

// draw rotated shape
rotateContext(context, rotation.origin, rotation.angle, () => {
    context.fillStyle = 'green';
    context.fillRect(position.x, position.y, width, height);
});
```
</code></pre>

# Answer
> -2 votes
Change the context, place your image, then reset the context by multiplying your first number by -1.

example:

```
    context.rotate(k);
    context.drawImage(img,c,d,e,f,g,h,i,j);
    context.rotate(k * -1)

```

---
Tags: javascript, html5, rotation, html-canvas
---


# Question
Title: Platformer enemy with raycast to detect obstacles keeps changing direction rapidly
I am making a 2D platform and implementing a character similar to a Mario Goomba. This character will move left or right, depending on whether or not a raycast determines that there is an object in front of it.

Currently there are 2 RayCasts, originating from the center of the sprite, on for left-side detection, and one for right. This script checks for a hit from either, and if a hit is detected it changes the moveDirection, and flips the sprite. The code works, however the character sprite will sporadically flip countless times, sometimes getting stuck. There seems to be no set trigger for it, as it appears to occur at random intervals. This leads me to believe that there is some issue with its layout in the code, however no combination of putting it in `Update()`, `LateUpdate()`, or `FixedUpdate()` really changes anything.

This is the script I created:

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

public class SimpleEnemyMovement : MonoBehaviour
{
private Rigidbody2D enemyRb;
private SpriteRenderer spriteRen;
[SerializeField] private float moveDirection;
[SerializeField] private bool turnAround;

[SerializeField] float movementSpeed;
[SerializeField] float rayLength;
[SerializeField] int layerMask;

// Start is called before the first frame update
void Start()
{
    enemyRb = GetComponent<Rigidbody2D>();
    spriteRen = GetComponent<SpriteRenderer>();
    moveDirection = 1;
}

// Update is called once per frame
void Update()
{

    transform.position = transform.position + new Vector3(moveDirection * movementSpeed * Time.deltaTime, 0, 0);

}

private void FixedUpdate()
{
    PatrolLogicController();
}

private void PatrolLogicController()
{

    RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, rayLength, layerMask);
    Debug.DrawRay(transform.position, Vector2.right * rayLength, Color.green);
    RaycastHit2D hit2 = Physics2D.Raycast(transform.position, Vector2.left, rayLength, layerMask);
    Debug.DrawRay(transform.position, Vector2.left * rayLength, Color.green);

    if(hit || hit2)
    {
        turnAround = !turnAround;
    }

    if (turnAround == false)
    {
        spriteRen.flipX = false;
        moveDirection = 1;
    }

    if (turnAround == true)
    {
        spriteRen.flipX = true;
        moveDirection = -1;
    }
}

```

}

# Answer
> 0 votes
The problem has been located. The issue was with my movement on `transform.position` taking place in `Update()`. The position update would occur every frame, but the `FixedUpdate()` method calls in set intervals of realtime, so the movement would update quicker than the Raycast could check for collision. Upon moving the `transform.position` into the `FixedUpdate()` method, this works flawlessly.

---
Tags: unity, c#, 2d, raycasting, platformer
---


# Question
Title: How to tile 4 images and blend the seams
**Scenario**

For the sake of example I have four textured planes that overlap each other. Theoretically this produces one large image but the textures come from a third party at run time and often are misaligned due to the cropping procedure which I have no control over.

**Question**

While keeping the four planes separate is there a way to blend the textures into one another so that my 4x4 looks like a seamless image ?

Related Question

**Extra**

My app is a 2d x,y free scroller so I need to add & take away planes often as a user scrolls.

# Answer
Here's a simple approach you can try, just drawing each texture a little larger so it overlaps its neighbours, and feathering the edges so it blends smoothly:

From left to right, I'm increasing the amount of overlap. At the far left, there's no overlap, and so hard seams are very noticeable. At the far right, I'm overlapping objects by about 60% of their width, so you get a very smooth transition, though it can start to muddy some of the details within each tile. In the middle I'm using about 16% overlap as a middle ground.

The shader that does this just renders each tile additively, with Z-writing turned off, so you don't get Z-fighting between tiles. It darkens the edges of each tile so that when they meet they add up to full brightness again. Set your camera's clear colour to black for this to look right.

```
Shader "Unlit/TileBlend"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Transparent" }
        LOD 100

        Blend One One
        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float _BlendFactor;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            float2 smoothstep2(float2 t) {
                return t * t * (3 - 2 * t);
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);

                float2 fromEdge = 1.0f - abs(i.uv - 0.5f) * 2.0f;
                float2 margin = saturate(fromEdge * _BlendFactor);
                float2 falloff = smoothstep2(margin);

                float opacity = falloff.x * falloff.y;

                return col * opacity;
            }
            ENDCG
        }
    }
}

```

Here's a script to set up a grid of textured quads with a desired amount of overlap, and adjust their scales and the `_BlendFactor` shader parameter to match:

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

public class TileBlender : MonoBehaviour
{
    // Cache material property ID for fast lookups.
    static readonly int BLEND_FACTOR_ID = Shader.PropertyToID("_BlendFactor");

    [Tooltip("Textures for each tile, ordered left-to-right, top-to-bottom")]
    public Texture2D[] tileTextures;

    [Tooltip("Size of the tile grid, x: columns, y: rows")]
    public Vector2Int layout = new Vector2Int(3, 3);

    [Tooltip("How much of the tile should blend with its neighbours?")]
    [Range(0, 1)]
    public float overlap;

    [Tooltip("Use TileBlend shader")]
    public Material blendMaterial;

    Renderer[] _tiles;

    static float ComputeBlendFactor(float overlap) {
        // Blend area in UV space is one tile overlap in each direction,
        // expressed as a ratio to the tile's full size.
        // Return the reciprocal so in the shader it's just a multiply, no divide.
        return (1.0f + overlap) / (2.0f * overlap);
    }

    // Adjust blending when overlap slider is changed in Inspector.
    void OnValidate() {
        if (_tiles == null) return;

        Shader.SetGlobalFloat(BLEND_FACTOR_ID, ComputeBlendFactor(overlap));
        foreach(var tile in _tiles) {
            tile.transform.localScale = Vector3.one * (1f + overlap);
        }
    }

    void Start() {
        _tiles = new Renderer[layout.x * layout.y];
        Shader.SetGlobalFloat(BLEND_FACTOR_ID, ComputeBlendFactor(overlap));
        int i = 0;
        for (int y = 0; y < layout.y; y++) {
            for (int x = 0; x < layout.x; x++) {
                _tiles[i] = MakeTile(x, y, tileTextures[i % tileTextures.Length]);
                i++;
            }
        }
    }

    Renderer MakeTile(int x, int y, Texture2D texture) {
        var quad = GameObject.CreatePrimitive(PrimitiveType.Quad);

        var mat = Instantiate(blendMaterial);
        mat.mainTexture = texture;

        quad.TryGetComponent(out Renderer renderer);
        renderer.sharedMaterial = mat;

        quad.transform.SetParent(transform, false);
        quad.transform.localPosition = new Vector3(x, y, 0);
        quad.transform.localScale = Vector3.one * (1f + overlap);

        return renderer;
    }

    void OnDestroy() {
        foreach(var tile in _tiles) {
            Destroy(tile.sharedMaterial);
        }
    }

}

```

Here's what it looks like as we adjust the `overlap` slider up and down:
> 3 votes

# Answer
I don't have enough information to give you a direct specific solution but I would suggest that you can stitch the planes together and texture it all as one plane and you could also try to change the texturing options. Maybe this will help https://learnopengl.com/Getting-started/Textures
> 0 votes

# Answer
It sounds like what you want is what a photographer might call "image stitching", which is often used for creating panoramic images from multiple photographs. You might find that software that's designed for stitching together photos automatically works for your images.

Note that stitching the images together like that can take a while - there's a big search space to work out which bits of which images match each other, especially when the overlapping parts of the images may not be exactly identical. With photographs, those images could all have different brightness, rotation, lens distortion, etc.
> 0 votes

---
Tags: unity, textures, blending
---


title: Why is my game not built?

text:
# Question
Title: Why is my game not built?
I have a simple Unity game with a single scene, which I am trying to build for Windows:

When I click "build", I am prompted to select a folder. I choose an empty folder and click "Select Folder". Then I see some pop-up messages as well as this warning:

But, the folder remains empty - nothing is built there.

How can I debug this error?

EDIT: I tried to build from the command line:

```
Unity -batchmode -projectPath D:\gamedev-code\01-unity-basics -buildWindows64Player D:\GameBuilds\01-basics-windows\

```

I got an error:

```
Aborting batchmode due to failure:
Failed to build player.

```

which is not very helpful..

# Answer
> 2 votes
The problem was a compilation error in a script I did not use.

I did not notice it before, because the scene runs fine without this script.

I have learned that, when building a game, Unity tries to compile all the scripts - even those not in the scene.

---
Tags: unity, build-process
---


# Question
Title: How to detect intersections with only colliders and not use the physics engine?
**I do not want to use the physics engine**, I only want the collider to detect when they have entered into another collider, then I want to handle what happens to the objects.
Moving static colliders (colliders that do not attach to a rigidbody) around has a penalty, so how would I accomplish this without incurring a penalty for moving colliders around that do not attach to a rigidbody?
I could use a Kinematic Rigidbody Collider for this, but this seems kind of hacky since they are meant to be used in conjunction with Rigidbody Colliders (at least thats what their intention seems like from the manual). I have also looked into CharacterController, it says it "does not make use of Rigidbody physics", but it does not say how the physic system treats it which would come with a penalty if the physic system sees it as a static collider (as it uses a capsule collider with no rigidbody). I tested to see if it did have a penalty, but unless stated how it works within the physics system, it is just speculation which could lead to undesired results.
Other than a Kinematic Rigidbody Collider or CharacterController, is there any way to accomplish this in unity?

# Answer
> 1 votes
Yes, Unity has it own intersect method.

Attach a collider to your game objects that should check for collision. You do not have to use a Rigidbody for Bounds.Intersects. Also it works for both 2D and 3D

```
//If the first GameObject's Bounds enters the second GameObject's Bounds, output the message
if (collider.bounds.Intersects(collider2.bounds))
{
   Debug.Log("Bounds intersecting");
}

```

# Answer
> 0 votes
The penalty you pay for moving colliders or having rigidbodies is the work of updating the data structures that make intersection tests fast. If you want fast intersection tests (you do), then there's a great piece of code already in the engine that does that:

It's called the physics engine.

You could write your own parallel code that does the same thing the physics engine is already doing, but I can just about guarantee your version will not be an improvement over the battle-tested code that's already in there.

It's easy to set up a physics scene that gets the benefits you want from the physics engine without incurring work you don't want done:

* If you want to detect collisions without doing the work of collision resolution and imparting forces, use trigger colliders that ghost through objects without pushing them or being pushed.
* If you want to move an object with a collider manually by setting its position, rather than with physics influences, and don't want to process collision resolution with it or spend time integrating its momentum each timestep, give it a kinematic rigidbody. That's exactly what the kinematic mode exists for.
* If you want to move an object similar to a humanoid character, the CharacterController gives you a good starting point for that. It's built to play nicely with the physics system while giving you more control than you get out of the box with a kinematic body, saving you from writing some common boilerplate.

> this seems kind of hacky since they are meant to be used in conjunction with Rigidbody Colliders (at least thats what their intention seems like from the manual).

Don't develop games by hearsay, superstition, or what something "seems" like. Test it and measure the results.

Using kinematic bodies and trigger colliders works out of the box, supports all collider shapes, and has over a decade of testing and performance optimization put into it. It's very likely sufficient for your needs. So start there, profile, and measure whether there's a real problem with this approach that needs to be solved.

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


# Question
Title: FindObjectOfType vs FindFirstObjectByType
Unity has two functions, with seemingly identical purposes, for finding an object by type.

* **`Object.FindObjectOfType<T>()`** which has been around forever.

> The first active loaded object that matches the specified type. It returns null if no Object matches the type.

There's also an overloaded version which accepts a single boolean argument indicating whether to search inactive objects. `FindObjectOfType<T>(bool includeInactive)` .
* **`Object.FindFirstObjectByType<T>()`** which I think is newer:

> Returns the first active loaded object that matches the specified type. If no object matches the specified type, returns null.

There's also an overloaded version which accepts a single enum argument indicating whether to search inactive objects. `FindFirstObjectByType<T>(FindObjectsInactive findObjectsInactive)`;

These functions seem to serve identical purposes, with the only difference between them being that `FindFirstObjectByType()`'s overload (rather pointlessly) takes an enum argument instead of a boolean argument.

**What's the difference between these two functions? Why do both exist?**

# Answer
I thought of the answer while typing out the question:

There is another new function, `Object.FindAnyObjectByType<T>()` which serves a similar purpose. While `FindFirstObjectByType()` returns the "first" (oldest?) object of the specified type, `FindAnyObjectByType()` doesn't sort in a specific order and is therefore faster.

`FindFirstObjectByType()` is functionally identical to `FindObjectOfType()`; the reason it exists with a new name is to distinguish it from `FindAnyObjectByType()`.
> 0 votes

---
Tags: unity
---


# Question
Title: How do I add a pointer to my XR Interactor line visual?
I am setting up my project with XR Interaction toolkit. As usual, there are two red rays from the controllers after the set up as shown below.

However, I want the rays to appear exactly as it is in the image below.

The rays will be short and when I point to an object, a pointer appears like I have in the below image. I have played around with the **XR Interactor Line visual**. I was able to reduce the length and width of the rays but the pointer isn't there for interacting with objects.

Another attempt I made was to add **XR Interactor Reticle Visual** component to my controller. I then added sphere prefab to the **reticle prefab**. It looked like want I want but also could not interact with buttons like the normal ray would.

# Answer
> 0 votes
I figured this out too a couple of days back and just felt I should write how I did it.

If you don't already have an **XR Interactor Line Visual** component added to your controller, add it. I reduced the **Line Width**, Changed the **Color Gradient** to white and **Invalid Color Gradient** to grey, I also changed the **Line Length**.

For the **Reticle**, I created a **sphere** gameObject on my scene, removed the **sphere collider**, dragged it to my material, reduced the scale to **0.03** in all dimensions. If it doesn't work after this, change the sphere's Material to **\_defaultMat**.

---
Tags: unity, c#, raycasting, oculus
---


# Question
Title: How to compare a GameObject's component settings to those of the original Prefab
I have a Prefab with a number of Components, such as:

* Rect Transform
* Text Mesh Pro
* Sprite Renderer
* Box Collider 2D

I think Instantiate a GameObject using the Prefab, and configure it. As the GameObject is configured, some of the settings get changed:

* The Sprite of the Sprite Renderer is customized
* The text in the Text Mesh Pro object gets changed
* The height/width of the Rect Transform gets customized to match the above
* The Size and Offset of the Box Collider also gets customized to match

As the game progresses over time, some of these settings may continue to change. This continues until the GameObject is no longer needed.

I'm looking for a way to reset all the GameObject's component settings to match the original Prefab. That will allow me to scrub the GameObject, and set up Object Pooling.

Resetting the GameObject's settings pretty easy to do manually: I can just audit the code and make a list of all possible changes, and manually change each of the settings back to the default value.

I don't mind doing this work, but am wondering if there's an easy way to check my work.

1. Is there a way that I can easily compare a GameObject's component settings to a Prefab's component setting, and identify which ones are different?
2. Or alternatively, is there a way to check if the settings for two components are identical? Other than just visually inspecting both Components' Settings...

Or if there's an easier way to do all this, please let me know!

# Answer
**Part 1** indirection

"We can solve any problem by introducing an extra level of indirection."

There are many opportunities for modification of `the GameObject`:

1. "Instantiate a GameObject using the Prefab, and configure it."
2. "As the game progresses over time, some of these settings may continue to change."
3. "... and manually change each of the settings back to the default value."(before put it back to the pool)

The question now is you want to reduce the effort of manually reviewing code. Why is this a problem? Because the code to access `the GameObject` is everywhere. Currently your code is highly coupled.

In order to solve this, we need to confine the access to `the GameObject` to the same place, that is to say, we need to abstract and encapsulate `the GameObject`. You may be interested in Facade pattern:

> Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex underlying or structural code.

We need to create a class that manages `the GameObject`, specifying which interfaces are exposed, and all access to `the GameObject` must be done through this class instead of directly accessing its child nodes/internal information:

```
public class MyText : MonoBehaviour
{
    private RectTransform trans;
    private TextMeshPro textMeshPro;
    private SpriteRenderer renderer;
    private BoxCollider2D collider;

    void Awake()
    {
        trans = xxx.GetComponent<RectTransform>();
        textMeshPro = xxx.GetComponent<TextMeshPro>();
        renderer = xxx.GetComponent<SpriteRenderer>();
        collider = xxx.GetComponent<BoxCollider2D>();
    }
    public void Init(string text,Sprite sprite)
    {
        SetText(text);
        SetSprite(sprite);
    }
    public void Reset()
    {
        SetText("");
        SetSprite(null);
    }
    public void SetText(string text)
    {
        textMeshPro.text = text;
        collider...
        trans....
    }
    public void SetSprite(Sprite sprite)
    {
        renderer.sprite = sprite;
    }

}

```

In the pseudo-code above, only four methods are exposed, because the outside only needs to call these methods to control its functions.

> The height/width of the Rect Transform gets customized to match the above. The Size and Offset of the Box Collider also gets customized to match.

These are completely dependent on its text content, so they don't need to be exposed, but processed internally.

**Part 2** memory pool

The memory pool is completely used to optimize performance, and it is necessary to consider whether it achieves the purpose for different usage scenarios. Everything is subject to performance testing, but I have some guesses here.

1. Is it necessary to reset the object before putting it back into the mempool? If you initialize every time before use, then reset is not necessary.
2. Are objects put into the same memory pool **similar enough**? For example where does the current `Sprite` come from? If they are loaded from another place (disk) and placed on this object, then the consumption of **modifying the difference** of the object in is very large, in other words, they are not similar enough. Generally speaking, the consumption of reading data from the disk is relatively large, and the memory pool strategy should try to solve this part of the consumption. You can create different memory pools for objects holding different sprites, which can maximize their similarity.
3. What happens when the object is recycled to the memory pool? There are a few different ways to handle unused pool objects in Unity. Examples include setting Active, turning off component functionality (such as a particle system), or simply moving it offscreen. Different objects will have different performance, similarly, the test shall prevail.
> 1 votes

---
Tags: unity, serialization, object-pools
---


# Question
Title: How to replicate TextMesh Pro Gradient ScriptableObject Interface?
I'm creating a scriptable object to store the color scheme for each level in my Brick Breaker game. There are a lot of options for how to input colors, but the way that TextMesh Pro does it for their Color Gradients is a great starting point. In their scriptable object (TMP \> Scripts \> Runtime \> TMP\_ColorGradient.cs), **each row is a set of two colors, where each color can either be input using the color selector or by pasting in the hexidecimal value**. When one of the fields is updated, the other field is updated automatically.

Sadly, the script file doesn't seem to contain the logic to recreate these input fields. I tried simply copying the file and renaming it, but the color format returns to the default ScriptableObject / SerializedField input style for Colors, namely without the text input option.

**Does anyone know how to recreate TMP's input fields?**

In addition to Stack Exchange's Similar Questions step, here are all the searches I did looking for answers: Search 01 - "tmp color gradient input" unity color serializable how to connect two serializable variables in unity tmp color gradient file

# Answer
> 1 votes
There's a very similar example in the ColorUtility.TryParseHtmlString doc page.

The main idea is to have a single `Color` field that is drawn with a custom `PropertyDrawer`, so the value of both representations is always the same.

As for having two properties in the same row, I think EditorGUILayout.BeginHorizontal should do.

Edit to address the comment:

The empty class is just declaring an Attribute (the things that go in square brackets). It's empty because the attribute itself doesn't do anything, it's just a tag that you apply to an existing field or property. So far, we are just saying "the attribute `ColorHtmlPropertyAttribute` exists".

Then, something else can use reflection to check "hey, does this specific field have the attribute `ColorHtmlPropertyAttribute`?" and, if it does, it can treat that field in any special way it wants.

In this case, the thing making that check is the code responsible for drawing the inspector (which we did not write), so it's a bit more confusing, but also way easier. Instead of writing the reflection stuff ourselves, we are just telling the inspector to use the `ColorHtmlPropertyDrawer` on any field that is marked with `ColorHtmlPropertyAttribute` with the line:

`[CustomPropertyDrawer(typeof(ColorHtmlPropertyAttribute))]`

And everything else is handled under the hood.

The last confusing thing about this whole attribute situation is that, in the example, the field is tagged `[ColorHtmlProperty]`, rather than  `[ColorHtmlPropertyAttribute]`, which is the name that we declared. This is some prime C# nonsense for you, where if you declare an attribute whose name ends with "Attribute" you are actually allowed to skip that when using it, for some reason. I hate it :)

And as for why there are to assignment statements, it's just because the change can have ocurred in any of the two places in the inspector. If you picked a color, the new value comes directly from the `EditorGUI.ColorField()` call, but if you wrote the html string you have to take the return value of the `EditorGUI.TextField()` call and parse it.

---
Tags: unity, color, text-mesh-pro, scriptable-object
---


# Question
Title: Is there a way to completely delete a specific Object Variable from an existing GameObject?
When my GameObjects have run their course, I would like to scrub them and prepare them to go back into an Object Pool.

Each of my main GameObjects has around ~20-30 Object Variables. Part of the scrubbing process is cleaning up all of the Object Variables.

I can reset some of the Object Variables to their default values, or even set them equal to Null.

But some of my Object Variables aren't always used for every GameObject.

Is there a way to completely delete a specific Object Variable from an existing GameObject? Or is my only option to set it to a default and/or Null value...

Thank you!

# Answer
No, there is not.

C# is a strongly typed language. That means every object is of a certain type, and that type determines what variables it has. Every object retains its type throughout its lifetime; you can not change the type of an object, you can only recreate it as a new object of a different type. And because the type of an object is unchangeable, and the type says what variables an object has, you can not add or remove variables of an existing object. All you can do is set the values of those variables to something that is to be interpreted as "initial", "unknown" or "undefined".

However, a general note about object pools: In many cases there is no reason to clean up an object when you move it to the pool. An object in the pool should not be doing anything, so its values shouldn't matter. When you retrieve the object from the pool, you are going to overwrite most of its values anyway. So there is no point in overwriting them twice. So the method you use to retrieve an object from the pool can fulfill both purposes: Overwrite those values that are required for the new identity of the object, and clear those which are not.
> 2 votes

---
Tags: unity, gameobject
---


# Question
Title: Procedural placement of objects with constraints
I need to procedurally place some objects on a 2D plane based on constraints like:

1. Two objects should not be placed on the same line.
2. On specific object should always be placed on the border of the plane.
3. Another object should be placed close to the center (in some range).
4. Etc.

There are a lot of topics on procedural generation of landscapes/heightmaps or environmental objects (like trees, stones, rivers, etc.), but not too much on this topic. I've found the wave function collapse approach and it feels like it can solve such a problem, but I'm not sure.

Maybe there are some simpler algorithms to solve such a constraint-based placement on grids or maybe non-grid landscapes that can be adopted.

# Answer
There are a lot of factors here like: object density, size, speed, memory, and storage types and amount.

For this example, I will assume "same line" is means both X and Y axes, the objects have the same size, should be fully populated(as many as possible), and the final size is square. If it is not square, some "holes" lines without objects will appear, populated to the fullest possible.

The grid is defined as the coordinates of the top left (X,Y) of each object scaled, integer divided by the object size (WIDTH, HEIGHT).

There is no requirement that the sprite WIDTH == HEIGHT for the grid to work.

`MinDimension` is the smaller of `WorldWidth / WIDTH` (`BoundX`), or `WorldHeight / HEIGHT` (`BoundY)`.

For a single screen without scrolling, replace `WorldWidth` with `ScreenWidth`; the same goes for `Height`

Initialize `Grid` as a 2D array of zeroes. X,Y for row major Set the diagonals to 1.

```
for(int i = 0; i < MinDimension; i++)  Grid1[i][i] = 1;

```

Randomly swap the rows:

The next lines become language dependant. This example is in C# to describe the operation in simplistic terms.

```
for (int j = 0; j < MinDimension * 2)
{
   int tmpR = rnd.Next(MinDimension);
   var tmp = Grid[j];
   Grid[tmpR] = Grid[j];
   Grid[j] = Grid[tmpR];
}

```

Other languages may require en element by element swap in a loop to accomplish the same thing.

The rest of the conditions fall during the object creation loops:

> Another object should be placed close to the center (in some range).

There is some uncertainty about this requirement conflicting with the first requirement. The word "another" meaning in addition to allows violation of the first rule. If not it will require randomly (in some range) selecting the grid close to the "center" square and zeroing the the rest of the row and column, and creating the object outside of the following loop.

Loop through the grid creating objects:

```
//prefer >> 1 over /2 if supported in the next lines(shown both ways):

CenterObjectX = rnd.Next(range) + BoundX / 2; //in some range.

CenterObjectY = rnd.Next(range) + BoundY >> 1; //in some range.

for(y = 0; y < BoundY; y++)
   for (x = 0; x < BoundX)
   {
      if (y == 0 || y == BoundY -1 || x == 0 || x == BoundX - 1)
      {
         if(Grid[x][y] == 1)
            //Create border object at x,y.
      }
      else
      {
         // check for additional center object position:
         if(CenterObjectX = x && CenterObjectY == y)
            // create center object at x,y
         else
            //create regular object at x,y
      }
   }

```
> 0 votes

---
Tags: procedural-generation
---


# Question
Title: Mouse input accumulates different number points at different frame rates
I'm working on a basic Vulkan renderer that's presently relying on Win32 raw mouse input for camera pitch and yaw. It's all very basic, but what I've noticed is that at higher frame rates, I'm accumulating fewer "points" of movement with comparable gestures of the mouse than I do at lower frame rates. This manifests as fewer degrees of rotation for the camera for a given amount of mouse input.

A `WM_INPUT` message will propagate the `lLastX` and `lLastY` values out via my event system untouched. The window receiving these messages is DPI aware (I've got 150% scaling on my development machine).

```
auto const *input = reinterpret_cast<::RAWINPUT *>(_raw_message);
switch(input->header.dwType) {
    case RIM_TYPEMOUSE: {
        auto const &mouse = input->data.mouse;
        if(mouse.lLastX != 0 || mouse.lLastY != 0) {
            EventBroker::emit<MouseMoveEvent>(
                mouse.lLastX,
                mouse.lLastY
            );
        }
    }
    default:
        break;
}

```

And the game code just adds those values to the camera's tracked pitch and yaw angles, accounting for frame time and a base movement speed. This camera setup is basically identical to that from the LearnOpenGL camera chapter.

```
void Demo::update() {
    auto const mouse_speed = _cam_data.mouse_speed * Timekeeper::frametime();
    _cam_data.pitch += _mouse.y_offset * mouse_speed;
    _cam_data.yaw   += _mouse.x_offset * mouse_speed;

    _mouse.y_offset = 0;
    _mouse.x_offset = 0;

    if(_cam_data.pitch > 89.9f)       { _cam_data.pitch = 89.9f;  }
    else if(_cam_data.pitch < -89.9f) { _cam_data.pitch = -89.9f; }

    auto const cos_yaw   = std::cosf(math::radians(_cam_data.yaw));
    auto const sin_yaw   = std::sinf(math::radians(_cam_data.yaw));
    auto const cos_pitch = std::cosf(math::radians(_cam_data.pitch));
    auto const sin_pitch = std::sinf(math::radians(_cam_data.pitch));

    _cam_data.forward.x = cos_yaw * cos_pitch;
    _cam_data.forward.y = sin_pitch;
    _cam_data.forward.z = sin_yaw * cos_pitch;

    _cam_data.forward = math::normalize(_cam_data.forward);
    _cam_data.side = math::normalize(
        math::cross(_cam_data.forward, Vec4::unit_y)
    );
    _cam_data.up = math::cross(_cam_data.side, _cam_data.forward);

    auto const kb_speed = _cam_data.kb_speed * Timekeeper::frametime();
    if(_kb.w)      { _cam_data.pos += _cam_data.forward * kb_speed; }
    else if(_kb.s) { _cam_data.pos -= _cam_data.forward * kb_speed; }
    if(_kb.a)      { _cam_data.pos -= _cam_data.side    * kb_speed; }
    else if(_kb.d) { _cam_data.pos += _cam_data.side    * kb_speed; }

    _persp_camera.orient(
        _cam_data.pos,
        _cam_data.forward,
        _cam_data.side,
        _cam_data.up
    );

    _vp_matrices.view = _persp_camera.view_matrix();
    _vp_matrices.proj = _persp_camera.proj_matrix();

    BufferTools::update_buffer(
        _vp_ubos[Swapchain::image_index()],
        &_vp_matrices
    );
}

```

In this case, `_cam_data.mouse_speed` happens to be `5.0f`. Nothing too fancy. I expect to achieve a similar visual movement for a similar mouse input regardless of frame rate.

So what am I fundamentally misunderstanding here? (Arithmetic, you say? Of course.) Shouldn't sampling once per frame, then multiplying by the frame time account for the different values one gets for the increased polling rate? Or is there more OS faffery behind the scenes? I've used raw mouse input several times in past projects, but it appears I only ever tested with vsync on. Or I was doing something different, but I can't track that difference down myself.

EDIT: Just to drive the arithmetic point home, I see that if I multiply the `WM_INPUT` mouse positions by a fixed value (rather than the frame time) higher frame rates create faster camera movement. Surely there's a simple(r?) solution to divorce the frame rate from the rotation rate.

# Answer
The problem is here:

```
auto const mouse_speed = _cam_data.mouse_speed * Timekeeper::frametime();

```

Multiplying by the frame duration is appropriate when you want to take a speed of movement and integrate it to get a displacement in position over that time interval.

But `_mouse.x_offset` and `_mouse.y_offset` are not speeds, they're *already* displacements measured over that time interval.

Assuming your hand is moving the mouse at a constant speed, over a short frame it will move a smaller distance, and over a long frame it will move a longer distance, so `x_offset` and `y_offset` are already scaled in proportion to the elapsed time, just by the nature of the way you're measuring them.

When you multiply them by delta time, you're "double dipping", so the result you get is the true speed multiplied by the *square* of the frame interval, yielding smaller-than-desired values on short frames and longer-than-desired values on long frames. (This is effectively the antiderivative of displacement... if that were a thing)

You'll note that while the OpenGL tutorial you linked does multiply camera speed by delta time when animating the camera on an auto-advancing orbit, they drop this when they introduce mouse control. Instead they scale the mouse input by a different variable, `sensitivity`, which is not scaled by delta time.

I know you said that multiplying by a constant speed without delta time seemed to have the opposite problem, but I'd recommend trying again, under a more controlled test (say, make a line of tick marks on a sheet of paper and run your mouse over them in time with a stopwatch). Subtle topics like control feel are very susceptible to the observer effect, where if we expect to see a particular outcome, we'll tend to perceive that outcome, whether or not it's verifiably there.

Here, you had a good reason to expect that not multiplying by delta time would result in exaggerated movement at high frame rates, because that's exactly what happens for most other kinds of input. So that prior belief can make evidence suggestive of faster movement jump out as confirmatory, or even lead you to subconsciously move your mouse faster to get the expected result.
> 1 votes

---
Tags: c++, windows, mouse, win32
---


# Question
Title: Explain how Inigo Quilez calculates SDF box normals
Inigo Quilez's website has a page of 3D ray-surface intersectors, one of which is for a basic 3D box:

```
// axis aligned box centered at the origin, with size boxSize
vec2 boxIntersection( in vec3 ro, in vec3 rd, vec3 boxSize, out vec3 outNormal )
{
    vec3 m = 1.0/rd; // can precompute if traversing a set of aligned boxes
    vec3 n = m*ro;   // can precompute if traversing a set of aligned boxes
    vec3 k = abs(m)*boxSize;
    vec3 t1 = -n - k;
    vec3 t2 = -n + k;
    float tN = max( max( t1.x, t1.y ), t1.z );
    float tF = min( min( t2.x, t2.y ), t2.z );
    if( tN>tF || tF<0.0) return vec2(-1.0); // no intersection
    outNormal = (tN>0.0) ? step(vec3(tN),t1)) : // ro ouside the box
                           step(t2,vec3(tF)));  // ro inside the box
    outNormal *= -sign(rd);
    return vec2( tN, tF );
}

```

In addition to calculating the intersection, it also calculates the surface normal at the point of intersection. Calculating the normal is the part I'm interested in. I would like to understand how it does this, but the page doesn't break down the math at all, and I haven't found any other sources that do (also, not understanding the process limits my understanding of what to search for).

Some parts make sense conceptually, like the calculation of near/far intersection points for the ray. But the calculation of constants that make up that calculation are lost on me. Why calculate `1.0/ray_direction`? How is `ray_origin/ray_direction` useful? Etc.

I'd like to understand how this works, rather than treat it like a black box.

**Edit:** I found another version, modified to only return normals, but shares many of the same calculations. It may be easier to explain, I just wish I knew how it worked.

```
vec3 boxNormal( in vec3 ro, in vec3 rd, vec3 boxSize)
{
    vec3 m = 1.0/rd;
    vec3 n = m*ro;
    vec3 k = abs(m)*boxSize;
    vec3 t1 = -n - k;
    return -sign(rd)*step(t1.yzx,t1.xyz)*step(t1.zxy,t1.xyz);
}

```

# Answer
We are looking at the function `boxIntersection`.

I'll reiterate the information from the comment:

> // axis aligned box centered at the origin, with size boxSize

* We are working with a box.
* Centered at the origin.
* And it is axis aligned.

And let us read the parameter names:

* `ro` is ray origin.
* `rd` is ray direction.
* `boxSize` is the size of the box.
* `outNormal` is the computed normal.

---

We will pretend for an instant that we don't have the code and see how we can approach this… By the way, I'll be writing pseudo-code.

As you probably know, the points along the ray can be described like this:

```
pt = ro + rd * t

```

However, let us step back a bit, and let us work on individual axis:

```
pt.x = ro.x + rd.x * t
pt.y = ro.y + rd.y * t
pt.z = ro.z + rd.z * t

```

And, of course, we want to compute the collision of that ray with the box. Let us start with just one of its planes... Since the box is axis aligned, and `boxSize` has its dimensions, there should be a plane of the box at `boxSize.x * 0.5`... Except that does not seem to match the shader. It appears there is a plane at `boxSize.x` instead. Which lead us to this equation:

```
ro.x + rd.x * t = boxSize.x

```

If we solve for `t`, we get this:

```
t = (boxSize.x - ro.x) / rd.x

```

If we do the same for all planes of the box we have:

```
ta = (-boxSize.x - ro.x) / rd.x
tb = (-boxSize.y - ro.y) / rd.y
tc = (-boxSize.z - ro.z) / rd.z
td = (boxSize.x - ro.x) / rd.x
te = (boxSize.y - ro.y) / rd.y
tf = (boxSize.z - ro.z) / rd.z

```

Which we can do in two lines:

```
t1 = (-boxSize - ro) / rd
t2 = (boxSize - ro) / rd

```

---

We can further approach the code we are trying to understand one step at a time.

First, in both lines we divide by `rd`, which is the same as multiplying by `1.0/rd`, we can pre-compute that:

```
m = 1.0/rd
t1 = (-boxSize - ro) * m
t2 = (boxSize - ro) * m

```

We can distribute those products:

```
m = 1.0/rd
t1 = m * -boxSize - m * ro
t2 = m * boxSize - m * ro

```

And `m * ro` is something else we can also pre-compute:

```
m = 1.0/rd
n = m * ro
t1 = m * -boxSize - n
t2 = m * boxSize - n

```

And we pre-compute `m * boxSize`:

```
m = 1.0/rd
n = m * ro
k = m * boxSize
t1 = -k - n
t2 = k - n

```

Ok, ok, let us write `n` first so it looks like the code we want:

```
m = 1.0/rd
n = m * ro
k = m * boxSize
t1 = - n - k
t2 = - n + k

```

We are missing an absolute value, we will get to that.

---

At this point it might help to have a geometric interpretation of these variables...

It might help to look at only one axis again, since these `t1` and `t2` should not be interpreted as position or vectors in space:

```
m.x = 1.0/rd.x
n.x = m.x * ro.x
k.x = m.x * boxSize.x
t1.x = - n.x - k.x
t2.x = - n.x + k.x

```

Remember that the `t` values (`t1.x` and `t2.x` for the `x` axis) are parameters to find the points along the ray. In this formula:

```
pt = ro + rd * t

```

One way of thinking of that is this: `t` tells you how many `rd`s the ray needs to advance to reach the point.

Thus, we are working in `rd` units. Hence, it makes sense that we divide by `rd`.

As per the other variables - once we stop worrying about the division by `rd` \- we can see that `k` is the separation between the planes of the box in `rd` units. And since the box is centered the origin, but the ray starts at `ro`, we also need to offset that by the `ro`... but also in `rd` units, i.e. `n`.

---

With that understanding we can understand that adding the absolute value to `k`, as shown below, would give us the same `t` values, it just changes the order in which we get them.

```
m = 1.0/rd
n = m * ro
k = abs(m) * boxSize
t1 = - n - k
t2 = - n + k

```

In what order do we get the `t` values? Well - assuming that `boxSize` is positive, which is not checked - `k` should be positive.

And thus `t1` would have smaller distances than `t2`. We can think of `t2` as the back face of the box, and `t1` as the front face.

We would not have gotten the back and front faces separated like this without the absolute value.

---

Let us also reason about the sign of `n`. In order to do so, it might help to change from this:

```
m = 1.0/rd
n = m * ro

```

To this:

```
n = ro / rd

```

And, again, let us look at only one axis:

```
n.x = ro.x / rd.x

```

So a components of `n` is positive if the component of `ro` and `rd` have the same sign. In other words, if the ray is going away from the origin.

Ergo, the components of `- n` are positive when the ray is looking towards the origin.

This makes sense given that when the box (which is centered at the origin) is behind the ray origin, the ray would have to travel backwards to intercept it. So when the ray is looking away from the origin (the center of the box) we get a negative `- n`. In that situation the ray might still collide with the box, if it is large enough. Which would be a case of `t2 = - n + k` (the back face), never `t1 = - n - k` (because - remember - `k` should be positive… unless the size of the box is inverted… And the intersection should be in front of the ray, and thus a positive `t`).

---

Back to the code:

```
m = 1.0/rd           // rd unit conversion
n = m * ro           // origin in rd steps
k = abs(m) * boxSize // box size in rd steps
t1 = - n - k         // front face ts
t2 = - n + k         // back face ts

```

Let us narrow our search for the correct `t`

I want you to imagine the box, and you are looking at one of the cornets. The planes of the front faces extend to infinity.

If we get the minimum (the first plane that the ray intersect) we would see these planes that cover the whole picture partitioning it in three and meeting at the corner of the box. The corner of the box is the point further away from the camera that we see.

But behind the front faces of the box, the box does not have any other front faces. In fact if we get the maximum, we get the planes coming out of the corner of the box and escaping to infinity (they won't cover the whole picture, at least not in perspective projection). The corner of the box is the point closer to the camera that we see.

So we want… The maximum:

```
m = 1.0/rd           // rd unit conversion
n = m * ro           // origin in rd steps
k = abs(m) * boxSize // box size in rd steps
t1 = - n - k         // front face ts
t2 = - n + k         // back face ts
front_t = max(t1.x, max(t1.y, t1.z))

```

And for the back faces we want the opposite:

```
m = 1.0/rd           // rd unit conversion
n = m * ro           // origin in rd steps
k = abs(m) * boxSize // box size in rd steps
t1 = - n - k         // front face ts
t2 = - n + k         // back face ts
front_t = max(t1.x, t1.y, t1.z)
back_t = min(t2.x, t2.y, t2.z)

```

Well, except the code does it a bit different:

```
m = 1.0/rd           // rd unit conversion
n = m * ro           // origin in rd steps
k = abs(m) * boxSize // box size in rd steps
t1 = - n - k         // front face ts
t2 = - n + k         // back face ts
tN = max(max(t1.x, t1.y), t1.z)
tF = min(min(t2.x, t2.y), t2.z)

```

Now we understand that the `N` in `tN` stands for `NEAR`, and the `F` in `tF` stands for `FAR`.

---

The next line I want to read from the code:

```
if( tN>tF || tF<0.0) return vec2(-1.0); // no intersection

```

This is checking two things:

* If the near face of the box is further away from the ray origin than the far face of the box `tN>tF`, there is no intersection.

How can `tN>tF` happen? Well, there are two situations:

+ Remember that we are considering these to be near and far (front and back) faces of the box based on an assumption of the sign of `k`, which is based on an assumption on the sign of `boxSize`. So `tN>tF` happens if the box is inverted (inside out).
    + The near planes also extend away from the camera, so you will find intersections with them that are behind the far planes. Similarly, the far planes also extend towards the camera… Thus, `tN>tF` happens out of the bounds of the box.
* If the far face of the box is behind the ray origin `tF<0.0` there is no intersection.

---

First version of the normal computation:

```
    outNormal = (tN>0.0) ? step(vec3(tN),t1)) : // ro ouside the box
                           step(t2,vec3(tF)));  // ro inside the box

```

I don't think that is right. The parenthesis do not seem to match.

Anyway, let us start by making sense of the comments. When `tN>0.0` it means that the near face is in front of the ray, and thus the ray origin is outside of the box.

Now, the `step` function will return `0.0` or `1.0` depending on the comparison of the arguments. In particular `step(edge, x)`

Let us expand `step(vec3(tN),t1)` to its components:

```
vec3(
    // 1.0 if tN < t1.x otherwise 0.0
    step(tN,t1.x),

    // 1.0 if tN < t1.y otherwise 0.0
    step(tN,t1.y),

    // 1.0 if tN < t1.z otherwise 0.0
    step(tN,t1.z)
)

```

Instead of writing `1.0 if blah otherwise 0.0`, I'll write `blah`, and take that `true` is `1.0` and `false` is `0.0`:

```
vec3(
    // tN < t1.x
    step(tN,t1.x),

    // tN < t1.y
    step(tN,t1.y),

    // tN < t1.z
    step(tN,t1.z)
)

```

So we get a `1.0` for any component such that `tN` is smaller than it. In other words, we get a `1.0` for any component greater or equal to `tN`.

As we know, `tN` is the maximum of `t1.x`, `t1.y`, and `t1.z`. So we get a `1.0` for any component greater or equal to the maximum of the components.

This means you get `(1.0, 1.0, 1.0)` for the corners. For the sides of the cube you get a `1.0` along the axis normal to the face. And for the edges between two faces you get a `1.0` along the axis normal of each face that meet.

For the other case we do similarly with `tF`, except the order is flipped because `tF` have the minimum not the maximum.

Thus, this (parenthesis fixed by me):

```
    outNormal = (tN>0.0) ? step(vec3(tN),t1): // ro ouside the box
                           step(t2,vec3(tF)); // ro inside the box

```

Gives you a vector with a `1.0` along the axis normal to each face the ray hits.

And the next line:

```
outNormal *= -sign(rd);

```

Gives it the opposite sign to the direction of the ray.

---

Second version of the normal computation:

```
return -sign(rd)*step(t1.yzx,t1.xyz)*step(t1.zxy,t1.xyz);

```

Again, the factor `-sign(rd)` gives us the opposite sign to the direction of the ray.

The rest is swizzling trickery, let us break it down. We have:

```
return -sign(rd)
    * step(t1.yzx,t1.xyz)
    * step(t1.zxy,t1.xyz);

```

Which is the same as:

```
return -sign(rd)
    * vec3(
        // t1.y < t1.x
        step(t1.y,t1.x),

        // t1.z < t1.y
        step(t1.z,t1.y),

        // t1.x < t1.z
        step(t1.x,t1.z)
    )
    * vec3(
        // t1.z < t1.x
        step(t1.z,t1.x),

        // t1.x < t1.y
        step(t1.x,t1.y),

        // t1.y < t1.z
        step(t1.y,t1.z)
    );

```

I remind you that when the expression I wrote is `true` we have a `1.0`, otherwise it is a `0.0`. Therefore, when we multiply them, it is equivalent to doing an `AND` on the expressions.

So, the above, is the same as:

```
return -sign(rd)
    * vec3(
        // t1.y < t1.x AND t1.z < t1.x
        step(t1.y,t1.x) * step(t1.z,t1.x),

        // t1.z < t1.y AND t1.x < t1.y
        step(t1.z,t1.y) * step(t1.x,t1.y),

        // t1.x < t1.z AND t1.y < t1.z
        step(t1.x,t1.z) * step(t1.y,t1.z)
    );

```

Which means this is what we are doing:

```
return -sign(rd)
    * vec3(
        // t1.x is the maximum
        step(t1.y,t1.x) * step(t1.z,t1.x),

        // t1.y is the maximum
        step(t1.z,t1.y) * step(t1.x,t1.y),

        // t1.z is the maximum
        step(t1.x,t1.z) * step(t1.y,t1.z)
    );

```

Notice that this code only consider the front faces. Thus it will work correctly as long as the origin of the ray is outside the box.

Although the opposite faces have the same normal, when the ray is inside the box, this code would be selecting the wrong one.

---

I found a third version of the code in Box - intersection. This version also comments on the checking both near and far faces:

```
    #if 1
    // this works as long as the ray origin is not inside the box
    vec4 res = vec4(tN, step(tN,t1) );
    #else
    // use this instead if your rays origin can be inside the box
    vec4 res = (tN>0.0) ? vec4( tN, step(vec3(tN),t1)) :
                          vec4( tF, step(t2,vec3(tF)));
    #endif

```

That version of the code also takes two matrices which represents transformation from and to the box space. *Which are used to encode rotation and translation of the box.* The code converts the ray into box space, and proceeds as usual, then converts the result back to ray space.
> 2 votes

# Answer
> Why calculate 1.0/ray\_direction?

```
m = 1.0/rd;

```

This allows the slower division operation to be treated as a multiply later. (I do not fully understand the correctness of the zero handling, but if it works...)

```
vec3 n = m*ro;` this is `n=ro/rd;

```

Scale the rays origin by the raycast, this scales the normalized ray per box axis.

```
vec3 k = abs(m)*boxSize;

```

This line scales the size of the box to the "rd" space. The `abs` is needed since the size is direction independent.

```
vec3 t1 = -n - k;
vec3 t2 = -n + k;

```

Translate the size about the normalized axis.

This set gives the bounds(top left and bottom right, or top right and bottom left ...(+-z expansion) due to the abs) of the original box in terms of the ray "normalized" vector. The `-n`  term is arbitrary, but used later in the collision check.

```
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );

```

This code gives the axis independent 2D bounds, from the transformed size of the box.

''' if( tN\>tF || tF\<0.0) return vec2(-1.0); // no intersection '''

Read the previous line as if the minimum of any element is greater than the maximum of any element or the maximum does not cross the new origin(+n), a collision has not occurred. This seems odd, but remember the (-n from before).

The `tN` and `tF` are 2 projections of the cube into 2d space, either contains it completely(`tN>tF`), or partially crosses(tF\<0.0),
> 1 votes

# Answer
The other answers do a great job of showing the in-depth mathematical derivation, so what I want to try here is to build some *intuition* for how this works:

It's parameterizing the problem in terms of *time*.

You can think of the ray as a particle that starts at position `ro` ("ray origin") relative to the center of the box and moves with constant velocity `rd` ("ray direction") over time. We can imagine this velocity being measured in metres per second, though the units are arbitrary since we'll fast forward along the ray's entire future in one instantaneous pass. To find the intersection (and the normal), we want to know at what time `t` that particle hits the box.

To do this, we need a way to convert between distances and time, which is what this line does:

```
vec3 m = 1.0/rd;

```

`m` is a component-wise reciprocal of the velocity, so `m.x` answers the question "how many seconds does it take the particle to cross +1 unit along the x axis?" (this time can be negative if `rd.x` is negative, meaning you'd have to go back into the past / backwards along the ray to move right along the x axis, if the ray is pointing left). This gives us our exchange rate between distance and time.

```
vec3 n = m*ro;

```

This converts the ray position into a time, for each component:`-n.x` answers the question "How long will it take the particle to reach the `x=0` plane?" (negative because `ro` is the vector from the box center to the ray origin, so it's measuring the distance backwards. That's why `n` always appears with a minus sign after this)

```
vec3 k = abs(m)*boxSize;

```

This applies a similar space-to-time conversion to the box dimensions, answering "how long does it take to get from the center of the box to one side?" along each axis. Here, `boxSize` is the box's half-extents, the distance from each side to the center.

From here it helps to think of the box as being bordered by six planes: three pairs of half-spaces like: `-boxSize.x <= x <= boxSize.x`, for each axis. From a given ray start point, three of those planes are on the "near" side of the box to us, and three of those planes are on the "far" side. To enter the box, we need to pass into all three near planes before we exit any of the far planes, otherwise we miss the box.

The next two variables give us the entry and exit times for each plane/half-space:

```
vec3 t1 = -n - k;
vec3 t2 = -n + k;

```

`t1` is the time it takes to reach the center plane minus the time it takes to travel between the center and one side, so that's the time when the particle enters the plane defining the near side of the box, on each axis.

Similarly, `t2` is the time when the particle exits the plane defining the far side of the box, on each axis.

But we don't need to be inside just one of these planes/half-spaces, we need to be inside all six at once to actually be in the box. So now we need to combine our per-axis calculations into an assessment for the box as a whole:

```
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );

```

`tN` ("time - near") is the first moment when the particle is on the "inside" of all three near planes. Ie. the latest time-of-entry for any one of the three near half-spaces.

`tF` ("time - far") is the earliest moment the particle exits any of the three far planes.

```
if( tN>tF || tF<0.0) return vec2(-1.0); // no intersection

```

If `tF` already happened in the past, then our ray started outside the box pointing away from it. If `tN` is greater than `tF`, then we pass by the box completely on one axis before we start to overlap it on another. Either way, we miss.

Otherwise, the particle does hit the box at time `tN`, which means we have an intersection point at position `ro + rd * tN`. But that might be in the past if `tN` is negative, meaning the ray origin was already inside the box.

In the case where `tN` is positive, we have a conventional intersection with whichever of the near planes we entered last:

```
outNormal = (tN>0.0) ? step(vec3(tN),t1)) : // ro ouside the box

```

This compares the last-entry time `tN` against the three entry times we used to compute it. This `step` function will return 1 on any axis that matches `tN` (or exceeds it, but that can't happen here since `tN` is the maximum of `t1`'s three components), and zero on the other axes. So if you hit the box from a side perpendicular to the x axis, you get a 1 in the first component: (1, 0, 0).

We can only hit a face that's pointing opposite our direction of motion though, so the `outNormal *= -sign(rd);` line fixes this into (-1, 0, 0) if we were traveling right (and so hit the side of the box facing left).

Note that you could get a ±1 on two or even all three axes if you cross two or three of the planes at the exact same time — ie. you hit the box exactly edge-on or corner-on. But that will be vanishingly rare.

In the event we start inside the box, we still need a value for `outNormal`, even though we don't hit a face as usual. In the first code you show, the other branch of the ternary expression does basically the same thing with the exit times, to give you the normal of the "inside" face of the box that the ray will exit through: `step(t2,vec3(tF)))`

The second code you show doesn't have a special case for starting inside the box, and always gives you the normal of the face you entered through, even if that entry happened "in the past" / "behind" the start of the ray.
> 1 votes

---
Tags: raycasting, normals, signed-distance-field
---


title: Unity best practices for 3D tilemap

text:
# Question
Title: Unity best practices for 3D tilemap
I looked at the forums and found out that it is not recommended to use the terrain system for the mobile platform. So then I decided to have a single plane as a "terrain" with single ground color. But I want to implement that the player can draw on that plane different tiles by grid, for example, a road tile. Or should I make whole "terrain" by the tiles and just replace texture when player draw? Is there any other methods?

# Answer
> -1 votes
I didn't end up using unity's tilemap system, I did my own like this:

Create your map with game objects, each game object has a sprite of the tile graphic. You can change the tile sprite easily and as often as you like then.

---
Tags: unity, textures, tiles, mobile, grid
---


# Question
Title: How can I use Body tracking in Android using ARCore or some other libraries?
I know that `ARCore` on Android **doesn't support Body Tracking** like `ARKit` does. But is there some alternative or workaround to achieve it? Some other **SDKs or Libraries** or maybe even if there is some way to do it through ARCore itself?

To make it clearer I plan to use something like this in an AR game for Android. I plan to develop it in `Unity 2019.4.x`.

My search result in Google didn't yield a useful result as it gets mixed with ARCore Motion Tracking (which isn't what I am talking about here) or implementation with ARKit. But I got a little hope that there might be some way out after reading this post on Unity Forums.

# Answer
> 1 votes
I am doing something similar to Father.io for my final year project for uni.

The closest solution that I can come up with is using a third-party application/addon such as;

* OpenCV
* Tensorflow
* Vuforia

These are the first three that spring to mind and most seem to be based on OpenCV any way.

If I happen to come across a tutorial of how to implement it, I'll try and link it here.

Happy hunting.

---
Tags: unity, android, augmented-reality
---


# Question
Title: Can an Immersive Sim be in third person?
I am planning out a video game which I will make in the future. It is a fantasy RPG, and it involves multiple choices, systematic enviornments, and many explorable regions. In addition, it will be in a top-down (Eagle's Eye) kind of format, similar to games such as Graveyard Shift or Stardew Valley. However, when planning out how it would be like, I happened to notice that it contains a lot of characteristics that could consider it as an immersive sim. Around this time, I am also thinking of making it a hybrid between open-world and immersive sim. However, one feature that make me unsure is that the camera is in third-person, and just that it is also top-down.

Is it possible for an Immersive Sim to be in third-person, and still be considered an Immersive Sim?

# Answer
> Is it possible for an Immersive Sim to be in third-person, and still be considered an Immersive Sim?

You are free to express yourself and your game anyway that you see fit.

**Never attempt to constrain your vision to accepted norms.**

Remakes are nice, but new is better, even if it defies simple description to your investors.
> 1 votes

# Answer
## The pragmatic answer

Being pragmatic, video game genres are labels (tags) that people use to find said video games.

*These labels or tags don't need to be mutually exclusive. And there might be synonyms. That last part should be obvious once you consider the range of language and cultures of the world.*

People are going to find your game by the genre labels you pick on whatever distribution platform you choose. And thus, you should pick labels that have games that are similar to it.

This also suggest that the criteria for what makes a game of an specific genre is constantly evolving.

So, chiefly, the genre is about player expectations. People might feel betrayed if they purchase something labelled "Immersive Sim" but don't get something that resembles their idea of "Immersive Sim".

It also also about skill transference. Games of a genre build on top of an existing library, and expect some basic familiarity with the mechanics※, which they can use as affordances in their game design.

※: It is very rare that a game targets absolute beginners, and teach the mechanics from the ground up. This is, in part, because the target audience that already knows what they want, are willing to pay for it, and are vocal about it… Are not the beginners.

Thus you can answer you question by looking at other games in the genre. This should not be a determinant for your game design, but you might want to be careful when picking the genre labels.

---

But can you find an "Immersive Sim" label on your intended distribution platform? Chances are you can't. Many people have played "Immersive Sim" without knowing the term. And thus, from a pragmatic point of view, the exercise might be futile.

What you could do, is look for games that you recognize as "Immersive Sim" and see which of the genre labels the have apply to you.

---

**Make your game, the way you want, and worry about it later.**

---

## The not-pragmatic answer

Video game genres are an attempt to capture and communicate the reality of the games. There aren't perfect examples of video game genres. Instead they are all approximations to a platonic ideal. And the reason why the genre seems to evolve is because we learn more about said platonic ideal through the exploration of the approximations… Which is also limited and influenced by technology.

Since we cannot study the platonic ideal directly, we have to resource to find the commonality between the approximations and codify it.

The position that Immersive Sims don't have to be first person makes sense if we consider the perspective an artifact of technological limitations. Even thought the same argument would suggest that the genre should move from first person to virtual reality… It does not preclude making third person Immersive Sims.

The reason we have the argument is because the genre was - arguably (we'll get to that) - born in the first person perspective. Since the - arguably - first game of the genre is Ultima Underworld, published by Origin Systems and produced by Warren Spector. It is important to notice that most of the games in the Immerisve Sim genre trace back to Warren Spector. *Without diminishing the influence of other important designers in the Immersive Sim genre such as Paul Neurath, Harvey Smith (Deus Ex) and Ken Levine (Bioshock).*

Ultima Underworld was also a first person game before first person shooters were a thing. And most of Immersive Sims remained first person: System Shock, Thief, Deus Ex… Prey… BioShock… Dishonored…

Looking at the games in the genre I find these commonalities: first person, single player, narrative driven, RPG elements, and emergent game play. It is worth noting that the genre does not require open worlds.

However, a relatively early notable game that is considered an Immersive Sim which bends the rule is Vampire: The Masquerade – Bloodlines, which has both first and third person perspectives. The game is also notable that it was outsider… I mean, it cannot be traced back to Warren Spector.

More recently we have Weird West, which is arguably an hybrid of Immersive Sim and Top-Down shooter, or a Top-Down shooter with *"Immersive Sim elements"*, yet it is also notable because we can argue it is in the Immersive Sim legacy: Weird West was developed by Raphaël Colantonio's WolfEye Studios, Raphaël Colantonio previously was the founder of Arkane Studios, and before that he was part of Electronic Arts working in the french localization of Origin System games - including System Shock, of which Warren Spector was producer.

We can also look at the precursors. Ultima Underworld could be described as a first person dungeon crawler RPG, except not everything is out to kill you. As such, it comes from an even longer line of games… And when do they approach the Immersive Sim platonic ideal to merit the name is unclear.

In fact, Raphaël Colantonio had argued and defends the position that Immersive Sims can be top down. And considers the genre can be traced back to Ultima VI: The False Prophet (source)… A point that came up - in part - because Wikipedia currently says on Immersive Sim:

> "Warren Spector considered Ultima VI: The False Prophet (1990) the first game to have an immersive sim mentality as while played from a top-down view, it relied less on events and planned-out puzzles, and instead provided the rulesets and systems through its living world to allow players to craft their own solutions to situations."

Which is not sourced. But probably is based on the article How Warren Spector Created a Genre, and Set Games Free, which says "Ultima VI: The False Prophet, which \[Warren\] Spector considers to be the first immersive sim", which I suspect to be a misquote… But if it ins't then probably we should not be counting Ultima Underworld as the first in the genre, but Ultima VI: The False Prophet, which had a top-down-esque oblique perspective.

*Heck, we should not have Warren Spector as gatekeeper of what an Immersive Sim is anyway.*

---

Thus, yes, you can make an Immersive Sim with a third person perspective. Can you still call it Immersive Sim? Sure, nobody is stopping you. Is it correct to call it so? Arguably. But it is certainly not a traditional Immersive Sim. You could go by saying *"Immersive Sim elements"* if you find it too controversial.
> 1 votes

---
Tags: game-design, game-mechanics, maps, open-world, top-down
---


title: Rigidbody drifting after being stopped

text:
# Question
Title: Rigidbody drifting after being stopped
I am struggling with an issue in Unity where I am stopping a rigidbody's motion, but after the motion is stopped the rigidbody still moves slightly. It is causing me major issues as I need the object to freeze with the exact position and rotation at the time it was stopped.

I have uploaded a small package where you can see this problem first hand. Any help in identifying the problem and overcoming it would be greatly appreciated.

To see the problem, simply create a new project and import the package. Start the game and press the "spacebar" key to see the issue, pressing the "r" resets the game so you can see it again (without having to restart the game in the editor each time).

---

As requested here is the code I am using to illustrate this problem:

```
public class PlayerController : MonoBehaviour{
private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();

}}

public class TrapController : MonoBehaviour {
// Trap data
float trapSpeed = 120;
float trapRadius = 3;

// Player data
private PlayerController player;
private Rigidbody playerRb;

void Start()
{
    player = FindObjectOfType<PlayerController>();
    playerRb = player.GetComponent<Rigidbody>();

    // Start the trap
    StartCoroutine(TrapPlayer());
}

private void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
        HaltTrap();
}

private IEnumerator TrapPlayer()
{
    Vector3 offset;
    float angle = 0;
    while (true)
    {
        // Force player to move in a circular motion
        angle += trapSpeed * Time.fixedDeltaTime;
        offset = new Vector3(Mathf.Cos(angle * Mathf.Deg2Rad), 0, Mathf.Sin(angle * Mathf.Deg2Rad)) * trapRadius;
        Vector3 position = transform.position + offset;
        playerRb.MovePosition(position);

        // Force player to face tangential
        Vector3 towardsTrap = transform.position - player.transform.position;
        playerRb.MoveRotation(Quaternion.LookRotation(towardsTrap * 90));
        yield return new WaitForFixedUpdate();
    }
}

private void HaltTrap()
{
    // Stop the motion
    StopAllCoroutines();

    playerRb.velocity = Vector3.zero;
    playerRb.angularVelocity = Vector3.zero;
    Debug.Log("1. Value when trap halted: " + player.transform.rotation.eulerAngles.y);

    // Start reporting the angle
    StartCoroutine(ReportAngle());

}

private IEnumerator ReportAngle()
{

    float value = player.transform.rotation.eulerAngles.y;
    Debug.Log("2. Value at start of Report: " + value);
    while (true)
    {
        float newValue = player.transform.rotation.eulerAngles.y;
        if (newValue != value)
        {
            Debug.Log("---> Value has changed to: " + newValue);
            value = newValue;
        }
        yield return null;
    }
}

```

This is an illustration of what happens when running the code:

It might be hard for you to see but if you look at the console you can see that the angle has changed after stopping it. I have tried toggling isKinematic on and off in the HaltTrap() function. This stops the rotational change from taking place whilst the object is stationary, but as soon as I try to move the position, the rotation changes. Thus, toggling this only seems to delay the change, not prevent it.

# Answer
> 0 votes
Okay so I think I have finally found a way to solve this problem by updating the function that stops the `rigidbody`:

```
private void HaltTrap()
{
    // Stop the motion
    StopAllCoroutines();

    Vector3 playerPos = player.transform.position;
    Quaternion playerRot = player.transform.rotation;

    playerRb.velocity = Vector3.zero;
    playerRb.angularVelocity = Vector3.zero;

    playerRb.isKinematic = false;
    playerRb.position = playerPos;
    playerRb.rotation = playerRot;
    playerRb.isKinematic = true;

    Debug.Log("1. Value when trap halted: " + player.transform.rotation.eulerAngles.y);

    // Start reporting the angle
    StartCoroutine(ReportAngle());

}

```

Some people already suggested toggling `isKinematic` off and on as a solution. This did not solve the problem, but setting `rb.position` and `rb.rotation` in between the toggling has solved the problem. I guess this breaks the queue of positions that `rb.MovePosition()` has accrued, thereby preventing the drift? I wrote an automated test to run this function 1000 times, and not once did I see a rotation change after halting the `rigidbody`. So it looks to me like this is a reliable solution.

---
Tags: unity, rigidbody, rigid-body-dynamics, motion
---