# Question
Title: Can my game have multiple rendering APIs?
I don't care how much you insist that Graphic API doesn't matter, I've tested it and I've seen other people test and yes switching graphic API can literally half your FPS.... 50% of your FPS gone just by switching how you render 3D stuff.

But some players might prefer sacrificing 80 fps to get that 1% boost in graphical quality... or some other players might just be playing on a particular machine that runs better on a Graphic API that would make other players run at low FPS.

For those type of people.... how do I put the option for them to switch Rendering API ?

# Answer
Godot won't let you change rendering backends in runtime. Thus, I'd suggest to create a launcher where the player can choose before running the actual game.

---

In Godot 3, you cannot change the rendering of the exported game. Thus, we might be talking of separate downloads.

*I suppose you might be able to reuse PCKs. See Exporting packs, patches, and mods.*

The options you have are, of course, GLES2 and GLES3. With GLES2 being intended to be compatible with more devices, while GLES3 does not care and goes for features (Consequently many old smartphones that support GLES3 did get black screens with Godot GLES3 exports because it was not implemented for compatibility, so it required some extensions without fallback if they weren't available).

---

In Godot 4 you can use command line arguments to change rendering.

You can get the valid options using `--help`. These are the options (at least on Windows 10):

* No Display

```
--display-driver headless

```
* Forward+ (Intended for modern desktop GPUs)

```
--rendering-method forward_plus --rendering-driver vulkan

```
* Mobile (Optimized for mobile GPUs)

```
--rendering-method mobile --rendering-driver vulkan

```
* Compatibility (Intended for old GPUs that do not support Vulkan)

```
--rendering-method gl_compatiblity --rendering-driver opengl3

```

Notes:

* There is an `--rendering-driver dummy` which is automatically selected when you use `--display-driver headless`.
* If you do not specify `--display-driver headless`, then `--display-driver windows` is assumed.
* To have display, you need to specify a working combination of `--rendering-method` and `--rendering-driver` or Godot will halt with an error message.
* The OpenGL rendering backend is not feature complete at the time of writing.
* You should be able to use Metal on macOS, but I don't have the means to test it at the time of writing.
* There might be other options added in the future (including DirectX support, for which the development is being financed by W4 Games), but it is not available in official builds at the time of writing.
> 4 votes

# Answer
> Can my game have multiple rendering APIs?

Yes, sure it can. Some games have the option to switch between OpenGL/Vulkan (Doom 2016) or DirectX11/12 (Total War: Warhammer II).

> I've tested it and I've seen other people test

So, you've tested and seen other people test, then you should know it's possible.

> For those type of people.... how do I put the option for them to switch Rendering API ?

May I suggest a drop-down list inside the graphics settings with all your supported APIs and let the player choose?

Or, if your game has a launcher, then it's also a very good place to put this option, so the user don't have to restart the whole game for the changes to take effect.
> 0 votes

---
Tags: godot
---


# Question
Title: How do I make an interactive visual indicator in Unity?
I have a pad I interact with in my game. How do I make a visual indicator like the one shown in the attached GIF? You see that there is a circle that appears on the tablet showing where the user is about to click.

I have a collider around the tab and on the index finger.

I have tried two methods that did not work for me. One of them is instantiating the game object I intend using as the indicator when the index finger's collider enters the collider around the tablet and then updating its local position to be that of the index finger and some offset. I then destroy it `OnTriggerExit`.

The indicator kind of move with the index finger but I could not get the exact behaviour I want. I'm also trying my best possible to avoid using `Update()`

Here is the method I tried that is closer to what I want:

```
public GameObject visualIndicator;
private float _moveSpeed = 15f;

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("indexFinger"))
    {
        reticle.SetActive(true);
    }
}

private void OnTriggerStay(Collider other)
{
    if (other.CompareTag("indexFinger"))
    {
        Vector3 targetPosition = other.ClosestPoint(transform.position);
        visualIndicator.transform.position = Vector3.Lerp(visualIndicator.transform.position, targetPosition, Time.deltaTime * _moveSpeed);
    }
}

private void OnTriggerExit(Collider other)
{
    if (other.CompareTag("indexFinger"))
    {
        reticle.SetActive(false);
    }
}

```

For this, I initially have the visual indicator set inactive on the pad. I also have a collider on the pad that protrudes out a bit such that once the finger collider collides with it, the visual indicator is set active and its position is updated to be the position of the point of collision in `OnTriggerStay`.

This looks very close to what I want but the visual indicator moves a bit up from the pad when looked from the side because its position is updated to be the point of collision of the pad's collider and the finger's. I want the visual indicator to only stay on the pad and follow the finger as shown in the following GIF:

# Answer
> 1 votes
Right now, you have this code for `OnTriggerStay`:

```
private void OnTriggerStay(Collider other) {
    if (other.CompareTag("indexFinger")) {
        Vector3 targetPosition = other.ClosestPoint(transform.position);
        visualIndicator.transform.position = Vector3.Lerp(visualIndicator.transform.position, targetPosition, Time.deltaTime * _moveSpeed);
    }
}

```

This aligns the visual indicator to a point on the *finger's* collider. It sounds like what you want is to align the visual indicator to a point on the `pad's` collider.

```
//...
new private Collider collider;

private void Awake() {
    collider = GetComponent<Collider>();
}

private void OnTriggerStay(Collider other) {
    if (other.CompareTag("indexFinger")) {
        Vector3 targetPosition = collider.ClosestPoint(other.transform.position);
        var viTransform = visualIndicator.transform;
        float t = Time.deltaTime * _moveSpeed;
        viTransform.position = Vector3.Lerp(viTransform.position, targetPosition, t);
    }
}

//...

```

---
Tags: unity, c#, virtual-reality
---


# Question
Title: How to detect objects within a radius without using a trigger collider?
I want an object to run code that detects objects around them, in a specific radius.

BUT I cannot use a trigger... or any game objects or components on the objects I'm trying to detect.

What could I do just using code?

# Answer
The classes `Physics` and `Physics2D` contain several useful static methods to detect `Collider`s and `Collider2D`s within geometric shapes. For example, if you want to get all objects overlapping a sphere with radius 10 around the current gameObject you would do this:

```
 var colliders = Physics.OverlapSphere(transform.position, 10f)
 foreach(var collider in colliders) {
       Debug.Log($"{collider.gameObject.name} is nearby");
 }

```

Most of these methods also have "NonAlloc" variants which overwrite an existing array instead of creating a new one. These methods are faster and generate no garbage (especially if you call them a lot), but are a bit harder to use and require that you know an upper limit of how many objects you are going to detect at most.
> 2 votes

# Answer
Contrary to the comments claiming this is an unnecessary or impractical thing to do in Unity, it's something I've had to do multiple times. In fact, just next month I'll be helping to exhibit a digital media art installation built in Unity as part of a student project that relies on this technique:

In this example, we were displaying a dynamic point cloud sourced from keywords in a Twitter feed. We had hundreds to low thousands of points to display and animate at a time, so having a separate GameObject and physics components acting on every one would have been a major performance draw.

Fortunately, there are lighter-weight ways to do that, even without resorting to Unity's ECS and job system (though I'd still probably advise using that route for production purposes once the system is stable).

The basic technique involves storing your "objects" not as GameObjects, but conventional C# objects or struct values in a big list or array.

When it comes time to display those objects, you can use a particle system as shown here (or a more modern solution would be to push the points to a VFX Graph), copying the important rendering information about your non-GameObject-objects into a buffer that the built-in systems can render efficiently in a big batch.

But I'm getting a bit off-track justifying why this is a problem solvable and worth solving in Unity. Now let's get to how you solve it, which can range from dirt simple to highly engineered, depending on your performance requirements.

In the example above, we modelled spring forces between the points in the cloud, so they'd spread out and interact rather than just drift randomly. To do that, we had a position and velocity member for each point data structure, and we needed to find all pairs close enough to each other to attract/repel. The naive way to do that is something like:

```
for (int i = 0; i < objects.Count; i++) {
    var thisObject = objects[i];
    for (int j = 0; j < objects.Count; j++) {
        var thatObject = objects[j].position;
        var difference = thisObject.position - thatObject.position;
        if (difference.magnitude < effectRadius) {
            thisObject.velocity += ComputeSpringEffect(difference);
        }
    }
    // Write the modified struct back into the list.
    objects[i] = thisObject;
}

```

But there are a couple of ways we can make this more efficient. We can check each pair just once instead of twice, and avoid an expensive square root in the radius check:

```
float radiusSquared = effectRadius * effectRadius;

for (int i = 1; i < objects.Count; i++) {
    var thisObject = objects[i];
    for (int j = 0; j < i; j++) {
        var thatObject = objects[j].position;
        var difference = thisObject.position - thatObject.position;
        if (difference.sqrMagnitude < radiusSquared) {
            Vector3 push = ComputeSpringEffect(difference);
            thisObject.velocity += push;
            thatObject.velocity -= push;
            objects[j] = thatObject;
        }
    }
    objects[i] = thisObject;
}

```

This is still \\$O(n^2)\\$, but about half the work as the naive version, and in practice a version of this was plenty to keep the installation running at high framerates. You might find it's all you need if the objects whose radii you're checking number in the hundreds to low thousands.

If you need to scale this up to tens of thousands of objects, or you have a more performance-intensive game and can't spare as much frame budget for these radius tests, then your next strategy should be to use an acceleration data structure called a spatial partition. The idea is to organize your object storage in such a way that it's fast to look up objects likely to be "nearby", without visiting every object in the list to check. That reduces your big-O complexity from \\$O(n^2)\\$ to something like \\$O(n \times b)\\$ where "b" is the number of items in each bin of the partition or \\$O(n + log (n) \times c)\\$ where "c" is the number of objects "close enough" to be returned - much smaller numbers, generally. These have been well documented elsewhere, so I won't go into great detail here, just note a few common search terms you can use:

* Spatial Hashing
* Quadtree / Octree
* Binary Space Partition (BSP)
* KD Tree
> 2 votes

# Answer
Here is the solution to the problem, this script helps to search for components within a radius, as well as the nearest and farthest of them https://github.com/Delmas237/VersatileUnityTools/tree/main/ComponentSearcher
> -1 votes

# Answer
You should use a quadtree/Octree or Bounding Volume Hierarchy

https://github.com/Nition/UnityOctree https://github.com/rossborchers/UnityBoundingVolumeHeirachy
> -2 votes

---
Tags: unity, c#, collision-detection
---


# Question
Title: Custom Executable for Source engine games?
I'm just wondering how source games have their own executables?

For example, Portal 2 has portal2.exe, LF42 has left4dead2.exe, Garry's Mod has a hl2.exe that displays gmod icon and has Facepunch Studios etc. in its metadata.

# Answer
> 1 votes
**Altering the "hl2.exe" Icon**

* Create your Icon (has to be 256x256p) and save it as an interlaced .png
* Find a .ico converting website and make convert the .png to .ico (*Gimp* Is a free Image editing application that can also save as .ico)
* Download and save the .ico in"\steamapps\sourcemods\MODNAME\resource" as "game.ico"

Now It should display your Icon, If not then restart your PC

*More about Source Engine Icons can be found at:* https://developer.valvesoftware.com/wiki/Making\_Icons\_and\_Integrating

These steps can also

---
Tags: source-engine, valve
---


# Question
Title: Opening Godot documentation when the caret is on an engine-related keyword
In Godot 3.x, pressing the `F1` shortcut while the blinking text cursor is on an engine-related keyword (methods, properties, etc.) will open the in-editor documentation window at the page related to such keyword.

This desirable behaviour allows me to move the text cursor on a keyword in a script, e.g. `_process`, and the documentation will show up on the right page after pressing the Help shortcut.

However, Godot 4.x doesn't behave this way. Pressing `F1` will open the *Search Help* window regardless of what text is currently selected in a script, prompting me to input the search terms for its documentation.

Is this the new state of things, or can I customise this behaviour and switch back to the previous functionality?

# Answer
> 1 votes
To open the documentation of the engine-related keywords, I use `Ctrl` \+ `LMB` (Left Mouse Button) on the desired keyword. It's that what you mean?

# Answer
> 1 votes
The *Contextual Help* hotkey might be what you're looking for.

On Windows / Linux press `Alt + F1`.
On Mac press `Alt + Shift + Space`.

I'm running 3.5.1 & for me, the contextual help behaves as you describe for built in Godot methods & properties & the same hot key is listed in the stable (4.1) hotkey listing. Oddly when I try just using `F1` by itself in 3.5.1 it brings up the help search but doesn't fill the search in for me as you described in your 3.x experience.

---
Tags: godot-4
---


title: Quarternion rotation flattening cube

text:
# Question
Title: Quarternion rotation flattening cube
I am trying to rotate a cube using a quaternion matrix with WGPU. However, whenever I try to rotate it, I end up with

I am using the matrix from https://en.wikipedia.org/wiki/Quaternions\_and\_spatial\_rotation. I have also tried multiplying the matrix and the vector in the wrong order, which in some occasions, results in something looking like a cube, but with a corner oddly stretched out.

My shader code is

```
fn vs_main(
    model: VertexInput,
    entity: EntityInput,
) -> VertexOutput {

    let rotation = mat4x4<f32> (
        vec4<f32>(entity.rotation_one, 0.0),
        vec4<f32>(entity.rotation_two, 0.0),
        vec4<f32>(entity.rotation_three, 0.0),
        vec4<f32>(0.0,0.0,0.0,1.0),
    );
    let translation = mat4x4<f32> (
        vec4<f32>(1.0,0.0,0.0,0.0),
        vec4<f32>(0.0,1.0,0.0,0.0),
        vec4<f32>(0.0,0.0,1.0,0.0),
        vec4<f32>(0.0,0.0,5.0,1.0),
    );
    let transformation = translation * rotation;
    var out: VertexOutput;
    out.tex_pos = model.tex_pos;
    out.clip_position = camera_mat * transformation * vec4<f32>(model.position, 1.0);
    return out;
}

```

and the rotation matrix I am using is

```
        let w = (self.angle.to_f32().unwrap().to_radians() / 2.0).cos();
        let angle = self.angle.to_f32().unwrap().to_radians();
        let x = self.axis.x.to_f32().unwrap() * (angle / 2.0).sin();
        let y = self.axis.y.to_f32().unwrap() * (angle / 2.0).sin();
        let z = self.axis.z.to_f32().unwrap() * (angle / 2.0).sin();
        // https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
        [
            [
                w.powi(2) + x.powi(2) - y.powi(2) - z.powi(2),
                2.0 * x * y + 2.0 * w * z,
                2.0 * x * z - 2.0 * w * y,
            ],
            [
                2.0 * x * y - 2.0 * w * z,
                w.powi(2) - x.powi(2) + y.powi(2) - z.powi(2),
                2.0 * y * z + 2.0 * w * x,
            ],
            [
                2.0 * x * z + 2.0 * w * y,
                2.0 * y * z - 2.0 * w * x,
                w.powi(2) - x.powi(2) - y.powi(2) + z.powi(2),
            ],
        ]

```

The WGSL shader code is column-major.

EDIT: I have corrected the mistakes in my matrix as pointed out by ratchet freak.

# Answer
> 0 votes
a in the formula under "From a quaternion to an orthogonal matrix" isn't the angle, it is the real or the w component of the quaternion. The value of which should be `cos(angle/2)`.

and you are not consistent whether to convert to radians.

```
let w = (self.angle.to_f32().unwrap().to_radians() / 2.0).cos();
let x = self.axis.x.to_f32().unwrap() * (self.angle.to_f32().unwrap().to_radians()/ 2.0).sin();
let y = self.axis.y.to_f32().unwrap() * (self.angle.to_f32().unwrap().to_radians()/ 2.0).sin();
let z = self.axis.z.to_f32().unwrap() * (self.angle.to_f32().unwrap().to_radians()/ 2.0).sin();

```

and then replace angle with w in the computation of the matrix.

# Answer
> 0 votes
I resolved the issue, it turns out then when I was defining the descriptor for the vertex buffer layout, I miscalculated the memory locations, and thus a column of the rotation matrix was being excluded.

---
Tags: rotation, quaternion
---


# Question
Title: Is it a good idea to solve movement of solid bodies with restrictions (e.g. connections) by shifting tangentially and projecting normally in phase sp?
I am trying to code my first 2d game with physics (in python), and so far my physics simulation works with solid bodies. I want to add connections, for example, so the player can rotate an arm and throw a ball. This appears nontrivial.

The algorithm for progressing the system forward by dt I currently have in head is as follows: (we work in an N-dimensional Euclidean space of coordinates and rotations of some material points, which are mass-normalized, so velocity has the same norm whenever kinetic energy is the same.

We start with position x, velocity v and acceleration a (the last of which can be arbitrarily influenced by external factors))

* Take the rows of the Jacobian matrix as the basis of the normal space
* Find the projection a\_tan of the acceleration a to the tangent space (I guess this means solving a linear system with the quadratic form matrix of the Jacobian rows)
* approximate the next position x\_1 as if it was moving in the entire phase space with velocity v and acceleration a\_tan
* Move this x\_1 along the normal vectors, using Newton's algorithm, until the values of all the restriction functions become smaller than some desired value MAX\_DEVIATION, getting the point x\_2
* Find the direction of the new velocity v\_1 by requiring that J(v\_1 - v) == 0 (the geodesic condition
* Get the other new velocity as v\_2 = v\_1 + a\_tan * dt
* Calculate the Jacobian at x\_2 (we can remember it at this point for the next step)
* Project v\_2 to the zeros of the Jacobian to get v\_3 (again, we can remember the inverse matrix of the quadratic form of the rows of the Jacobian for later)
* Set (x\_2,v\_3,something) as the new triplet (the "something" comes from outside forces)

Is this a good approach for this task? I did not study mechanics very deeply, so perhaps there is a completely different point of view on all this?

Or maybe there is just a python module I can use for this? A universal one --- I think this problem is normally solved in physics modules, but it works within their physical worlds with their collisions and forces, and I want to write those on my own.

# Answer
I think what you are saying is probably a good idea. I have tried it and it works. Out of curiosity I wrote some python simulation for some example I cooked up. I can share it here, if it is of any interest.

I did not even need to find the tangential component of the acceleration to the constraint because I calculate the constraint accelerations take care of that. In a nutshell, the algorithm is:

Assume the acceleration of the system, without imposed constraints, is given by

```
a = acceleration(time, x, v)

```

and the constraints, written as a vector valued function/map, are

```
C(x) = L

```

Then, the equations of motion are

```
x'' = acceleration(t, x, v) + constraint_acceleration(x)
C(x) = L

```

To solve this system numerically, iterate the following sequence of calculations until time reaches prescribed stopping time:

```
1) given the current time, x, v, u

2) Set a = acceleration(time, x, v)

3) Solve for x_next and u_next the non-linear system:
      x_next = x + dt*v + dt*dt*a + dt*[DC(x)^T]u_next
      C(x_next) - L = 0
   where DC(x)^T is the Jacobian of C(x) transposed

   E.g. apply Newton's method with adjustment "bias" and initial guess u_next=u by iterating:
      x_next = x + dt*v + dt*dt*a + dt*[DC(x)^T]u_next
      u_next = u_next - bias*([DC(x)^T][DC(x)])^(-1) (C(x_next) - L)
   until norm(C(x)-L) < small enough error

4) Set
   time = time + dt
   x = x_next
   v = v + dt*a + [DC(x)^T]u_next
   u = u_new

If time has not exceeded the prescribed sopping time, go back to 1)

```

Here is some python code, simulating an example, where there is standard gravitational acceleration, some air resistance and some time-dependent wind, that dies down to zero:

```
import math
import numpy as np
import matplotlib.pyplot as plt
from vpython import *

g=9.8
g_accel = -g * np.array([0,1,0,1,0,1,0,1])
e = np.array([1,0,1,0,1,0,1,0])

# A function that initializes the configuration of the system
def initialize(q):
    L_1 = q[0:2].dot(q[0:2])
    L_2 = q[0:2]-q[2:4]
    L_2 = L_2.dot(L_2)
    L_3 = q[2:4]-q[4:6]
    L_3 = L_3.dot(L_3)
    L_4 = q[0:2]-q[6:8]
    L_4 = L_4.dot(L_4)
    L_5 = q[4:6]-q[6:8]
    L_5 = L_5.dot(L_5)
    return np.array([L_1, L_2, L_3, L_4, L_5])

# A function that initializes the configuration of the system
def init_pos():
    angle = np.pi * np.array([75, 60, -5, 10]) / 180
    L = np.array([1.2, 1., 1.5, 1.3])
    q = np.empty(8, dtype=float)
    for i in range(4):
        q[2*i : 2*i+2] = L[i]*np.array([np.sin(angle[i]), -np.cos(angle[i])])
    for i in range(1,3):
        q[2*i : 2*i+2] = q[2*i : 2*i+2] + q[2*i-2 : 2*i]
    q[6 : 8] = q[6 : 8] + q[0 : 2]
    return q

# Ture acceleration: in this example:
# constant gravity + wind that dies down with time + air resistance:
def acceleration(time, q, v):
    a = g_accel + 7*e/(1 + ((time-1)/8)**8) - 0.01*math.sqrt(v.dot(v))*v
    return a

# the constraints of the system, written as a map C(q) - L = 0
def C(q, L):
    c_1 = q[0:2].dot(q[0:2]) - L[0]
    c_2 = q[0:2]-q[2:4]
    c_2 = c_2.dot(c_2) - L[1]
    c_3 = q[2:4]-q[4:6]
    c_3 = c_3.dot(c_3) - L[2]
    c_4 = q[0:2]-q[6:8]
    c_4 = c_4.dot(c_4) - L[3]
    c_5 = q[4:6]-q[6:8]
    c_5 = c_5.dot(c_5) - L[4]
    return np.array([c_1, c_2, c_3, c_4, c_5])

# The Jacobian DC(q) of the constraint map, transposed
def DC_T(q):
    q_12 = q[0:2] - q[2:4]
    q_23 = q[2:4] - q[4:6]
    q_14 = q[0:2] - q[6:8]
    q_34 = q[4:6] - q[6:8]
    J = np.array([[    q[0],    q[1],              0,0,              0,0,              0,0],
                  [ q_12[0], q_12[1],-q_12[0],-q_12[1],              0,0,              0,0],
                  [              0,0, q_23[0], q_23[1],-q_23[0],-q_23[1],              0,0],
                  [ q_14[0], q_14[1],              0,0,              0,0,-q_14[0],-q_14[1]],
                  [              0,0,              0,0, q_34[0], q_34[1],-q_34[0],-q_34[1]]])
    return J.T

# the propagation of the system for a single time-step
def one_step(time, x, v, u_old, L, bias, dt):
    a = acceleration(time, x, v)
    v_half = v + dt * a
    x_half = x + dt * v_half
    Dc_T = DC_T(x)
    M = Dc_T.T.dot(Dc_T)
    M = np.linalg.inv(M)
    u = u_old
    for i in range(8):
        dv_out = Dc_T.dot(u)
        x_out = x_half + dt*dv_out
        c = C(x_out, L)
        error = np.abs(c).max()
        if error < 1e-7: break
        u = u - bias * M.dot(c)
    return time + dt, x_out, v_half + dv_out, u, error

# the full propagation of the dynamics
def propagate(x_start, v_start, L, n_time_steps, dt):
    u = np.zeros(L.shape[0], dtype=float)
    bias = 20
    x, v = x_start, v_start
    X = np.empty((n_time_steps+1, x.shape[0]), dtype=float)
    Error = np.empty((n_time_steps+1,), dtype=float)
    X[0] = x
    time = 0
    for t in range(1, n_time_steps+1):
        time, x, v, u, error = one_step(time, x, v, u, L, bias, dt)
        X[t] = x
        Error[t] = error
    return X, Error

# The animation of the actual simulation:
# starting with the initialization of the system
q = init_pos()
L =  initialize(q)
w = np.zeros(q.shape[0], dtype=float)
u = np.zeros(L.shape[0], dtype=float)
dt = 0.03
n = 1000
t_stop = n*dt

# generation of the dynamics for the system.
# X is an array that contains the configuration
# for the system for every time-step.
# Err is the array of all errors, i.e. how much the
# configuration fails to satisfy the constraints.
X, Err = propagate(q, w, L, n, dt)

# print the min and max errors (optional):
print(Err.min(), Err.max())

# animation using Vpython:
animation = canvas(title='Linkage-under-gravity-air-drag-and-wind',
     width=1700, height=900,
     center=vector(0,0,0), background=color.black)

shift = vector(0, np.sum(L[0:3])/2, 0)

fixed=sphere(pos = shift,
             color = color.blue,
             radius = 0.1,
             make_trail=False)

bob = []
bar = []

for i in range(q.shape[0] // 2):
   bob.append( sphere(pos = shift + vector(q[2*i], q[2*i+1], 0),
                      color = color.red,
                      radius = 0.15,
                      make_trail=False))

for i in range(L.shape[0]-1):
   bar.append( cylinder(pos = bob[i].pos,
                        axis = vector(0,0,0),
                        radius = 0.023,
                        color = color.red))

bar.append( cylinder(pos = bob[3].pos,
                        axis = vector(0,0,0),
                        radius = 0.023,
                        color = color.red))

bar[0].axis = fixed.pos - bar[0].pos
bar[1].axis = bar[0].pos - bar[1].pos
bar[2].axis = bar[1].pos - bar[2].pos
bar[3].axis = bar[0].pos - bar[3].pos
bar[4].axis = bar[2].pos - bar[3].pos

#u = np.zeros(L.shape[0], dtype=float)
t = 0
for t in range(X.shape[0]):
    rate(30)
    for i in range(q.shape[0] // 2):
        bob[i].pos = shift + vector(X[t, 2*i], X[t, 2*i+1], 0)
        bar[i].pos = bob[i].pos
    bar[4].pos = bob[3].pos
    bar[0].axis = fixed.pos - bar[0].pos
    bar[1].axis = bar[0].pos - bar[1].pos
    bar[2].axis = bar[1].pos - bar[2].pos
    bar[3].axis = bar[0].pos - bar[3].pos
    bar[4].axis = bar[2].pos - bar[3].pos

```
> 1 votes

---
Tags: physics, mathematics, movement, python, joints
---


# Question
Title: Why do my svg sprites (vector images) appear to have very low resolution in the game view and how can I fix this issue?
I recently drew a game sprite for my game using Adobe Illustrator 2021. I exported the sprite using the Export for Screens menu to export the entire artboard. The problem I have in Unity 2021+ is that when I import the svg sprite and add it to the scene view, the sprite appears to have incredibly low resolution in the game view. I have already installed vector graphics to Unity (com.unity.vectorgraphics) and researched about the issue I'm having to no avail. The sprite is 396 x 278 pixels in adobe illustrator before exporting. Here are a few screenshots of my svg sprite in Unity:

As you can see in the 4th image, even though vector sprites should have scaling resolution when zoomed, the resolution is extremely poor when zoomed in the game view. I have already tried the following methods to fix my issue:

1. Increasing Pixels Per Unit: Turned out that this actually decreased my resolution even more. As pixels per unit increased, the sprite in the game view became smaller and smaller until it became a singular pixel
2. Increasing Gradient Resolution: Did not do much for resolution quality after the value of 100.
3. Changing Tesselation Settings to advanced and minimizing Step Distance as well as maximizing Sampling Steps: Similar increasing Gradient Resolution, there was a limit to how much it improved sprite resolution quality.

Those of you who have experience importing and using vector images in Unity 2021+, please help me fix this issue. This is stalling my other development progress as well, since one of the shaders I have to implement relies on high-quality sprites.

\*Added main camera settings

# Answer
> 1 votes
As mentioned in the comments, you're using the wrong method to check how the SVGs scale.

The zoom slider in the game window does not re-render your scene at a higher resolution.

It takes your existing render at a fixed resolution and draws each pixel larger.

So no content, not SVGs, not SDFs or other mathematically computed effects, *nothing* will get more detailed or smoother as you zoom in, and that's the deliberate behaviour of this zoom feature.

The reason for this is so that you can more easily examine things like aliasing artifacts without having to peer uncomfortably close at your screen, or take screenshots to enlarge in another program, or use an extra magnifier app hovering over the Unity window. It integrates this "let me see those exact pixels, but bigger" workflow into the editor interface itself.

To see how your game would look at a different resolution, keep the zoom slider at 1x and change the resolution drop-down box in the top left corner of the game view. This changes the size of the virtual screen the game is being rendered into, prior to any pixel zooming. So SVGs, SDFs, and other shader effects will be rendered smoother as you increase the resolution here. This rendering will faithfully match what you would actually see on a device that has more (or fewer) screen pixels to draw on.

# Answer
> 0 votes
Internally, all graphics are rasterized before they are sent to the video card.

My takeaway from this insight is to save your image in the largest dimension to a PNG.

Memory is cheap, scaling is a standard operation in the GPU and not so bad on the CPU, whereas runtime rasterization is an expensive CPU operation.

If memory or GPU transfer time is the bottle neck, use mip-maps instead.

Efficient real-time vector graphics last happened on a control board in a CRT for several Arcade games in the 1980's. It is a great idea, but has no modern hardware support.

Just because a feature is there does not mean it should be used.

# Answer
> 0 votes
My fix is to import your vector art as PNGS and increase the max size to something high like 8192 in the sprite inspector. Here's what to change:

I had the same problem with my sprites. I designed them as vector images and imported them as PNGs in the way I described above. Hope this helps.

---
Tags: unity, sprites, resolution, svg, vector-art
---


# Question
Title: How to prevent an object with high velocity from passing through a collider?
Consider a simple 2D platformer. I have a `BoxCollider2D` on the player object and a `TilemapCollider` on the ground below(grid). I created a "jump" script for the player through which the player object jumps and comes back to the ground, clean. But when the player object goes relatively high and comes down with a high velocity, it doesn't collide with the ground(grid) instead it goes right through the tilemap collider and into the void.

How can this behaviour be prevented?

# Answer
To prevent a collider from passing through another collider at high velocity, change the "Collision Detection" option on its "Rigidbody 2D" from "Discrete" (default) to "Continuous".

**Note :** Continuous collision detection has overhead and will have impact on the engine performance, but will provide a much better collision detection system.
> 4 votes

# Answer
In the 2D world, changing your collider from discrete to continuous is not going to fix your problem if you're moving the wrong way. You also have to make sure that you are using the `MovePosition` command of your rigidbody (**not** using `.position`), or a super high velocity will still go through even a continuous collider.
> 1 votes

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


# Question
Title: Why isn't my framebuffer getting updated?
```
Ref<Framebuffer> colorSource = framebufferStack->peek();
colorSource->bind();
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());

for(int i = 0; i < width*height; i++)
{
  pixels[i*4] = 127;
  pixels[i*4+1] = 127;
  pixels[i*4+2] = 127;
  pixels[i*4+3] = 255;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());

```
1. I copy the framebuffer into some uint8\_t vector
2. I modify the uint8\_t vector
3. I try to overwrite the framebuffer on the GPU
4. I read the framebuffer to make sure it was overwritten (I am getting the original values not the 127 127 127 255 ones).

# Answer
I needed to not only bind the framebuffer but also the texture associated with this framebuffer.
> 1 votes

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


title: writing a custom Quaternion.FromTo

text:
# Question
Title: writing a custom Quaternion.FromTo
I'm using the new Unity.Mathematics library. I'm trying to to replace `Quaternion.FromTo(Vector3 from, Vector3 to)` which returns a quaternion with what it would take to get a vector "from" rotated to become linearly dependent with "to".

My implementation ultimately uses the `quaternion.AxisAngle` method, I use a cross product to find the axis and a dot product and arccos to find the angle.

Here's what I have so far, I think the `angle between` is working but I included it just in case. The custom `QuaternionFromToFast` method is definitely not.

```
public static float AngleBetween(float3 v1, float3 v2)
        {
            return AngleBetweenFast(math.normalizesafe(v1), math.normalizesafe(v2));
        }

        public static float AngleBetweenFast(float3 v1Normalized, float3 v2Normalized)
        {
            float dot = math.dot(v1Normalized, v2Normalized);
            return math.acos(dot);
        }

        public static quaternion QuaternionFromToFast(float3 fromNormalized, float3 toNormalized)
        {
            float angleBetween = AngleBetweenFast(fromNormalized, toNormalized);
            float3 axis = math.cross(fromNormalized, toNormalized);
            var fromToRotation = quaternion.AxisAngle(axis, angleBetween);

            return fromToRotation;
        }

```

---

###### Here's some debug code and a gif to illustrate the issues.

When I use Unity's `Quaternion.FromTo` the basis vectors are all be rotated onto the same line towards the target (the blue sphere). However that is not the case with my own implementation.

```
Gizmos.color = Color.green;
            Gizmos.DrawRay(float3.zero, math.mul(MathUtils.QuaternionFromTo(math.right(), target), math.right()));
            Gizmos.color = Color.red;
            Gizmos.DrawRay(float3.zero, math.mul(MathUtils.QuaternionFromTo(math.forward(), target), math.forward()));
            Gizmos.color = Color.blue;
            Gizmos.DrawRay(float3.zero, math.mul(MathUtils.QuaternionFromTo(math.left(), target), math.left()));

            Gizmos.DrawSphere(target, .1f);

```

# Answer
> -1 votes
> "from" rotated to become linearly dependent with "to".

It is unclear what you are asking for.

All true vectors must be based from the origin. Points in space are not calculatable vectors for operations.

You must tranlate both points so that one point resides at the origin:

```
Vector3 displacement = to - from;

```

The rotation in Euler angles is the normalization of this vector.

```
Vector3 rot = math.normalizesafe(displacement);

```

From there you have the angles in radians:

Follow at a constant speed:

```
Position += rot * speed;

```

Project shadow movement on a world axis:

```
displacement.y = 0; // or hightmap[x,z];
Position += displacement;

```

Convert to a rotation matrix and transform onto a different axis and apply affine transformation(s), may cause streching and transform back to world space.

Too many possibilities to enumerate here.

And lastly convert it to a Quaternion

```
Quaternion.FromEulerAngles(rot);

```

From there slerp will allow linear rotational speed.

---
Tags: unity, mathematics, geometry, quaternion, linear-algebra
---


title: Resize Sprite To Match Screen Size

text:
# Question
Title: Resize Sprite To Match Screen Size
My game's resolution is 1920 x 1080, and I have a background sprite that is also 1920 x 1080. I have made the background sprite a child of my MainCamera & dragged it further back on the Z-axis so that it is rendered behind everything else in the scene.

Because I have dragged it so far back in the scene, it no longer covers the entirety of my game screen.

To remedy this, I'm resizing my sprite by doing the following:

I've made a child gameObject of the MainCamera and attached my sprite to it. I've also attached the following Script to the child gameobject:

```
[SerializeField] private Camera _camera;
[SerializeField] private SpriteRenderer _spriteRenderer;

void Update()
    {
        ScaleBackgroundImage();
    }

    private void ScaleBackgroundImage()
    {
        float fovRadians = Mathf.Deg2Rad * _camera.fieldOfView;
        float visibleHeightAtDepth = transform.localPosition.z * Mathf.Tan(fovRadians) * 2f;

        float spriteHeight = _spriteRenderer.sprite.rect.height
                           / _spriteRenderer.sprite.pixelsPerUnit;

        float scaleFactor = visibleHeightAtDepth / spriteHeight;

        _spriteRenderer.transform.localScale = Vector3.one * scaleFactor;
    }

```

For good measure, here is the what the sprite's game object and camera look like in the inspector:

# Answer
> 2 votes
Here's how you can compute the necessary scaling factor:

```
// Angle the camera can see above the center.
float halfFovRadians = camera.fieldOfView * Mathf.Deg2Rad / 2f;

// How high is it from top to bottom of the view frustum,
// in world space units, at our target depth?
float visibleHeightAtDepth = depth * Mathf.Tan(halfFovRadians) * 2f;

// You could also use Sprite.bounds for this.
float spriteHeight = spriteRenderer.sprite.rect.height
                   / spriteRenderer.sprite.pixelsPerUnit;

// How many times bigger (or smaller) is the height we want to fill?
float scaleFactor = visibleHeightAtDepth / spriteHeight;

// Scale to fit, uniformly on all axes.
spriteRenderer.transform.localScale = Vector3.one * scaleFactor;

```

This matches the height of the sprite to the height the camera can "see" at that depth. I'm assuming here that your sprite's pivot is its center, placed at `(0, 0, depth)` in the camera's coordinate system, and that the aspect ratio of the sprite is known to be as wide or wider than the widest supported resolution so it fills the frame.

Alternatively, as I mentioned previously, you could make a shader that does this automatically for a standard Unity quad with vertices running from (-0.5, -0.5) to (0.5, 0.5) by transforming them to the viewport corners:

```
Shader "Unlit/FillCameraFrame"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        [Toggle(PRESERVE_ASPECT)] _PreserveAspect ("Preserve Aspect Ratio", Float) = 1
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma shader_feature PRESERVE_ASPECT

            #include "UnityCG.cginc"

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

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

            sampler2D _MainTex;
            float4 _MainTex_ST;

        #ifdef PRESERVE_ASPECT
            float4 _MainTex_TexelSize;
        #endif

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = float4(v.vertex.xy * 2.0f, 0.5f, 1);
                o.vertex.y *= -1;

                float2 uv = v.uv;

            #ifdef PRESERVE_ASPECT
                float cameraAspect = _ScreenParams.x * (_ScreenParams.w - 1.0f);
                float invTextureAspect = _MainTex_TexelSize.w * _MainTex_TexelSize.x;
                float conversion = invTextureAspect * cameraAspect;

                // Scale from center, rather than from the corner.
                // (Delete the 0.5 shifts if you prefer to anchor at left)
                uv.x = (v.uv.x - 0.5f) * conversion + 0.5f;
            #endif

                o.uv = TRANSFORM_TEX(uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col * col.a;
            }
            ENDCG
        }
    }
}

```

This also works for tiling background images, repeating them if a very wide camera viewport exceeds the image's aspect ratio. (Or clamping them and filling the excess with the leftmost/rightmost column of texels, if you set the texture to clamp instead of repeat)

# Answer
> 2 votes
Building off of @DMGregory's solution, you can calculate the depth of the object without assuming it's at (0, 0, depth) using some vector math:

This turns into this code:

```
float depth = Vector3.Dot(spriteRenderer.transform.position - camera.transform.position,
                camera.transform.forward);

```

So the final (C#) answer becomes:

```
// Angle the camera can see above the center.
float halfFovRadians = camera.fieldOfView * Mathf.Deg2Rad / 2f;

// What depth is the object at in terms of the camera?
float depth = Vector3.Dot(spriteRenderer.transform.position - camera.transform.position,
    camera.transform.forward);

// How high is it from top to bottom of the view frustum,
// in world space units, at our target depth?
float visibleHeightAtDepth = depth * Mathf.Tan(halfFovRadians) * 2f;

// You could also use Sprite.bounds for this.
float spriteHeight = spriteRenderer.sprite.rect.height
                     / spriteRenderer.sprite.pixelsPerUnit;

// How many times bigger (or smaller) is the height we want to fill?
float scaleFactor = visibleHeightAtDepth / spriteHeight;

// Scale to fit, uniformly on all axes.
spriteRenderer.transform.localScale = Vector3.one * scaleFactor;

```

In my case, I have a 2D sprite that I would like to keep at the same size regardless of how far away it is. To do this, instead of dividing by the height of the sprite, I instead divide by the pixel height of the game:

```
...

// How many times bigger (or smaller) is the height we want to fill?
float scaleFactor = visibleHeightAtDepth / screenHeight;

...

```

# Answer
> 0 votes
Multiply the width and height by a scaling factor.

---
Tags: unity, scripting
---


title: Un-pause game button not working

text:
# Question
Title: Un-pause game button not working
I can successfully pause my game with Godot 4.1 with:

```
func _process(delta):

    if Input.is_action_just_pressed("action_quit"):
        print("pause...")
        pause()

func pause():
    Globals.game_paused = !Globals.game_paused
    print("game paused? " + str(Globals.game_paused))
    get_tree().paused = ! get_tree().paused

```

But that's as good as it gets: Once the "action\_quit" key is hit the game is permanently paused from this point on.

I've got a sneaking suspicion that *\_process* is on holiday at this point and `get_tree().paused = ! get_tree().paused` isn't being processed. I may be wrong.

How do I check for a keyboard call to un-pause the game?

# Answer
The `process_mode` of the `Node` controls when their `Script` get to run.

---

By default `process_mode` is set to `PROCESS_MODE_INHERIT`, which mean they take the value from their parent.

And, also by default, the `process_mode` of the `root` of the `SceneTree` is set to `PROCESS_MODE_PAUSABLE`, which means that when you set the `paused` property of the `SceneTree` to `true`, the `Node` will stop executing its `Script`...

And since everything else has `process_mode` set to `PROCESS_MODE_INHERIT` by default, then every `Script` stops executing too.

---

To be able to remove the pause you need an `Script` to run when `paused` is `true`...

That means changing the `process_mode` of the `Node` that has the `Script`.

Aside from `PROCESS_MODE_INHERIT` and `PROCESS_MODE_PAUSABLE`, your options are:

* `PROCESS_MODE_WHEN_PAUSED` which is the opposite of `PROCESS_MODE_PAUSABLE`. It will make the `Script` only run when `paused` is true. Since you want to use the same script to pause and unpause, this won't work for you.
* `PROCESS_MODE_ALWAYS` which makes the `Script` run regardless of `paused`. This is what you want.
* There is also `PROCESS_MODE_DISABLED` that makes the `Script` never run. This is sometimes useful to temporarily disable entire `Script` from code.

---

I want to reiterate that this is about disabling entire `Script`s, not just `_process` (which you can do with `set_process`) or any other specific methods. *So, no, `_unhandled_input` won't work.*
> 2 votes

# Answer
You are correct in that the `_process`, `_physics_process`, `_input`, and `_input_event` functions will not be called when a Node is paused. However signals continue to work and cause their connected function to run.

As such you can solve this problem by making a popup or panel to handle pausing. Make sure to set its pause mode to `WhenPaused` \- doing so will ensure that it & its children will work when paused. Then you can add code so that the pressing the pause button will enable & show the pause screen:

```
func _on_pause_button_pressed():
    get_tree().paused = true
    $pause_popup.show()

```

To unpause and resume the game, do the opposite when the pause screen is closed:

```
func _on_pause_popup_close_pressed():
    $pause_popup.hide()
    get_tree().paused = false

```

You can find more information about this in the pausing games and process mode documentation.
> 2 votes

---
Tags: godot, godot-4
---


# Question
Title: OpenGL texture not displaying despite setting uniform int
As you can see in the linked image, despite assigning a texture unit, there is no texture being drawn on the screen. In the main loop, I am receiving error 1282, and there are no further errors throughout the code, I have checked with sporadic calls to the error checking function.

I am using an M2 Mac, could that be a root cause?

```
#include <glad/glad.h>  // GLAD helper library for OpenGL function pointer help
#include <GLFW/glfw3.h> // GLFW helper library for window management
#include <iostream>
#include "shaders/Shader.h"
#include "Textures/Texture.h"
#define STB_IMAGE_IMPLEMENTATION
#include "ext/stb_image.h"

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);

/* Default screen size values */
const unsigned int SCR_HEIGHT = 600;
const unsigned int SCR_WIDTH = 800;

int main() {

    /* configure window and set glfw/opengl settings */
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // macOS specific apparently?

    /* create window object */
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Learn-OpenGL", NULL, NULL);
    if (window == NULL) {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    /* init GLAD before using any opengl functions */
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {  // OS specific location of function pointers
        std::cout << "Failed to init GLAD" << std::endl;
        return -1;
    }

    /* init viewport prior to rendering -> makes it so screen coords work */
    glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);     // separate to GLFW window size so make them equal!

    /* callback to allow for user window resizing */
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    /* Set up our shader */
    Shader shader("shaders/vertexShading.glsl", "shaders/fragmentShading.glsl");

    /* Set up our texture */
    Texture texture("../res/container.jpg");

    /* Define x,y,z positions of each vertex on our vertices.
       Normalised device coords -> always between -1 and 1 */
    float vertices[] = {
            // positions          // colors           // texture coords
            0.5f,  0.5f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 1.0f,   // top right
            0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f,   // bottom right
            -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 0.0f,   // bottom left
            -0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1.0f    // top left
    };

    /*  VBO holds the actual vertex data.
        VAO keeps track of how to use the vertex data from a VBO.
        EBO specifies the order in which the vertices should be connected to form shapes. */
    unsigned int VBOs[2], VAOs[2];
    glGenBuffers(2, VBOs);
    glGenVertexArrays(2, VAOs);

    /* vertices data */
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);
    glBindVertexArray(VAOs[0]);

    /* copy vertex data into the buffer's memory */
    /* static draw since data is set once and used many times. Use dynamic if the data changes a lot */
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    /* how we should interpret vertex data per vertex attribute */
    // position attr
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);   // we set location as 0 in our shader code
    // color attr
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3*sizeof(float)));   // offset of size 3 floats
    glEnableVertexAttribArray(1);   // we set location as 1 in our shader code
    // texture attr
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6*sizeof(float)));
    glEnableVertexAttribArray(2);

    shader.use();
    shader.setUniformInt("ourTexture", 0);

    /* window loop */
    while(!glfwWindowShouldClose(window)) {
        // input -------------------------------------------------------------------------------------------------------
        processInput(window);

        // rendering ---------------------------------------------------------------------------------------------------
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);   // greenish
        glClear(GL_COLOR_BUFFER_BIT);   // clear colour buffer

        /* bind texture data */
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture.getID());

        shader.use();

        /* draw vertices */
        glBindVertexArray(VAOs[0]);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        // unbind buffers ----------------------------------------------------------------------------------------------
        glBindVertexArray(0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

        // check and call events + swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height) {
    glViewport(0, 0, width, height);
}

void processInput(GLFWwindow *window) {
    /* ability to close window */
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
        glfwSetWindowShouldClose(window, true);
    }

    /* ability to swap between fill and wireframe modes -> hold w key */
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    } else {
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }
}

```

```
//
// Created by Henry Fielding on 23/8/2023.
//

#include "Texture.h"

Texture::Texture(const char* fp) {
    /* load in texture file and set values */
    data = stbi_load(fp, &width, &height, &numChannels, 0);

    /* generate texture id */
    glGenTextures(1, &ID);

    /* bind it so any subsequent GL_TEXTURE_2D commands apply to it */
    glBindTexture(GL_TEXTURE_2D, ID);

    /* configure texture wrapping and filtering options. changes behaviour view docs to see differences */
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    /* ... actually generate the texture */
    if (data) {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    } else {
        std::cerr << "FAILED TO LOAD TEXTURE" << std::endl;
    }

    /* free image data */
    stbi_image_free(data);
}

unsigned int Texture::getID() {
    return ID;
}

```

```
#version 330 core

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;

out vec3 ourColor;
out vec2 TexCoord;

void main() {
    gl_Position = vec4(aPos, 1.0);
    ourColor = aColor;
    TexCoord = aTexCoord;
}

```

#version 330 core

out vec4 FragColor;

in vec3 ourColor;
in vec2 TexCoord;

uniform sampler2D ourTexture;

void main()
{
    FragColor = texture(ourTexture, TexCoord);
}
```

# Answer
> 0 votes
Can you add .txt extension and try?

Like so:

`Shader shader("shaders/vertexShading.glsl.txt", "shaders/fragmentShading.glsl.txt");`

# Answer
> -1 votes
Try updating your GPU drivers, also check to see if the openGL Mac lib is there and not missing.

*source (It's a minecraft error fix but theoretically should work for you):*
https://gameserrors.com/minecraft-opengl-error-1282/#:~:text=If%20you%20are%20experiencing%20the,Errors%20option%20and%20keep%20playing.

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


# Question
Title: How to compare a vector to a rotation in Godot 4.1?
## The Context

In Godot 4.1, I have a third-person character controller. It's a CharacterBody3D with a child Node3D called PlayerContent. The visual components of the character (model, etc.) are all children of PlayerContent. To move the character, I've created a Vector3 called direction that gets the joystick input:

```
func get_input_direction():
  direction.x = Input.get_axis("move_left", "move_right")
  direction.z = Input.get_axis("move_forward", "move_backward")

```

The player can be Z-targeting or moving freely. In the case of moving freely, I rotate PlayerContent to match the direction of movement (giving the illusion that the character is turning, even though the CharacterBody3D isn't). In the case of Z-targeting, I rotate PlayerContent towards the target.

In order to make **direction** relative to the camera, I rotate **direction** by the camera's rotation.

```
func player_direction_to_camera():
  get_input_direction()
  direction = direction.rotated(Vector3.UP, camera.rotation.y)

```

Lastly, I set the **velocity** variable that *move\_and\_slide()* uses to equal **direction**.

## The Question

I'd like to be able to tell which way **direction** is compared to the value the Vector2 is being rotated by. For example, if the player is moving *left* (relative to PlayerContent's rotation), I'd like to be able to specify the dodge type to be *left\_dodge* (or something to that effect.) Or *forward\_dodge*, or *backflip*, or anything like that.

I'm not very good at vector math, so I'd appreciate some help with this.

# Answer
I'm not sure I understand the issue... So, I'll give you three scenarios, hopefully I cover your case.

---

**First scenario**: You want to know which way is `camera.rotation.y` rotating.

For that you can `wrapf` it:

```
wrapf(camera.rotation.y, -PI, PI)

```

Then the sign will tell you which way it is rotating.

---

**Second scenario**: You want to compare `direction` to the orientation of `PlayerContent` (or some other object).

The forward direction of `PlayerContent` would be:

```
var target_direction := -PlayerContent.global_transform.basis.z

```

*If `PlayerContent` is not what you want, you can replace it with any other `Node3D` (e.g. the `Camera3D` or the `CharacterBody3D`).*

And wince we know the rotation uses `Vector3.UP` as axis, we can use it in `signed_angle_to`:

```
direction.signed_angle_to(target_direction, Vector3.UP)

```

And again, you can use the sign to discriminate.

---

**Scenario tree**: You a `Basis` (perhaps from a `Transform3D`, for example from the `Camera3D`) or a `Quaternion`, and you want to know which way it rotates.

You need a vector that you know to be perpendicular to the axis. In our case the axis is `Vector3.UP`, so we can use `Vector3.FORWARD`...

Then compared with it transformed version:

```
Vector3.FORWARD.signed_angle_to(r * Vector3.FORWARD, Vector3.UP)

```

*Where `r` is the `Basis` or `Quaternion`.*

And once more, the angle will tell you which way it rotated.

---

**Bonus**: If you need the `Transform3D` of something relative to something else you can do this:

```
var r := something_else.global_transform.affine_inverse() * something.global_transform

```

That will give you a `Transform3D` such that `something_else.global_transform* r` is `something.global_transform`. That is the transform needed to go from `something_else` to `something`, in other words, the transform of `something` relative to `something_else`.
> 1 votes

---
Tags: mathematics, vector, godot-4, character-controller
---


# Question
Title: Cooldown in the new input system of unity
A few days ago I first used the new input system of unity for my game and I ran into a problem. So basically I cant seem to figure out how to implement cooldown in the new system. Either it just overall doesnt work, it breaks other code or it just gives me a hundred errors. I just cant figure it out. I hope someone can help me implement just a very simple adjustable cooldown timer for the playerattack. I already want to thank everyone helping me with this!

Btw: I used the startTimeBtwAttack and timeBtwAttack variables for my cooldown in the past, but they dont work anymore. Had to remove some code so yeah...

PlayerAttack and Movement script:

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

public class Move : MonoBehaviour
{

public int damage;
private float timeBtwAttack;
public float startTimeBtwAttack;

public float attackRangeX;
public float attackRangeY;

public Transform attackPos;
public LayerMask whatIsEnemies;

//Move Start
[SerializeField] private Rigidbody2D rb2D;
[SerializeField] private float speed;
private Vector2 moveInputValue;

private void OnMove(InputValue value)
{
    moveInputValue = value.Get<Vector2>();
    Debug.Log(moveInputValue);
}
private void MoveLogicMethod()
{
    Vector2 result = moveInputValue * speed * Time.fixedDeltaTime;
    rb2D.velocity = result;
}
    private void FixedUpdate()
    {
        MoveLogicMethod();
    }
//Move End

//Attack Start

private void OnPlayerAttacking()
{
    Collider2D[] enemiesToDamage = Physics2D.OverlapBoxAll(attackPos.position, new Vector2(attackRangeX, attackRangeY), 0, whatIsEnemies);
            for (int i = 0; i < enemiesToDamage.Length; i++) {
                enemiesToDamage[i].GetComponent<Enemy>().TakeDamage(damage);
            }
            timeBtwAttack = startTimeBtwAttack;
}
void OnDrawGizmosSelected(){

        Gizmos.color = Color.black;
        Gizmos.DrawWireCube(attackPos.position, new Vector3(attackRangeX, attackRangeY, 1));
}
//Attack End
}

```

Then there is the enemyScript for the enemy to receive damage:

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

public class Enemy : MonoBehaviour {

public int health;
private Animator anim;

void Update(){
    if(health <= 0){

        Destroy(gameObject);
    }
}

public void TakeDamage(int damage){
health -= damage;
Debug.Log("damage TAKEN !");

}
}

```

Let me know if you need more infos!

# Answer
> 1 votes
You can solve this the same way I explained previously. Keep a timestamp of your last successful attack, and compare it to the time when the trigger condition fires (in this case, when the button press causes `OnPlayerAttacking()` to be called). If less time has passed than your desired cooldown, abort execution without performing the attack.

```
[Tooltip("Minimum time between attack inputs, in seconds")]
public float attackCooldown = 0.5f;

float _lastAttackTime;

private void OnPlayerAttacking()
{
    // If attacking too close to previous attack, ignore this input.
    if (Time.time - _lastAttackTime < attackCooldown) return;

    var enemiesToDamage = Physics2D.OverlapBoxAll(
               attackPos.position,
               new Vector2(attackRangeX, attackRangeY),
               0,
               whatIsEnemies
    );

    foreach (var enemy in enemiesToDamage) {
         enemy.GetComponent<Enemy>().TakeDamage(damage);
    }

    _lastAttackTime = Time.time;
}

```

As I mentioned before, comparing float timestamps is not good when you need millisecond precision, but for accepting/rejecting inputs, frame precision on the order of 10 ms is plenty, and floats are good enough for that, even when your game has been running for days.

# Answer
> 1 votes
Here is another approach, using a cooldown timer that gets decremented and reset in the `update` method.

For this to work, you must set `isPressedButton` whenever your player attack button is pressed and released.

// Input state
private bool isPressedButton;

// Button cooldown
[Tooltip("Minimum time between button inputs being processed (in seconds)")]
[SerializeField] private float buttonCooldownDuration = 0.4f;
private float buttonCooldownCurrent;

// Update method
void Update()
{
    // If pressed the button, and the cooldown is over
    if (isPressedButon && buttonCooldownCurrent <= 0)
    {
        // Perform the button action...

        // Reset the button cooldown
        buttonCooldownCurrent = buttonCooldownDuration;

        // Skip the rest
        return;
    }

     // Decrement the button cooldown
     buttonCooldownCurrent -= Time.deltaTime;

}
```

---
Tags: unity, c#, timer, combat, time
---


# Question
Title: Efficient Queries in an archetype-based Entity Component System
I am currently writing an archetype-based ECS for learning purposes. What I noticed is that my current implementation is incredibly slow with large amounts of archetypes.

Each of my queries iterates over ALL archetypes and uses a dynamic bitset to check if the archetype is eligible for the query or not. So there are unnecessary iterations every time a query is executed. This is slow because the bitsets are also different sizes to support "infinite components". The bitsets are too long to be fast and too small to get a speed up by vectorization.

```
// Pseudo code, In query iterator
foreach(var archetype : archetypes){

    unit[] queryBitSet = myQuery.BitSet;
    unit[] archetypeBitSet = archetype.BitSet;

    // Checking if query matches archetype
    var min = Math.min(queryBitSet.Length, archetypeBitSet.Length);
    for(var index = 0; index < min; index++){

        if(queryBitSet[index] & archetypeBitSet[index] != queryBitSet[index]){
           ...
        }
    }

    ... Process archetype if query matches
}

```

The bitsets are all quite small, have only a few `uint` items. Nevertheless, with a large mass of archetypes, the queries become incredibly slow. I can't think of any improvement.

Therefore, something else is needed: query caching. But how would this be implemented in an archetype-based ECS anyway? What would this look like in pseudo code? What else would you improve for ideal and performant archetype queries?

# Answer
As I sketched in a previous answer, the way I'd approach this would be to...

1. Register each needed query at system start-up (ie. once)
2. Store the cached query as an object containing a list of matching archetypes
3. Add matching archetypes to the query only at registration or when a new archetype is instantiated

That means that however expensive the matching might be, it does not occur every frame (or every system evaluation within a frame) - all that work happens at game boot or level load, or on the rare occasion where you need to spawn an object from a never-seen-before archetype.

All the high-frequency iteration happens over the cached list of matching archetypes, so there's no search/matching workload there.

```
public static class QueryManager {

    // I used a SortedSet here so you can get O(log n) lookups
    // and insertion, since your bit sets can be ordered
    // lexicographically for a binary search via Query.CompareTo()
    static SortedSet<Query> _queryCache = new();

    static List<Archetype> _archetypes = new();

    static Query _tempQuery;

    // When a new query is registered, cache all matching
    // archetypes known at that time and return the cached query.
    // Cached queries are shared/de-duplicated between multiple requests.
    public static Query RegisterQuery(ComponentSignature components) {

        _tempQuery.signature = components;
        if (!_queryCache.TryGetValue(_tempQuery, out Query cached)) {

            _tempQuery.matches = new List<Archetype>();
            foreach(var archetype in _archetypes) {
                if (_tempQuery.Matches(archetype)) {
                    _tempQuery.matches.Add(archetype);
                }
            }

            cached = _tempQuery;
            _queryCache.Add(cached);

            // Set aside a fresh temporary for the next attempt,
            // since our old one got promoted to a permanent cached version.
            _tempQuery = new Query();
        }
        return cached;
    }

    // When a new archetype is registered, add it to all
    // cached queries that match it.
    public static void RegisterArchetype(Archetype archetype) {
        _archetypes.Add(archetype);

        foreach(var query in _queryCache) {
            if (query.Matches(archetype)) {
                query.matches.Add(archetype);
            }
        }
    }
}

```

Your system might then look something like...

```
public class FallingSystem {

     Query _positionAndFallComponents;

     public void Initialize() {
         // Potentially expensive matching, done only when initializing:
         _positionAndFallComponents = QueryManager.RegisterQuery(
                                        new ComponentSignature(
                                           typeof(PositionComponent),
                                           typeof(FallComponent)
                                      ));
     }

     public void Update(float timeStep) {
         // Within a frame, we can iterate the query immediately,
         // without paying for any matching logic per use.
         foreach(var archetype in _positionAndFallComponents.matches) {
             var positions = archetype.GetComponents<PositionComponent>();
             var falls = archetype.GetComponents<FallComponent>();

             int count = archetype.EntityCount;
             for (int i = 0; i < count; i++) {
                 positions[i].y -= falls[i].speed * timeStep;
             }
         }
     }
}

```

(And the archetypes could be similar to the ones I sketch in this answer)
> 1 votes

---
Tags: c#, entity-component-system
---


# Question
Title: Why can't I access my custom signal under the SignalName subclass when trying to emit it?
I have recently decided to start learning Godot after previously having experience with Unity, and am continuing with C# as my primary scripting language. While everything else regarding signals seems to be working, I find myself struggling to emit custom signals, as they are not defined within the `SignalName` subclass as the Godot Documentation claims.

Complete script:

```
using Godot;
using System;

public partial class Icon : Sprite2D
{
    [Signal]
    public delegate void RotatingToggledEventHandler(bool isRotating);

    bool rotating = true;

    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
    }

    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Process(double delta)
    {
        if(rotating)
        {
            Rotate((float) delta);
        }
    }

    public override void _Input(InputEvent @event)
    {
        if(@event.IsActionPressed("ui_accept"))
        {
            rotating = !rotating;
        }
        StringName rotatingToggled = "RotatingToggled";
        EmitSignal(SignalName.RotatingToggled);
    }
}

```

`SignalName` subclass:

```
public class SignalName : Node2D.SignalName
{
      public static readonly StringName FrameChanged;
      public static readonly StringName TextureChanged;

      public SignalName();
}

```

The event which is to be triggered by the signal emit:

```
using Godot;
using System;

public partial class main : Node2D
{
    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Process(double delta)
    {
    }
    private void OnIconRotatingToggled(bool isRotating)
    {
        GD.Print("hello there");
        if(isRotating)
        {
            GetNode<Label>("RotatingStatus").Text = "Rotating: active";
        }
        else
        {
            GetNode<Label>("RotatingStatus").Text = "Rotating: inactive";
        }
    }
}

```

The receiver method is already linked to `main.cs`.

The error:

Error code is `CS0117`.

ADDITIONAL INFO: I am using VS code as my text editor, and have the C#, godot-tools, and C# tools for Godot extensions enabled, and am connected to the GDScript language server. All other facets of scripting seem to be working. For context, I am trying to reconstruct this tutorial in C# to teach myself Godot signals.

# Answer
What you need to emit a signal is an `StringName`. You should be able to confirm that by looking at the definition of `EmitSignal`.

An `StringName` is an internal string in Godot engine.

---

`SignalName`, on the other hand, is a convenient way to get the `StringName` you need to pass to reference the signal. And it should be generated automatically.

It is not relevant if the `StringName` comes from `SignalName` or not, what matter is if the `StringName` is correct. Consequently it is not necessary to subclass `SignalName`.

*Do not confuse `StringName` and `SignalName`.*

---

Thus, if the signal you want is not in `SignalName`, you can still use `EmitSignal`, like this:

```
EmitSignal("RotatingToggled");

```

*This is also the way you would use it if you added signal dynamically during execution (with `AddUserSignal`).*

Here, the `string` will be implicitly converted to an `StringName`. You could do that conversion yourself. You could also extract the value to a variable. And if you want to reuse it, perhaps promote said variable to a readonly field. And if you really want, move that field to another class - which you need to reference correctly - and said class could perhaps extend `SignalName` \- which is completely irrelevant - … None of that is necessary for this to work.
> 2 votes

---
Tags: c#, godot, godot-4
---


# Question
Title: Player double jumps immediately with a single press when using new Input System
I am making a 2.5D runner game and I want to switch my input from the legacy Input Manager to Unity's new Input System package.

I am facing a problem when I'm trying to implement the double jump when the player presses space twice. With the legacy Input Manager, there was `bool CanDoubleJump` which is true when the player is grounded, for double jump I was checking if `CanDoubleJump` is true and player pressed jump. It was working perfectly fine. Here's is the code.

using UnityEngine;

namespace EndlessRunning
{
    [CreateAssetMenu(fileName = "New Object", menuName = "ScriptableObject/Ability/DoubleJump")]
    public class DoubleJump : ScriptableObjectData
    {
        [SerializeField]
        private bool CanDoubleJump = true;

        public override void OnEnter(PlayerStateBase playerStateBase, Animator animator, AnimatorStateInfo stateInfo)
        {

        }
        public override void OnUpdate(PlayerStateBase playerStateBase, Animator animator, AnimatorStateInfo stateInfo)
        {

            //if (playerStateBase.characterControl.DoubleJump)
            //{
            //    animator.SetBool(HashManger.Instance.DicMainParameters[AnimatorParameters.DoubleJump], true);
            //    playerStateBase.characterControl.CanDoubleJump = false;
            //}

            if (playerStateBase.characterControl.Grounded)
            {
                CanDoubleJump = true;
            }
            else
            {
                if (CanDoubleJump && playerStateBase.characterControl.Jump)
                {
                    animator.SetBool(HashManger.Instance.DicMainParameters[AnimatorParameters.DoubleJump], true);
                    CanDoubleJump = false;
                }
            }
        }

        public override void OnExit(PlayerStateBase playerStateBase, Animator animator, AnimatorStateInfo stateInfo)
        {
        }
    }
}
``|

I tried to do the same thing with the new Input System, but it is not working: the character goes into double jump even if space is pressed only once. I am using Unity events for calling the function, and `CandoubleJump` is defined in character control, working the same way.

**Code**

```cs
using UnityEngine;
using UnityEngine.InputSystem;

namespace EndlessRunning
{
    public class PlayerInputController : MonoBehaviour
    {
        [SerializeField]
        private CharacterControl control;
        public PlayerInput inputComp;

        private void Awake()
        {

            inputComp = GetComponent<PlayerInput>();
            control = GetComponent<CharacterControl>();
        }

        private void Update()
        {
            //RunModInput() Legacy;
        }

        //input system new
        public void JumpMethod(InputAction.CallbackContext context)
        {
            if (context.performed)
            {
                if (!control.StartRun)
                {
                    control.StartRun = true;
                }
                else
                {
                    control.Jump = true;
                }

                if (control.CanDoubleJump && control.Jump)
                {
                    control.DoubleJump = true;
                    control.CanDoubleJump = false;
                }
            }
            else
            {
                control.Jump = false;
                control.DoubleJump = false;
            }
        }

        #region Run Mod Input legacy
        //private void RunModInput()
        //{
        //    if (InputManger.Instance.StartRun)
        //    {
        //        control.StartRun = true;
        //    }
        //    else
        //    {
        //        control.StartRun = false;
        //    }
        //    if (InputManger.Instance.Jump)
        //    {
        //        control.Jump = true;
        //    }
        //    else
        //    {
        //        control.Jump = false;
        //    }
        //    if (InputManger.Instance.Slide)
        //    {
        //        control.Slide = true;
        //    }
        //    else
        //    {
        //        control.Slide = false;
        //    }
        //    if (InputManger.Instance.Dash)
        //    {
        //        control.Dash = true;
        //    }
        //    else
        //    {
        //        control.Dash = false;
        //    }
        //}
        #endregion
    }
}
</code></pre>

# Answer
> 0 votes
**figured out the solution: updated code** i also had to check that the player must not be grounded for the double jump to work

```
  public void JumpInput(InputAction.CallbackContext context)
    {
        if (context.performed)
        {
            if (!control.StartRun)
            {
                control.StartRun = true;
            }
            else
            {
                control.Jump = true;

                if (!control.Grounded && control.CanDoubleJump && control.Jump)
                {
                    control.DoubleJump = true;
                    control.CanDoubleJump = false;
                }
            }

        }
        else
        {
            control.Jump = false;
            control.DoubleJump = false;
        }
    }

```

# Answer
> 2 votes
If `control.StartRun == false` and `control.CanDoubleJump == true` you are double-jumping right after jumping.

```
//...
            else
            {
                control.Jump = true;
            }

            if (control.CanDoubleJump && control.Jump)
            {
                control.DoubleJump = true;
                control.CanDoubleJump = false;
            }
//...

```

---
Tags: unity, c#, input, jumping
---


# Question
Title: What exactly does the XNA redistributable installer do?
I was wondering why I cannot just put all XNA dlls in the same directory as the game.exe, but I need to install that XNA redistributable?

if i try to run it i get an "assembly not found" error http://msdn.microsoft.com/en-us/library/shhcw6y9(v=vs.80).aspx even though that assembly (dll) is there in the same directory.

# Answer
Well installers often do many other things than just copying files. For example XNA redist tries to install/update DirectX on a user computer to required version. I guess it can also write some required information to registry.

However, even if you can just copy XNA files with your game, that, most certainly, will violate license terms.
> 9 votes

# Answer
When you have a redistributable, it usually is for not sending the end user the complete engine you used, as the end user only need some specific files. For XNA is the same.
> 1 votes

# Answer
You can examine the contents of any MSI installation package using tools like less msiérables or MSI Viewer.

It's also possible to query via a script and the MSI API but it's non-trivial (Docs).

Just be aware that *being able to see the contents doesn't give you any additional rights not already granted by the license*.
> 0 votes

---
Tags: xna
---


title: Wheel Colliders falling through ground

text:
# Question
Title: Wheel Colliders falling through ground
I have read through hours of forums and tried everything, But this issue still persists. I have attached a video showing the issue as well as all of my collider settings. Any help would be appreciated.

https://youtu.be/KiTAY2nXfOo

# Answer
As I saw, the weight of the tire seems disproportionate to the weight of the car. Try to lower the weight of the tires.

(While in play mode, showing the screen and selecting the entire car and showing rigidbody component may be more helpful to understand whether the tires are flying or not)
> 0 votes

---
Tags: unity, collider, meshcollider
---


title: How to overshoot with direction_to

text:
# Question
Title: How to overshoot with direction_to
I've managed to get my sprite enemies shoot at the player with

```
@export var bullet_speed  = 100

@onready var p = get_node("/root/main/player")
@onready var target_pos = p.global_position

func _physics_process(delta):
    var dir = self.global_position.direction_to(target_pos)
    global_position.x += (dir.x * bullet_speed) * delta
    global_position.y += (dir.y * bullet_speed) * delta

```

However, the projectiles will reach their destination and then stop. I'm not sure why. I thought I was get the angle between them and send them off in that direction (until they get to edge of the screen), rather than a location.

I need them to overshoot so the projectiles move beyond their original target. Do I need to do a bit of trig, calculate the opposite and adjacent, double it and then send them to *that* location?

# Answer
> 3 votes
In you code, you care computing the direction form the current position to the target every (physics) frame:

```
func _physics_process(delta):
    var dir = self.global_position.direction_to(target_pos)

```

*By the way, the direction is not an angle, it is a normalized vector.*

Since you are computing it every (physics) frame, if and when your object reaches the target it wouldn't have a direction to move.

---

To have the behavior you want, you should compute the direction once and keep using it.

For example:

```
@export var bullet_speed  = 100

@onready var p = get_node("/root/main/player")
@onready var dir = global_position.direction_to(p.global_position)

func _physics_process(delta):
    global_position.x += (dir.x * bullet_speed) * delta
    global_position.y += (dir.y * bullet_speed) * delta

```

*Alternatively, you could do it in `_ready` instead.*

No trigonometry involved. It is pretty much forgetting about the target, and just go in a direction.

---
Tags: trigonometry, godot-4
---


# Question
Title: Reading JSON nested objects with JsonUtility
I currently have a JSON file:

```
{
    "locations": [
        {
            "name": "Mars",
            "type": "mining",
            "metals": 500,
            "gas": 0
        },
        {
            "name": "Jupiter",
            "type": "gas",
            "metals": 0,
            "gas": 1000
        }
    ]
}

```

And a script that reads it:

```
public class JSONReader : MonoBehaviour
{
    public TextAsset textJSON;

    [Serializable]
    public class Location
    {
        public string name;
        public string type;
        public int metals;
        public int gas;
    }

    [Serializable]
    public class LocationArray
    {
        public Location[] locations;
    }

    public LocationArray mLocationArray = new LocationArray();
    public Location[] locationArray;

    void Start()
    {
        mLocationArray = JsonUtility.FromJson<LocationArray>(textJSON.text);
        locationArray = mLocationArray.locations;

        foreach (Location loc in locationArray)
        {
            Debug.Log(loc.name);
        }

```

I'm intending to modify the JSON file to add more locations and also nest the planets in star systems, however I'm not quite sure how to modify my script to accommodate the nesting. I've read that JSONUtility cannot output 2-dimensional arrays, however is that the only way that nested JSON data can be handled? Do I absolutely need to use a third-party library for this?

# Answer
> 1 votes
As @Evorlor mentioned in comments, you should using Newtonsoft Json (also known as Json.Net)

https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.2/manual/index.html

It's the go-to default everywhere C# is used, it's cross-platform, very flexible and incredibly lightweight.

Once you've got that installed, all you need to do is define an object that has the same structure as your Json.

So... If you hypothetically wanted to support this Json:

```
[
    {
        "name": "Sol",
        "type": "star",
        "metals": 0,
        "gas": 0,
        "locations": [
            {
                "name": "Mars",
                "type": "mining",
                "metals": 500,
                "gas": 0
            },
            {
                "name": "Jupiter",
                "type": "gas",
                "metals": 0,
                "gas": 1000,
                "locations": [
                    {
                        "name": "Europa",
                        "type": "moon",
                        "metals": 0,
                        "gas": 0
                    },
                }
            }
        ]
    },
    {
        "name": "Proxima Centauri",
        "type": "star",
        "metals": 0,
        "gas": 0,
        "locations": [
            {
                "name": "Proxima Centauri C",
                "type": "mining",
                "metals": 500,
                "gas": 0
            }
        ]
    }
]

```

You could use a class structure like this:

```
public class Location
{
    public string name { get; set; }
    public string type { get; set; }
    public int metals { get; set; }
    public int gas { get; set; }

    public List<Location> locations { get; set; }
}

```

And if your json is in a string `jsonConfig`...

```
using Newtonsoft.Json;
...
var rootLocationList = JsonConvert.DeserializeObject<List<Location>>(jsonConfig);

```

`rootLocationList` is now a `List<Location>`

If a given location has child locations, there will be a populated list at `locations`, otherwise `locations` will be `null`.

Any location can have sub-locations, so you have almost¹ as many levels of nesting as you wish.

Note that I've changed the root of your Json to a list of locations. If you want other properties *besides* a list of locations, create a root object with a `List<Location> locations` property and whatever other properties you need).

You can also map using different names in the Json, should you wish:

```
public class Location
{
    ...
    [JsonProperty("locations")]
    public List<Location> childLocations { get; set; }
}

```

Check out the other parameters on the JsonProperty attribute to get an idea of what's possible.

¹ There's a default limit of 64 levels deep, but it's configurable.

---
Tags: unity, json
---


# Question
Title: Front faces are transparent after setting glEnable(GL_DEPTH_FUNC) and glDepthTest(GL_LEQUAL)
I've been learning OpenGL over the past year or so, and I've never face this issue before, I've been refactoring the old version of my renderer to make it cleaner now that I'm more confident with OpenGL (or so I thought). I tried to render a simple cube to make sure I everything was working correctly in the new version. Even though the OpenGL initialization is identical to the old the cube renders incorrectly with the front faces see through. Like in this image:

Here is the old renderer I made from LearnOpenGL.com:

And here is the new OpenGL initialization function for the see through cube one:

```
gl_context = SDL_GL_CreateContext(window);
YE_CRITICAL_ASSERTION(gl_context != nullptr , "Failed to create OpenGL context");

int glad_init = gladLoadGLLoader(SDL_GL_GetProcAddress);
YE_CRITICAL_ASSERTION(glad_init != 0 , "Failed to initialize GLAD");

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClearDepth(1.f);

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA , GL_ONE_MINUS_SRC_ALPHA);

// glEnable(GL_MULTISAMPLE);

glFrontFace(GL_CCW);

glClearColor(config.clear_color.r , config.clear_color.g , config.clear_color.b , config.clear_color.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

if (config.vsync) SDL_GL_SetSwapInterval(kOpenGLSwapInterval);

```

And the render function:

```
glViewport(0 , 0 , size.x , size.y);
glClearColor(config.clear_color.r , config.clear_color.g , config.clear_color.b , config.clear_color.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
texture->Bind();
shader->Bind();
cube_vao->Draw(YE::DrawMode::TRIANGLES);
shader->Unbind();
glActiveTexture(GL_TEXTURE0);
texture->Unbind();
SDL_GL_SwapWindow(window);

```

And for reference the old ones as well:

Initialize:

```
int sdl_init = SDL_Init(SDL_INIT_EVERYTHING);
YE_ASSERT(sdl_init == 0 , "SDL2 failed to initialize");
if (sdl_init != 0) return false;

// SDL_SetRelativeMouseMode(SDL_TRUE);

config.flags |= SDL_WINDOW_OPENGL;

window = SDL_CreateWindow(config.title.c_str() , config.x , config.y , config.w , config.h , config.flags);
YE_ASSERT(window != nullptr , "SDL2 failed to create window");
if (window == nullptr) return false;

        window_size = { config.w , config.h };
        window_pos = { config.x , config.y };
        framebuffer_size = window_size;

        rendering_to_scrn = config.render_to_screen;
        clear_color = { config.r , config.g , config.b , config.a };

SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK , SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER , 1);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE , 8);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS , 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES , 24);

SDL_SetWindowMinimumSize(window , 200 , 200);

context = SDL_GL_CreateContext(window);
YE_ASSERT(context != nullptr , "SDL2 failed to create OpenGL context");
if (context == nullptr) return false;

if (config.vsync)
            SDL_GL_SetSwapInterval(1);

int glad_init = gladLoadGLLoader(SDL_GL_GetProcAddress);
YE_ASSERT(glad_init != 0 , "GLAD failed to initialize");
if (glad_init == 0) return false;

glEnable(GL_DEPTH_TEST);
glEnable(GL_LEQUAL);

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

glEnable(GL_MULTISAMPLE);

glClearColor(clear_color.r , clear_color.g , clear_color.b , clear_color.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

```

Draw:

```
glViewport(0 , 0 , static_cast<uint32_t>(window_size.x) , static_cast<uint32_t>(window_size.y));
glClearColor(clear_color.r , clear_color.g , clear_color.b , clear_color.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

// tons of shader calls for model and boxes and light and everything else
// ...

glActiveTexture(TEXTURE0);
cube_text->Bind();
cube_shader->Bind();
cube->Draw();
cube_shader->Unbind();
cube_text->Unbind();

SDL_GL_SwapWindow(window->GetWindow());

```

Also here are my glm calls for calculating the view/proj matrices:

New:

```
// not moving camera yet so no recalculating vectors
projection = glm::perspective(
    glm::radians(fov) ,
    static_cast<float>(win_size.x) / win_size.y ,
    clip.x , clip.y
);
view = glm::lookAt(position , position + front , up);

```

Old:

```
front.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
front.y = sin(glm::radians(pitch));
front.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
front = glm::normalize(front);

right = glm::normalize(glm::cross(front , world_up));
up = glm::normalize(glm::cross(right , front));

projection_matrix = glm::perspective(glm::radians(fov) , (16.f / 9.f) , clipping_near , clipping_far);
view_matrix = glm::lookAt(position , position + front , up);

```

also here are my shaders:

Vertex:

```
#version 460 core

layout (location = 0) in vec3 in_pos;
layout (location = 1) in vec3 in_color;
layout (location = 2) in vec2 in_texcoord;
layout (location = 3) in float in_opacity;

out vec3 frag_color;
out vec2 frag_texcoord;
out float frag_opacity;

uniform bool camera_active = false;

uniform mat4 model;
uniform mat4 proj;
uniform mat4 view;

void main() {
    gl_Position = model * vec4(in_pos , 1.0);
    if (camera_active) {
        gl_Position *= proj * view;
    }
    frag_color = in_color;
    frag_texcoord = in_texcoord;
}

```

Fragment:

```
#version 460 core

in vec3 frag_color;
in vec2 frag_texcoord;
in float frag_opacity;

out vec4 FragColor;

uniform vec3 view_pos;
uniform sampler2D tex0;
uniform sampler2D tex1;

void main() {
    FragColor = texture(tex0 , frag_texcoord);
}

```

I can not find what I'm doing wrong and would appreciate any help at all. As a note I have copied the cube vertex data from the old to the new so it is the same, and also the cube vertex data from learnOpenGL.com doesnt work either. The same problem occurs.

# Answer
> 2 votes
I was doing my matrix multiplications in the wrong order :/ its proj * view * model * vec4(pos , 1.0); for what I wanted.

---
Tags: opengl, rendering
---