# Question
Title: desired velocity and the local space z axis
This question is related to my previous post here , but, even though I did get some insight, I didn't fully get it, and hence have another dilemma. Since the dead earth series is not publicly available, I'll try to explain as much as possible.

Initial around 21:35 timecode of the lesson 13 of the series, the author tries to find the direction the `navMeshAgent` should turn. For this, he applies the sign of the cross product between `desiredVelocity` vector and the `local z-axis` of the `navMeshAgent`. If the result was negative, he turns left, if positive he turns right. Note that here, he does not convert the `desiredVelocity` vector to the `navMeshAgent`'s local space.

But, later, we come to a case where we require the angle between the `desiredVelocity` vector and the `navMeshAgent`'s local z-axis. In this case, he does convert the `desiredVelocity` vector to the local space of the navMeshAgent using `transform.InverseTransformVector(desiredVelocity)`. I don't really get the concept behind it. Why are we not converting the `desiredVelocity` vector to localSpace in the former case? Obviously the direction might change from conversion of one space to another, so the result should be affected. Please help me understand this. Thanks in advance.

# Answer
> 1 votes
This is all about apples to apples comparisons and what's the path of least resistance to the information we want.

When we just want to know whether one vector in the horizontal plane is to the left or right of another, checking the sign of the cross product is a nice quick way to do that, at just six multiplications and three subtractions — less than a matrix multiplication or quaternion rotation. (In fact, since we only care about the sign of the y component in that case, we can do it with two multiplications and a comparison — though the compiler might or might not figure out that optimization for us)

We could do this equally well in either world space or local space, since we'll get the same output vector either way, just expressed in a different basis. Since `transform.forward` already gives us the object's forward direction in world space, we can just use the world space velocity directly with that and not do any space conversions. So here, world space is the path of least resistance.

When we want to know the specific angle between two vectors, that can get a bit trickier. If we normalized the velocity first we could use the arcsine of the length of the cross product, but that's two square roots and divisions plus a transcendental, and it can give incorrect results if our vectors are not perfectly in-plane (say the velocity is tilted slightly uphill — we'd get an angle in a tilted plane instead of the pure horizontal angle we might expect)

But if we could express the velocity as a direction relative to the object's orientation, then we could use the convenient 2-argument arctangent function to get the exact planar angle we want. And here again, Unity offers a convenient path to get there with `transform.InverseTransformVector`, which provides exactly the needed transformation. Now we have the velocity in a coordinate scheme where z+ is the object's forward and x+ is its right, and finding the turning angle is as easy as expressing that vector in polar coordinates. So here, local space gives us the path of least resistance to what we want.

Note that if we need to do both in a single function, then we might as well use the latter trick with local space. That will get us both the angle and its sign at once. But if we're doing them separately, and either the velocity or the orientation may change in between, then using the shortest route to each data point makes sense.

The tutorial may also be deliberately trying to show you a variety of ways to find out about vector angles, to build up your toolbox.

---
Tags: unity, vector, navmesh
---


# Question
Title: How Can I Order The Scores List By Newest Added? Unity C#
I have 5 scripts to make the scoreboard. But I don't know how to order the list (the scores which are stores in a list) by newest added. Can someone please help me? Thanks :)

First Script:

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

public class RowUi : MonoBehaviour
{
    public TextMeshProUGUI score;
}

```

Second Script:

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

public class ScoreManager : MonoBehaviour
{
    private ScoreData sd;

    private void Awake()
    {
        var json = PlayerPrefs.GetString("scores", "{}");
        sd = JsonUtility.FromJson<ScoreData>(json);
    }

    public IEnumerable<Score> GetHighScore()
    {
        // **THIS IS WHERE THE SCORE IS ORDERD BY DESCENDING** //
        return sd.scores.OrderByDescending(x => x.score);
    }

    public void AddScore(Score score)
    {
        sd.scores.Add(score);
    }

    private void OnDestroy()
    {
        SaveScore();
    }

    public void SaveScore()
    {
        var json = JsonUtility.ToJson(sd);
        PlayerPrefs.SetString("scores", json);
    }
}

```

Third Script:

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

public class ScoreUi : MonoBehaviour
{
    public static ScoreUi instance;

    public RowUi rowUi;
    public ScoreManager scoreManager;

    private void Start()
    {
        instance = this;

        if(gameObject.activeInHierarchy == true)
        {
            ScoreUi.instance.AddScoreToBoard();
        }

        var scores = scoreManager.GetHighScore().ToArray();
        for(int i = 0; i < scores.Length; i++)
        {
            var row = Instantiate(rowUi, transform).GetComponent<RowUi>();
            row.score.text = scores[i].score.ToString();
        }
    }

    public void AddScoreToBoard()
    {
        scoreManager.AddScore(new Score(UserInput.instance.score));
    }
}

```

Fourth Script:

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

[Serializable]
public class ScoreData
{
    public List<Score> scores;

    public ScoreData()
    {
        scores = new List<Score>();
    }
}

```

Fifth Script:

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

[Serializable]
public class Score
{
    public int score;

    public Score(int score)
    {
        this.score = score;
    }
}

```

I hope I explained this well enough and if you need extra info, just tell me :)

# Answer
First, we can add a date field to the score type. We'll make it a `long` so it's easy to serialize, but also add a getter to access it as a `DateTime` object for when that's more convenient to read.:

```
[Serializable]
public class Score
{
    public int score;
    public long timestamp;
    public System.DateTime dateAdded {
        get {
            return System.DateTime.FromFileTimeUtc(timeStamp);
        }
    }

    public Score(int score)
    {
        this.score = score;
        // Assign our time stamp whenever logging a new score.
        timestamp = System.DateTime.Now.ToFileTimeUtc();
    }
}

```

Then we can order our scores by date the same way we order them by value:

```
public IEnumerable<Score> GetHighScore()
{
    // **THIS IS WHERE THE SCORE IS ORDERED BY DESCENDING** //
    return sd.scores.OrderByDescending(x => x.score);
}

public IEnumerable<Score> GetLatestScore()
{
    // **THIS IS WHERE THE SCORE IS ORDERED FROM NEWEST TO OLDEST** //
    return sd.scores.OrderByDescending(x => x.timeStamp);
}

```

To erase the saved scores, just reset your score data before saving:

```
public void ClearAllSavedScores() {
    // Replace our score data with a new empty list of scores.
    sd = new ScoreData();
    // Save this empty collection to replace what's in PlayerPrefs.
    SaveScore();
}

```

As you can see, all of this is a pretty trivial modification of what you already had, plus use of the standard `DateTime` type you can find fully explained in the Microsoft .NET documentation. If you struggle with this, then you may want to work your way through some more beginner programming tutorials to learn the ins and outs of the language.
> 0 votes

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


# Question
Title: ParticleEffect using TextureAtlas in libGDX
I am using `ParticleEffect` with a texture stored inside `TextureAtlas`. The code below shows how I load a particle:

```
ParticleEffect particle = new ParticleEffect();
particle.load(Gdx.files.internal("particles/particle01.pe"), gamePlayAtlas);

```

I am not sure if I have to call `particle.dispose()` inside `ApplicationLister`'s `dispose` method, or is it enough if I only call `dispose` on the `AssetManager` instance with which I loaded the `TextureAtlas`?

# Answer
> 0 votes
If the `ParticleEffect` owns the texture you need to call `dispose`, and it owns it only if the texture is loaded using a `FileHandle`, so if it comes from `TextureAtlas` it doesn't own it and you don't need to call `dispose`.

But, the `dispose` method of `ParticleEffect` is aware of this so it's safe to call `dispose` even if it is not the owner of the texture.

ParticleEffect source code for the `dispose` method

---
Tags: java, libgdx, assets, particles, asset-management
---


# Question
Title: Does the Z axis matter at all in a 2D project, when using layer collision for all collision detection?
As I understand it, the Z axis is responsible for the rendering position of the object in relation to the camera/other objects, and layer collision only checks if an object collides based on the x/y position.

```
For example;

I have a Ball on z = 5.

I have a box on z = -5.

I have the ball on a layer called "Ball".

I have the box on a layer called "Box".

```

As long as the check box that intersects Ball and Box is ticked in the collision manager, they will always trigger a collision regardless of the difference in their Z axis.

Is this correct? Does the layer collision manager simply ignore the Z axis in a 2D environment?

I've tried looking for documentation that more fully explains how the layer collision manager works, but I've only been able to find unity's own documentation that doesn't explain how xyz coordinates interact with layer collisions, if at all.

# Answer
Z depth can be used for parallax effects if you choose to use a perspective camera.

You can choose to use z depth for visual sorting (which object should render in front of another), and to filter potential hits for physics checks like overlaps or raycasts \- providing a minimum or maximum depth range you want to consider for those queries.

Or you can also choose not to use z depth for these purposes, such as by overriding the default sort axis with a custom one. The choice is yours.

Z ordering does not affect 2D physics collisions, which happen in pure XY space.
> 1 votes

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


# Question
Title: How can I create a custom plane with raycast?
```
using UnityEngine;

[ExecuteAlways]
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class CustomPlane : MonoBehaviour {

    public float width = 1;
    public float length = 1;

    private float oldWidth;
    private float oldHeight;

    public void Start()
    {
        oldWidth = width;
        oldHeight = length;

        Create();
    }

    private void Update()
    {
        if(oldWidth != width || oldHeight != length)
        {
            Create();

            oldWidth = width;
            oldHeight = length;
        }
    }

    private void Create()
    {
        MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();

        Mesh mesh = new Mesh();

        Vector3[] vertices = new Vector3[4]
        {
            new Vector3(0, 0, 0),
            new Vector3(width, 0, 0),
            new Vector3(0, length, 0),
            new Vector3(width, length, 0)
        };
        mesh.vertices = vertices;

        int[] tris = new int[6]
        {
            // lower left triangle
            0, 2, 1,
            // upper right triangle
            2, 3, 1
        };
        mesh.triangles = tris;

        Vector3[] normals = new Vector3[4]
        {
            -Vector3.forward,
            -Vector3.forward,
            -Vector3.forward,
            -Vector3.forward
        };
        mesh.normals = normals;

        Vector2[] uv = new Vector2[4]
        {
            new Vector2(0, 0),
            new Vector2(1, 0),
            new Vector2(0, 1),
            new Vector2(1, 1)
        };
        mesh.uv = uv;

        meshFilter.mesh = mesh;
    }
}

```

Later, the problem is I want to fire a ray on the plane and that ray will also get to a terrain.

The plane is above the terrain in the air I want to shoot a ray on the plane and that it will spawn objects too also on the terrain.

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

public class SpawnObjects : MonoBehaviour
{
    public GameObject prefabToSpawn;
    public Terrain terrain;
    public CustomPlane plane;
    public float yOffset = 0.5f;
    [SerializeField] private LayerMask terrainLayer;

    private float terrainWidth;
    private float terrainLength;
    private float xTerrainPos;
    private float zTerrainPos;

    private float planeWidth;
    private float planeLength;
    private float xPlanePos;
    private float zPlanePos;

    private float yValTerrain;
    private float yValPlane;

    private float randXTerrain;
    private float randZTerrain;

    private float randXPlane;
    private float randZPlane;

    private Collider terrainCollider;
    void Awake()
    {
        if (terrain != null)
        {
            //Get terrain size
            terrainWidth = terrain.terrainData.size.x;
            terrainLength = terrain.terrainData.size.z;

            //Get terrain position
            xTerrainPos = terrain.transform.position.x;
            zTerrainPos = terrain.transform.position.z;

            terrainCollider = terrain.GetComponent<Collider>();
        }

        if (plane != null)
        {
            planeWidth = plane.width;
            planeLength = plane.length;
            xPlanePos = plane.transform.position.x;
            zPlanePos = plane.transform.position.z;
        }
    }
    private void Update()
    {
        SpawnThroughPlane();
    }

    public void SpawnThroughPlane()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (plane.GetComponent<MeshCollider>().Raycast(ray, out hit, Mathf.Infinity))
            {
                var prefab = Instantiate(prefabToSpawn);

                Vector3 pos = prefab.transform.position;
                pos.y = terrain.SampleHeight(prefab.transform.position);
                prefab.transform.position = hit.point + pos;
            }
        }
    }
}

```

This spawn objects on the plane but not on the terrain I think because the plane collider blocks it to get to the terrain.

Not sure what to do to solve it.

I tried in the SpawnThroughPlane method to use :

```
var ray = new Ray(plane.transform.position, Vector3.down);

```

And

```
if(Physics.Raycast(ray, out var hit, Mathf.infinity, terrainLayer))

```

And on the top of the script added

```
[SerializeField] private LayerMask terrainLayer;

```

Then I added in the editor a new layer at index 8 name Terrain and changed the Terrain layer to Terrain and in this variable terrainLayer I set it to Terrain too but it didn't work it's spawning the objects on the same position on the terrain and not on the plane at all.

Update :

A screenshot that will explain better what I'm trying to archive.

I want that when I click the mouse it will spawn objects on the mouse cursor position only on the plane area and that where I click on the plane it will spawn also the objects on the terrain. to convert the positions from the plane to the terrain positions.

Imagine it like a cloud that drop rain. When I click on the plane this is where a drop will be falling on the terrain. The plane is like a cloud.

# Answer
Your question contains much code but defines your issue a bit vaguely. I hope I understood what you're trying to achieve, though.

If you want to spawn objects both on the plane in the air *and* on the corresponding position on the terrain, you can:

```
Vector3 posOnPlane = Physics.Raycast(...);

```

```
float heightFromTerrain = Terrain.activeTerrain.SampleHeight(posOnPlane);

```
* Spawn the second instance in the new position across the terrain.

```
posOnPlane.y -= heightFromTerrain;
Instantiate(groundedGameObject, posOnPlane, Quaternion.identity);

```
> 0 votes

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


# Question
Title: How do I find the circumcenter of a triangle in 3D?
I want to find the circumcenter of a triangle. Wolfram only shows how to find the circumcircle of a triangle in R2. How can I find the circumcenter of a triangle in R3?

# Answer
> 20 votes
The circumcenter of a triangle can be found by the following formula, which I mined from an old posting by Jonathan Shewchuk from the Geometry Junkyard

$$\begin{align} &\text{Triangle in } \Bbb R^3\text{:}\\ &m = a + \frac {\lVert c-a\rVert^2 \left\[(b-a) \times (c - a) \right\] \times (b-a) + \lVert b-a\rVert^2 \left\[(c-a) \times (b - a) \right\] \times (c-a)} {2 \lVert (b - a) \times (c - a) \rVert^2} \end{align}$$

Where \\$m\\$ is the circumcenter of the triangle.

Some C++ code, given Vector3f's with overloaded +, -,

```
Vector3f a,b,c // are the 3 pts of the tri

Vector3f ac = c - a ;
Vector3f ab = b - a ;
Vector3f abXac = ab.cross( ac ) ;

// this is the vector from a TO the circumsphere center
Vector3f toCircumsphereCenter = (abXac.cross( ab )*ac.len2() + ac.cross( abXac )*ab.len2()) / (2.f*abXac.len2()) ;
float circumsphereRadius = toCircumsphereCenter.len() ;

// The 3 space coords of the circumsphere center then:
Vector3f ccs = a  +  toCircumsphereCenter ; // now this is the actual 3space location

```

Here is a picture of a triangle and its circumsphere

# Answer
> 1 votes
JavaScript - MY WORK - 5 TRIANGLE CENTERS IN 3D

```
function incenter(A,B,C) {
    var a=vlen(subv(A,B)),b=vlen(subv(B,C)),c=vlen(subv(C,A));
    var x = multv(C,a), y = multv(A,b), z = multv(B,c);
    return divv(addallv(x,y,z),a+b+c);
}

function centroid(A,B,C) {
    return divv(addallv(A,B,C),3);
}

function midpoint(A,B) {
    return divv(addv(A,B),2);
}

function orthocenter(A,B,C) {
    var c = circumcenter(A,B,C);
    return addallv(subv(A,c),subv(B,c),subv(C,c),c);
}

function circumcenter(A,B,C) {
    var z = crossprod(subv(C,B),subv(A,B));
    var a=vlen(subv(A,B)),b=vlen(subv(B,C)),c=vlen(subv(C,A));
    var r = ((b*b + c*c - a*a)/(2*b*c)) * outeradius(a,b,c);
    return addv(midpoint(A,B),multv(normaliz(crossprod(subv(A,B),z)),r));
}

function nine_point(A,B,C) {
    return midpoint(orthocenter(A,B,C),circumcenter(A,B,C));
}

function outeradius(a,b,c) { /// 3 lens
    return (a*b*c) / (4*sss_area(a,b,c));
}

function sss_area(a,b,c) {
    var sp = (a+b+c)*0.5;
    return Math.sqrt(sp*(sp-a)*(sp-b)*(sp-c));
    //semi perimeter
}

```

If you need the remaining functions, you can fint them in this working code example \- hit the pyramid button twice.

# Answer
> 1 votes
```
//Unity/C#
Vector3 ac = c - a;
Vector3 ab = b - a;
Vector3 abXac = Vector3.Cross(ab, ac);

// this is the vector from a TO the circumsphere center
Vector3 toCircumsphereCenter = (Vector3.Cross(abXac,ab) * ac.sqrMagnitude + Vector3.Cross(ac,abXac) * ab.sqrMagnitude) / (2f * abXac.sqrMagnitude);
float circumsphereRadius = toCircumsphereCenter.magnitude;

// The 3 space coords of the circumsphere center then:
Vector3 ccs = a + toCircumsphereCenter; // now this is the actual 3space location

```

---
Tags: mathematics, geometry
---


# Question
Title: If I want to use textures and colors, how do I put them into my fragment shader?
I have many mesh objects in my scene and I have applied an image texture to some objects but I want to set different colors for the other objects. How do I do that? This is my fragment shader

```
#version 430 core

out vec4 color;

in VS_OUT
{
    vec2 tc;
    vec3 normals;

}

fs_in;

layout(binding=0)uniform sampler2D tex;

// uniform mat4 model_matrix;

void main(void)
{

color= texture(tex, fs_in.tc);
}

```

This is my code

```
glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture[0]);
    GLint tex_location = glGetUniformLocation(program, "tex");
    glUniform1i(tex_location, 0);
    Fence.Draw();

    glActiveTexture(GL_TEXTURE0 + 1);
    glBindTexture(GL_TEXTURE_2D, texture[1]);
    GLint tex_location1 = glGetUniformLocation(program, "tex");
    glUniform1i(tex_location1, 1);
    Ground.Draw();

    glActiveTexture(GL_TEXTURE0 + 2);
    glBindTexture(GL_TEXTURE_2D, texture[2]);
    GLint tex_location2 = glGetUniformLocation(program, "tex");
    glUniform1i(tex_location2, 2);
    O_Roof.Draw();

    glActiveTexture(GL_TEXTURE0 + 3);
    glBindTexture(GL_TEXTURE_2D, texture[3]);
    GLint tex_location3 = glGetUniformLocation(program, "tex");
    glUniform1i(tex_location2, 3);
    O_BlueCandies.Draw();

```

Say I want to add the color blue to O\_BlueCandies object and the color red to another one and so on how can I do that?

# Answer
**You need to implement the change.**

There are many ways to do this.

For example, we can swap components. In fact, we could just pass a single `int` to rotate the components:

```
    vec4 col = texture(tex, fs_in.tc);
    vec4 rotated_color = vec4(
            col[(0 + rot) % 3],
            col[(1 + rot) % 3],
            col[(2 + rot) % 3],
            col.w
        );
    color = rotated_color;

```

Which - given an integer `rot` \- will rotate the RGB components. When `rot` is set to `0`, you get the original coloring. With `rot` set to `1` green becomes red, red becomes blue, and blue becomes green. With `rot` set to `2` green becomes blue, blue becomes red, and red becomes green.

---

Or we could pass a 3 by 3 matrix which will allow all sort of transformations, and transform the color by that:

```
    vec4 col = texture(tex, fs_in.tc);
    vec4 transformed_color = vec4(m * col.xyz, col.w);
    color = transformed_color;

```

In fact, I would argue for adding a translation so the center is at `(0.5, 0.5, 0.5`) and that way we can rotate without worrying of negatives (this also has the effect that a mirror transformation give you negative colors).

```
    vec4 col = texture(tex, fs_in.tc);
    vec3 offset = vec3(0.5, 0.5, 0.5);
    vec4 transformed_color = vec4((m * (col.xyz - offset) + offset), col.w);
    color = transformed_color;

```

Then you can provide a rotation matrix `m` that maps the blue axis to the red axis (or viceversa). Of course, the red axis is x, the green axis is y, and the blue axis is z. So we want a rotation around the y axis.

---

Or you might implement a hue rotation algorithm. See How to change hue of a texture with GLSL?

---

Depending on the approach you take, **You will to pass some data to the GPU about the change.**

When does the change happen?

* Are the blue and red objects two render calls?

You can add an uniform for that (you already know how to declare and pass data via uniforms). *Or they could be entirely different shader programs, but I'm not suggesting that.*
* Are the blue and red objects instances on the same render call?

You can pass an uniform array or a texture, and access it using the instance id (you get `gl_InstanceID` in the vertex shader).
* Are the blue and red objects a single mesh?

You could use vertex attributes. Or you could pass an uniform array or a texture, and access it using vertex indexes (similarly to `gl_InstanceID`, in the vertex shader you get `gl_VertexID`).

*This is not an exhaustive list of cases.*

**Note**: You can pass information from the vertex shader to the fragment shader (make an `out` variable in the vertex shader and a matching in variable `in` the fragment shader).

**See also**: How to do instancing the right way in OpenGL
> 1 votes

---
Tags: opengl, shaders, textures
---


title: How to Rotate Camera only once

text:
# Question
Title: How to Rotate Camera only once
I have a simple camera rotate script which rotates the camera around my game scene

i only want it to do it once at the start to show off the level

or how can i rotate it a whole 360 degrees then stop?

How can i achieve this?

My camera rotate script

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

public class CamRotate : MonoBehaviour
{
    public float speed = 5f;
    void Update()
    {
        transform.Rotate(0, speed * Time.deltaTime, 0);
    }
}

```

# Answer
> 0 votes
This is very trivial. If you're finding that this task is a blocker for you, then you should definitely consider putting your game aside and working through some beginner Unity tutorials to practice the basics like this.

```
// Create a coroutine that can stretch over
// several frames, starting automatically
// when the object spawns.
IEnumerator Start() {

    // Cache the orientation of the object.
    Quaternion originalOrientation = transform.rotation;

    // Loop until we hit 360 degrees.
    for (float degrees = 0;
           degrees < 360f;
           degrees += Time.deltaTime * speed
    ) {
        // Rotate our original pose by this angle.
        Quaternion yaw = Quaternion.Euler(0, degrees, 0);
        transform.rotation = yaw * originalOrientation;

        // Wait one frame, then resume the loop.
        yield return null;
    }

    // Return exactly to our initial pose.
    transform.rotation = originalOrientation;
}

```

---
Tags: unity
---


# Question
Title: Calculating world position with parent and child transform with translation and rotation
I have two *Quaternion* transforms, and a viewmatrix. These are custom transforms made by Dice, and I'm working on some custom modding for an older version of Battlefield.

Now, I don't have the entire context of these, as I've reversed engineered these, however I'm lost on how to calculate the Child's world location with the parent.

One is the parent transform, and here's what it looks like

**Parent/Root**

translation: Vector4(-497.010f, 116.293f, -393.720f, 0.0f)

rotation: Quaternion(0.000f, 0.0707f, 0.000f, 0.707f)

**Child**

```
translation: Vector4(0.018f, 1.547f, 0.030f, 0) // note how translation is simply an offset of the parent
rotation: Quaternion(0.000f, 0.0707f, 0.000f, 0.707f) // I made this value up, I can't remember what a good example was

```

How do I factor in the ***parents*** rotation? I've tried the following:

```
relativeRotation = inverse(parent.Rotation) * child.Rotation
var transformed = Vector4.Transform(childTranslation, relativeRotation) + parent.Translation

```

However it doesn't seem to be accurate. What am I missing here? Speficically I'm looking to calculate the 3d coordinate (with rotation applied) of the child, i.e. the world location.

There's also a scale for both, but its the same value for all parent and child:

var scale = Vector4(1, 1, 1, 0)

Current code:

```
parent
child

childWorldLocation  = Vector4.Multiply(Vector4.Transform(child.Translation, parent.Rotation), parent.Scale) + parent.Translation;

screenCoordinate = Util.WorldToScreen(new Vector3(childWorldPosition.X, childWorldPosition.Y, childWorldPosition.Z), viewProjection); // this works fine for any vec3 origin, not the issue

```

Result is most of the child transforms are near the bottom where the parent translation is.

W2S:

```
    public static Vector2 WorldToScreen(Vector3 position, Matrix viewProjection) {

        float w = viewProjection.M14 * position.X + viewProjection.M24 * position.Y + viewProjection.M34 * position.Z + viewProjection.M44;

        if (w < 0.01) {
            return Vector2.Zero;
        }

        var screenPositionX = viewProjection.M11 * position.X + viewProjection.M21 * position.Y + viewProjection.M31 * position.Z + viewProjection.M41;
        var screenPositionY = viewProjection.M12 * position.X + viewProjection.M22 * position.Y + viewProjection.M32 * position.Z + viewProjection.M42;

        float invw = 1.0f / w;

        screenPositionX *= invw;
        screenPositionY *= invw;

        float x = (float)H.ViewPortX / 2; //viewport is the resolution x,y
        float y = (float)H.ViewPortY / 2;

        x += 0.5f * screenPositionX * (float)H.ViewPortX + 0.5f;
        y -= 0.5f * screenPositionY * (float)H.ViewPortY + 0.5f;

        return new Vector2(x, y);
    }

```

# Answer
> 1 votes
The child's rotation does not change the child's position. Try it: do a pirouette - you stay in the same place, despite the fact that you are rotating through a full 360 degrees.

So, child rotation does not factor into this expression at all:

```
var childWorldPosition = Vector4.Scale(
                             Vector4.Transform(child.Translation, parent.Rotation),
                             parent.Scale
                       ) + parent.Translation;

```

The child's rotation affects only the child's rotation:

```
var childWorldRotation = Quaternion.Compose(parent.Rotation, child.Rotation);

```

(Though you may need to flip the order of the arguments if your quaternion composition method takes the "more local" argument first and the "more global" argument second)

---
Tags: 3d, vector, quaternion
---


title: Loop over a list with within X seconds

text:
# Question
Title: Loop over a list with within X seconds
I have a list of harvested crops. There's a capacity of let's say 100 crops(100 items in a list). Now I want to empty the list within X seconds when max full (2 sec in my case). This should be relative to the max cap. If the list is 100 it should take 2 sec if 50 then 1 sec accordingly. What should be the approach for achieving that?

The reason for this is that I want to iterate over each crop item and animate them towards some point for selling. I have tried for loop but it's not quite giving me the right time as my max cap changes over time when the user upgrades but I want the animation time to be constant to 2 sec when the list is maxed up.

This is what I tried:

```
 private IEnumerator MoveHarvestToStore()
{
    float startTime = Time.time;
    animationTimeForSelling = 2.0f * trunkCapacityFilled / trunkTotalCapacity;
    Debug.Log("Anim Time = " + animationTimeForSelling);

    for (int i = pickablesInHarvester.Count - 1; i >= 0; i--)
    {
        float animTime = animationTimeForSelling / pickablesInHarvester.Count;
        yield return new WaitForSeconds(animTime);
    }
    float endTime = Time.time;
    Debug.Log("Time took = " + (endTime - startTime));
}

```

The problem with the above code is that this is not consistent in terms of time. Following are the logs with the same trunkCapacityFilled and trunkTotalCapacity every time:

Anim Time = 2, Time took = 2.17

Anim Time = 2, Time took = 2.15

Anim Time = 2, Time took = 2.16

Anim Time = 2, Time took = 2.213

Anim Time = 2, Time took = 2.13

# Answer
> 0 votes
Remember that `WaitForSeconds` waits *at least* that long. It's only ticked once per frame, so if a frame lands slightly before the waiting deadline, you don't resume until the next frame later - which might be nearly 16 ms later than planned if you're running at 60 FPS. So if you have an average of 8 ms extra delay per item, times 350 items, that could slow down your full iteration by nearly 3 seconds in total!

What you can do is keep track of how long you've *actually* waited at each step. So if the next frame lands a little later than your desired wake-up time, you subtract the time you overslept from your next alarm, to correct for the error. That way the error does not have an opportunity to accumulate.

```
float accumulator = 0f;
for (int i = pickablesInHarvester.Count - 1; i >= 0; i--)
{

    float animTime = animationTimeForSelling / pickablesInHarvester.Count;
    accumulator += animTime;
    while (accumulator > 0) {
        yield return null;
        accumulator -= Time.deltaTime;
    }
}

```

# Answer
> 1 votes
Divide your current amount by max amount and you'll get the percentage amount of items that you have, then multiply this number by you full time and you'll end with the seconds to empty the current bag.

currentAmount / maxAmount * maxTime = x

Taking your example

50 / 100 = 0.5 0.5 * 2 (sec) = 1 sec

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


# Question
Title: Callback to a dynamic value in GameObject.transform
I'm currently writing an `InputManager` using Unity's "new" input system. The `InputManager` receives all player input via `SendMessage()` and disseminates it to the appropriate objects (player, UI, et cetera). In an attempt to adhere to SRP (single-responsibility principle), I want as much of the message massaging to occur in the `InputManager` as possible.

For player movement in the `InputManager`, I have the following:

```
public void OnMovement(InputValue input)
{
    if (playerControl == null)
        playerControl = player.GetComponent<PlayerControl>();

    playerControl.OnMovement(input, playerMovementSpeed, cmCam.gameObject.transform.localEulerAngles);
}

```

on the `PlayerControl` script, I have:

```
void Update()
{
    var q = Quaternion.Euler(cmCam.transform.localEulerAngles);
    q.x = 0;
    this.gameObject.transform.localPosition += q * moveVec * Time.deltaTime * playerMovementSpeed;
}

public void OnMovement(InputValue input, float speed, Vector3 cameraRotationAngle)
{
    playerMovementSpeed = speed;

    Vector2 inputVec = input.Get<Vector2>();

    // Must multiply quat * vec | vec * quat causes an exception
    //moveVec = Quaternion.Euler(cameraRotationAngle) * new Vector3(inputVec.x, 0, inputVec.y);
    moveVec = new Vector3(inputVec.x, 0, inputVec.y);
}

```

I'm using the `Quaternion` of the `CinemachineCamera` so that as the camera rotates, directional movement accounts for it without having to stop and restart movement. At the same time, because it's a pseudo-isometric view, I want the `x-value` of the camera to be ignored (otherwise forward/backward movement has a skipping to it).

The current code **works** as-is, but querying and modifying the camera's returned `transform` value every frame via update seems less than ideal. I can't measure the performance impact because I can't figure out another way to do it.

Is there a way to make some sort of callback value that will give me \`Quaternion(w, 0, y, z)' of that camera's transform every frame?

Ignore the `cameraRotationAngle` in the signature of `playerControl.OnMovement` \- that was part of my initial attempt, but the value isn't updated until movement stops and restarts, so that will likely be removed.

# Answer
> modifying the cameras transform every frame via update seems less than ideal.

Then I have good news for you: you're not doing that. The code you've shown does not modify the camera's transform component in any way shape or form.

> Is there a way to make some sort of callback value that will give me \`Quaternion(0, y, z, w)' of that camera's transform every frame?

First, that is *not* what you want. Zeroing out the x component of a quaternion is not a way to remove the pitch component of the rotation. Instead, this can add a twisting roll to the camera.

Here's a gif that demonstrates this. On the left is the source object for the rotation, which I show pitching down then yawing through a full 360 degrees. On the right there's are two copies of the object, in blue and red. The blue copy is using the correct flattening code I show below. The red copy is just setting `quaternion.x = 0`. You can see that while they're equivalent at `yaw = 0`, as we rotate around the y, the red copy develops a rolling twist - deviating more than 6 degrees from level, as shown in the transform properties on the right. This error can grow much larger if the source pitch is greater.

It looks like what you want is a camera-relative flattening method, as shown here:

Camera relative movement is pushing into/off the ground instead of parallel

If you'd like to make the syntax look like a member method call, you can do that with an extension method:

```
public static class TransformExtensions {
    public static Quaternion GetPlanarRotation(this Transform transform, Vector3 planeNormal = default) {
        if (planeNormal == default) planeNormal = Vector3.up;

        return Quaternion.LookRotation(planeNormal, -transform.forward) * Quaternion.Euler(90, 0, 0);
    }
}

```

Then you can just say...

```
var q = cmCam.transform.GetPlanarRotation();
transform.localPosition += q * moveVec * Time.deltaTime * playerMovementSpeed;

```
> 1 votes

---
Tags: unity, movement, input, quaternion
---


# Question
Title: How should I automatically update my entire game's files?
How should I automatically update my player's game assets and executables? It is preferable for the update software to be free. Updates must be small in size and not waste cpu-time. Also it has to be easy to run a update server to create new versions or logistically.

My use case is for updating player game versions such as in massive online clients or running distributed game testing or even normal games.

# Answer
There's a question on Stack Overflow here that might be of use. It relates to patching binary files in an efficient way (basically storing the differences between versions rather than the entire files).

It's also worth being aware that if you install the game files into "Program Files" on Windows Vista and up then you'd also need to take into account the user not necessarily having the permission to modify the files. There's a little bit of info from the DirectX help files here on that too.

Once you have your patch generated, you'll want to probably be checking the current version of the game exe with something hosted on the web somewhere, then download and launch a separate patcher with patch content. The main game exe won't be able to patch itself while it's running. There are plenty of cheap file hosting solutions out there you can store your patch and other data on.
> 7 votes

# Answer
I noticed that you tagged the question client-server, so I assume you're also asking how to physically distribute the patch. Depending on your budget, the easiest for users is to simply provide an HTTP download on your website, but this requires the most bandwidth from your server (patch size * games purchased), a slightly less user friendly option is to upload your content as a bittorrent and run some seeds from your servers. This reduces bandwidth requried on your server, but will be more of a pain for your users unless you are like Blizzard and have the resoruces to build a bittorrent client into your game.

The bottom line is that it depends on how large (MB/GB) your patch or update will be and how much money you have to throw at a server and bandwidth to distribute your patch to end users.

From a software perspective, there are many ways to distribute and install game updates, but in general you should stick with the methods used by traditional software. Have the user download an update installer, which knows how to prompt the user for adminsitrative access to their machine and copy/update files as necessary checking versions (user may have skipped v1.1 and installed v1.2 directly).
> 2 votes

# Answer
I was searching the internet for an interesting answer to a question like this, but considering I can't find a better solution to what I already have, let's just go ahead and answer this question from years ago for any future wanderers.

First, I would suggest storing your assets into an archive-based system. What I mean by this is organizing your assets into categories that fit into individual indices like so:

```
Index 0 (Sprites):
    - Image 1
    - Image 2
    - Image 3
Index 1 (Sounds):
    - Sound 1
    - Sound 3
Index 2 (Scripts):
    - Script 1
    - Script 2

```

Once you have them organized like that, go ahead and program a type of Cache Store that holds something called a Checksum Table or Version Table. This table will hold information of all the files within the Cache Store such as the corresponding index it's in, the file size, file type, and file ID.

Now that your Cache system is complete, you can do two things. The first thing is write something up to pack this Cache Store into a Zip, GZip, BZip, 7Zip, Rar, or whatever your preference and send that over to the client from the server and unpack it onto the user's computer, or...you can try it the second way which saves A LOT bandwidth. The second way consists of the client sending an update request from the server once the client is connected to the network. The server then sends the client the Checksum/Version table which consists of the file information in the cache and the client will compare its current cache with the server's and make a list of files to request from the server. The server sends the requested file data to the client and the client will individually update each new file.
> 0 votes

---
Tags: client-server
---


# Question
Title: Why is Unity using a Quaternion for rotation, but a Vector3 for angular velocity?
Unity uses quaternions for storing the rotation of rigid bodies, but vectors for the angular velocity. Why? I thought you'd use a quaternion instead of that vector also. I don't know much about quaternions and stuff, so please excuse me if this is a dumb question.

# Answer
Because not only is a Vector3 more compact, a quaternion can only represent a rotation of up to +/- 1 turn signed.

If you're storing angular velocity as "rotations per second" your object could be spinning at more than 1 rotation per second, a quaternion doesn't work for this (even if you chose a smaller time base you will reach a similar problem)

A Vector3 angular velocity can be longer than 1 unit of length to represent faster rotations than a quaternion could.

It's also much easier to work with when calculating friction, combining/adding angular velocity, multiplying by the frame delta time, clamping rotation speed (a simple vector length check), etc
> 2 votes

---
Tags: unity
---


# Question
Title: How to detect if player want to do a wall run?
I have a third person character and I want to make it wall run. However since there will be a wall run animation, I don't want the player to do the Inputs for a wallrun and at the end change direction with touching the wall. I don't want the animation to start but have the player not wall run. I also don't want to start the animation right when the player start the wall run since I want a transition. What would be a good way to be sure the player will wall run ? Would having an input forcing the character to wall run be a good solution ? I don't want to controls to be too complicated, so would there be a better solution ?

# Answer
> 0 votes
If the player makes an input that can result in a wall run, use a ray cast to find a viable wall, if any. If there isn't a wall, don't transition into a wall run... But if there is, play the transition animation, while interpolating the character to the wall for the same duration. Then the character can wall run.

You are going to have other challenges. In particular what happens when the character wall runs into a corner. Either on the inside or outside of a corner. You will have to decide if you transition the wall run to follow the wall or not.

So you will have a ray cast to check if the character reached the end of the wall (or perhaps the outside of a corner). And perhaps another to check for the inside of a corner, depending if that is something you want as part of the mechanic.

---
Tags: animation, game-mechanics, third-person-view
---


# Question
Title: Cannot properly get 2D top-down tile-based collisions
I am using HTML, CSS, and plain JavaScript for a 2D top-down tile-based simulation. I am trying to do collisions in which, for example, if I move up and hit the ceiling collision tile, I cannot proceed to go up and can still move left, right, or down.

Each title is a 64x64 HTML IMG element, including the player. The player's movement uses CSS Transform style for X and Y movements when moving with arrow keys.

For my collision function, I have the following code:

```
function checkCollision(arrPassableMovements) {
    let childrens = cntWorldBaseCollision.children;
    let tenantDOM = imgWorldTenant.getBoundingClientRect();

    // For number of tiles set in the collision world
    for (let i = 0; i < childrens.length; i++) {

        // Get the HTML element of that tile
        let childrenElement = document.getElementById(childrens[i].id);

        // Get the JavaScript DOM object of that tile
        let childrenDOM = childrenElement.getBoundingClientRect();

        // If that tile's last fixed character ends with C
        if (childrens[i].id.substring(9) == 'C') {

            if (Math.abs(tenantDOM.x - childrenDOM.x) * 2 < (tenantDOM.width + childrenDOM.width) &&
                Math.abs(tenantDOM.y - childrenDOM.y) * 2 < (tenantDOM.height + childrenDOM.height)) {

                // Checks for up. Else, down.
                if (tenantDOM.bottom - childrenDOM.bottom > 0 &&
                    tenantDOM.top - childrenDOM.top > 0) {
                    arrPassableMovements[0] = false;

                } else if (tenantDOM.bottom - childrenDOM.bottom < 0 &&
                    tenantDOM.top - childrenDOM.top < 0) {
                    arrPassableMovements[1] = false;
                }

                // Checks for left. Else, right.
                if (tenantDOM.left - childrenDOM.left > 0 &&
                    tenantDOM.right - childrenDOM.right > 0) {
                    arrPassableMovements[2] = false;
                } else if (tenantDOM.left - childrenDOM.left < 0 &&
                    tenantDOM.right - childrenDOM.right < 0) {
                    arrPassableMovements[3] = false;
                }

            }
        }
    }
}

```

The issue begins after it is determined that the player is intercepting a collision tile. Let us say that we move up to block a ceiling tile; then, it is impossible to move left or right unless we go back—the same story with left tile, unable to move up or down unless we go right.

I had tried the following:

* Checking if it is not possible to move up or down, allow left and right movement. This, of course, meant that left and right collisions were nullified.

```
if (!arrPassableMovements[0] || !arrPassableMovements[1]) {
      arrPassableMovements[2] = true;
      arrPassableMovements[3] = true;
}

```
* In addition to the above, I have also added that allows up and down movement if it is not possible to move left or right, allow up and down motion. Same story as one above.

```
if (!arrPassableMovements[2] || !arrPassableMovements[3]) {
     arrPassableMovements[0] = true;
     arrPassableMovements[1] = true;
}

```

If I have to speculate, it has to be how I check when to nullify exact movements. In other words, possibly not enough additional conditional statements to correctly conclude that we cannot move in this direction.

NOTES:

* Player is referred to as tenant
* children(s) as the world tile (both plain and collider-bound tiles.)
* Each world tile has a fixed identification. For example, imgWBC000C breaks down the following: three characters for what HTML element it is, followed by the abbreviation for World Based Collision and a number of that, and if it is plain (P) or collision (C) tile.
* arrPassableMovements is an array with four booleans that starts with true. Each element is as follows: up, down, left, and right.
* If you believe that the provided codes are not enough, then refer to the intragarden-dev repository. The ones used are in world.js: https://github.com/Tyu-Uyt/intragarden-dev/blob/menu-redesign/world.js

# Answer
> 1 votes
If I understand correctly, `checkCollision` should give you the direction in which the player can move. So you are calling it before the motion.

However, you are checking if the character is already colliding, here:

```
if (Math.abs(tenantDOM.x - childrenDOM.x) * 2 < (tenantDOM.width + childrenDOM.width) &&
    Math.abs(tenantDOM.y - childrenDOM.y) * 2 < (tenantDOM.height + childrenDOM.height)) {
    // …
}

```

Perhaps I'm misunderstanding, however, I believe you should be checking if the character will collide if it moves in each direction. Something like this:

```
let step = 3;

// …

if (Math.abs(tenantDOM.x - childrenDOM.x) * 2 < (tenantDOM.width + childrenDOM.width) &&
    Math.abs(tenantDOM.y - childrenDOM.y - step) * 2 < (tenantDOM.height + childrenDOM.height)) {
    arrPassableMovements[0] = false;
}

if (Math.abs(tenantDOM.x - childrenDOM.x) * 2 < (tenantDOM.width + childrenDOM.width) &&
    Math.abs(tenantDOM.y - childrenDOM.y + step) * 2 < (tenantDOM.height + childrenDOM.height)) {
    arrPassableMovements[1] = false;
}

if (Math.abs(tenantDOM.x - childrenDOM.x - step) * 2 < (tenantDOM.width + childrenDOM.width) &&
    Math.abs(tenantDOM.y - childrenDOM.y) * 2 < (tenantDOM.height + childrenDOM.height)) {
    arrPassableMovements[2] = false;
}

if (Math.abs(tenantDOM.x - childrenDOM.x + step) * 2 < (tenantDOM.width + childrenDOM.width) &&
    Math.abs(tenantDOM.y - childrenDOM.y) * 2 < (tenantDOM.height + childrenDOM.height)) {
    arrPassableMovements[3] = false;
}

```

*I'm not sure if I flipped the directions.*

You can - of course - optimize that further, since there are repeated checks and computations there.

*There are other optimizations you could do, like keeping the tile elements in an actual array, so you can go directly to the ones nearby the character instead of iterating over them all, but that is beyond the question.*

---
Tags: 2d, collision-detection, javascript, tiles, top-down
---


# Question
Title: Getting info about the script a [PropertyAttribute] is attached to in Unity
Is there a way to access info about the script that a PropertyAttribute is part of in Unity? In my case: getting the memberInfos of the script:

```
class MyBehavior : MonoBehavior
{
   [MyAttribute] public float dog;
   public float cat;
   //I want "myAttribute" to be able to know about the "cat" float.
}

```

I want to recreate SirenX Odin Inspector's TabGroup and other render-by-group attributes and am wondering how to go about it in a path-of-least-resistance way.

My plan was to have a \[LabelTag(string label)\] which amassed all relevant members via reflection and then renders them in one go in OnGUI(){}. But the `declaringType` of the property attributes are returning null so I'm at a loss.

```
[CustomPropertyDrawer(typeof(MyAttribute))]
public class MyDrawer : DecoratorDrawer
{
  public override void OnGUI(Rect position)
  {
     GroupLabel groupLabel = (GroupLabel) attribute;
     Type attribType = attribute.GetType();
     Type declaringType_ISNULL = attribType.DeclaringType;
     //declaring type is null
  }
}

```

The only other solution I can think of is using something like sourceGenerators to autogenerate editor windows based off these attributes on the fly. While Unity doesn't support sourceGenerators yet, there's probably some equivalent more hacky thing I can do to insert myself into the editor build pipeline, but that seems like more hassle and potential jankinesss then I'm willing to attempt.

If anybody has any suggestions, or any insights into how SirenX Odin Inspector achieved this, that would be great!

Thanks.

# Answer
You want the declaring type of the *field* that uses the attribute, not the declaring type of the attribute itself. (The attribute type is defined in its own class file, so it has no tie back to the many different classes that might reference it)

Here's a quick & dirty demo of this, gathering up field names that occur after the label but before a different label:

```
[System.AttributeUsage(System.AttributeTargets.Field)]
public class GroupLabelAttribute : PropertyAttribute
{
    public string label;
    public GroupLabelAttribute(string label) {
        this.label = label;
    }
}

[CustomPropertyDrawer(typeof(GroupLabelAttribute))]
public class GroupLabelDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        var fields = fieldInfo.DeclaringType.GetFields();

        string names = fieldInfo.Name;

        int start = System.Array.IndexOf(fields, fieldInfo);
        int end = start;
        for (int i = start + 1; i < fields.Length; i++) {
            if (fields[i].GetCustomAttribute(typeof(GroupLabelAttribute)) != null)
                break;
            names += ", " + fields[i].Name;
            end++;
        }

        // Now we know the range of fields start to end that belong under this group.
        // For a quick demo, we'll just print out their names in place of the field:
        EditorGUI.LabelField(position,
            ((GroupLabelAttribute)attribute).label
            + "->" + fieldInfo.DeclaringType.ToString()
            + ":" + names);
    }
}

```
> 1 votes

---
Tags: unity, editors, serialization, code-reflection
---


title: How do I add light to my textures?

text:
# Question
Title: How do I add light to my textures?
How do I add light to my textures using this? I have this

```
GLfloat ka = 1.0;
glm::vec3 ia = glm::vec3(0.5f, 0.5f, 0.5f);

```

and in the fragment shader

```
out vec4 color;

in VS_OUT
{
    vec2 tc;
    vec3 normals;
}

fs_in;

layout(binding=0)uniform sampler2D tex;

void main(void)
{
color= texture(tex, fs_in.tc);
}

```

We were given this example but I don't understand what to do.

```
out vec4 color;
uniform vec3 materialColor;
uniform vec3 ia; // Ambient colour
uniform float ka; // Ambient constant
void main(void){
color = vec4( ka * ia , 1.0);
}

```

Help?

# Answer
Just multiply the two expressions you already have:

```
color= texture(tex, fs_in.tc) * vec4( ka * ia , 1.0);

```

This tints the colour of the texture by the colour and intensity of the ambient light.

This is shown in nearly every example shader and definitely in every single "how to get started with glsl shaders" tutorial on the net, so it does not look like you researched this at all. Please take the time to do a bit more legwork and reading before posting a question here in future.
> 0 votes

---
Tags: opengl, textures, lighting
---


# Question
Title: How do I change from virtual camera (e.g dolly track) to main camera?
I want to show a cinematic view of my scene and then be able to play it with the camera attached to my player.

I have set up a dolly track and virtual camera and all works fine but I can't then play as my main character.

How can I do this?

# Answer
You setup up two virtual Cams. One for your Cinematic View and one for your Playercharacter. The thing about the Cinemachine is, that the "real" camera switches to the position and paramteres of the virtual cameras. You can do the switching via the timeline, which isn't so flexibel https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineTimeline.html

**or** which seems for you more suitable via script and a "playbale director". Just create an empty with a box collider, playable director and following script

```
public class CinematicsTrigger : MonoBehaviour
    {
        bool alreadyTriggerd = false;

        private void OnTriggerEnter(Collider other)
        {
            if (!alreadyTriggerd && other.gameObject.tag == "Player")
            {
                alreadyTriggerd = true;
                GetComponent<PlayableDirector>().Play();
            }

        }
    }

```

In the playbale director you need to reference a "playbale" "Timeline Asset". A Timeline assets contains the virtualcameras for your cinematic. You can create a Timeline via rmb\>create\>Timeline https://docs.unity3d.com/2017.1/Documentation/Manual/class-PlayableDirector.html
> 2 votes

---
Tags: unity, camera, cinemachine
---


# Question
Title: GL error GL_INVALID_OPERATION: mismatched type setting uniform of location "4" in program "1"
I get this error while trying to add lighting

```
Message: Error has been generated. GL error GL_INVALID_OPERATION in Uniform1i: (ID: 2882512024) GL error GL_INVALID_OPERATION: mismatched type setting uniform of location "4" in program 1, "" using shaders, 2, "", 3, ""
type: ERROR --- id: 1282 --- severity: HIGH

```

this is my fragmentshader

```
out vec4 color;

in VS_OUT
{
    vec2 tc;
    vec3 normals;
}

fs_in;

layout(binding=0)uniform sampler2D tex;

uniform vec3 lightColor;

void main(void)
{
color= texture(tex, fs_in.tc)* vec4(lightColor, 1.0);

}

```

I have this in my render

```
GLint lightColor_location = glGetUniformLocation(program, "lightColor");
    glUniform1i(lightColor_location, 0);
    glUniform3f(lightColor_location, lightColor.r, lightColor.g, lightColor.b);

```

and this declared

glm::vec3 lightColor = glm::vec3(1.0f, 1.0f, 1.0f);
```
</code></pre>

# Answer
> 1 votes
```
glUniform1i(lightColor_location, 0);

```

This says "set `lightColor` to the single number value zero".

But `lightColor` *isn't* a single number - it's *three* numbers! You can't set a variable that wants three numbers by giving it only one.

The line immediately after that looks more correct:

```
glUniform3f(lightColor_location, lightColor.r, lightColor.g, lightColor.b);

```

Here we're trying to set a 3-component variable by giving it 3 numbers, so we've matched the input to the intended output.

---
Tags: opengl, textures, lighting
---


# Question
Title: How to make windows that pick up what appears in the other
Basically there are 2 windows that you can drag and drop around the screen. Whatever appears in one window will also appear in the other. The two windows cannot go one over the other.

This is a demo for the mechanic: https://youtu.be/9U4Zoagd\_40?t=83

I'm looking for a few steps in the right direction. How can something like this be implemented?

As I see from a comment below there are multiple parts to a mechanic like this, my focus for now would be 2) Making each rectangle display a superposition of the level content that's behind both

# Answer
> 0 votes
Here's a sketch of how you'd accomplish the rendering look:

Make two extra orthographic cameras in your scene, moving and sizing each to capture the rectangle covered by one window. Set their layer so that they can see the level tiles, but not the windows themselves, the player character, or other things the windows shouldn't be copying. They should also probably not see the background (set their clear colour to transparent black), to help with the layering later.

Assign a RenderTexture to the target field of each of these cameras, so they save what they see into a texture.

Assign a material to each window's quad with a custom shader that blends together these two RenderTextures into a single semi-transparent image.

For efficiency, you can re-render the view from these cameras only when one of the windows moves, but re-rendering every frame also won't break the bank.

# Answer
> 0 votes
As for how you could implement 3) from the comment.

* Have a duplicate actor that is invisible.
* Once you enter the window, spawn the invisible one in the second window.
* Disable control of first actor and control the invisible instead.
* Let the first actor mirror the position of the second actor.
* Hand over control to first actor once you leave the window.

This way you can handle as well interactions for 4). Spawn always an invisible object of whatever enters the window (like bullets) and handle the original the same way the invisible one gets treated.

---
Tags: unity, c#, 2d, game-mechanics
---


# Question
Title: Help with software design of a turn based combat system using SDL2
I have been working on a RPG where the player is free to wander an open world but when a monster is encountered or on keyboard command the game switches to a turn based system. Note this is not like final fantasy like games, I intend for the turn based combat to take place in the same map, there is no scene transition.

I am trying to wrap my head around how to implement the turn based combat system. Right now I have a basic game loop that handles the main world map where the player can move above, pick up items, engage in dialogue with npcs, this looks like this:

```
while (does_not_quit){
        input();
        logic();
        render()
        }

```

Within logic() there is a keyboard command that switches the game to turn based mode, turn based meaning the player and npcs' movement and actions are now controlled by aciton points and these refresh once per turn. My question is, mechanically from a software design point of view, what is the best way to implement this turn based system on top of the main game loop?

Currently, what I do is, upon entering turn based mode, I start to check player movement against available action points which are read from a json file for each npc (and player). But how do I generate the effect of turns? For example, when the NPCs move I have to halt all commands from the player and I want each NPC to move separately, one after another and then when its the player's turn again, keyboard commands are restored and the player makes his moves before hitting "end turn". Naively, I have tried using a for loop to cycle through all the npcs+players in a given turn but this doesn't seem right?

I have played around with a few methods but it just doesn't feel right and I feel that there must be some classic design patterns that do this but I haven't been able to find any literature on this.

Can anyone advise?

# Answer
> 1 votes
When your game has different modes it's in, and each mode should have different logic and different UI, then that's often a use-case for the state machine pattern.

So instead of having all your game logic in your one `logic()`-function, you create a separate `logic`-function for each state your game can be in.

You might also want to create an `enter`-function and `leave`-function for each state which do the logic for initializing and cleaning up the state. In order to keep everything that belongs to one state together, it can be a good idea to keep those three functions for each state together in one source file for each state. Or if your code gets too long for that, you might want to create a separate folder for each state.

Your logic-function would then look something like that:

```
void logic(void) {
    /* stuff you want to happen in every state */

    case (currentState) {
        STATE_WALK:
            walk_logic();
            break;
        STATE_DIALOG:
            dialog_logic();
            break;
        STATE_COMBAT:
            combat_logic();
            break;
    }
}

```

Now you can switch states by changing the value of `currentState` between a bunch of constants. But wait, remember to call the enter and leave functions. To make sure you don't skip them, you might want to create an utility function for that:

```
void switchState(int newState) {
    // exit the old state
    case (currentState) {
        STATE_WALK:
            walk_leave();
            break;
        STATE_DIALOG:
            dialog_leave();
            break;
        STATE_COMBAT:
            combat_leave();
            break;
    }
    // enter the new state
    case (newState) {
        STATE_WALK:
            walk_enter();
            break;
        STATE_DIALOG:
            dialog_enter();
            break;
        STATE_COMBAT:
            combat_enter();
            break;
    }

    // NOW we can change the state
    currentState = newState;
}

```

Note that you can also have more than one state-machine in your game. For example, your function `combat_logic` might in turn be implemented by a state machine itself switching between states like "select unit", "select unit action", "select action target", "execute action", "execute ai" etc. This pattern of state-machines within states of other state-machines is called "Hierarchical State Machines".

---
Tags: architecture, rpg, sdl2, turn-based
---


title: Humanoid rig breaks my animation

text:
# Question
Title: Humanoid rig breaks my animation
The humanoid rig behaves strangely with my animation from Blender. Here is a demo of the problem - video.

Can anyone suggest what the problem might be?

# Answer
> 1 votes
It appears that you don't have "Apply Root Motion" checked in your Animator component.

Without that setting, the root bone of your 3d model stays bolted to the game object and all the other bones move relative to it.

With that setting, the whole gameObject will move when the animation moves the root bone. So in effect the object will move down when the root bone moves down.

Leaving this disabled can be useful in some cases because it ensures that your C# scripts retain full control over the position of the game object. But it is of course inconvenient when you have animations like this which change the height of the object root. It also means that you are now responsible for making sure that the speed of the walk cycle matches the speed with which you move the object. When you use root motion, then the movement speed is defined by the root motion of the walk animation in blender.

# Answer
> 1 votes
The wrong bone was assigned to hips slot in the Humanoid rig settings.

I figured this out, assuming that my hip bone for some reason does not have animation, it hangs static in the air. Then I looked into the Humanoid rig configuration and saw a bone in the thigh slot that I really didn't animate and which is generally a root, not a hip.

---
Tags: unity, animation, skeletal-animation, import
---


# Question
Title: How to generate a correct RGB + Luminance histogram?
I am trying to create a debug tool that would help me visualize an image RGB and luminance histogram. I have created a compute shader where I gather the histogram data

```
#pragma kernel Clear
#pragma kernel Gather

Texture2D<float4> Input;

struct HIST {
    uint4 color;
};
RWStructuredBuffer<HIST> HistogramBuffer;

[numthreads(64, 1, 1)]
void Clear(uint3 id : SV_DispatchThreadID)
{
    HistogramBuffer[id.x].color = uint4(0, 0, 0, 0);
}

[numthreads(8, 8, 1)]
void Gather(uint3 id : SV_DispatchThreadID)
{
    uint4 col = uint4(255.0 * Input[id.xy]);

    InterlockedAdd(HistogramBuffer[col.r].color.r, 1);
    InterlockedAdd(HistogramBuffer[col.g].color.g, 1);
    InterlockedAdd(HistogramBuffer[col.b].color.b, 1);
    InterlockedAdd(HistogramBuffer[dot(col.rgb, float3(0.2126729, 0.7151522, 0.0721750))].color.a, 1);
}

```

And in the c# code after I've gathered the data I create a final output texture.

```
using UnityEngine;
using UnityEngine.UI;

internal sealed class Histogram : MonoBehaviour
{
    public const int HISTOGRAM_BINS = 256;
    uint[] histogramData;

    [SerializeField]
    ComputeShader shader;
    ComputeBuffer histogramBuffer;

    [SerializeField] RawImage output = null;
    [SerializeField] Texture2D input;

    public void Start()
    {
        //Init kernels
        int clearKernel = shader.FindKernel("Clear");
        int gatherkernel = shader.FindKernel("Gather");

        //Init data
        histogramBuffer = new ComputeBuffer(HISTOGRAM_BINS, sizeof(uint) * 4);
        histogramData = new uint[HISTOGRAM_BINS * 4];

        //Set data
        shader.SetTexture(gatherkernel, "Input", input);
        shader.SetBuffer(gatherkernel, "HistogramBuffer", histogramBuffer);
        shader.SetBuffer(clearKernel, "HistogramBuffer", histogramBuffer);

        //Execute shader
        shader.Dispatch(clearKernel, HISTOGRAM_BINS / 64, 1, 1);
        shader.Dispatch(gatherkernel, input.width / 8, input.height / 8, 1);

        //Get data
        histogramBuffer.GetData(histogramData);

        //Find highest value
        uint highestValue = uint.MinValue;
        for (int i = 0; i < histogramData.Length; i++)
        {
            if (histogramData[i] > highestValue)
            {
                highestValue = histogramData[i];
            }
        }

        //Create final output texture
        Texture2D final = new Texture2D(HISTOGRAM_BINS, input.height)
        {
            filterMode = FilterMode.Bilinear,
            wrapMode = TextureWrapMode.Clamp
        };
        final.Apply();

        //Init the texture pixels array
        Color32[] pixels = new Color32[HISTOGRAM_BINS * input.height];

        //Get all red values from the histogram data array
        uint[] reds = new uint[HISTOGRAM_BINS];
        for (int i = 0, h = 0; i < HISTOGRAM_BINS; i++, h += 4)
        {
            reds[i] = histogramData[h];
        }
        pixels = ComputeChannelHistogram(pixels, in reds, highestValue, new Color32(255, 0, 0, 255));

        //Get all green values from the histogram data array
        uint[] greens = new uint[HISTOGRAM_BINS];
        for (int i = 0, h = 1; i < HISTOGRAM_BINS; i++, h += 4)
        {
            greens[i] = histogramData[h];
        }
        pixels = ComputeChannelHistogram(pixels, in greens, highestValue, new Color32(0, 255, 0, 255));

        //Get all blue values from the histogram data array
        uint[] blues = new uint[HISTOGRAM_BINS];
        for (int i = 0, h = 2; i < HISTOGRAM_BINS; i++, h += 4)
        {
            blues[i] = histogramData[h];
        }
        pixels = ComputeChannelHistogram(pixels, in blues, highestValue, new Color32(0, 0, 255, 255));

        //Get all lum values from the histogram data array
        uint[] lum = new uint[HISTOGRAM_BINS];
        for (int i = 0, h = 3; i < HISTOGRAM_BINS; i++, h += 4)
        {
            lum[i] = histogramData[h];
        }
        pixels = ComputeChannelHistogram(pixels, in lum, highestValue, new Color32(127, 127, 127, 255));

        //Set pixels
        final.SetPixels32(pixels); final.Apply();

        //Set output image
        output.texture = final;
    }
    Color32[] ComputeChannelHistogram(Color32[] pixels, in uint[] data, float max, Color32 color)
    {
        for (int x = 0; x < HISTOGRAM_BINS; x++)
        {
            float p = Mathf.InverseLerp(0F, max, data[x]);
            for (int y = 0; y < input.height * p; y++)
            {
                int index = x + (y * HISTOGRAM_BINS);
                Color32 pixelColor = pixels[index];

                pixelColor.r += color.r;
                pixelColor.g += color.g;
                pixelColor.b += color.b;

                pixels[index] = new Color32(pixelColor.r, pixelColor.g, pixelColor.b, 255);
            }
        }
        return pixels;
    }
}

```

However, I am getting weird results and not sure why.

E.g. input image (Figure 1)

The histogram that is generated

The histogram that is generated in Photoshop

Can someone please help me understand what am I doing wrong here and how can I fix it to have better results? I just recently started looking at histograms, I understand what they show and are, the vertical is a number of pixels and the horizontal bars that go from left to right are the tones, so left is blacks, the middle is midtones, and right is whites, but for some reason I have a difficult time creating one...

# Answer
> 1 votes
The solution to the problem I was having was firstly ensuring that the input image was not compressed in any way, so having it as none.

Moreover, the maxSize in the import settings of the texture had to be set higher than the input original size. Limiting the maximum texture size results in a lack of information in the histogram graph.

It is probably best to load the texture through the script, that way you will not have any issue with size limitation.

I have also changed the highest value for each RGB graph to the highest value in the channel array, instead of the entire histogram data array as I've done before.

The last issue that made the graph lack detail was fixed by dividing the gather compute shader dispatch thread groups, width for x, and height for y by 8, instead of 16.

---
Tags: unity, c#, hlsl, image-processing
---


# Question
Title: Math formula for: the higher the stress, the higher the difficulty
My game has a stat called `Stress`, and the player has some missions to do. Each mission has a computed stat called `Difficulty` with its own base value. So, let's say:

* Mission 1, Difficulty 1

However, I want to sum to this difficulty an `X` amount, where `X` is a % of the player's stress. Turns out I don't want this % to be static, but instead, the higher is the amount of the player's `Stress`, the higher is the percentage. To illustrate:

* `Stress` = 10
* Mission 1, Difficulty 2
* `Stress` = 20
* Mission 1, Difficulty 2
* `Stress` = 30
* Mission 1, Difficulty 3
* `Stress` = 40
* Mission 1, Difficulty 5
* `Stress` = 50
* Mission 1, Difficulty 8
* `Stress` = 100
* Mission 1, Difficulty 50

*The numbers are merely illustrative and don't represent the exact numbers I'd expect.*

As you can see, the difficulty doesn't scale linearly.

I don't know the proper keywords to browse for this, so that's why I'm here with this poor vocabulary. Also, I apologize in anticipation if this is duplicated.

# Answer
We can throw your example numbers into a spreadsheet and chart them, say using Google Sheets, and get a look at what the progression looks like:

We can add a trend line to the graph to try to fit a formula to the data. In Google Sheets, this can be found under:

Chart editor \> Customise \> Series (Difficulty) \> Trend Line

I used these settings, and got a pretty decent fit with a polynomial of degree two (a quadratic):

We could use exactly the equation that the trend line found for us, but it has a dip in the middle which isn't ideal. So let's see if we can make our own version using that as inspiration.

Here I tried squaring the stress value, and dividing by 10000 (bringing a maximum of 100 * 100 stress down to an output value of 1). Then I multiplied the result by 49 and added 1, to get an output between 1 and 50.

That gets pretty close to your numbers, but it over-estimates a little in the middle. Let's try cubing stress instead. Here I'll normalize stress between 0 and 1 by dividing by 100, then cube this normalized value, multiply by 49 and add 1 as before. And then let's take the ceiling (next integer higher than the number we get out). That reproduces your example values perfectly.

Moreso than any particular formula though, I hope this demonstrates for you a method that you can use to explore and find formulas on your own.
> 6 votes

---
Tags: mathematics, game-design
---


# Question
Title: Why does a public variable define a private one?
What is the point of such work with variables?

```
public GameObject Obj => _obj;
[SerializeField] private GameObject _obj;

```

A private variable loses its privacy when we create a public variable that defines a private one. For me it looks meaningless and only confuses.

# Answer
> 1 votes
This doesn't create a public *variable* that defines a private one, it creates a public **property**. Using a property allows you to later add code you always want to get executed when that variable is getting set and/or read. This is not happening in this example (yet), but when you create properties like this preemptively, then it gets a lot easier to add this functionality later.

Further, this particular syntax creates a property which can only be read but not written. That means that other scripts can find out what `_obj` this component references, but they can not change it. There are often situations where changing a variable like that at runtime can lead to unexpected behavior. For example, when you do some stuff with that gameObject in `Start()`. So when you write a MonoBehavior which does not support changing a variable at runtime, then it's a good idea to follow this pattern so that nobody later thinks they can do that without causing any weird bugs.

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


# Question
Title: Why is there only one variable displayed in the Inspector?
Using the following code, only one variable is shown in the inspector:

```
[SerializeField] private GameObject _obj;

```

This makes sense, since there is only one field.

---

However, with this code, there is still only one variable in the inspector. I would expect there to be two variables:

```
public GameObject Obj => _obj;
[SerializeField] private GameObject _obj;

```

---

Why aren't there two variables in the second example?

# Answer
```
public GameObject Obj => _obj;

```

This is not a variable, it's a property. It's equivalent to this:

```
public GameObject Obj {
    get {
        return _obj;
    }
}

```

So it's just syntactic sugar for a `public GameObject GetObject() { return _obj; }` method.

Since Unity's Inspector displays *serialized fields*, not methods, there's nothing here for it to display (no stored value that belongs to the symbol `Obj`). The stored value belongs to the "backing field" `_obj`, so that field is the only one the Inspector shows.

You can ask the compiler to automatically generate a private backing field for you instead of writing one yourself, using an auto-implemented property:

```
public GameObject Obj { get; private set; }

```

This is equivalent to....

```
private GameObject _hiddenCompilerGeneratedField;
public GameObject Obj {
    get {
        return  _hiddenCompilerGeneratedField;
    }
    private set {
         _hiddenCompilerGeneratedField = value;
    }
}

```

This way your code can still set the private backing field by calling the setter (like `Obj = foo;`), even though we don't have a visible name to call that field, since the compiler is generating it for us.

That's a convenient way to make a variable that only code in this class can set, while other code can still read it - useful for maintaining invariants and minimizing the surface area for bugs. If the variable ever gets set to the wrong value, there are fewer places that could have happened, making the problem easier to reason about.

The trouble with this is that the compiler generates that field as private, without the `[SerializeField]` attribute. Since Unity's Inspector is built on its serialization system, which only serializes fields that are public or marked with `[SerializeField]`, this compiler-generated field gets skipped over.

So in the example code you've found with both `Obj` and `_obj`, the author is trying to work around this limitation by declaring their backing field and public getter manually.

There's a somewhat neater way to do that though, if all you want is a serialized private field with a public getter. You can use a modified version of the `[SerializeField]` attribute to target the hidden backing field generated by the compiler when declaring an auto-property:

```
[field: SerializeField]
public GameObject Obj { get; private set; }

```

Just like the `Obj` and `_obj` example, this also creates a serializable field that can show in the inspector and be set by code inside this class, and exposes it via a public property getter. The only difference here is that now we can set the private field via `Obj`'s setter, without needing to define a separate name for it ourselves.

Just remember that when exposing the backing field of a property to the inspector like this, you're exposing only the storage for the variable - not the get and set methods. As the Unity documentation notes:

> If you use properties in your script, any of the property getters and setters are never called when you view or change values in the Inspector windows as Unity serializes the Inspector window fields directly. This means that: While the values of a field in the Inspector window represent script properties, **changes to values in the Inspector window do not call any property getters and setters in your script**.

That's not an issue for auto-properties, since by definition they have nothing else that's supposed to happen in their getters/setters, but it can be a risk if you define your serialized backing field separately and then start putting extra code into the property getter/setter, forgetting that the Inspector and deserializer will bypass those entirely.
> 11 votes

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


# Question
Title: How to rotate my enemy so it scans the area?
Hi I am new to unity so I am not super familiar with methods. I am trying to make my enemy rotate left then right double the amount that it rotated and back to the middle like this: +10 degree, -20 degree then +10 degree back to 0. I am trying transform.rotate however I believe I have a bad understanding of it and doing something wrong.

Edit: Even though I got the answer and it works the problem was that it inconsistently rotated like it went: +5 degree then -2 then +5 again. Next time I ran it it would be different values even though they were the same in the script.

Here is the method:

IEnumerator LookAroundArea(GameObject self)
    {
        if (10 >= Random.Range(1, 500))
        {
            Debug.Log("it runs");

            self.transform.Rotate(new Vector3(0, 1, 0), 45 * Time.deltaTime * 45);
            yield return new WaitForSeconds(1.0f);
            self.transform.Rotate(new Vector3(0, -1, 0), 45 * Time.deltaTime * 90);
            yield return new WaitForSeconds(2f);
            self.transform.Rotate(new Vector3(0, 1, 0), 45 * Time.deltaTime * 45);
            yield return new WaitForSeconds(1.0f);
        }
        dontrunagain = true;
    }
```
</code></pre>

# Answer
`Transform.Rotate` rotates the object the full amount you asked for, instantly. It is not a tweening function that starts a gradual rotation that will complete over time.

If you want to rotate something over time, you can make your own coroutine for that:

```
IEnumerator Rotate(Transform self, Quaternion from, Quaternion to, float duration) {

    for (float t = 0; t < 1f; t += Time.deltaTime / duration) {
        // Rotate to match our current progress between from and to.
        self.rotation = Quaternion.Slerp(from, to, t);
        // Wait one frame before looping again.
        yield return null;
    }

    // Ensure we finish exactly at the destination orientation.
    self.rotation = to;
}

```

Then you can just invoke that coroutine and wait for it to finish its work:

```
IEnumerator LookAroundArea(Transform self)
{
    if (10 >= Random.Range(1, 500))
    {
        Debug.Log("it runs");

        // Cache the start, left, and right extremes of our rotation.
        Quaternion start = self.rotation;
        Quaternion left = start * Quaternion.Euler(0, -45, 0);
        Quaternion right = start * Quaternion.Euler(0, 45, 0);

        // Yield control to the Rotate coroutine to execute
        // each turn in sequence, and resume here after each
        // invocation of Rotate finishes its work.

        yield return Rotate(self, start, left, 1.0f);

        yield return Rotate(self, left, right, 2.0f);

        yield return Rotate(self, right, start, 1.0f);
    }
    dontrunagain = true;
}

```
> 1 votes

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


# Question
Title: Deriving shadow position from a 2D heightmap
I have a 2D heightmap with discrete values. Based on these values they should cast a fixed position shadow (constant angle respective to the "sun"). I can figure out how to cast it on a flat surface (0 in the heightmap). But not entirely sure how to cast it on elevated tiles (heightmap value \> 0) because obviously the shadow is going to be shorter. How do I "walk" the tiles that should be shadowed? Themselves will cast a shadow as well but that may be overridden if behind them is a taller cliff which completely shadows the current tile.
Note that I'm interested in the algorithm of determining each tile's shadow value, not the rendering side of it. Here's an example screenshot of a game doing the same:

# Answer
> 4 votes
You can associate a "shadow height" with each cell on your map. This is the elevation something would need to have above 0 / "sea level" in order to rise out of the shadow and into the light.

You can initialize the shadow height of all tiles on the left edge of your map to zero.

Then, working across your map from left to right, each tile can compute its shadow height using its neighbouring tile to the left:

```
this.shadowHeight = max(leftNeighbour.terrainHeight + leftNeighbour.tileHeight,
                        leftNeighbour.shadowHeight
                  ) - shadowSlope;

```

...where `shadowSlope` is a parameter you can tune to control the length of your shadows, representing the slope of the terminator between lit and shadowed regions. Low values behave like sunrise/sunset, where the light rays are almost parallel to the ground and shadows get super long. High values behave more like noon where the light rays are coming down almost vertically, making tiny shadows.

Any tile with `shadowHeight > terrainHeight` is in shadow.

If you want to simulate soft shadows, you can set the shadow darkness to be proportionate to `shadowHeight - terrainHeight`.

Result provided by KayleMaster:

---
Tags: 2d, geometry, isometric, shadows, heightmap
---


title: Camera angle for dimetric projection

text:
# Question
Title: Camera angle for dimetric projection
I have a simple 3D engine and I want to make a isometric(dimetric) game, but where tiles are not real 3D planes, but 2D images like this one:
As I understand this tile is drawn in dimetric 1:2 projection But **I can't get right camera angles in order to have view, where all given tiles would fit perfectly by pixel.** After reading this page I've tried rotating camera relatively to itself by x=26.565deg y=45deg but that gave me bad result.
It's clearly visible, that tiles don't fit together nicely.
I've tried different value, by just handpicking them, and the closes one was x:30deg y:45deg angles. But there is a problem with gaps between tiles. It maybe somehow related to problem, that I don't know how to calculate length of one tile edge in world space, currently when I put tiles in scene I space them by 45units, which also is a handpicked value.

You would ask, "Why do I try to do this in 3D engine?". I want to mix 2D tile and object sprites with simple 3D objects in one game. I've already did isometric terrain with 2D engine, where everything can be simply calculated and doesn't need to position a camera.

# Answer
> 0 votes
Ok, got it!) It turns out that 30deg angle is perfect for this, I can't prove it matematicaly but it works. Problem with gaps also dissappeared, when I spaced tiles with distance of 45.261 between each other. 1/2LENGTH\_OF\_TILE\_SPRITE\_32PX * (1/Cos(45)) = 45.261.

# Answer
> 0 votes
I've been trying to get my 3d models line up with the 2D tiles I have used in Unity in an isometric view. Turns out its technically a 'Diametric" view and through experimenting I have found that placing an orthographic camera at **Z-45d** with an **X value of 60.5d** has resulted in them almost perfectly lining up. I'm not a math guy by any means no idea why it is, but its working. Hope this helps someone!

---
Tags: isometric
---


# Question
Title: Check if NavMeshAgent can reach position with dynamic obstacles
I am currently checking if a position in the NavMesh is reachable. It is reachable without the NavMesh obstacles. But the moment I add it, NavMesh's `CalculatePath()` continues to return true. Note that I do have those obstacles to have carving set to true. How do I solve this problem?

Reference: https://answers.unity.com/questions/1184356/how-to-know-if-a-navigationmeshagent-is-impossible.html

# Answer
I fixed my problem by doing the ff:

```
public bool CanReachPosition(Vector2 position)
{
      NavMeshPath path = new NavMeshPath();
      agent.CalculatePath(position, path);
      return path.status == NavMeshPathStatus.PathComplete;
}

```

After getting the path, we need to check if the path is `NavMeshPathStatus.PathComplete` or if the path is getting to the destination. The path will be `.PathPartial` if the path is incomplete.
> 1 votes

# Answer
There is a NavMeshObstacle for dynamic obstacles. As you already, pointed out you are using them with Carving set to true (so they make a whole in navmesh, that agents should avoid - described in docs, see "carving"). But checking boolean result of NavMeshAgent.CalculatePath(target, path) is not enough as it is about whether path is found or not. We need to check if path is full (not partial) through path.status after the call, e.g.:

```
using UnityEngine;
using UnityEngine.AI;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public Transform target;
    private NavMeshAgent agent;
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        NavMeshPath path = new NavMeshPath();
        agent.CalculatePath(target.position, path);
        if (path.status == NavMeshPathStatus.PathComplete)
        {
            // ...
        }
    }
}

```

Example based on docs on CalculatePath. For full list of path statuses, see AI.NavMeshPathStatus.
> 1 votes

---
Tags: unity, 2d, ai, navmesh
---


# Question
Title: Why is ScreenToWorldPoint always giving same coordinates with mouse position?
Whenever I use `ScreenToWorldPoint(Input.mousePosition)` and display the output in console this always gives me the same coordinates.

MyCode:

```
Vector3 screenToWorld;

void Update()
{
    screenToWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Debug.Log(screenToWorld);
}

```

# Answer
> 11 votes
If I remember correctly, for `ScreenToWorldPoint` you need to provide a Z value. This represents a distance to a plane, on which you want to get your resulting position. Try to use this:

```
new Vector3( Input.mousePosition.x, Input.mousePosition.y, 1.0f )

```

as your input position.

Here you have Unity example: https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

# Answer
> 2 votes
To make it properly you should pass the camera's *z*, like this:

```
Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, mainCamera.transform.position.z)) * -1;

```

However, I do not recommend you using `Camera.main`, performance is way better if you keep a reference to the camera.

```
public Camera mainCamera;

mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, mainCamera.transform.position.z * -1));

```

You should multiply *z* by -1 here because this will bring you the inverted values of X and Y otherwise.

# Answer
> 2 votes
Check your camera projection. It will be perspective. It is because, in perspective view, depth is in the calculation. Since your mouse is in screen space, in simple words your mouse is on the camera itself. So you are trying to convert the camera coordinate into the world. That is why that code will debug the position of the camera itself. So all you need to do is to add a distance from the camera to convert the point.

```
Vector3 screenToWorld;

void Update()
{
    screenToWorld = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 5f));
    Debug.Log(screenToWorld);
}

```

5f is the distance from the camera plane the coordinates will be converted. Now, this issue will not happen when you switch to orthographic projection in the camera setting as there is no depth calculation required.

A small trick to understand this is to look at the camera gizmo in both the projection. Perspective has a pyramid-like structure where orthographic has a cuboid-like. So the camera origin in the case of perspective is like a point and your mouse is operating on that point so it will only give you the camera coordinate. Isn't it? Now it's just a trick to remember that's all.

# Answer
> 1 votes
The `Camera.main.ScreenToWorldPoint()` will return the camera's poisiton if you do not include the camera's Z position in the world, if the camera is set up with perspective projection.

For perspective projection:

```
public Camera camera;

Camera.main.ScreenToWorldPoint(new Vector3(Input.mousPosition.x,
 Input.mousePosition.Y, camera.transform.position.z));

```

For orthographic projection:

```
Camera.main.ScreenToWorldPoint(Input.mousePosition);

```

will work fine.

# Answer
> 1 votes
This works fine for me:

```
Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0,0, Camera.main.transform.position.y));

```

# Answer
> 1 votes
Another solution could be:

```
float zCoord = Camera.main.WorldToScreenPoint(transform.position).z;

Vector3 mousePosition = Input.mousePosition;
mousePosition.z = zCoord;
Vector3 pos = Camera.main.ScreenToWorldPoint(mousePosition);

```

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


# Question
Title: How would I go about preparing my skybox for a z-up world orientation?
\****Solved!**\** Special thanks to comments from Maximus Minimus and Jherico. Scroll down for the solution made in the shader.

I am working on a vulkan renderer in rust using the ash crate. I would like to keep a z-up world orientation as all the 3d tools I've used use this orientation and I would like to be consistent in that workflow.

When positioning my view in this orientation I haven't been able to get the skybox in the proper orientation. I've tried exporting a cube in blender with z-up coordinates. That just left me with a strange triangle pattern of a skybox. Changing the face load order won't help as the x-axis is still in the wrong orientation. I haven't found any documentation that would help with a z-up oriented skybox (or at least one that I can understand). If I need different textures, is there a place to get z-up skybox textures, or do I have to rotate these by hand? Looking for advice or a point in the right direction. Images below to help illustrate my desired outcome.

As you can see, the skybox works fine with y-up orientation (model hasn't been rotated for y-up). I want my skybox to look like this using z-up orientation.

But on z-up world orientation my skybox also flips 90 degrees on the x axis.~  z-up from the side~

\****Solved!**\** Solution as mentioned in the comments is to change the orientation on the vertices. Changing the vertices themselves led me down to disaster. Most convenient place for this, was in the shader. I added a self-explanatory function to my glsl vertex shader. The code should be easy to follow.

```
#version 450

layout(binding = 0) uniform UniformBufferObject {
    mat4 model;
    mat4 view;
    mat4 proj;
} ubo;

layout(location = 0) in vec3 inPosition; // incoming vertices
layout(location = 0) out vec3 outTextureDirection; // outgoing vertices for cubemap sampler

// returns a 90 degree x-axis rotation matrix
mat4 get_z_correction_matrix()
{
    float s = sin(radians(90.0));
    float c = cos(radians(90.0));
    return mat4(
        1, 0, 0, 0,
        0, c, s, 0,
        0, -s, c, 0,
        0, 0, 0, 1
    );
}

void main() {

    outTextureDirection = inPosition;

    mat4 ZUP_CORRECTION = get_z_correction_matrix(); // used to correct for my z-up view

    mat4 no_translation_view = ubo.view;
    no_translation_view[3] = vec4(0.0, 0.0, 0.0, 1.0); // so skybox doesn't move with camera;

    gl_Position = ubo.proj * no_translation_view * ZUP_CORRECTION * vec4(inPosition, 1.0);
}

```

# Answer
From what I can tell, Ash isn't a rendering engine, just a wrapper around the Vulkan API. Therefore you are presumably using your own engine and shaders to actually render everything.

So, just modify your skybox shader to apply a transform to the skybox vertices to rotate them 90 degrees on the X axis. That will result in Z UP and Y backwards. Alternatively, since the default Vulkan coordinate system is Y up, your model rendering code must be applying some kind of transform to all vertex coordinates to make the Z up into Y up on the fly. Just don't do that to your skybox model vertex data.
> 1 votes

# Answer
Assuming the skybox faces are loaded in the following order: front, back, up, down, right, left, and the skybox texture is a cubemap rather than 6 individual faces, you can reorient it for z-up by applying the following matrix to it's texture coords (this also positions it correctly relative to the players eye position):

```
0, 0, 1, 0, -1, 0, 0, 0, 0, 1, 0, 0, eyepos.y, -eyepos.z, -eyepos.x, 1

```

(You may or may not need to transpose this depending on your preferred convention).
> 1 votes

---
Tags: 3d, graphics-programming, vulkan, skybox, rust
---


# Question
Title: How to remove the influence of a region of a texture, using texture stages?
I created a 512x512 shadow texture, and I don't want to render the center part on my Terrain. Can something like this be done? I didn't find anything on the internet about this

(Example as in the picture)

I want to do this because I want to have a different texture in the center. If I don't cut it, it blends with my second, and I will have texture0 + texture1.

If I don't blend the textures, I will have texture0 or texture1.

Code:

```
STATEMANAGER.SetTransform(D3DTS_TEXTURE0, &m_matDynamicShadow);
STATEMANAGER.SetTexture(0, m_lpCharacterShadowMapTexture);

STATEMANAGER.SetTransform(D3DTS_TEXTURE1, &m_matDynamicShadow2);
STATEMANAGER.SetTexture(1, m_lpCharacterShadowMapTexture2);

STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);

STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT);
STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE);

```

# Answer
> 0 votes
Since you're using `D3DTOP_MODULATE` (multiplication) to blend your textures, you can effectively remove the influence of this texture in regions you don't want it to affect by painting it white in those places. (White maps to one, and multiplying anything by one returns the input unchanged).

You could do this by rendering a plain white quad into the middle of your texture after generating your shadow information, or by clearing the texture to white and using a stencil test to prevent rendering of shadow information into the middle square in the first place.

---
Tags: textures, directx9
---