title: Broken model matrix builder

text:
# Question
Title: Broken model matrix builder
I'm trying to setup basic render pipeline in Vulkan and am currently setting up the perspective, view and model matrices.

The line that calculates the position in the vertex shader is this:

```
gl_Position = ubo.model * vec4(inPosition, 1.0);

```

where `inPositio`n is a `vec3`, while `ubo.model` is a `mat4` representing the model matrix

I'm not touching the camera or perspective yet, so the camera is in the origin looking towards the positive Z axis. This is the object I'm passing to the vertex shader:

```
const std::vector<float> vertices = {
    -0.25f, -0.25f, 0.0f,
    0.25f, 0.25f, 0.0f,
    -0.25f, 0.25f, 0.0f,
    0.25f, -0.25f, 0.0f,
};

const std::vector<uint16_t> indices = {
    0, 1, 2,
    0, 3, 1
};

```

Object initial `m_position` and `m_rotation` are set to `glm::vec3(0.0f)` and `glm::quat(0.0f)`.

These are the transformations that I then apply to the object:

```
object->translate(glm::vec3(0.0f, 0.0f, 0.5f));
object->rotate(glm::vec3(glm::radians(5.0f), 0.0f, 0.0f));

```

First line pushes the object 0.5 toward the positive Z, moving it away from the camera. The rotate function actually takes a `glm::quat`, but passing in a `vec3` interprets the vector as euler angles and casts them to an equivalent quaternion.

I've also bound the rotate call to be called once per frame, so I can observe how the object is rotated.

These are the translate and rotate functions:

```
void Mesh::translate(glm::vec3 offset) {
    m_position += offset;
}

void Mesh::rotate(glm::quat rotation) {
    m_rotation = m_rotation * rotation;
}

```

I'm honestly not sure if I'm multiplying the rotations in the right order, but it seems to work the same however I order it. I know that the quaternion multiplication is not commutative, but perhaps the change here can only be observed with a perspective.

This is the code that (currently) calculates the model matrix out of model position and rotation:

```
glm::mat4 Mesh::getMeshMatrix() {
    glm::mat4 meshMatrix(1.0f);

    meshMatrix = glm::mat4_cast(m_rotation) * meshMatrix;
    meshMatrix = glm::translate(meshMatrix, m_position);

    return meshMatrix;
}

```

`m_rotation` is a `glm::quat` and `m_position` is a `vec3`. I'm also not sure about the rotation multiplication order, but since the `meshMatrix` is an identity matrix, I don't think it makes a difference in this particular case.

If I comment out both of the lines, I get a square in the middle of my window, as expected (I set the window to have the aspect ratio of 1, at least until I introduce the perspective matrix).

If I comment out only the rotation line, I get the same output as earlier. The square is pushed back `0.5f`, but since there's no perspective, it looks the same. I've tried changing the translate function call to move it left, right, up and down and it works as one would expect. I believe that the translation works as it should.

If I comment out only the translation, the square rotates around the X-axis (horizontally). Only one side of it is visible (due to face culling), and even then, I can only see the half of the square because either upper or lower half is now within negative Z-axis and is being clipped out. I can also change the call to rotate it around the Y-axis and Z-axis. Rotation along the Y-axis is analogous to the X-axis rotation, only the rotation is now vertical. Rotating it around the Z-axis spins the square in a way that it's visible all the time (like watching a carousel from above), which is to be expected since the z coordinates are not changed. So I conclude that rotation works as it should.

The problem arises when I comment out nothing. What I get is a square that is first translated along the Z-axis, and then the whole system is rotated around the origin. The result is what you'd see if you were in a rolling barrel with the square taped to the inside of it. As the square is rotated in the negative z it disappears due to the fact that it's behind the camera (and even if not for that, I still could not see it due to face culling).

This is what would happen if I were to translate the object before I rotate it. but no matter on how I order the two lines, I get the same result.

Once `meshMatrix` is returned from the `getMeshMatrix`, it will be copied to the GPU as is, with no further modifications, so I can't see and error happening there. And position and rotation are completely separated prior to that function, so I don't believe that anything fishy happens beforehand. And finally, translation and rotation work properly on their own, so their interaction must somehow be wrong. And only thing that can really be wrong is order of operations, but changing the order does not change the output, which seems wrong.

What gives? What am I missing?

# Answer
I found what I messed up. It seems that `glm::translate(mat4, vec3)` doesn't do what I though it does.

What I thought it does is that it takes the provided `mat4` and `vec3`, treats the `mat4` as a transformation matrix, and applies the translation described by `vec3`.

It obviously works in some other way (or there is a detail I have missed that breaks it in the way I used it).

The function that actually does what I want is the following:

```
glm::mat4 Mesh::getMeshMatrix() {
    glm::mat4 identity(1.0f);

    glm::mat4 rotate = glm::mat4_cast(m_rotation);
    glm::mat4 translate = glm::translate(identity, m_position);

    return translate * rotate;
}

```

It's a bit more memory inefficient, but at least it works.

If anyone comes across this and figures out what exactly I did wrong, feel free to add a comment, edit my answer, or write an answer of your own.
> 0 votes

---
Tags: c++, matrix, models, mesh
---


# Question
Title: Event manager/system for an open world adventure game in Unity
I'm making an adventure game set in a school (think Bully, but much less scope as I am one person) and I'm starting to program the last important systems like a sound manager and an event system and I'm a bit confused about the event system.

Basically, I want to be able to track stuff like missions completed that may cause some stuff to happen like changing dialogue of a character. One other example is that talking to one character before another will cause you to interact with them differently. I don't want to handle this kind of stuff for each indivdual NPC, especially since each NPC has one script that holds stuff like their current dialogue and other important data.

Another thing in my game is that the time is based on periods rather than a real-time system. Every time you complete a mission or some other event, it will change (the periods are Morning, Afternoon, Evening, and Midnight), which also changes the position of NPCs and may also change their dialogue.

How would I design such a system?

# Answer
> 1 votes
Most games handle this with a large array of boolean (in some cases integer) story flags.

Your dialogue system should be able to check these flags and trigger different dialogue lines depending on whether or not certain flags are set.

Example: When the player completed Quest X, you set QUEST\_X\_COMPLETED to true. When the player completed this quest with the evil choice, you also set QUEST\_X\_EVIL to true. But when the player completed this quest with the good choice, you instead set QUEST\_X\_GOOD to true.

Now the NPC involved in that quest would check those flags. If QUEST\_X\_COMPLETED is false, they tell the player to complete Quest X already. When it is true, it thanks the player for completing Quest X. When QUEST\_X\_EVIL is set, they then call out the player for being such a meanie. When QUEST\_X\_GOOD is set, they then call out the player for being such a wuss.

You might also need a system which allows you to use story flags to decide whether or not certain objects in the game appear at all. So certain objects will only be there when the story requires them to be there. Is your game one scene of many scenes? When your game has many scenes and the player frequently switches between them, then it might be sufficient to have a script which checks the story flag for that object in `Start()` and then calls `SetActive(false)` when the required flag isn't set. But if you require that certain objects appear immediately within the same scene when a certain flag is set, then you might require a separate controller object which takes care of monitoring story flags and activate game objects as soon as their spawn conditions are met.

The current time of day should also be a set of story flags. So you can use the same system to check flags like TIME\_IS\_MORNING or TIME\_IS\_EVENING in your story system and your game object activate/deactivate system.

(By the way: It's fortunate that you want a system where time advances only at predictable moments and not a real-time daycycle where the time period can change at any time. Because with a real-time system you would have to find a solution to what happens when an NPC is supposed to spawn/despawn while the player sees or even interacts with it. Such a game mechanic can get really glitchy if you don't remember to think of all the edge-cases)

---
Tags: unity, events
---


# Question
Title: How can I continue to rotate a 2D UI Object using OnPointerEnter when object is on its side? (OnPointerExit is triggered)
I have been wracking my brain on this for days. I'm trying to create a nice looking hand of cards, when the card is hovered over, it bobs up and down and rotates. This is triggered by OnPointerEnter, however, whenever it turns on its side and out of the mouses path OnPointerExit triggers, I've tried MANY things, including a bool that triggers the hover effect OnPointerEnter but it is just toggled off when it's turned on its side.

Is it possible to use the collider on my card with OnPointerEnter? Because that would probably solve my problem but haven't found anything on this.

Since the card is on UI, I have some placeholder code in there in order the have the inspected card render on top and return to its place.

```
    void Update()
{
    if (inspect)
    {

        transform.localScale = cardUpscale;

        posOffset = transform.position;

        transform.Rotate(new Vector3(0f, Time.deltaTime * degreesPerSecond, 0f), Space.World);

        // Float up/down with a Sin()
        tempPos = posOffset;
        tempPos.y += Mathf.Sin(Time.fixedTime * Mathf.PI * frequency) * amplitude;

        transform.position = tempPos;
    }
}

public void OnPointerEnter(PointerEventData eventData)
{
    zoomPlaceholder = new GameObject();
    zoomPlaceholder.name = "zoomPlaceholder";
    zoomPlaceholder.transform.SetParent(this.transform.parent); //binds the placeholder to the hand
    zoomPlaceholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex());

    LayoutElement cardProxy1 = zoomPlaceholder.AddComponent<LayoutElement>();
    cardProxy1.preferredHeight = this.GetComponent<LayoutElement>().preferredHeight;
    cardProxy1.preferredWidth = this.GetComponent<LayoutElement>().preferredWidth;
    cardProxy1.flexibleHeight = 0;
    cardProxy1.flexibleWidth = 0;

    zoomPosition = transform.parent;
    transform.SetParent(transform.parent.parent);
    inspect = true;
}

public void OnPointerExit(PointerEventData eventData)
{
    inspect = false;

    this.transform.SetParent(zoomPosition);
    this.transform.SetSiblingIndex(zoomPlaceholder.transform.GetSiblingIndex());

    transform.localScale = cardNormalScale;

    Destroy(zoomPlaceholder);

}

```

# Answer
Use a parent object that is the rectangle for the Handler for OnPointerEnter/Exit and put the card image as a child object.

Apply the transforms to the child object, not the object that handles the pointer enter/exit.
> 1 votes

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


# Question
Title: How do I move Space Invaders like enemies in groups efficiently?
So like the title says I want my Enemies to move on a Grid like in Space Invaders. Say I have 8 rows and 12 columns. Now there are 10 Enemies in each row and there are 5 rows filled. In total I have 50 Enemies. Since I am using OOP I got 50 Objects. Now I want to shift all Enemies from left to right as far as possible. So if all Enemies are alive I can shift them 2 to the right and 2 to the left. If I destroy all Enemies in a column the Enemies can shift 3 to the left and to the right.

How do I check efficiently how many times I can shift over / check if a column is empty. How should I initialize the grid and shift all Enemies by one? For me this looks like it could get pretty laggy if I don't make it efficiently. Note: All Objects are dynamically allocated and I am using C++.

I hope I could make it clear. If you guys don't understand it, I could try to explain it a bit better.

# Answer
# Moving the invaders as one

Something that @Krangogram has alluded to in their answer is that the individual invaders don't actually move by themselves, so one approach to efficiently move the invaders is to treat them as a single invader formation and the move the formation as a whole. You could define this similar to:

```
class Invader {
   // x,y offset within the formation. Each invader should have a unique offset from
   // (0,0), the top left, to (FORMATION_WIDTH-1,FORMATION_HEIGHT-1), the bottom right.
   int offsetX, offsetY;

   // Whether this invader is alive.
   bool isAlive;
};
class InvaderFormation {
   // The invaders within the formation, includes dead invaders
   std::vector<Invader *> invaders;

   // The location of the top left invader in the formation.
   int x, y;
};

```

Since every invader's location is defined as an offset from the formation as a whole, you can move every invader at the same time with `invaderFormation->x += DELTA` or `invaderFormation->y += DELTA`.

# Checking for the edge

As for how to determine whether the invaders can continue moving in a direction or if they've reached the edge, with 50 invaders you're probably safe to enumerate them all without running into any performance issues. But maybe in the future the screen will be bigger/scroll and there'll be a million invaders, so let's look how you can optimize this check.

The first thing to notice about this problem is that the only invaders you actually care about are the ones on the sides of the formation. The ones in the middle will never touch an edge as long as there's an invader on the side of the formation. But wait, you don't even need to figure out a way to track and enumerate those on the sides, because another thing to notice about this problem is that it doesn't matter which invader is on the side, all that matters is there's at least one.

So you could define your invader formation closer to something like this:

```
class Invader {
   int offsetY;
   bool isAlive;

   // The column of the formation this invader is in. The invader's offset within the
   // formation can now be defined as (column.offsetX, offsetY). It's fine to keep offsetX
   // in this class too though.
   InvaderFormationColumn* column;
};
class InvaderFormationColumn {
   // offsetX is also in the index into InvaderFormation::columns
   int offsetX;

   // How many invaders are still alive in this column
   int aliveCount;
};
class InvaderFormation {
   // All of the columns...
   std::vector<InvaderFormationColumn *> columns;

   // ...And more specifically, shortcuts to the leftmost and rightmost columns
   // that have at least 1 living invader
   InvaderFormationColumn* leftmostColumn;
   InvaderFormationColumn* rightmostColumn;

   int x, y;
};

```

Now you can know if the invader formation has reached the edge with a single check:

`invaderFormation->x + invaderFormation->leftmostColumn->offsetX == LEFT_EDGE` or

`invaderFormation->x + invaderFormation->rightmostColumn->offsetX == RIGHT_EDGE`.

But you'll need to update these `leftmostColumn` and `rightmostColumn` pointers whenever an invader dies in order to keep them up-to-date:

```
// When an invader is killed:
invader->isAlive = false;
invader->column->aliveCount--;

// Assuming there is still at least 1 living invader in the formation:
if (invader->column->aliveCount == 0) {
   // All invaders are dead in this column, so check if the formation needs to point to
   // a new leftmost/rightmost column
   if (invader->column->offsetX == invaderFormation->leftmostColumn->offsetX) {
      // Look for a new leftmost column, starting from the current one
      // You can stop at the rightmost column because you know there's no invaders still
      // alive in any columns past that.
      for (int i = invaderFormation->leftmostColumn->offsetX; i <= invaderFormation->rightmostColumn->offsetX; i++) {
         InvaderFormationColumn* column = invaderFormation->columns[i];
         if (column->aliveCount > 0) {
            invaderFormation->leftmostColumn = column;
            break;
         }
      }
   }
   // And similarly for the rightmost column moving towards the leftmost column
}

```
> 0 votes

# Answer
When i created a Space Invaders clone, I moved the 'row' and then the enemy just had a fixed offset in X from that 'row' object. I think in the end I used just one object to cover all enemies with offset of X and Y.
> 0 votes

---
Tags: c++, grid
---


# Question
Title: how to add script based on current scene and considering DontDestroyOnLoad?
How to add script based on current scene? I try

```
GameObject car = GameObject.FindGameObjectWithTag("InGame");

if (SceneManager.GetActiveScene().name == "TestDrive")
        {
            car.AddComponent<CarCtrl>();
        }

```

but nothing what I expected I want if I am on scene **TestDrive** there it attaches script **CarCtrl** to car
I am using also `DontDestroyOnLoad` (because I want to pass 3d model between two scenes CarSelect and TestDrive) but have issue because the script attach to previous scene also (this is **CarSelect**) but I want only to attach the script in scene **TestDrive**
I have the answer I should use level manager but I can't find way to start

CarCtrl in TestDrive scene

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

public class CarCtrl : MonoBehaviour
{
    private Rigidbody rb;
    private BoxCollider bc;

    public float horizontalInput;
    public float verticalInput;

    public float steerAngle;

    public List<Transform> Wheels;

    [Header("input")]
    public float steerInput;

    public float turnSpeed = 10f;

    public float maxSteerAngle = 30f;
    public float engineForce = 20;

    public const int topSpeed = 300;

    private TextMeshProUGUI speedText;

    private float speed = 0.0f;

    public void GetInput()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
    }

    private void Steer()
    {
        var dt = Time.deltaTime;
        steerAngle = maxSteerAngle * horizontalInput * dt;
        var smoothedSteering = Mathf.Lerp(0.0f, steerAngle, 10);
        var turnForce = transform.up * turnSpeed * smoothedSteering;
       // Debug.Log(turnForce);

        Wheels[0].Rotate(transform.forward * -1, steerAngle);
        Wheels[1].Rotate(transform.forward * -1, steerAngle);

        rb.AddRelativeTorque(turnForce, ForceMode.Acceleration);
    }

    private void Accelerate()
    {
        // speed in m/s
        speed = rb.velocity.magnitude;
        var force = transform.forward * -1 * engineForce * verticalInput;
        var speedKph = Car.MpsToKmh(speed);
        if (speedKph < topSpeed)
        {
            var speedtxt = speedKph.ToString();
            rb.AddForce(force, ForceMode.Acceleration);
            speedText = (TextMeshProUGUI) FindObjectOfType<TextMeshProUGUI>();
            speedText.text = $"speed: {speedtxt} kmh";

            rollWheels();
        }
    }

    private void FixedUpdate()
    {
        GetInput();

        Accelerate();

        Steer();
    }

    // Start is called before the first frame update
    private void Start()
    {
        //stop rotating
        Destroy(GetComponent<Turn>());

      //  AddWheels();

        var car = new Car("make", "model");
        print(Car.AckermannLeft(2, 2, 10));

        this.gameObject.transform.Translate(-30, 0, 0, Space.World);

       rb = GetComponent<Rigidbody>();

        rb.useGravity = true;

    }

    private void rollWheels()
    {
        var angle = engineForce * verticalInput;
        foreach (var wheel in Wheels)
        {
            wheel.Rotate(Vector3.right, angle);
        }
    }

    private void AddWheels()
    {
        Transform fl = GameObject.Find("Wheel_FL").transform;

        Transform fr = GameObject.Find("Wheel_FR").transform;
        Transform rl = GameObject.Find("Wheel_RL").transform;
        Transform rr = GameObject.Find("Wheel_FL").transform;

        Wheels.Add(fl);
        Debug.Log(Wheels);

        Wheels.Add(fr);
        Wheels.Add(rl);
        Wheels.Add(rr);
    }

}

```

DontDestroyOnLoad

```
 using UnityEngine;

public class DontDestroyOnLoad : MonoBehaviour
{
    // Start is called before the first frame update
    private void Start()
    {
        GameObject car = GameObject.FindObjectOfType<Turn>().gameObject;

        var camera = GameObject.Find("Main Camera");

        camera.transform.parent = car.transform;

    }

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

```

Scenes

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class Scenes : MonoBehaviour
{
    // Start is called before the first frame update
    private void Start()
    {
    }

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

    public void ChangeToMenu()
    {
        SceneManager.LoadScene("Menu");
    }

    public void ChangeToTracks()
    {
        SceneManager.LoadScene("Tracks");
    }

    public void ChangeToMakes()
    {
        SceneManager.LoadScene("Makes");
    }

    public void ChangeToModels()
    {
        SceneManager.LoadScene("Models");
    }

    public void ChangeToGarage()
    {
        SceneManager.LoadScene("Garage");
    }

    public void ChangeToCarSelect()
    {
        SceneManager.LoadScene("CarSelect");
    }

    public void ChangeToTestDrive()
    {
        SceneManager.LoadScene("TestDrive");
    }
}

```

# Answer
Ok I know why this not working because I have attached script CarCtrl to prefab initially in inspector and I should disable script on CarSelect and enable on TestDrive and no issue with it but disable in DontDestroyOnLoad in CarSelect

```
var carCtrl = GameObject.FindGameObjectWithTag("InGame").GetComponent<CarCtrl>();
                carCtrl.enabled = false;

```

also make enabler of script in TestDrive

```
if (SceneManager.GetActiveScene().name == "TestDrive")
        {
            var carCtrl = GameObject.FindGameObjectWithTag("InGame").GetComponent<CarCtrl>();
            carCtrl.enabled = true;

        }

```
> 0 votes

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


# Question
Title: How can I create this navigation system?
I try to make a **navigation/waypoint** system. Well I have a concept but no idea how I could create this system. Well here's an **image** and an **explanation**:

You can see 3 waypoints as well as an goal and a player. The function should take the player position (*X,Y,Z*), a waypoint position array as well as an goal position. If the player is now on the position like in the image then it should output the second waypoint position because it's the closest waypoint in the direction of the goal. If the player is on the second waypoint position then it needs to output the third waypoint and so on to the finish. Well that's my crude concept. I hope that somebody can help! **Thanks in advance :D**

---

NOTE: You can add any values you want to add the most important thing is that it helps me :)

# Answer
> 0 votes
The best way I can think of is having a list of waypoints in order from furthest to closest. Then given a waypoint you know you already passed you could just find the closest waypoint that you haven't passed yet. Something like.

```
public int nextWaypointIndex(Vector3 playerLocation, List<Vector3> orderedWaypoints,
                                int passedThisWaypoint) {

    int nextWaypoint = passedThisWaypoint + 1;
    float lowestDistance = Vector3.Distance(playerLocation, waypoints[nextWaypoint]);

    for (int i = passedThisWaypoint + 2; i < waypoints.Count; i++) {
        if (Vector3.Distance(playerLocation, waypoints[i]) <= lowestDistance) {
            nextWaypoint = i;
            lowestDistance = Vector3.Distance(playerLocation, waypoints[i]);
        }
    }

    return nextWaypoint;
}

```

---
Tags: waypoints
---


# Question
Title: Proper way to supply different textures and multiply matrices for thousand of terrain meshes
## What I have

* Terrain chunks of size 64x64 meters in a custom format
* PVR textures
* OpenGLES2 renderer
* GLSL shader

None of the above can be changed in any way, i.e. I can't modify the existing code of shader or change the renderer.

## Terrain

Each terrain chunk consists of 64 tiles of size 8x8 meters and are placed in a grid. Each tile has 3 layers of textures so theoretically there can be 192 different textures per chunk.

The way I currently load terrain is via script. I create a mesh for every tile in a chunk, so that's 64 meshes per chunk.

## Shader

The shader input consist of:

* 3 textures and their texture mask
* 3 matrices
* minor stuff

The matrices needed are calculated in every frame in the following way:

```
var M = _object.transform.localToWorldMatrix;
var V = Camera.main.worldToCameraMatrix;
var P = Camera.main.projectionMatrix;
_material.SetMatrix("WorldViewProjectionMatrix", P * V * M);
_material.SetMatrix("WorldViewT", (V * M).transpose);
_material.SetMatrix("World", M);

```

## What I need

Loading the entire terrain would take a lot of time and resources, so I only load the nearest chunks depending on player position and its a 5x5 chunks area. And still on average I have:

* 25 chunks
* 25 * 64 = 1600 tile meshes
* 25 * 64 = 1600 materials
* up to 25 * 192 = 4800 different textures (only theoretically! Currently there is no more than 20-30 per chunk and the average across loaded chunk is about 300 textures)
* about 6400 matrix operations

The amount of materials does not seem to have a huge impact on performance, but the matrix calculates make the fps drop from ~80FPS to ~12. I could've reduced the matrix operations down to 100 if I could render single chunk as a single mesh instead of 64 submeshes, but I don't see a way to properly pass the textures to shader.

So basically what I need is an approach that would allow me to render terrain chunk as a single mesh and a way to pass different textures for different tile parts of a mesh. Do I even look in the right direction?

# Answer
Without being able to modify your shader code.. you are not going to be able to leverage advanced techniques for this type of problem. The best you can do in your case is minify the matrix operations. Which given the way the shader params work in your question, is forcing you to pre-multiply the camera matrices with the object matrix before submitting to the shader.

You could premultiply P * V one time per frame for all operations.

If you can't modify the shaders or code, but have control over the creative, then you could enforce design rules where each chunk must use the same 6 textures. Then you could use batching to batch all the submeshes into 1 mesh with the same 6 textures. Thus reducing that chunk to a single draw call.
> 2 votes

---
Tags: unity, opengl-es2, terrain-rendering
---


# Question
Title: ASSIMP Skinning seems to be somewhat inverted
I'm currently implementing Skinning using Assimp as my asset importer. I've relied heavily on the following tutorial in order to skin meshes (http://ogldev.atspace.co.uk/www/tutorial38/tutorial38.html) So some of you might be familiar with the code. I'm also using GLM as my math library.

In order to successfully cast Assimp matrices to GLM matrices (If I recall they are in a different order so have to be transposed), I have the following helper functions:

```
static inline glm::vec3 vec3_cast(const aiVector3D &v) { return glm::vec3(v.x, v.y, v.z); }
static inline glm::vec2 vec2_cast(const aiVector3D &v) { return glm::vec2(v.x, v.y); } // it's aiVector3D because assimp's texture coordinates use that
static inline glm::quat quat_cast(const aiQuaternion &q) { return glm::quat(q.w, q.x, q.y, q.z); }
static inline glm::mat4 mat4_cast(const aiMatrix4x4 &m) { return glm::transpose(glm::make_mat4(&m.a1)); }
static inline glm::mat4 mat4_cast(const aiMatrix3x3 &m) { return glm::transpose(glm::make_mat3(&m.a1)); }

```

Now, when calculating the transformation matrix of a bone, the following method is used:

```
void AnimatedMesh :: ReadNodeHeirarchy(float AnimationTime, const aiNode* pNode, const glm::mat4& ParentTransform)
{
    string NodeName(pNode->mName.data);

    const aiAnimation* pAnimation = m_Animations[0];

    glm::mat4 NodeTransformation = mat4_cast(pNode->mTransformation);

    const aiNodeAnim* pNodeAnim = FindNodeAnim(pAnimation, NodeName);

    if (pNodeAnim)
    {
        // Interpolate scaling and generate scaling transformation matrix
        aiVector3D Scaling;
        CalcInterpolatedScaling(Scaling, AnimationTime, pNodeAnim);
        glm::vec3 scale = glm::vec3(Scaling.x, Scaling.y, Scaling.z);
        glm::mat4 ScalingM = glm::scale(glm::mat4(1.0f), scale);

        // Interpolate rotation and generate rotation transformation matrix
        aiQuaternion RotationQ;
        CalcInterpolatedRotation(RotationQ, AnimationTime, pNodeAnim);
        glm::quat rotation = quat_cast(RotationQ);
        glm::mat4 RotationM = glm::toMat4(rotation);

        // Interpolate translation and generate translation transformation matrix
        aiVector3D Translation;
        CalcInterpolatedPosition(Translation, AnimationTime, pNodeAnim);
        glm::vec3 translation = glm::vec3(Translation.x, Translation.y, Translation.z);
        glm::mat4 TranslationM = glm::translate(glm::mat4(1.0f), translation);

        // Combine the above transformations
        NodeTransformation = TranslationM * RotationM * ScalingM;
    }

    glm::mat4 GlobalTransformation = ParentTransform * NodeTransformation;

    if (m_BoneMapping.find(NodeName) != m_BoneMapping.end())
    {
        unsigned int BoneIndex = m_BoneMapping[NodeName];
        m_BoneInfo[BoneIndex].FinalTransformation = m_GlobalInverseTransform * GlobalTransformation * m_BoneInfo[BoneIndex].BoneOffset;
    }

    for (unsigned int i = 0; i < pNode->mNumChildren; i++)
    {
        ReadNodeHeirarchy(AnimationTime, pNode->mChildren[i], GlobalTransformation);
    }
}

```

We calculate the final position of the bone in the vertex shader like this:

```
#version 440 core

#define ANIMATED_MESH
#define MAX_BONES 100

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
layout (location = 3) in vec3 aTangent;
layout (location = 4) in vec3 aBitangent;
#ifdef ANIMATED_MESH
layout (location = 5) in uvec4 BoneIDs;
layout (location = 6) in vec4 Weights;
#endif

out vec3 FragPos;
out vec2 TexCoords;
out vec3 Normal;
out mat3 TBN;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
#ifdef ANIMATED_MESH
uniform mat4 gBones[MAX_BONES];
#endif

void main()
{
    vec4 pos = vec4(aPos, 1.0f);

#ifdef ANIMATED_MESH
    mat4 BoneTransform = gBones[BoneIDs[0]] * Weights[0];
    BoneTransform     += gBones[BoneIDs[1]] * Weights[1];
    BoneTransform     += gBones[BoneIDs[2]] * Weights[2];
    BoneTransform     += gBones[BoneIDs[3]] * Weights[3];
    pos               *= BoneTransform;
#endif

    FragPos = vec3(model * pos);
    TexCoords = aTexCoords;

#ifdef NORMAL_MAP
    vec3 T = normalize(vec3(model * vec4(aTangent, 0.0)));
    vec3 N = normalize(vec3(model * vec4(aNormal, 0.0)));
    T = normalize(T - dot(T, N) * N);
    vec3 B = cross(N, T);
    TBN = mat3(T, B, N);
#else
    Normal = transpose(inverse(mat3(model))) * aNormal;
#endif

#ifdef ANIMATED_MESH
    Normal *= BoneTransform.xyz;
#endif

    gl_Position = projection * view * vec4(FragPos, 1.0);
}

```

Apologies for all the pasted code. I'm almost certain that the bone information is being sent properly and received in the vertex shader so my last thought is that it must be with calculating the transformation. This is strange to me as my code is exactly implemented how successful implementations of the same code. If you see here is the expected result taken inside Unity3D:

and this is my actual result taken from within my engine:

There are a few telling things in the actual result. First, the head goes far too forward, this to me seems like the head movement has been inverted and the bait's going as much forwards as it should be going backward.

Another thing is the leg on the left of the screen, instead of bending backwards, it tries to bend forwards. Lastly, and most obviously, is the arms, they seem twisted in towards each other. It seems the right arm is where the left arm should be and vice-versa.

I wanted to know if anyone could see where this issue could arise? All matrices taken from Assimp are cast into glm matrices using the helped functions mentioned above so they should be in the right format. This includes the bone offset matrices. If you need to see any more sections of the code, feel free to ask. I only tried to limit that amount of code pasted to where I thought the issue was most likely to avoid pasting too much code.

Thank you.

# Answer
My issue was in the vertex shader. When calculating gl\_Position, I was doing this

```
gl_Position = projection * view * vec4(FragPos, 1.0);

```

Where FragPos was calculated as follows: vec4 pos = vec4(aPos, 1.0f);

```
mat4 BoneTransform = gBones[BoneIDs[0]] * Weights[0];
BoneTransform     += gBones[BoneIDs[1]] * Weights[1];
BoneTransform     += gBones[BoneIDs[2]] * Weights[2];
BoneTransform     += gBones[BoneIDs[3]] * Weights[3];
pos               *= BoneTransform;

FragPos = vec3(model * pos);

```

As you can see, this completely removes the w component of the vector and thus gave weird results. My updated shader is this:

```
#version 440 core

#define ANIMATED_MESH
#define NORMAL_MAP
#define MAX_BONES 100

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
layout (location = 3) in vec3 aTangent;
layout (location = 4) in vec3 aBitangent;
#ifdef ANIMATED_MESH
layout (location = 5) in uvec4 BoneIDs;
layout (location = 6) in vec4 Weights;
#endif

out vec3 FragPos;
out vec2 TexCoords;
#ifdef NORMAL_MAP
out mat3 TBN;
#else
out vec3 Normal;
#endif

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
#ifdef ANIMATED_MESH
uniform mat4 gBones[MAX_BONES];
#endif

void main()
{
    vec4 PosL = vec4(aPos, 1.0f);

#ifdef ANIMATED_MESH
    mat4 BoneTransform = gBones[BoneIDs[0]] * Weights[0];
    BoneTransform     += gBones[BoneIDs[1]] * Weights[1];
    BoneTransform     += gBones[BoneIDs[2]] * Weights[2];
    BoneTransform     += gBones[BoneIDs[3]] * Weights[3];
    PosL               = BoneTransform * vec4(aPos, 1.0f);
#endif

    FragPos = vec3(model * PosL);
    TexCoords = aTexCoords;

#ifdef NORMAL_MAP
    #ifdef ANIMATED_MESH
        vec3 T = normalize(vec3(model * BoneTransform * vec4(aTangent, 0.0)));
        vec3 N = normalize(vec3(model * BoneTransform * vec4(aNormal, 0.0)));
    #else
        vec3 T = normalize(vec3(model * vec4(aTangent, 0.0)));
        vec3 N = normalize(vec3(model * vec4(aNormal, 0.0)));
    #endif

    T = normalize(T - dot(T, N) * N);
    vec3 B = cross(N, T);
    TBN = mat3(T, B, N);

#else
    #ifdef ANIMATED_MESH
        Normal = transpose(inverse(mat3(model))) * aNormal * BoneTransform.xyz;
    #else
        Normal = transpose(inverse(mat3(model))) * aNormal;
    #endif
#endif

    gl_Position = projection * view * model * PosL;
}

```

Where we multiple the final bone transform (PosL) as a complete 4 component vector
> 1 votes

---
Tags: opengl, skeletal-animation, glm, assimp, skinning
---


# Question
Title: How do I move my infinite runner player when the game zone shares the screen with a match 3 game?
So I am seeking to make a Match 3 with an infinite runner element. The match 3 portions are all already totally done, but I'm running into trouble figuring out how to best approach the Runner portion.

I'm not entirely new to Unity, but I'm newer, though I'm not new to programming. This is what the game generally looks like:

<sup>(Source)</sup>

My problem is I am unsure the best way to do the movement. My immediate thought was, I should have the player run in place, and the world move around him, so that the camera and the match 3 portion don't have to have any movement.

Is there another option that is simple that I'm over looking? Following the player as he moved seems like it would be really weird for the match 3 dots, as the camera is flying off into the X along with the player, and keeping the dots up with them sounds like it would be more trouble than its worth.

Any help is appreciated, thanks!

# Answer
> 0 votes
Regardless of how you implement the running game, you can implement the Match 3 game using the UI system. A screen space canvas will always stay on the screen no matter where the camera is.

Another way to have two games in one is to have both games in the same physical space with their own cameras and separate them by using different layers. Put the two games on different layers so they don't interact with each other. Set the two camera culling masks to render one game each and then use the clear flags and depth settings to control the order in which the two games get drawn to the screen.

For more information, check out the manual section about layers and about cameras.

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


# Question
Title: Someone downloaded my game but it failed on Game Start due to code that doesnt exist
As stated in the title, they get the following error:

```
 ############################################################################################
 FATAL ERROR in
 action number 1
 of Other Event: Game Start
 for object obj_music_controller:

 ds_map_find_value argument 1 incorrect type (undefined) expecting a Number (YYGI32)
 at gml_Script_scr_checkLastLoggedInJson
 ############################################################################################
 --------------------------------------------------------------------------------------------
 stack frame is
 gml_Script_scr_checkLastLoggedInJson (line -1)
 gml_Object_obj_music_controller_Other_2

```

The function ds\_map\_find\_value() is not being called in the script scr\_checkLastLoggedInJson(). (Even if it was, how could it be happening at line -1?)

Nor is it called in the Game Start event of the obj\_music\_controller object. I also checked every use of ds\_map\_find\_value() in the entire game and they are all fine.

Furthermore, this is only happening with 1 person. And they have tried uninstalling it and re-downloading. Even after i uploaded a new version of the game, this still happened to them and only them.

EDIT: scr\_checkLastLoggedInJson()

---

```
var result = false;

if (file_exists("saveJson.json"))
{
    var saveJson = scr_loadJSONFromFile("saveJson.json");//ds_map
    var saveJsonNames = saveJson[? "Names"]; //ds_list
    var userSaveData = noone;
    var saveJsonSaves = noone;

    if (ds_list_size(saveJsonNames) == 1) //If there is only 1 user, that is the one to load.
    {
        result = true;
        var username = saveJsonNames[| 0];
        global.username = username;
    }
    else
    {
        //Find the user who was last logged in and assign them to global.username.
        for (var i = 0; i < ds_list_size(saveJsonNames); i++)
        {
            var username = saveJsonNames[| i];
            saveJsonSaves = saveJson[? "Saves"];//ds_map

            if (!is_undefined(username))
            {
                userSaveData = saveJsonSaves[? username]; //ds_map

                if (userSaveData[? "Last Logged In"])
                {
                    result = true;
                    global.username = username;
                    ds_map_destroy(userSaveData);
                    ds_map_destroy(saveJsonSaves);
                    break;
                }
            }
        }
    }

    if  (ds_exists(userSaveData, ds_type_map))
    {
        ds_map_destroy(userSaveData);
    }

    if  (ds_exists(saveJsonSaves, ds_type_map))
    {
        ds_map_destroy(saveJsonSaves);
    }

    ds_list_destroy(saveJsonNames);
    ds_map_destroy(saveJson);
}

return result;

```

---

# Answer
> 2 votes
I fixed it. Idk what caused this, but here we go. My save file is structured like this: `{"Names":[], "Saves":{}}`. Somehow the "Saves" key wasnt created (only in the case of this specific person) so at some point in the code it does `saveJsonSaves = saveJson[? "Saves"]` and then saveJsonSaves is undefined. So i added code to catch this scenario and reconstruct the missing "Saves" key.

---
Tags: game-maker
---


title: How should shader be structured? (GLSL)

text:
# Question
Title: How should shader be structured? (GLSL)
I've been writing, deleting and rewriting OpenGL programs in C++ but usage of shaders confuse me. I don't know how it should be structured.

Scenario A: (In a world we have a sun, the sun should shine upon everything in the world and on a lake or there would be fog which should only be visible from outside the building but not inside)

So far, I am thinking that I would write a global sun structure in C++ then pass its value to all shaders, then in all used shaders I would write the same lighting functions over and over again.

So I would be repeating codes... How would you construct your shader program in such scenario? And Should I write a shader for each model?

# Answer
`I would write the same lighting functions over and over again`

...Why?

A shader pipeline is a series of actions:

* Inputs from CPU (or GPU, in some cases; optional)
* Vertex Shader
* Geometry Shader (optional)
* Fragment Shader
* Retrieve buffers to CPU (optional)

^ At no stage is there any repetition in this sequence.

If you're saying that you need to do the same thing from different places... well, let's say you have two higher level lighting functions called "outdoor lighting" vs. "indoor lighting"; if there are parts of their code that are the same, then you factor these out into separate sub-functions, that you call from different places in your higher-level lighting functions. Most of these smaller functions will be very small, \< 10 lines, performing some elementary action.

It's basic Refactoring 101.
> 0 votes

---
Tags: opengl, shaders, glsl, fragment-shader
---


# Question
Title: How can I convert an html5 web game to an android app?
I have already made an html5 game and it is in service. I want to service this at Android app too. I know little about Java or Kotlin, so I think the least risky way is to use a webview. There is already a function to save game data with Oauth authentication. I thought this part should be replaced with google play Oauth.

However, there is a problem that the app does not run when the player is offline. (Run the app fails to load any html document)

However, if you load a local html file, it will be rejected from the existing firebase SDK because there is no domain.

In fact, I know very little about native app development, so I don't know that what I don't know, what I need.

What should I do in this situation?

Do I need to rebuild my app in Kotlin or Java from scratch? Do I have to use the same engine as Unity? Do I have to rebuild with a framework like cordova?

The question may not fit here, but I need help. Please.

# Answer
> 3 votes
Your first step should typically be to simplify the app down to its simplest working version. Gut everything that is causing the app to fail to run on the new platform (comment it out OR put in mock/dummy functions or modules) and get the app into a basic working state.

Remove all non essentials: user authentication, ads, payments, leaderboards, social media linkage.

Aim to make the game runnable first on the **original** platform **without any integrations** (firebase etc.), then try run in WebView on Android...

...Then reintroduce all the stuff you disabled, one step at a time, until you have a working app on the **target** platform.

---

The reason you're doing this is that, before you start going down 999 rabbitholes that could cost you a lot of time, you need to know that the basic game, no frills, *can even be run at all on the target platform*. You're reducing risk, as early as possible.

---
Tags: unity, android, html5, porting
---


# Question
Title: How do you generate seamless Perlin noise?
I've done a research and tried implementing for months, but I've gotten nowhere trying to make seamless/tileable Perlin noise.

**Here** is my current Perlin noise file without seamless implementation. In my program, I am calling FractionalBrownianMotion to generate.

Each of the research articles have given me issues. In FractionalBrownianMotion I change the call from Perlin to PerlinSeamless.

## Research Articles

> How to make one-axis tileable simplex noise? Produces broken noise using x2, y2 as period; xsize, ysize as map size. Also tried vice-versa.

Added code:

```
public float PerlinSeamless(float x, float y)
{
    int width = gradientArray.GetLength(0);
    int length = gradientArray.GetLength(1);

    // map size 250
    float x1 = 0, x2 = 50;
    float y1 = 0, y2 = 50;
    float dx = x2 - x1;
    float dy = y2 - y1;

    //Sample noise at smaller intervals
    float s = x / width;
    float t = y / length;

    // Calculate our 3D coordinates
    float nx = x1 + Mathf.Cos(s * 2 * Mathf.PI) * dx / (2 * Mathf.PI);
    float ny = y1 + Mathf.Sin(t * 2 * Mathf.PI) * dy / (2 * Mathf.PI);
    float nz = t;

    return Perlin3D(nx, ny, nz);
}

public float Perlin3D(float x, float y, float z)
{
    y += 1;
    z += 2;
    float xy = perlin3DFixed(x, y);
    float xz = perlin3DFixed(x, z);
    float yz = perlin3DFixed(y, z);
    float yx = perlin3DFixed(y, x);
    float zx = perlin3DFixed(z, x);
    float zy = perlin3DFixed(z, y);
    return xy * xz * yz * yx * zx * zy;
}
private float perlin3DFixed(float a, float b)
{
    return Mathf.Sin(Mathf.PI * Perlin(a, b));
}

```

> How do you generate tileable Perlin noise? `hashed = perm[perm[int(gridX)%per] + int(gridY)%per]` goes OOB.
>
> 3D Perlin Noise Technique does not replicate 2D noise when z value always 0, but using this method for 3D Perlin noise assuming that's the way it's supposed to be

I have also tried various implementations of non-answer accepted comments in these articles to see only broken noise.

# Answer
To make the noise tile, all you need is to ensure that the gradient you select for integer point `(x, y`) is the same as the gradient point you select for `(x + j*tileFrequency, y + k*tileFrequency)`, where `tileFrequency` is the number of grid cells across your tile.

(See this answer for a bit more illustration of how this gets us seamless tiling)

Inside your Perlin noise function, you'll usually have something that looks like this:

```
float PerlinNoise(float x, float y) {

    int xFloor = Mathf.FloorToInt(x);
    int yFloor = Mathf.FloorToInt(y);

    Vector2 g1 = GetPerlinGradient(xFloor, yFloor);
    Vector2 g2 = GetPerlinGradient(xFloor + 1, yFloor);
    Vector2 g3 = GetPerlinGradient(xFloor + 1, yFloor + 1);
    Vector2 g4 = GetPerlinGradient(xFloor, yFloor + 1);

   /...

```

What we need to do is wrap around those indices where we're fetching the gradients, something like this:

```
int Wrap(int v, int period) {
    if(v < 0)
        return (v % period) + period;
    return v % period;
}

```

(If coordinates don't go negative in your situation, you can skip the `if` — I suspect not handling this case is why you were seeing out of bounds errors)

This wrapping means one corner of our tile is always at zero, no matter how we've shifted our inputs. For a single octave that's fine, but if we want to stack octaves this can show visible correlations as the pattern of gradients near zero repeats. So we'll add some parameters to shift our window after wrapping, which also gives us more ways to vary up our noise tile based on an input seed. :)

```
float TiledPerlinNoise(float x, float y, int period, int xShift, int yShift) {

    int xFloor = Mathf.FloorToInt(x);
    int yFloor = Mathf.FloorToInt(y);

    int left = Wrap(xFloor, period) + xShift;
    int right = Wrap(xFloor + 1, period) + xShift;

    int bottom = Wrap(yFloor, period) + yShift;
    int top = Wrap(yFloor + 1, period) + yShift;

    Vector2 g1 = GetPerlinGradient(left, bottom);
    Vector2 g2 = GetPerlinGradient(right, bottom);
    Vector2 g3 = GetPerlinGradient(right, top);
    Vector2 g4 = GetPerlinGradient(left, top);

    // ...

```

Now we can use this with a collection of octave amplitudes and frequencies to generate tiling turbulence:

```
float TiledTurbulence(float x, float y, Octave[] octaves) {
    float sum = 0f;
    foreach (var octave in octaves) {

        sum += octave.amplitude
               * TiledPerlinNoise(
                    x * octave.frequency,
                    y * octave.frequency,
                    octave.frequency,
                    octave.xShift,
                    octave.yShift);
    }
    return sum;
}

```

Here the input x & y are in "tilespace", so 1.0 is one tile width.

Note that if your periods are always powers of two, you can use a bitmask instead of the modulo operator to do your wrapping, for a little extra efficiency. :)
> 1 votes

---
Tags: unity, tilemap, perlin-noise, noise, simplex-noise
---


title: Can I use System.Windows.Rect in Unity?

text:
# Question
Title: Can I use System.Windows.Rect in Unity?
I need to work with a Rect that has Left, Top, Bottom, Right.

Unity's Rect has x, y, width and height instead.

Also, Unity's Rect doesn't accept `Rect.Compare(otherRect)`.

`System.Windows.Rect` however seems a good choice for my needs.

I would like to ask if it's ok to use `System.Windows.Rect` in my Unity script and if it will be cross-platform.

# Answer
It will not work as unity uses Mono and a subset of the core libraries, Windows is not going to be one of them.

Unity Rect has Contains and Overlaps to do logic tests for rects and points.
> 2 votes

# Answer
Instead of using `System.Windows.Rect` I'd just write extension methods:

```
public static int left(this Rect rect) {
    return rect.x - rect.width * 0.5f;
}
public static int right(this Rect rect) {
    return rect.x + rect.width * 0.5f;
}
public static int top(this Rect rect) {
    return rect.y + rect.height * 0.5f;
}
public static int bottom(this Rect rect) {
    return rect.y - rect.height * 0.5f;
}

```

And write my own comparison extension method:

```
public static bool isEqualTo(this Rect rect, Rect otherRect) {
    return rect.x == otherRect.x && rect.y == otherRect.y &&
            rect.width == otherRect.width && rect.height == otherRect.height;
}

```
> 2 votes

---
Tags: unity, c#, .net
---


# Question
Title: Time to render each frame is proportional to the amount of models in the scene
This question is deliberately written in a "High-Level" manor to avoid screeds and screeds of code snippets, hopefully I can get my point across, I am using C++ and OpenGL.

I have a game engine, and in the engine I have my "game loop" that is called every frame, one of the things in this game loop is my call to `Render()`, before a call to `SwapBuffers()`, nothing new there.

Essentially my engine draws the scene using a scene graph, that is I have `GameObject`'s and each object has a `GameComponent`. So when the `Render()` is called in the "game loop" I get the root `GameObject` and render its `GameComponent` and then move onto the next `GameObject` and render its `GameComponent`, etc. until all `GameObject`'s and each of their `GameComponent`'s are drawn using `glDrawElements(...)`.

One of the `GameComponent`'s a `GameObject` can have is a `MeshRenderer`, that is a `Mesh` paired with a `Texture`. In my scene I want to add loads of tree models, therefore I create for example 50 `GameObject`'s that each have a `MeshRenderer` component (a tree) that will eventually in the game loop described above be drawn.

The issue with this is that the time it takes to render a frame is directly proportional to the number of tree models I have (O(N) I think is how you word it). For example with 100 trees the render time is 23ms, with 200 trees it is 46ms, with 400 trees it is 90ms so on and so forth.

This is terrible, I need at least 1000 trees in my "game world" and even at around 400 my game is "laggy". Because the time to draw a frame is proportional to the number of tees I know that each frame it is re-drawing each mesh essentially (every frame drawing 100 trees, and then 200 and so on, and the time to draw scales with it)

My question is this - How can I store the mesh data so that I don't need to draw them from scratch every frame, I can just draw them once, and then re-use that data for the next frame, but don't re-draw it all? is there a way to firstly use `glDrawElements(...)`, then store that mesh data(all the vertices etc.) and then every frame after call something like for example `glDrawExcistingElements()` instead of `glDrawElements(...)`. Ultimately meaning that for consecutive frame draws the time is the exact same wether I have 1 tree or 1000 trees because the system is simply saying "here is the scene I already drew", instead of "lets draw it all again from scratch".

# Answer
As said in comments, what you are looking for is probably instancing: instead of `gldrawElements` you use `glDrawElementsInstanced`. The first thing you want too look for is probably this tutorial. They give an example of drawing 100.000 asteroids(!) with complexity of ~500 vertices with one draw call and still having excellent FPS. Without it the program chokes on ~1k asteroids with something on \<10FPS level.

For further optimizations you would have too look more into LODding (reducing mesh complexity the farther the object is - for example farthest trees could be just 2d sprites). Some kind of occlusion culling (frustum, occlusion) could be a next step (reducing the amount of overdraw for pixels).

Also remember that in an opengl program changing any state should be done as rarely as possible. It means that you should group your rendering calls by the state they depend upon, including mesh data, textures, element arrays etc. The state remains bound as long as you need it and explicitly need it. If you want to use the same mesh for many objects (for example trees with different textures, it's called static mesh in some engines) you don't have to bind/unbind mesh data everytime you render a tree, but just store for example a uniform indexed by instance\_id into the texture atlas (like minecraft does for example).
> 3 votes

---
Tags: opengl, c++
---


# Question
Title: How to convert this resource texture creation code from DirectX 11 to DirectX 12?
I have some code below that is Directx 11 that im using to make a resource texture.

```
D3D11_TEXTURE2D_DESC fullScreenTextureDesc;
        ZeroMemory(&fullScreenTextureDesc, sizeof(fullScreenTextureDesc));
        fullScreenTextureDesc.Width = 800;
        fullScreenTextureDesc.Height = 600;
        fullScreenTextureDesc.MipLevels = 1;
        fullScreenTextureDesc.ArraySize = 1;
        fullScreenTextureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        fullScreenTextureDesc.SampleDesc.Count = 1;
        fullScreenTextureDesc.SampleDesc.Quality = 0;
        fullScreenTextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
        fullScreenTextureDesc.Usage = D3D11_USAGE_DEFAULT;

        HR(device->CreateTexture2D(&fullScreenTextureDesc, nullptr, &fullScreenTexture));

```

How can i convert this to directx 12?

# Answer
> 1 votes
The conversion of that code is easy:

```
D3D12_RESOURCE_DESC desc = {};
desc.Width = 800;
desc.Height = 600;
desc.MipLevels = 1;
desc.DepthOrArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;

CD3DX12_HEAP_PROPERTIES defaultHeapProperties(D3D12_HEAP_TYPE_DEFAULT);

hr = device->CreateCommittedResource(
    &defaultHeapProperties,
    D3D12_HEAP_FLAG_NONE,
    &desc,
    D3D12_RESOURCE_STATE_COPY_DEST,
    nullptr,
    IID_PPV_ARGS(&tex)); // tex is type ID3D12Resource*

```

That said, it's very challenging to just do a naive port of DirectX 11 to DirectX 12. There's a lot of differences needed to get good performance, and your application is responsible for *a lot* of conditions, edge-cases, and timing.

> You should take a look at DirectX Tool Kit for DX12.

---
Tags: directx
---


# Question
Title: Unity get more than 2 lines of log height
Unity does only display 2 lines in height for each log, at least with the default settings. I couldn't find a menu, where I could change this.

I want to display a matrix, and I need to see the log live, so it's no option for me to click on each log separately. Has unity no option to increase the height of a log line? And additionally is there no option to hide the "source" of the log like the line "UnityEngine.Debug:Log(Object)" I mean I can hide it if I click "collapse" but I don't want to collapse the entries, since it stacks the same entries which is not what I want....

Edit: I just saw, that there exist some plugins, which would do the job I guess. But I wonder if there is a way to solve this with the Unity console, since I don't want to pack my project full of utility stuff for developing...

# Answer
> 3 votes
Okay this is a simple workaround, which works but is still not the way I would like to have it. I think Unity lacks of configurability....

The trick here is, that Unity pushes everything of the log in an overflow part, so the "UnityEngine.Debug:Log(Object)" disappears, because it would be in line 3. So if you keep your log exactly two lines height, you can achieve almost a clean log.

The Code:

```
Debug.Log("-   -\n" +
          "|    |");
Debug.Log("|    |\n" +
          "-  -");

```

The Output:

# Answer
> 3 votes
In the more current versions of Unity it is now possible to change the number of lines shown for messages in the Console.

You can do so from the context menu of the Console window under the menu item "Log Entry".

The maximum number of lines that can be shown using this method is 10.

Also the setting applies to all message in the Console, so it unfortunately can't be used to only selectively print one supersized message amidst other more compact ones.

# Answer
> 0 votes
Don't think you can change that. Instead, split every matrix into multiple `Debug.Log()` lines, and use some sort of separator (e.g. underscores) to separate matrices legibly.

P.S. I agree, this sucks, as you should be able to use the alternating greys for separation!

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


# Question
Title: How can I fix the artifacts near the shadow edges in my variance shadow map?
I'm trying to implement variance shadow mapping in my engine. I'm using WebGL 2 and now I have only one directional light source. It's working, but it has a serious issue near the shadow edges and I don't know how to solve it.  The back of the cube isn't entirely in shadow, the edges are in light.

The shadow on the sphere is too small, I think about half of the sphere should be in shadow.

This is how I implemented variance shadow mapping:

1. Create the shadow map

Vertex shader:

```
#version 300 es

layout(location = 0) in vec3 i_positiom;

uniform mat4 projectionViewModelMatrix;

void main(){
    gl_Position = projectionViewModelMatrix * vec4(i_positiom, 1.0f);
}

```

Fragment shader:

```
#version 300 es

precision highp float;

out vec4 o_color;

void main(){
    float depth = gl_FragCoord.z;
    float depthSquared = depth * depth;
    float dx = dFdx(depth);
    float dy = dFdy(depth);
    depthSquared += 0.25f * (dx * dx + dy * dy);
    o_color = vec4(depth, depthSquared, 0.0, 1.0);
}

```

The texture's size is 1024x1024, it uses linear filtering, but doesn't use mipmapping or multisampling. The result looks like this:
2. Blur the shadow map, horizontally, then vertically

Vertex shader:

```
#version 300 es

layout (location = 0) in vec3 i_position;
layout (location = 1) in vec2 i_textureCoordinates;

out vec2 io_textureCoordinates;

void main(){
    io_textureCoordinates = i_textureCoordinates;
    gl_Position = vec4(i_position, 1.0f);
}

```

Fragment shader:

```
#version 300 es

precision highp float;

in vec2 io_textureCoordinates;

uniform sampler2D image;
uniform bool horizontal;

out vec4 o_color;

void main(){
    ivec2 texSize = textureSize(image, 0);
    float blurAmount = 1.0;
    vec2 blurScale = horizontal ? vec2(blurAmount / float(texSize.x), 0.0) : vec2(0.0, blurAmount / float(texSize.y));
    vec4 color = vec4(0);

    color += texture(image, io_textureCoordinates + (vec2(-2.0) * blurScale)) * (1.0 / 16.0);
    color += texture(image, io_textureCoordinates + (vec2(-1.0) * blurScale)) * (4.0 / 16.0);
    color += texture(image, io_textureCoordinates + (vec2(0.0) * blurScale)) * (6.0 / 16.0);
    color += texture(image, io_textureCoordinates + (vec2(1.0) * blurScale)) * (4.0 / 16.0);
    color += texture(image, io_textureCoordinates + (vec2(2.0) * blurScale)) * (1.0 / 16.0);

    o_color = color;
}

```
3. Render the scene and calculate the shadows

```
float calculateShadow(vec3 N, vec3 L){
    /*if(dot(N, -L) < 0.0){
        return 0.0;
    }*/
    vec3 projectionCoordinates = io_fragmentPositionLightSpace.xyz / io_fragmentPositionLightSpace.w;
    projectionCoordinates = projectionCoordinates * 0.5 + 0.5;
    float currentDepth = projectionCoordinates.z;
    vec2 moments = texture(shadowMap, projectionCoordinates.xy).xy;
    if (currentDepth <= moments.x) {
    return 1.0;
    }
  float variance = moments.y - (moments.x * moments.x);
  variance = max(variance, 0.00002);
  float d = currentDepth - moments.x;
  float pMax = variance / (variance + d * d);
    return smoothstep(0.1f, 1.0f, pMax);
}

```

I tried many things, like changing shadow map resolution, filtering, blur kernel size, blur amount, changing the magic numbers in calculateShadow (which are there to prevent light bleeding), but the best I could do is what you can see (it's commented out) at the beginning of the calculateShadow function. If the angle between the surface's normal vector and the light direction is greater than 90°, then it's in shadow.

It solves the problem, however on the sphere the shadow becomes too sharp:

# Answer
As DMGregory pointed out, I can't just multiply the fragment's final color with the shadow value. This is because this color is calculated by using information like ambient color or an environment map which is not related to the light source which casts the shadows. This makes sense because these parts of the lighting are not related to any light sources, they more or less try to simulate multiple light sources or bouncing light rays. Because of this we have no information about the light's direction and we don't know whether or not the light's path is blocked. My problem was that I multiplied the ambient part of the shading, not only the diffuse and the specular parts.

This is how I modified my shader to solve the problem.

Fragment shader before

```
...
float shadow = calculateShadow(...);
vec3 diffuse = calculateDiffuseColor(...);
vec3 specular = calculateSpecularColor(...);
vec3 ambient = calculateAmbientColor(...);
return (ambient + diffuse + specular) * shadow;

```

Fragment shader after

```
...
float shadow = calculateShadow(...);
vec3 diffuse = calculateDiffuseColor(...);
vec3 specular = calculateSpecularColor(...);
vec3 ambient = calculateAmbientColor(...);
return ambient + diffuse * shadow + specular * shadow;

```
> 0 votes

---
Tags: glsl, opengl-es, webgl, shadows, shadow-mapping
---


title: Faster way to load VBOs in LWJGL

text:
# Question
Title: Faster way to load VBOs in LWJGL
I'm currently working on a Minecraft clone for a university project and I'm having some trouble loading a lot of chunks at the same time without reducing performances.
What I'm currently doing is:

1. Creating the VAO
2. Creating the VBOs
3. Buffering the data in the VBOs
4. Rendering them (that isn't causing any lag)
5. Destroying the VAO and VBOs when the chunk is no longer needed

I tried to look at other solved questions but they were too specific or too vague, or maybe I'm just dumb.
The chunks are made of 16x16x16 blocks and its VBOs contain only the vertices of the visible blocks (like Minecraft's doing).
I'm looking for a better way(in terms of speed and performance) to load them.

# Answer
> 2 votes
> Destroying the VAO and VBOs when the chunk is no longer needed.

This is the main thing that you're doing wrong, and it implies that you're also creating resources at runtime. Creating and destroying resources at runtime is a slow operation and something you should try to do as little of as possible.

Instead you should keep a pool of free VBOs/etc, and rather than destroying objects that aren't needed, just return them to the free pool. When you need new objects, check the free pool first before creating new ones.

Yes, this means that there will be times when you have objects in your free pool that aren't being actively used, and it's tempting to think of this as "wasting memory", but it's not - try to think of it instead as implementing a fast allocator by keeping these objects ready for reuse if needed.

---
Tags: opengl, java, lwjgl, lwjgl3
---


# Question
Title: How do I move/select menu options through UI joystick and buttons?
I have a working Menu system in my game. I am able to move across the menu using `Up`/`Down` arrow keys and select those options using the enter key. The problem is how do i get that arrow key functionality to a UI joystick and enter key functionality to a UI button that I have.

Any help would be greatly appreciated. Thank you in advance. Let me know if you need any more details, happy to provide videos of the problem, code, or the entire project if need be.

# Answer
> 0 votes
I solved the problem by hard rigging it.

I used the joystick input -\> up/down/left/right input sets the button (`GameObject`) in that direction as the current selected in the `EventSystem`.

For button click and invoking that button's functionality I used `ExecuteEvents.Execute()`.

---
Tags: unity, gui, menu
---


# Question
Title: Right way to get reference from across scene object in unity
I need a reference for the game-object from another scene but the problem is that the scene object by default is off. So I thought that I should place its reference in another script and get a reference from it. But it will introduce me to a new script (third script) which means a new dependency. Now here is the triangle to solve the issue (which i don't like and posting here)

First scritp where the refrence is require

The actual refrence (Script/game-object) reside in a separate scene.

The reference holder

My consideration is that this is not the right way to do this job as its required dependency. How can i efficient and more professionally deal with it?

# Answer
If this object belongs to a scene, I would consider the scene an object in and of it self. In other words, I would have a top level object with a SceneXManager, with references and/logic for the objects inside itself.

The SceneManager would be *enabled*, and the reference to the other object would be set via the inspector. Then it does not matter if the object you need is disabled or not.
> 1 votes

---
Tags: unity, c#, architecture, refactoring
---


# Question
Title: Unity3D Hex Grid neighbor search with radius
I am trying to develop a small Game with a Hex Grid. I need to find the Neighbors of one Hex Tile in a specific radius.

Here is a screenshot of my Problem: Screenshot

I followed this awesome tutorial along and implemented some of the systems presented here: https://www.redblobgames.com/grids/hexagons/

```
public GameObject[] GetNeighbarsInRange(Vector2 pos, int range) {

    List<GameObject> tiles = new List<GameObject>();

    int min = -range, max = range;

    for (int x = min; x <= max; x++) {

        for(int y = min; y <= max; y++) {

            for(int z = min; z <= max; z++) {

                if (x + y + z == 0) {

                    Vector2 newPos = getVector2Coord(new Vector3(x, y, z)), newTilePos = new Vector2(pos.x + newPos.x, pos.y + newPos.y);
                    tiles.Add(getTile(newTilePos));

                }

            }

        }

    }

    return tiles.ToArray();

}

public Vector2 getVector2Coord(Vector3 pos) {

    int x = (int) pos.x, z = (int) pos.z;
    int newX = x, newZ = z + (x - (x&1)) / 2;
    return new Vector2(newX, newZ);

}

public Vector3 getVector3Coord(Vector2 pos) {

    int x = (int) pos.x, y = (int) pos.y;
    int tileX = x, tileZ = y - (x - (x&1)) / 2, tileY = -tileX - tileZ;
    return new Vector3(tileX, tileY, tileZ);

}

```

Here you can see my Neighbor calculation and my Cube to Offset Coords and my Offset Coords to Cube Functions. My Grid is based on the Offset Coord System, I am saving my Grid in a 2D Array and when I search for neighbors I convert them into the Cube Format. My Problem is for the even cols its working fine but for the odd cols, it is not. My Question is how can I fix this?

It is btw. the same if I increase the radius to 2 instead of 1.

Kind regards,

Alex

(Sorry for my bad English I am from Germany:D)

# Answer
> 1 votes
It looks like you just forgot to convert your center tile to cubic coordinates before trying to add cubic offsets to it:

```
public GameObject[] GetNeighbarsInRange(Vector2 pos, int range) {
    // Add this line to the top of your method.
    var centerCubePos = getVector3Coord(pos);

    List<GameObject> tiles = new List<GameObject>();

```

...then later down, make sure you're adding your offsets in cubic coordinates, where the math all works out uniformly. Convert only the *final* result back to offset coordinates.

```
    var cubePosOffset = new Vector3(x, y, z));
    var newTilePos = getVector2Coord(centerCubePos + cubePosOffset);
    tiles.Add(getTile(newTilePos));

```

---

Also, a note on efficiency:

```
for x...
   for y...
       for z...
           if(x + y + z == 0)
           ...

```

Here you're looping over \\$(2 \cdot range + 1)^3\\$ cells and skipping most of them, to find just \\$3 \cdot (range)\cdot (range + 1) + 1\\$ results that you actually want - a cubic amount of work for a square number of results. At a radius of 2 you're checking 125 cells for 19 actual hits. At 3 you're checking 343 cells for 37 hits.

We can do this much more efficiently.

One small change would be:

```
for x...
   for y...
       // Once we know x & y, there's only one z that can satisfy
       // x + y + z == 0, so just set it directly instead of looping again:
       z = -x - y;
       // Reject out-of-range zs calculated this way.
       if(z < min || z > max)
           continue;

```

Now we're doing only a square amount of work, though we still generate some coordinates we have to skip (at a radius of 2 we search 25 cells for 19 hits, at a radius of 3 we search 49 cells for 37 hits).

Much better, but we could go further if we wanted to and skip no cells at all, by using the technique described as "Spiral Rings" on the Red Blob Games site.

# Answer
> -1 votes
You can get neighbor search with radius alghoritm from my fog of war method:

```
private void UpdateFogOfWar() {
    var playerCell = tilesGrid.WorldToCell(this.transform.position);

    for (int y = -viewRadius; y <= viewRadius; y++) {
        for (int x = -viewRadius; x <= viewRadius; x++) {
            if ((x * x) + (y * y) <= (viewRadius * viewRadius))
                fogOfWarTilemap.SetTile(new Vector3Int(playerCell.x + x, playerCell.y + y, playerCell.z), null);
        }
    }

    UpdatePathFindingGridTable();
}

```

---
Tags: unity, grid, tiles
---


# Question
Title: How to access rotation-Z value in script?
My script(MouseLookController) is attached to a GameObject and I want to limit it's rotation between 90deg and -90deg.(Rotation is 40 deg in example image)

Problem is I can't access this value to check it. How can I access the rotation Z of this gameobject?

I've tried:

```
transform.localEulerAngles.z
transform.rotation.z
transform.eulerAngles.z

```

Meaning they won't return 40.695 value, where is this value currently stored?
Couldn't find it in the GameObject.

# Answer
Manipulating individual components of a quaternion is almost never what you want to do.

The three imaginary components of the quaternion (x, y, z) describe your axis of rotation, and the real component (w) describes how much to rotate around it, subject to the constraint that the whole 4-vector has a length of 1 (so as you change the rotation angle, the axis vector grows and shrinks). So changing just one component doesn't make sense - the different parts of the quaternion have to change in concert.

Instead, you generally want to use the convenience methods of the `Quaternion` class to do your operations - which ends up making for much clearer and more intuitive code, as a bonus.

```
Quaternion ClampRoll(Quaternion orientation, float minRoll, float maxRoll) {

    // Find which direction the z+ axis of this orientation points in the world.
    Vector3 forward = orientation * Vector3.forward;

    // Form a reference orientation with no roll, looking in that direction.
    Quaternion noRoll = Quaternion.LookRotation(forward, Vector3.up);

    // Use this to isolate just the roll part of our orientation, removing everything else.
    Quaternion rollAlone = orientation * Quaternion.Inverse(noRoll);

    // Now we know we have the z angles alone, with no other confounding factors.
    // Use DeltaAngle to get it in the range -180...180
    float rollAngle = Mathf.DeltaAngle(0, orientation.eulerAngles.z);

    // Now we can clamp it into our desired range.
    float clamped = Mathf.Clamp(rollAngle, minRoll, maxRoll);

    // And fold it back into our roll-free rotation to finish the job.
    return noRoll * Quaternion.Euler(0, 0, clamped);
}

```

You might be able to skip the first few steps there, but myself I don't trust the way Euler angles wrap around, which can lead to unexpected behaviour. So I like to isolate just the rotation angle I care about, relative to the identity orientation, to minimize the potential for surprises in a corner case I didn't think about. ;)
> 3 votes

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


# Question
Title: Implementing a movement and collision system with Vectors and Area
I've scoured gamedev for around 45 minutes, but I'm unable to find a detailed approach to implementing a movement and collision system for games - specifically, when to use which process, and what to do in them.

**CONTEXT:** I've made around 20 2-D games, most of which are physics simulators. I have a pretty good knowledge of AWT graphics (too deep into it to start javafx). My games are usually structured like this:

```
function 'move' inside a particular object:
    move the object
    if the object has collided into an immovable object like the ground:
        escape from the immovable object
        change velocity accordingly
    if the object has collided with a movable object:
        the current object should retrace its path to escape collision
        change both velocities accordingly and move each object with their velocity ONCE

call the function 'move' for each object

```

I'm completely uneducated in game development, and I've gotten a bit too comfortable with this flawed system because it has worked for almost every one of my games.

---

I've been studying a lot about game dev online, so I'm trying to make a system where every object moves freely once, then all their collisions are logged and resolved, in that order. But I'm still unsure how to resolve the collision.

This question: Collision Resolution is pretty much the same as mine, but I still can't understand when I should change positions and velocities. Should I change both at the same time on collision detection? What happens if you collide into an object, so you retrace your steps, but now you've collided with something else?

If anyone can link a more concrete question / answer, I'll be immensely grateful. I'm using vectors to store the position and velocity of each entity (player or npc), if that's helpful.

# TL;DR

What property of an entity should I change on collision detection: velocity or position, or both? If the entity escapes the collision, but runs into a new one, should I resolve its new collision, or should I go on to solving the other collisions?

# Answer
**The Easy Stuff**

I would suggest that you start by learning 2D collision detection between (non-rotating) circles. Here, rotation can be considered a non-factor - and that *greatly* reduces the complexity of the problem.

In essence, with non-rotating colliding circles, all you need to do is look at the degree to which they would have intersected in a given frame's motion, given their motion vectors, and push them back along their motion vectors by an amount that causes them to just touch (given circles' radii, this is some basic pythagoras / trigonometry).

Non-rotated i.e. axis-aligned boxes and rectangles are also trivial for which to detect and resolve collisions. This you could try as a second experiment, or even first.

**The Tougher Stuff**

Rotating bodies such as rectangles or other polygons colliding *accurately* is a much harder problem that requires numerical integration (per frame) to solve, as opposed to circles and AABBs which can be stepped once, and then analysed for a single push back for each intersected pair. Convex polygons are hard enough; concave ones greatly increase the complexity of the solution further - hence many libraries rather resolve concave polygons into a number of smaller, convex ones.

Making this work, let alone making it work in real-time, is non-trivial.

I suggest that if you really want to know how this is done (rather than using a library like Box2D) that you search for Christer Ericson's Real Time Collision Detection, the *de facto* standard on this topic.
> 2 votes

---
Tags: java, movement, collision-resolution
---


# Question
Title: How to store a Transform[,] grid in an ArrayList?
I am new to Unity game dev and trying to expand my knowledge of data structs. I'm building a match-3 game, and I currently have a multi-dimensional ArrayList holding transform coordinates on a grid of x width and y height. I have game objects tied to these coordinates in world space, with the grid syncing the data back in game space. I am attempting to push these coordinates into the nested list (familyList) to be deleted pending 3 or more units being added to familyArrayList (seen below).

Here's the abridged code:

```
private static Transform[,] grid = new Transform[width, height];
public static ArrayList familyArrayList = new ArrayList();

// Go through game grid line by line and add game objects from game space into family ArrayList
for (int y = height - 1; y >= 0; y--)
        {
            for (int x = 0; x < width; x++)
            {
                if (grid[x, y] != null)
                {
                    // Add grid[x, y] to familyArrayList
                    familyArrayList.Add(grid[x, y]);
                    Debug.Log(familyArrayList[0]);

```

Output:

```
Green Unit(Clone) (UnityEngine.Transform)

```

**How can I get familyArrayList to properly story the grid coordinates and not the game object the grid coordinates are referencing?** i.e. `familyArrayList[0] == '3,4'` Should I instead use a nested list? At a later point in the code, I want to clear the game object from the board in world space as well as set the grid\[x,y\] to null:

```
// Loop through all family array and destroy game objects
foreach (var x in familyArrayList)
{
    Destroy(familyArrayList(x).gameObject);
}
// Loop through all family array and set their values to null in grid as well
foreach (var x in familyArrayList)
{
    familyArrayList(x) = null;
}

```

But I get errors like "Argument 1: cannot convert from 'object' to 'int'" and "Non-invocable member 'Piece.familyArrayList' cannot be used like a method" which I can imagine are explained by my above problem of not storing the grid coordinates properly and instead storing the referenced game object. I'm truly stumped on this problem and thank anybody in advance who can point me in the right direction to solving this.

# Answer
> 1 votes
I think you might be confusing C# with Java or Javascript.

Change your Java list to a C# list and add the type so that the compiler know that we intend to store Transform objects in this list (unless you intentions is to mix it with other types, but that is not recommended anyways because you might run into casting errors):

```
public static List<Transform> familyArrayList = new List<Transform>();

```

Second possible mistake is, that your `Debug.Log(familyArrayList[0])` is hard coded to the first element. I assume you intended to view the last added element:

```
Debug.Log(familyArrayList[familyArrayList.Count-1]);

```

C#'s foreach works different than Javascript. To to iterate through each GameObject, you need to do:

```
foreach (var x in familyArrayList)
{
    Destroy(x.gameObject);
}

```

And if you need to reference the list, you cannot use a foreach as that will only give you a reference to the element inside the list. So instead, just use a normal for-loop:

```
for (int i = 0; i < familyArrayList.Count; ++i)
{
    familyArrayList[i] = null;
}

```

# Answer
> 0 votes
Firstly, as Jasper Citi mentioned in an earlier answer, you generally don't want to use the `ArrayList` type in C#. The generic `List<T>` type introduced later in the language's evolution covers the same use cases, with the benefit of strict typing for better efficiency.

> How can I get familyArrayList to properly \[store\] the grid coordinates, and not the game object the grid coordinates are referencing?

Make a list of coordinates instead. We can use the `Vector2Int` type to store an (x, y) coordinate pair of integers.

```
public List<Vector2Int> coordinatesInFamily = new List<Vector2Int>();

```

You can then add coordinates to it like so:

```
for (int y = height - 1; y >= 0; y--) {
    for (int x = 0; x < width; x++) {
        // Skip empty grid cells.
        if (grid[x, y] == null)
            continue;

        // Add the coordinate pair [x, y] to our list.
        var coordinates = new Vector2Int(x, y);
        coordinatesInFamily.Add(coordinates);

        Debug.LogFormat("Added coordinates {0}, containing {1}", coordinates, grid[x,y].name);
     }
}

```

Then you can clear your items like so:

```
foreach(Vector2Int coordinates in coordinatesInFamily) {
    // Destroy the game object at this position, and remove it from the grid.
    Destroy(grid[coordinates.x, coordinates.y].gameObject);
    grid[coordinates.x, coordinates.y] = null;
}
// Remove all entries from our family list in one fell swoop.
// (Faster and less error-prone than deleting them one at a time as we loop through)
coordinatesInFamily.Clear();

```

The reason you were getting errors before is due to some syntax mistakes:

* When you type `foreach (var x in familyArrayList)`, that `x` refers to an item in your collection, not the index of that item. (ie. here it's an `Object`, not an `int`) You can hover over the variable in your IDE to reveal what type it holds, or explicitly specify the type instead of `var` to make it more visible.
* So you don't need to try to fetch the `x`th element from your list like this `familyArrayList(x).gameObject`. The variable `x` already holds the `Transform` itself - just boxed into a generic `Object` because `ArrayList` isn't strictly typed.
* Also, even if you did need to index into the list, you used the wrong brackets for that. Those round parentheses `()` are used for function calls - use square brackets `[]` to index an item from a collection, like `familyArrayList[0]`

---
Tags: unity, c#, data-structure, gameobject
---


# Question
Title: UE4: "Ignore Move Input" Does not get Set back on
I have the following issue:

I have some logic which I call to Set Ignore Move Input on for a specific player character, based on a boolean. However, after half a second, I set it back on.

Everything works great, I can not move my character while it kicks.. However, if I press the "kick" input twice in succession.. the Set Ignore Move Input breaks and never gets turned off, even if I "Kick" again later.

Here is the blueprint .. Any help is greatly appreciated (and yes I realize that to somebody more experienced this blueprint makes little to no sense, but I'm just starting out... My core issue as a software developer here is I don't understand what locks me out of the logic that would reset Ignore Move Input back off).

Thank you for your time!

# Answer
> 1 votes
@Natalo77

Thank you! Your tips solved the issue. The code now looks as follows (I've collapsed the entering and exiting of "Kicking"). I've also made a Pure function which will return whether or not an action is being executed.

---
Tags: movement, unreal
---


title: What causes this z position change?

text:
# Question
Title: What causes this z position change?
This is a follow-up on the following thread.

I'm applying a code that will move an object just outside the camera's frustum. I have used the same code in other projects, and it worked fine.

However, I'm using it with URP now, and I'm experiencing a z-position change while I expected only a x position change.

And I just don't see why it does that.

I have recorded a video here.

If I press the button, the cube should be moved to the left only. But it also moves to the back (z position).

And this is the script that I have applied to the cube in the video:

```
using System;
using UnityEngine;

public class PlaceOutsideCamera : MonoBehaviour
{
     public void PlaceOutsideFrustum(Transform uTransform, bool uLeft)
    {
        uTransform.position = pPlaceOutsideFrustum(uTransform, uLeft);
    }
    public static Vector3 pPlaceOutsideFrustum(Transform uTransform, bool uLeft)
    {
        var frustumPlanes = GeometryUtility.CalculateFrustumPlanes(Camera.main);
        Ray ray;
        Plane plane;

        if (uLeft)
        {
            // 1.
            ray = Camera.main.ScreenPointToRay(new Vector3(0, Camera.main.pixelHeight / 2f, 0));
            plane = frustumPlanes[0];
        }
        else
        {
            ray = Camera.main.ScreenPointToRay(new Vector3(Camera.main.pixelWidth - 1, Camera.main.pixelHeight / 2f, 0));
            plane = frustumPlanes[1];
        }

        float fDistance = Mathf.Abs(Camera.main.transform.position.z - uTransform.position.z);

        // 2.
        var borderPoint = ray.GetPoint(fDistance);

        // 3.
        var frustumOutside = -plane.normal;

        Bounds b = BoundsFromTransform(uTransform);
        // 4.
        var halfDiameter = b.size.magnitude / 2f;

        return borderPoint + frustumOutside * halfDiameter;
    }
    public static Bounds BoundsFromTransform(Transform uTransform)
    {
        try
        {
            Bounds bounds = new Bounds(uTransform.position, Vector3.zero);//wir hätten auch einfach new Bounds() nehmen können, meint Manfredas

            foreach (Renderer renderer in uTransform.GetComponentsInChildren<Renderer>())
            {
                bounds.Encapsulate(renderer.bounds);
            }

            Vector3 nOff = bounds.center - uTransform.position;

            return new Bounds(nOff, bounds.size);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.Break();
            return new Bounds();
        }
    }
    public void OnGUI()
    {
        if (GUI.Button(new Rect(0, 350, 100, 50), "DoThis!"))
        {
            pDoThis();
        }
    }
    private void pDoThis()
    {
        this.PlaceOutsideFrustum(this.transform, true);
    }

}

```

Can anybody tell me why my code does this? I just don't see it. Thank you very much for the help!

Edit: Here is another video that shows the camera position in the Inspector.

# Answer
> 1 votes
I'd like to expand on Jon Koelzer's answer, with a bit more detail about what aspects of the code cause this, and how to modify the code to correct it.

When you measure your distance like this:

```
float fDistance = Mathf.Abs(Camera.main.transform.position.z - uTransform.position.z);

```

...you're measuring the distance along the z axis only.

But when you apply this distance to your ray like this:

```
 var borderPoint = ray.GetPoint(fDistance);

```

...you're measuring the distance diagonally, along the direction of the ray. Part of that distance moves along the z axis, but part of it moves along the x axis (pushing the object off the left side of the screen).

Because you're dividing what was previously just the z depth between two axes, the amount that ends up in your final z distance is less than what you started with, making the object move closer to the camera with each invocation.

Then of course we move a little closer to the camera again when we apply the half-bounding-box offset, since we're moving along the frustum plane normal, and that points slightly backward as the planes fan outward.

You can fix this by not thinking about rays at all.

```
// Cache the camera reference for brevity, and so we don't search for it repeatedly.
var camera = Camera.main;

// Measure the depth along the camera's forward vector, so it works regardless of rotation.
float forwardDepth = Vector3.Dot(uTransform.position - camera.transform.position, camera.transform.forward);

// Use this depth to specify the point in viewport-depth space we want from the camera.
Vector3 viewportEdge = new Vector3(0f, 0.5f, forwardDepth);

// This will hold the signed secant of the angle our frustum plane normal makes
// with the camera's right vector - see diagram below for why!
float shiftScale;

if(uLeft) {
   shiftScale = -1f / Vector3.Dot(frustumPlanes[0].normal, camera.transform.right);
} else {
   // Since we're in viewport space, not screenspace, we don't need pixel dimensions.
   viewportEdge.x = 1f;

   shiftScale = -1f / Vector3.Dot(frustumPlanes[1].normal, camera.transform.right);
}

// Convert our viewport-depth point to a point in world space, not a ray.
Vector3 worldPoint = camera.ViewportToWorldPoint(viewportEdge);

// Get bounds for shifting it out of frame.
Bounds b = BoundsFromTransform(uTransform);
var radius = b.extents.magnitude;

// Shift directly left or right, with no component forward/back, so we preserve depth.
return worldPoint + shiftScale * radius * camera.transform.right;

```

As for how that `shiftScale` is calculated - we can get it with a little trigonometry:

And the fact that since the plane normal and `camera.transform.right` are both unit vectors, their dot product gives us `cos(theta)` :)

# Answer
> 1 votes
The planes that define your frustum are canted and the amount is dependent on your FOV setting, which I've circled in red on the right in the diagram below. If I'm not mistaken, the lower your FOV, the more narrow that frustum is- the narrower your frustum is, the less your object will translate along the Z-axis.

This is just a rough sketch, but the vector Fo represents your frustumOutside variable. The Fo vector is angled and has used both the x and z elements to express this direction, that's where your Z movement comes from.

# Answer
> 0 votes
If you want to move it on x axis only then you need to restrict z axis of cube's transformation. There might be other ways to do it but the easiest way for now is

```
public void PlaceOutsideFrustum(Transform uTransform, bool uLeft)
{
    uTransform.position = new Vector3(pPlaceOutsideFrustum(uTransform, uLeft).x, pPlaceOutsideFrustum(uTransform, uLeft).y, uTransform.position.z);
}

```

# Answer
> 0 votes
Jon's answer explains where your problem is coming from. The planes of the frustum aren't perpendicular to the x axis. I suggest a different approach:

If your objective is to put the object outside the camera's view, consider changing the object position based on raycasting the screen edge and adding to that half the width of the object. The object will now be outside of the camera's view independently of the FOV.

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


title: User input text in pygame

text:
# Question
Title: User input text in pygame
I want a text box to appear on the screen. I am doing this by:

```
TextButton= pygame.draw.rect(Screen,Red, (100, 100, 150,50),2)

```

How can I allow the user to enter a text into this text box in Pygame? The text box should say 'Enter your name here'. When the user clicks on it, they should be able to enter their name, and submit it if the textbox is not empty. How can I do this in pygame?

# Answer
Pygame does not support this feature. Usually this sort of thing is handled by GUI libraries, but I'm not aware of any that works with pygame, so I think you have to build it yourself. Here's what you need to do:

* Keep a string for user input
* Draw that string, and whatever else you need for the text box
* When the user has pressed a key:
    + If it's a character, add it to the string
    + If it's a special key like backspace, delete the last character

That gives you the bare minimum, if you want other features like movable cursor, you need to write more code.
> 0 votes

# Answer
Here is some code I use in my game. It's not exactly what you asked for, but it's close.

```
import pygame
pygame.init()
validChars = "`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./"
shiftChars = '~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?'

class TextBox(pygame.sprite.Sprite):
  def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.text = ""
    self.font = pygame.font.Font(None, 50)
    self.image = self.font.render("Enter your name", False, [0, 0, 0])
    self.rect = self.image.get_rect()

  def add_chr(self, char):
    global shiftDown
    if char in validChars and not shiftDown:
        self.text += char
    elif char in validChars and shiftDown:
        self.text += shiftChars[validChars.index(char)]
    self.update()

  def update(self):
    old_rect_pos = self.rect.center
    self.image = self.font.render(self.text, False, [0, 0, 0])
    self.rect = self.image.get_rect()
    self.rect.center = old_rect_pos

screen = pygame.display.set_mode([640, 480])
textBox = TextBox()
shiftDown = False
textBox.rect.center = [320, 240]

running = True
while running:
  screen.fill([255, 255, 255])
  screen.blit(textBox.image, textBox.rect)
  pygame.display.flip()
  for e in pygame.event.get():
    if e.type == pygame.QUIT:
        running = False
    if e.type == pygame.KEYUP:
        if e.key in [pygame.K_RSHIFT, pygame.K_LSHIFT]:
            shiftDown = False
    if e.type == pygame.KEYDOWN:
        textBox.add_chr(pygame.key.name(e.key))
        if e.key == pygame.K_SPACE:
            textBox.text += " "
            textBox.update()
        if e.key in [pygame.K_RSHIFT, pygame.K_LSHIFT]:
            shiftDown = True
        if e.key == pygame.K_BACKSPACE:
            textBox.text = textBox.text[:-1]
            textBox.update()
        if e.key == pygame.K_RETURN:
            if len(textBox.text) > 0:
                print (textBox.text)
                running = False
pygame.quit()

```
> 0 votes

# Answer
you can try this code

```
import pygame
vec = pygame.math.Vector2
class Text_box:
def __init__(self, x, y, width, height, bg_colour=(124, 124, 124), active_colour=(255,255,255),
             text_size=24, text_colour=(0,0,0), border=0, border_colour=(0,0,0)):
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.pos = vec(x, y)
    self.size = vec(width, height)
    self.image = pygame.Surface((width, height))
    self.bg_colour = bg_colour
    self.active_colour = active_colour
    self.active = False
    self.text = ""
    self.text_size = text_size
    self.font = pygame.font.SysFont("Times New Roman", self.text_size)
    self.text_colour = text_colour
    self.border_colour = border_colour
    self.border = border
    self.numbers = [48,49,50,51,52,53,54,55,56,57]
    self.special = [8,32]

def update(self):
    pass

def draw(self, gameDisplay):
    if not self.active:
        self.text = "Enter your name"
        if self.border == 0:
            self.image.fill(self.bg_colour)
        else:
            self.image.fill(self.border_colour)
            pygame.draw.rect(self.image, self.bg_colour,
                             (self.border, self.border, self.width-self.border*2,
                              self.height-self.border*2))

        text = self.font.render(self.text, False, self.text_colour)
        text_height = text.get_height()
        self.image.blit(text, (self.border*2, (self.height-text_height)//2))
    else:
        if self.border == 0:
            self.image.fill(self.active_colour)
        else:
            self.image.fill(self.border_colour)
            pygame.draw.rect(self.image, self.active_colour,
                             (self.border, self.border, self.width-self.border*2,
                              self.height-self.border*2))
            if self.text == "Enter your name":
                self.text = ""
            else:
                text = self.font.render(self.text, False, self.text_colour)
                text_height = text.get_height()
                text_width = text.get_width()
                if text_width < self.width-self.border*2:
                    self.image.blit(text, (self.border*2,(self.height-text_height)//2))
                else:
                    self.image.blit(text, ((self.border*2)+(self.width-text_width-self.border*3),(self.height-text_height)//2))

    gameDisplay.blit(self.image, self.pos)

def add_text(self, key):
    try:
        if chr(key).isalpha():
            text = list(self.text)
            text.append(chr(key))
            self.text = ''.join(text)
            print(self.text)
        elif key == 8:
            text = list(self.text)
            text.pop()
            self.text = ''.join(text)
        #for space
        #elif key == 32:
            #text = list(self.text)
            #text.append(' ')
            #self.text = ''.join(text)
        else:
            print(key)
    except:
        print(key)

def check_click(self, pos):
    if pos[0] > self.x and pos[0] < self.x+self.width:
        if pos[1] > self.y and pos[1] < self.y+self.height:
            self.active = True
        else:
            self.active = False
    else:
        self.active = False

def return_value(self):
    return self.text

```
> -1 votes

---
Tags: gui, python, pygame
---