# Question
Title: How to deal with large number of Navmesh Agents?
I have more than 200 units in a single scene, all of them use Unity's `NavmeshAgent` to set their destinations to the main target. The problem I'm facing is that some of the units stop moving when the number of units is large, and they only resume moving when the first few units are destroyed.

I have already tried:

1. Updating the destination only once every 20 frames:

```
if (Time.frameCount % 20 == 0)
{
    // ...
}

```
2. Using a coroutine:

```
private IEnumerator StaggerSetNewDestination(Vector3 position)
{
   myNavMeshAgent.SetDestination(position);
   yield return new WaitForSeconds(0.1f);
}

```

However, none of these solutions seem to work.

# Answer
> 1 votes
When you start talking about hundreds or thousands of agents, A\* pathfinding just doesn't cut it... Too many calculations per frame.

One common approach as mentioned by DMGregory is "flow fields"... For each target/destination, create a texture or 2D array and populate each cell with the path direction at that location.

Agents can then look up the value for their current location and head in the right direction.

Example: https://www.youtube.com/watch?v=zr6ObNVgytk

Steering behaviours and/or added randomness can help make the movement appear less regimented.

Another thing to bear in mind is that having a script on *n* objects means at least *n* function calls per frame.

Unity attempts to address this with an "Entity Component System" known as DOTS (Data-Oriented Technology Stack).

Fundamentally, the idea is that you have a set/group of things that need to navigate and a single method loops through them and handles the movement.

There's an ECS renderer that can render objects/meshes based on their position data in the set.

This means you don't need an actual game object, which significantly reduces overhead.

NB: ECS is **not** ready for production yet. There's a preview available that's pretty good and handles all the basics including physics, but advanced functionality that interacts with other systems (like animation controllers) was lacking the last time I checked in.

It may or may not suit your needs. There are also libraries on the asset store that achieve something similar.

---
Tags: unity, performance, path-finding, navmesh
---


# Question
Title: Semi transparent objects show fuzzy halos when in shadow
I'm having some issues when drawing a semi transparent object after an opaque object, and the object is in the shadows.

On the left, the torch is rendered just fine, I can see a nice blend of the border pixels with the wall behind it. On the right, I'm far away that the wall and torch are in shadows (I don't have ambient light) and as you can see, the border of the flame is rendered in the dark.

I guess I should specify that I'm writing my own engine.

Here is my WebGL enabled attributes and blend function:

```
gl.enable(gl.DEPTH_TEST);

gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );

gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0, 0, 0, 1);

```

I tried with different blendFunc parameters, but I always have one issue or another.

Here is my vertex shader

```

    attribute vec3 aPosition;
    attribute vec2 aTexcoord;
    attribute vec3 aNormal;

    uniform mat4 uTransform;
    uniform mat4 uProjection;
    uniform mat4 uWorldTransform;

    varying vec2 vTexcoord;
    varying vec3 vNormal;
    varying vec3 vWorldPosition;

    void main(void) {
      gl_Position = uProjection * uTransform * vec4(aPosition, 1.0);

      vTexcoord = aTexcoord;
      vNormal = (uWorldTransform * vec4(aNormal, 0.0)).xyz;
      vWorldPosition = (uWorldTransform * vec4(aPosition, 1.0)).xyz;
    }

```

And my fragment Shader

```
#define MAX_LIGHTS 8

    precision mediump float;

    struct Light {
      vec4 color;
      vec3 position;
      float radius;
    };

    uniform sampler2D uTexture;
    uniform vec4 uColor;
    uniform Light uLights[MAX_LIGHTS];

    varying vec2 vTexcoord;
    varying vec3 vNormal;
    varying vec3 vWorldPosition;

    void main(void) {
      vec4 color = texture2D(uTexture, vTexcoord) * uColor;
      if (color.a == 0.0) {
        discard;
      }

      vec4 reflectedLight = vec4(0, 0, 0, 1);
      for (int i=0;i<MAX_LIGHTS;i++) {
        vec3 distanceVector = uLights[i].position - vWorldPosition;
        vec3 lightDirection = normalize(distanceVector);
        float distance = distanceVector.x * distanceVector.x + distanceVector.y * distanceVector.y + distanceVector.z * distanceVector.z;

        float attenuation = clamp(1.0 - distance / (uLights[i].radius * uLights[i].radius), 0.0, 1.0);
        attenuation *= attenuation;

        reflectedLight += (max(dot(vNormal, lightDirection), 0.0) * uLights[i].color) * attenuation;
      }

      gl_FragColor = color * reflectedLight;
    }

```

I'm using only one light, the one from the player, with these parameters:

```
color: vec4(1, 1, 1, 1)
radius: 6
position: player.position

```

And finally, I'm uniforming the lights like:

```
scene.lights.forEach((light: LightPoint, index: number) => {
      this._gl.uniform3f(this._shader.uniforms[`uLights[${index}].position`], light.position.x, light.position.y, light.position.z);
      this._gl.uniform4f(this._shader.uniforms[`uLights[${index}].color`], light.color.r, light.color.g, light.color.b, light.color.a);
      this._gl.uniform1f(this._shader.uniforms[`uLights[${index}].radius`], light.radius);
    });

```

The light color, position, and radius work just fine. I think is an issue with the blending, but I'm not sure, I've been toying with the blendFunc and the shader but I haven't been able to fix this.

Thanks for your time.

# Answer
Found the issue. Apparently the alpha was being mixed with the background color of the html body (white in my case but I did try it with other colors as well). So the fix is to add this when getting the context:

`const gl = canvas.getContext('webgl', { alpha: false });`
> 1 votes

---
Tags: glsl, html5, webgl, alpha-blending
---


# Question
Title: Errors in Play Mode test setting Animator parameters
I've just started adding tests to my game project in Unity. I know the difference between EditMode and PlayMode tests. I've written a PlayMode test that triggers a change to the Animator internally, but this fails as the parameter in the Animator doesn't seem to be changing. I also get the warning `Animator is not playing an AnimatorController` everytime I call `GetFloat` or `SetFloat`, which I suspect is an indicator of my issue.

**Script under test**

```
public class ChangeDirection : MonoBehaviour
{
    public Animator animator;

    public void SetDirection(Direction direction)
    {
        var directionVector = new Vector2(0f, 0f);

        switch (direction)
        {
            case Direction.Up:
                directionVector = Vector2.up;
                break;

            case Direction.Down:
                directionVector = Vector2.down;
                break;

            case Direction.Left:
                directionVector = Vector2.left;
                break;

            case Direction.Right:
                directionVector = Vector2.right;
                break;
        }

        animator.SetFloat("Horizontal", directionVector.x);
        animator.SetFloat("Vertical", directionVector.y);
    }
}

```

**PlayMode test**

```
public class ChangeDirectionTests
{
    [UnityTest]
    public IEnumerator SetDirection_DirectionUp_VerticalChanged()
    {
        var gameObject = new GameObject();
        var animator = gameObject.AddComponent<Animator>();

        animator.SetFloat("Horizontal", 0f);
        animator.SetFloat("Vertical", 0f);

        var changeDirection = new ChangeDirection();
        changeDirection.animator = animator;
        changeDirection.SetDirection(Direction.Up);

        Assert.AreEqual(0f, animator.GetFloat("Horizontal"));
        Assert.AreEqual(1f, animator.GetFloat("Vertical"));
    }
}

```

**Test output**

```
SetDirection_DirectionUp_VerticalChanged (0.017s)
---
Expected: 1.0f
  But was:  0.0f
---
at ChangeDirectionTests.SetDirection_DirectionUp_VerticalChanged () [0x00063] in /home/samuelslade/source/games/pokemon-world/Assets/Tests/EditMode/ChangeDirectionTests.cs:22
---
Animator is not playing an AnimatorController
Animator is not playing an AnimatorController
You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed.  MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
Animator is not playing an AnimatorController
Animator is not playing an AnimatorController
Animator is not playing an AnimatorController
Animator is not playing an AnimatorController

```

The warning around using the `new` keyword to create a `MonoBehaviour` has this further detail:

```
You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed.  MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor ()
ChangeDirection:.ctor ()
ChangeDirectionTests/<SetDirection_DirectionUp_VerticalChanged>d__0:MoveNext () (at Assets/Tests/PlayMode/ChangeDirectionTests.cs:17)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)

```

I'm clearly misunderstanding how this works, so any direction to help me understand how best to approach writing tests in Unity would be appreciated.

# Answer
Two mistakes here:

1. `AddComponent<T>()` adds a new component in its *default* state. That means the `Animator` you create this way has its `runtimeAnimatorController` property in the default state of `null` \- you didn't tell it *which* Animator Controller Graph it should be using. Not every such graph has parameters named "Horizontal" and "Vertical", so before you try to write or read such parameters, you need to provide a graph that has them.
2. As your error message tells you, it is not valid to create a free-floating `MonoBehaviour` in user code via `new`. Scripts deriving from `Component` must be attached to a `GameObject`. It looks like what you meant to write was something more like...

```
var changeDirection = gameObject.AddComponent<ChangeDirection>();
changeDirection.animator = animator;
changeDirection.SetDirection(Direction.Up);

```

This creates the new `MonoBehaviour` instance and attaches it to the parent `GameObject` in one operation, letting the engine wire up everything needed behind the scenes to make the component work.

I think both of these issues would be easier to solve if you made a prefab object that has the animator and control script you want to test already set up (with the appropriate animator controller assigned and the `ChangeDirection` script attached). Then your test script can load that asset and instantiate a copy of it to test.
> 1 votes

---
Tags: unity, c#, unit-testing
---


title: error creating a c++ project in unreal

text:
# Question
Title: error creating a c++ project in unreal
I was working on some test project since I'm beginner in unreal engine, and I suddenly started getting this:

```
The project could not be compiled. Would you like to open it in Rider?

Running C:/Program Files/Epic Games/UE_5.1/Engine/Build/BatchFiles/Build.bat Development Win64 -Project="D:/rough/UnrealEngine/MyGame/MyGame/MyGame.uproject" -TargetType=Editor -Progress -NoEngineChanges -NoHotReloadFromIDE
Running UnrealBuildTool: dotnet "..\..\Engine\Binaries\DotNET\UnrealBuildTool\UnrealBuildTool.dll" Development Win64 -Project="D:/rough/UnrealEngine/MyGame/MyGame/MyGame.uproject" -TargetType=Editor -Progress -NoEngineChanges -NoHotReloadFromIDE
Log file: C:\Users\baga\AppData\Local\UnrealBuildTool\Log.txt
Creating makefile for MyGameEditor (no existing makefile)
Expecting to find a type to be declared in a module rules named 'RD' in UE5Rules, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null.  This type must derive from the 'ModuleRules' type defined by Unreal Build Tool.

```

I've done what I could, including reinstalled visual studio and its dependencies, reinstalled unreal engine itself, but this doesn't go away. It always pops this error when i create a blank/non-blank c++ project in unreal engine.

When I compile the solution from visual studio, I get these error:

```
Microsoft.MakeFile.targets(44, 5): [MSB3073] The command ""C:\Program Files\Epic Games\UE_5.1\Engine\Build\BatchFiles\Build.bat" MyGameEditor Win64 Development -Project="D:\rough\UnrealEngine\MyGame\MyGame\MyGame.uproject" -WaitMutex -FromMsBuild" exited with code 6.

```

Not sure what is causing the issue, but, I'm literally not being able to start anything. Any insight would be really helpful. Thanks in advance.

# Answer
The bug definitely seems to be from the Rider link plugin. However, many posts suggested uninstall it, but, in my case, I had only uninstalled it from the plugin menu in UE. That somehow didn't work. So, I manually deleted the `RiderLink` and `RiderCodeAccess` folder from the unreal engine installation folder,typically under `C:\...\Epic Games\....\Plugins\Developer`.

However, after you do this, UE doesn't list rider as your source code editor. In that case, completely reinstall the rider link from unreal engine, or, after you open the solution file from rider, it gives you option to install rider link. But, you'd also require the `RiderSourceCodeAccess` folder. I suggest you directly follow the instruction from github, and install it in project:

```
- Get the source code of the main branch;
- Unzip RiderSourceCodeAccess.zip to RiderSourceCodeAccess folder;
- Copy RiderSourceCodeAccess folder to {GameProjectRoot}/Plugins/Developer; a. If {GameProjectRoot}/Plugins/Developer does not exist, create it;
(For Windows and .sln project model only) Re-generate solution files - uproject file > context menu > Generate Visual Studio project files;
- Build UE project using Rider (or any other IDE that you've setup for your OS);
- Start Unreal Editor;
- Edit > Editor Preferences ... > General > Source Code > Source Code Editor;
- Select Rider from drop down list. NB: only Rider with C++ plugins will be available from drop down list.

```
> 1 votes

# Answer
This is happens when you have Unreal open and you try to compile from Rider (or Visual Studio). In order to compile from Rider (or Visual Studio) you need to first close unreal.
> 0 votes

---
Tags: windows, unreal-5
---


# Question
Title: Moving Camera2D along with custom KinematicBody2D causes both to stop
I want to design a rigid body that moves up at a constant speed and can only be moved left and right manually. When I set the `Camera2D` to go vertically with the rigid body (current on), in the test mode, the rigid body moves a little and stops. (Both camera and rigid body stop).

What's wrong with this script?

```
extends KinematicBody2D

var number = 0
var player_velocity = Vector2(0,0)
var player_speed = 210

func _physics_process(delta):
    if Input.is_action_pressed("ui_right"):
        player_velocity.x = player_speed

    if Input.is_action_pressed("ui_left"):
        player_velocity.x = -player_speed

    player_velocity.y = player_velocity.y + 30
    player_velocity = move_and_slide(player_velocity)
    player_velocity.x = lerp(player_velocity.x, 0, 0.1)

```

# Answer
> 0 votes
I'll point out that there is a `RigidBody2D`, and you are using a `KinematicBody2D`. I'll assume that when you say "rigid body" you mean `KinematicBody2D`.

---

## The `Camera2D` issue

I don't know how you have setup your `Camera2D`, but I'll presume that it is a child of the `KinematicBody2D` or otherwise it is following it.

I need to point out that if the object is moving and the camera is moving with it, it will appear static on the screen. So if you don't have something else in the scene that allows you tell that it is moving, you might believe it is not.

In fact, I believe that what you describe as "moves a little and stops" is the `Camera2D` catching up to the `KinematicBody2D`. *Or was it a `RigidBody2D`? Same difference, it is catching up to whatever it is following.*

---
Tags: camera, godot
---


title: Unreal 5 Actor Can't Move

text:
# Question
Title: Unreal 5 Actor Can't Move
I have an Unreal 5 actor with some basic blueprints involving a "Simple Move to Location".

I've created a NavMeshBoundsVolume, and both the actor and destination point are inside it. The actor's mesh isn't inside any other mesh, except for the nav volume.

Yet, when I run the game, the enemy doesn't move.

# Answer
> 0 votes
1 - The "Controller" slot in the Move can't be empty, which isn't intuitively clear. I used a Get Controller node and set the target to Self.

2 - Completely separate from the node graph, there's this idea of "Components" in the blueprint, which is new to me. My pawn needed a FloatingPawnMovement component, which I added via the left panel.

3 - From the output log, `DefaultSceneRoot has to be 'Movable' if you'd like to move it with FloatingPawnMovement.` I was able to change that in the main outliner.

DefaultSceneRoot → Transform → Mobility → Movable

Those three changes together fixed the issue.

---
Tags: movement, ai, unreal, unreal-5
---


# Question
Title: How to get better performance with pygame?
I'm not a gamedev, I'm a API/Cloud dev, performance has never been an issue for me since most of the time we are limited by network calls.

I've been playing with that for the past 2 days, I wanted to make particles that follow each others but to my surprise, even with a R9 5950x, I can't simulate more than 60 particles

After that it behaves weirdly, a lot less particles are showed, or the screen just becomes black.

I think the most "cpu hungry" thing is sensing where the closest particle is. For that each "agent" need to iterate over every other agent and check if the position of that agent is in its field of view (a triangle attached to the "head" of the agent)

mains.py :

```
import pygame
import time
import math
import random

import numpy as np

from drawer import draw_polygon_alpha
from models import Point, Color, DirectionVector2C, Vector2D, Triangle

width, height = 800, 600

class CarLikeAgent:
    """
    Car like : direction is always going forward, so when the rotation is changed the direction vector need to be recomputed
    initialize it with direction vector going to the top of the window (up) then apply initial rotation
    """

    def __init__(self, id, position: Point, rotation: float, velocity: float, mass: float, color: Color):

        self.id = id

        initial_direction_vector: DirectionVector2C = DirectionVector2C(0, -1) # going up
        initial_direction_vector.rotate(rotation)
        self.direction_vector: DirectionVector2C = initial_direction_vector

        self.position: Point = position
        # should I make velocity a vector that has different values for x and y ?
        self.velocity: float = velocity
        self.mass: float = mass
        self.color: Color = color
        self.rotation: float = rotation
        self.remaining_turn_angle: float = 0
        self.max_angle_per_frame: float = 1/self.velocity
        self.max_angle_per_frame: float = 5
        # second point is the summit, or point that is attached to the head
        self.field_of_view_triangle = None
        self._head_location = None
        self._body_radius = 3
        self._head_radius = 3
        self._last_positions = []
        self._display_fov = False

    def draw_yourself(self, screen):
        # drwaing the trail
        current_color = np.array(self.color.get_tuple())
        current_radius = radius=self._body_radius
        for nparray_point in reversed(self._last_positions):
            current_color = current_color / 1.1
            current_radius = current_radius/1.05
            pygame.draw.circle(surface=screen, color=current_color, center=nparray_point, radius=current_radius, width=5)

        # drawing the agent
        pygame.draw.circle(surface=screen, color=self.color.get_tuple(), center=self.position.get_tuple(), radius=self._body_radius, width=5)
        #pygame.draw.circle(surface=screen, color=self.color.get_tuple(), center=self._head_location.get_tuple(), radius=self._head_radius, width=3)
        if self._display_fov:
            draw_polygon_alpha(screen, (0, 0, 255, 80), self.field_of_view_triangle.get_tuple())

    def update_fov(self):
        """
        Make a triangle that groe from the "head" and then follow the direction vector, it "sees" what is inside the triangle
        """

        fov_distance = 300
        fov_wideness = 500

        a = np.array(self._head_location.get_tuple())  # "summit" of the triangle, point attached to the "head"
        b = np.array(self._head_location.get_tuple()) + (-fov_wideness / 2, fov_distance)
        c = np.array(self._head_location.get_tuple()) + (fov_wideness / 2, fov_distance)

        pivot = a
        triangle = (a, b, c)
        angle_degrees = self.rotation + 180 # why 180? i don't know
        angle_radians = math.radians(angle_degrees)
        rotation_matrix = [
            [math.cos(angle_radians), -math.sin(angle_radians)],
            [math.sin(angle_radians), math.cos(angle_radians)]
        ]
        # Translate the triangle so that the pivot point is at the origin
        translated_triangle = [(vertex[0] - pivot[0], vertex[1] - pivot[1]) for vertex in triangle]

        # Rotate the translated triangle using the rotation matrix
        rotated_triangle = [(rotation_matrix[0][0] * vertex[0] + rotation_matrix[0][1] * vertex[1],
                             rotation_matrix[1][0] * vertex[0] + rotation_matrix[1][1] * vertex[1])
                            for vertex in translated_triangle]

        # Translate the rotated triangle back to its original position
        final_triangle = [(vertex[0] + pivot[0], vertex[1] + pivot[1]) for vertex in rotated_triangle]
        self.field_of_view_triangle = Triangle(
            Point(final_triangle[0][0], final_triangle[0][1]),
            Point(final_triangle[1][0], final_triangle[1][1]),
            Point(final_triangle[2][0], final_triangle[2][1]),
        )

    def _add_position_to_last_positions_history(self, current_position: np.ndarray):
        if len(self._last_positions) > 15:
            self._last_positions = self._last_positions[1:]
        self._last_positions.append(current_position)

    def update_position(self, velocity_coefficient):

        def compute_point_on_circle_coords(center, radius, angle_degrees):
            angle_radians = math.radians(angle_degrees)
            x = center.x + radius * math.cos(angle_radians)
            y = center.y + radius * math.sin(angle_radians)
            return Vector2D(x, y)

        new_x = (self.position.x + self.direction_vector.x*(self.velocity * velocity_coefficient))

        if new_x > width:
            new_x = new_x - width
        if new_x < 0:
            new_x = new_x + width

        new_y = (self.position.y + self.direction_vector.y*(self.velocity * velocity_coefficient))

        if new_y > height:
            new_y = new_y - height
        if new_y < 0:
            new_y = new_y + height

        magic = 270
        self._head_location = compute_point_on_circle_coords(self.position, self._body_radius, self.rotation + magic)
        self.position = Point(new_x, new_y)
        self._add_position_to_last_positions_history(np.array([new_x, new_y]))

    def update_rotation(self, wanted_angle_in_degree):
        if wanted_angle_in_degree > 360 or wanted_angle_in_degree < -360:
            raise ValueError("Are you serious?")

        # we turn the amount we couldn't turn last frame due to the mass of the agent
        if wanted_angle_in_degree == 0 and self.remaining_turn_angle is not None:
            wanted_angle_in_degree = self.remaining_turn_angle

        if wanted_angle_in_degree < 0:
            sign = -1
        else:
            sign = 1

        turn_angle = 0
        if abs(wanted_angle_in_degree) > self.max_angle_per_frame:
            turn_angle = self.max_angle_per_frame * sign
            self.remaining_turn_angle = (abs(wanted_angle_in_degree) - self.max_angle_per_frame) * sign
        else:
            turn_angle = wanted_angle_in_degree

        self.direction_vector.rotate(turn_angle)
        self.rotation = self.rotation + turn_angle

        if self.rotation > 360:
            self.rotation = self.rotation - 360
        elif self.rotation < -360:
            self.rotation = self.rotation + 360

    def compute_distance_with_point(self, point: Point):
        point1 = self.position.get_tuple()
        point2 = point.get_tuple()
        return math.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2)

    def update_remaining_angle_for_closest_visible_agent(self, agents):
        selected_agent = None
        shortest_distance = 999999999999999
        for other_agent in agents:
            if other_agent == self:
                continue

            if self.field_of_view_triangle.is_point_inside(other_agent.position):
                distance = self.compute_distance_with_point(other_agent.position)
                if distance < shortest_distance:
                    shortest_distance = distance
                    selected_agent = other_agent

        if selected_agent is None:
            return

        dx = self.direction_vector.x
        dy = self.direction_vector.y
        # to compute that wee need to translate the absolute coordinate in coordinate with a new center, the base of the direction vector
        x = selected_agent.position.x - self.position.x
        y = selected_agent.position.y - self.position.y
        angle_deg = math.degrees(math.atan2(y, x) - math.atan2(dy, dx))
        self.remaining_turn_angle = angle_deg

def build_agents(width, height):
    agents = []
    for x in range(60):
        agents.append(
            CarLikeAgent(
                id=str(x).zfill(5),
                position=Point(random.randint(1, width), random.randint(0, height)),
                velocity=3,
                rotation=random.randint(0, 359),
                mass=1.0,
                color=Color(255, 0, 0)
            )
        )
    return agents

def clear_screen(screen):
    screen.fill((0,0,0))

pygame.init()

agents = build_agents(width, height)
framerate = 60
time_in_a_frame = 1/framerate
one_percent_of_time_in_a_frame = time_in_a_frame/100
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
crashed = False
previous_time = time.time()
while not crashed:
    # limit fps to 60
    clock.tick(framerate)
    print("iteration")

    # compute velocity coefficient to mitigate fps variation
    now = time.time()
    dt = now - previous_time
    velocity_coefficient = (dt/one_percent_of_time_in_a_frame)/100
    previous_time = now

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

    clear_screen(screen)

    for agent in agents:
        agent.update_position(velocity_coefficient)
        agent.update_rotation(0)
        agent.update_fov()
        agent.draw_yourself(screen)

    # second loop because every agent position needs to be updated before doing that
    for agent in agents:
        agent.update_remaining_angle_for_closest_visible_agent(agents)

    pygame.display.flip()

```

models.py :

```
from geometry import rotate_2d_vector, is_point_inside_triangle

class Color():
    def __init__(self, r: int, g: int, b: int):
        self.r: int = r
        self.g: int = g
        self.b: int = b

    def get_tuple(self):
        return self.r, self.g, self.b

class Vector2D:

    def __init__(self, x: float, y: float):
        self.x: float = x
        self.y: float = y

    def get_tuple(self):
        return self.x, self.y

    def rotate(self, angle_degrees):
        self.x, self.y = rotate_2d_vector(self.x, self.y, angle_degrees)

class DirectionVector2C(Vector2D):

    def __init__(self, x: int, y: int):
        if x < -1 or x > 1:
            raise ValueError("dirention vector can only be -1, 0 or 1 for any given direction")
        if y < -1 or y > 1:
            raise ValueError("dirention vector can only be -1, 0 or 1 for any given direction")
        super().__init__(x, y)

class Point:

    def __init__(self, x: int, y: int):
        self.x: int = x
        self.y: int = y

    def get_tuple(self):
        return self.x, self.y

class Triangle:

    def __init__(self, a: Point, b: Point, c: Point):
        self.a: Point = a
        self.b: Point = b
        self.c: Point = c

    def get_tuple(self):
        return (self.a.x, self.a.y), (self.b.x, self.b.y), (self.c.x, self.c.y)

    def is_point_inside(self, point: Point):
        return is_point_inside_triangle(self.get_tuple(), point.get_tuple())

```

geometry.py :

```
import math

def rotate_2d_vector(x, y, angle_degrees):
        angle_radians = math.radians(angle_degrees)
        new_x = x * math.cos(angle_radians) - y * math.sin(angle_radians)
        new_y = x * math.sin(angle_radians) + y * math.cos(angle_radians)
        return new_x, new_y

def is_point_inside_triangle(triangle_coords, point_coord):
        a, b, c = triangle_coords

        x1, y1 = a[0], a[1]
        x2, y2 = b[0], b[1]
        x3, y3 = c[0], c[1]

        x, y = point_coord

        # Calculate the area of the triangle
        A = 0.5 * (-y2 * x3 + y1 * (-x2 + x3) + x1 * (y2 - y3) + x2 * y3)

        # Calculate the barycentric coordinates of the point
        s = 1 / (2 * A) * (y1 * x3 - x1 * y3 + (y3 - y1) * x + (x1 - x3) * y)
        t = 1 / (2 * A) * (x1 * y2 - y1 * x2 + (y1 - y2) * x + (x2 - x1) * y)

        return s > 0 and t > 0 and 1 - s - t > 0

```

drawer.py :

```
import pygame

def draw_rect_alpha(surface, color, rect):
    shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA)
    pygame.draw.rect(shape_surf, color, shape_surf.get_rect())
    surface.blit(shape_surf, rect)

def draw_circle_alpha(surface, color, center, radius):
    target_rect = pygame.Rect(center, (0, 0)).inflate((radius * 2, radius * 2))
    shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA)
    pygame.draw.circle(shape_surf, color, (radius, radius), radius)
    surface.blit(shape_surf, target_rect)

def draw_polygon_alpha(surface, color, points):
    lx, ly = zip(*points)
    min_x, min_y, max_x, max_y = min(lx), min(ly), max(lx), max(ly)
    target_rect = pygame.Rect(min_x, min_y, max_x - min_x, max_y - min_y)
    shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA)
    pygame.draw.polygon(shape_surf, color, [(x - min_x, y - min_y) for x, y in points])
    surface.blit(shape_surf, target_rect)

```

Would writing it in C++ would solve the problem? or is there some gamedev design pattern that can be used to make it more efficient? at the end of main.py you can see the main logic

I saw the direction\_vector/velocity/dt for independant framerate in a basic tutorial video but the rest is all me (except the math, it's for google searches). What I mean is that I coded it as I code API stuff.

Thanks.

# Answer
> 1 votes
I don't know about "black magic", but there are definitely some obvious optimizations available here. Which ones will pay off most in your case depends on what your profiling says is consuming the most time.

**Spatial partition:** don't check every agent against every other agent. Divide your space into bins, and check agents in nearby bins. This takes you from \\$O(n^2)\\$ where \\$n\\$ is the total number of agents to \\$O(n \times m)\\$ where \\$m\\$ is the number of agents per bin.

**Don't check each pair twice:** if you want to find all pairs of nearby agents AB, you don't also need to find pairs BA.

Check each agent only against those that came before it in iteration order. If you're iterating your bins left-to-right, top-to-bottom, then you check for agents in bins above and to the left (knowing bins below and to the right will handle checking this agent later on).

This roughly halves your work, but since it's just a constant factor, it doesn't change the big-O.

**Batching:** GPUs are great at rendering large sets of similar content all at once. When you send drawing instructions one at a time, inter-mixing different types of content, you force them to use only a tiny fraction of the available silicon.

Instead of asking each agent to draw itself, interleaving its dot trails and triangle field of view, try writing all the dot positions/sizes and all the triangle positions/orientations to a buffer, then drawing those buffers in a single pass each.

**Avoid allocations in a hot loop:** creating and reversing lists requires memory allocation, which is slow. Instead, consider re-using a scratch buffer where the language constructs allow.

**Avoid unnecessary math:** trigonometric and square root functions are relatively expensive, and you don't need them in most of this code. Your forward direction vector already contains the cosine and sine of your rotation angle, so you can use its components instead of calling trig functions and building a rotation matrix.

Most games will implement an FoV check as a wedge rather than a triangle, which lets you check whether a point is in view with just a length check and dot product - cheaper than a full point-in-triangle test (and it avoids the weirdness of agents being less sensitive/having shorter vision range dead-ahead than in the periphery).

---
Tags: performance, python, pygame
---


# Question
Title: How to briefly turn an entire sprite another color in Unity?
Let's say there's a simple Sprite, like this Umbrella:

I'd like to briefly turn the entire Sprite a different color (say, red), as a visual error message in my game.

Of course if I just change the Color of the Umbrella's Sprite Renderer to Red, then the Sprite color changes to a Purplish/Black.

I'd like to have the Sprite color turn the entire Sprite a precise shade of the Red that I input.

Obviously I could easily do this by creating red versions of all of my sprites, then temporarily swapping out the sprite. But I'd rather avoid that if possible, as I have 60+ sprites.

After researching this, it seems like the solution might be shaders. Is there a simple shader I could use to achieve this, that doesn't put a heavy load on CPU? I'm looking to deploy my game to mobile devices, so I'm hoping for a mobile-friendly solution. If there isn't a simple shader, then I'll just use the "create a plain red version of every sprite" approach since I know that's computationally cheap.

# Answer
> 2 votes
**Step 1:** Go to the Unity Download Archive and navigate to the version you're using. Hit the drop-down and download the built-in shaders for that version.

**Step 2:** Make a copy of the default sprite shader found under `DefaultResourcesExtra/Sprites-Default.shader` in that download.

**Step 3:** Modify the shader like so - first give it a customized name at the top:

```
Shader "Sprites/ColorLerp"
{

```

Then replace the fragment shader function with a custom one:

```
    Pass
    {
    CGPROGRAM
        #pragma vertex SpriteVert
        #pragma fragment ColorLerpFrag // Use our version instead of the default.
        #pragma target 2.0
        #pragma multi_compile_instancing
        #pragma multi_compile_local _ PIXELSNAP_ON
        #pragma multi_compile _ ETC1_EXTERNAL_ALPHA
        #include "UnitySprites.cginc"

        fixed4 ColorLerpFrag(v2f IN) : SV_Target
        {
            // Sample sprite texture.
            fixed4 c = SampleSpriteTexture (IN.texcoord);
            // Blend toward sprite component color depending on its alpha.
            c.rgb = lerp(IN.color.rgb, c.rgb, IN.color.a);
            // Pre-multiply alpha to work with the blending function.
            c.rgb *= c.a;
            return c;
        }
    ENDCG
    }

```

This replaces the normal multiplicative tint behaviour with one where the sprite texture blends to a solid colour based on the colour swatch you set in the `SpriteRenderer` component. When that swatch has 100% alpha, you see the normal sprite texture unmodified. At 0% alpha, you see the swatch colour, regardless of what's in the texture (but the texture's alpha is still used to control the opacity and keep the shape's silhouette).

Slap this on a material, and use this material on sprites that need this effect. When you want a sprite to change to a red colour, set `spriteRenderer.color = new Color(1, 0, 0, 0);`, then when you want to change it back, `spriteRenderer.color = Color.white;`

In terms of cost, this adds one scalar addition and one vector fused multiply-add to the default shader - nothing significant, so you probably won't notice any difference in throughput.

---
Tags: shaders
---


# Question
Title: How to open-source both game code and assets?
I want something permissive which will allow to earn from derived works but will require to mention base (my) work. I know about BSD and MIT which is golden classic for software. And I know about CC-BY which is feels like my case for work of arts. Like sprites or sounds. But what to use for case when you git repository have both software and assets? Can I be good with one option? Or should I mix them somehow?

Oh. It runs on Monogame if this is important.

# Answer
> 1 votes
You are correct in that CC is more suited to work of arts whereas software licenses or better suited for code. For that reason, I recommend using both.

As this answer on the Open Source SE, it's both possible and common to use separate licenses for those two aspects of your project.

It's slightly more complicated as you need to select more than one license and should probably delineate what is and is not covered by each. However, it gives you more flexibility and allows you to play to the strengths of each license with respect to the material of interest.

# Answer
> 0 votes
*I am not a lawyer*. You should seek legal advice elsewhere, but Microsoft uses the MIT license for both software and assets in many cases for samples.

The larger issue is probably if you have the rights to release these things yourself (i.e. you are the sole copyright owner for all files involved).

---
Tags: licensing, open-source
---


# Question
Title: Get and change hold durations of an InputActionAsset's bindings through script
I have an input action in my project that is performed after being held for a length of time. By default it begins after 0.2 seconds, but I'm trying to add a slider to increase or decrease it in my options menu.

In other words, I want to get the float value of "Hold Time" for the Hold interaction of an `InputAction`. I could create the input action within a script and create its interactions there, but it's much easier to use the input actions editor in the engine to create the actions and access them in a script.

How do I take an `InputAction` created in the editor and get/modify its Hold Time float value?

# Answer
> 0 votes
You can get or even modify the `HoldInteraction.duration` using the `InputAction.CallbackContext`, like this:

```
void OnEnable() {
  _holdAction.started += OnHoldActionStarted;
  _holdAction.canceled += OnHoldActionCanceled;
}

void OnDisable() {
  _holdAction.started -= OnHoldActionStarted;
  _holdAction.canceled -= OnHoldActionCanceled;
}

protected void OnHoldActionStarted(InputAction.CallbackContext context) {
  var holdInteraction = context.interaction as HoldInteraction;
  holdInteraction.duration = 2f;
}

// ... restore the original hold time

```

# Answer
> 0 votes
The disadvantage of Charlie's answer is that you have to wait until the action has been performed to change the value - so you'd need to set the slider value to the hold duration you want, cache that value somewhere, then wait until the next time the control is held and inject the cached value there.

Unfortunately the input binding API is all string-based, but nothing a little regex can't tackle:

```
static readonly Regex HoldDurationFinder = new Regex(@"Hold(\([^\)]*?(duration=(\d+\.?\d*))?[^\)]*\))?", RegexOptions.Compiled);

public static bool TryGetHoldDuration(InputBinding binding, out float duration) {
    var interactions = binding.effectiveInteractions;

    var match = HoldDurationFinder.Match(interactions);

    if (!match.Success) {
        duration = -1;
        return false;
    }

    if (match.Groups[3].Success) {
        duration = float.Parse(match.Groups[3].Value);
    } else {
        duration = InputSystem.settings.defaultHoldTime;
    }

    return true;
}

public static string ModifyHoldDurationString(InputBinding binding, float duration, bool add = false) {
    var interactions = binding.effectiveInteractions;

    var match = HoldDurationFinder.Match(interactions);

    // Hold interaction with specified duration - change the duration value.
    if (match.Groups[3].Success) {
        var group = match.Groups[3];
        return $"{interactions.Substring(0, group.Index)}{duration}{interactions.Substring(group.Index + group.Length)}";
    }

    // Hold interaction with other parameters - insert duration at the front of the list.
    if (match.Groups[1].Success) {
        var group = match.Groups[1];
        return $"{interactions.Substring(0, group.Index)}(duration={duration},{interactions.Substring(group.Index + 1)}";
    }

    // Hold interaction with no parameters - replace with parametrized version.
    if (match.Success) {
        var group = match.Groups[0];
        return $"{interactions.Substring(0, group.Index)}Hold(duration={duration}){interactions.Substring(group.Index + group.Length)}";
    }

    if (!add) return null;
    // No hold interaction - add one.
    string addition = $"Hold(duration={duration})";
    if (string.IsNullOrWhiteSpace(interactions))
        return addition;
    return $"{addition},{interactions}";
}

public static void ChangeAllHoldDurations(InputAction action, float duration) {
    var bindings = action.bindings;
    for (int i = 0; i < bindings.Count; i++) {
        var binding = bindings[i];
        var newInteractions = ModifyHoldDurationString(binding, duration);

        if (newInteractions != null) {
            binding.overrideInteractions = newInteractions;
            action.ApplyBindingOverride(i, binding);
        }
    }
}

```

This lets you fetch and manipulate the hold duration from the input action directly, even when the action is not being performed.

By using `overrideInteractions`, these modifications persist only in play mode, and the asset's configuration will revert to what you set up in the editor when you exit play mode - ensuring that changes you make in testing don't "leak" into the game's default settings.

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


# Question
Title: How do I create a button with a font by code?
I have written a code that would create background image as a button and then show a letter on that button. This should become a virtual keyboard.

I am experiencing weird drawing that looks like this:

I do not see what my mistake is.

The following is the code that I have placed on the canvas object:

To replicate the problem, do the following:

* The project requires a canvas, parented to the root.
* Add the script "VirtualKeyboard" to it which is stated in this post.
* Next, add an image to this canvas and name it "BackgroundImage". Set the image's anchor preset to "stretch / stretch". Set its color to red.
* Press Play

(Please note that in the code stated below I have removed most of the buttons to keep this post short):

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

public class VirtualKeyboard : MonoBehaviour
{
    public class vbutton : MonoBehaviour
    {
        public int index;
        public float left;
        public float top;
        public float width;
        public float height;
        public string caption;
    }
    private vbutton pMakeKey(int index, float left, float top, float width, float height, string caption)
    {
        vbutton newButton = new vbutton();
        newButton.index = index;
        newButton.left = left;
        newButton.top = top;
        newButton.width = width;
        newButton.height = height;
        newButton.caption = caption;
        return newButton;
    }

    public float screenWidth = Screen.width;
    public float screenHeight = Screen.height;
    public float referenceWidth = 1920f; // Replace with your reference width
    public float referenceHeight = 1080f; // Replace with your reference height

    public float ratioX;
    public float ratioY;

    void Start()
    {
        ratioX = screenWidth / referenceWidth;
        ratioY = screenHeight / referenceHeight;
        List<vbutton> keys = new List<vbutton>();

        keys.Add(pMakeKey(1038, 1028 * ratioX, 141 * ratioY, 57 * ratioX, 43 * ratioY, ""));
        keys.Add(pMakeKey(1040, 1028 * ratioX, 185 * ratioY, 57 * ratioX, 43 * ratioY, ""));

        // Get the canvas to use as parent for the keyboard keys
        Canvas canvas = GetComponent<Canvas>();

        for (int i = 0; i < keys.Count; i++)
        {
            // Create a new GameObject for the key
            GameObject key = new GameObject(keys[i].caption);

            RectTransform keyRectTransform = key.AddComponent<RectTransform>();
            keyRectTransform.SetParent(canvas.transform);
            keyRectTransform.SetParent(transform);
            keyRectTransform.anchoredPosition = new Vector2(keys[i].left, -keys[i].top);
            keyRectTransform.sizeDelta = new Vector2(keys[i].width, keys[i].height);

            // Add a Button component to the key
            Button button = key.AddComponent<Button>();

            // Add a Text component to the key and set its text to the current key string
            Text text = key.AddComponent<Text>();
            text.text = keys[i].caption;
            text.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); // Set the font
            text.color = Color.black;
            text.fontSize = 24; // Set the font size
            text.alignment = TextAnchor.MiddleCenter; // Center the text

            // Add a callback function to the button click event
            button.onClick.AddListener(() => OnButtonClicked(keys[i].caption));
        }
    }
    void OnButtonClicked(string buttonCaption)
    {
        Debug.Log("Button " + buttonCaption + " was clicked!");
        // Do whatever you need to do when a button is clicked here
    }
}

```

This screenshot shows the properties of the "BackgroundImage" that I use as a background:

And this is what the gameview looks like as well as the Canvas properties:

# Answer
The keyRectTransform.sizeDelta was simply too small to show the text. Once I made it bigger, the text would show up.
> 1 votes

---
Tags: unity-ui
---


# Question
Title: How to add visual movement to a car's wheels?
I'm fairly new to Unity and game development in general, I'm trying to build a basic car and give visual movement to the wheels. The car controls are pretty basic: accelerate "w" key, turn right "d" key, turn left "a" key, decelerate "s" key. The wheel moves and turns according to the key pressed, but the problem is that the wheel changes its position during the game mode. I am only working with one wheel until I know how to do this correctly.

The player object has a Rigidbody component and the movement script, also is composed by two childs objects: the car body, this object has a mesh collider component, and the wheels, this object also has their own child objects: wheel colliders and wheel models.

This is what the wheels look like from edit mode:

And this is how the wheels look like from play mode:

Code from the script:

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

public class SimpleCarController : MonoBehaviour
{
   [SerializeField] private Rigidbody _rb;

   [SerializeField] Transform frontLeftTransform;
   [SerializeField] Transform backLeftTransform;

   [SerializeField] WheelCollider frontLeft;
   [SerializeField] WheelCollider frontRight;
   [SerializeField] WheelCollider backLeft;
   [SerializeField] WheelCollider backRight;

   public float acceleration = 500f;

   public float breakingForce = 300f;

   public float maxTurnAngle = 50f;

   private float currentAcceleration = 0f;
   private float currentBreakForce = 0f;
   private float currentTurnAngle = 0f;

   void Start()
   {
       _rb = GetComponent<Rigidbody>();
   }

   public void FixedUpdate()
   {
       currentAcceleration = acceleration * -Input.GetAxis("Vertical");

       backRight.motorTorque = currentAcceleration;
       backLeft.motorTorque = currentAcceleration;

       if (Input.GetKey(KeyCode.Space))
           currentBreakForce = breakingForce;
       else
           currentBreakForce = 0;

       frontRight.brakeTorque = currentBreakForce;
       frontLeft.brakeTorque = currentBreakForce;
       backLeft.brakeTorque = currentBreakForce;
       backRight.brakeTorque = currentBreakForce;

       currentTurnAngle = maxTurnAngle * Input.GetAxis("Horizontal");

       frontLeft.steerAngle = currentTurnAngle;
       frontRight.steerAngle = currentTurnAngle;

       UpdateWheel(frontLeft, frontLeftTransform);
       UpdateWheel(backLeft, backLeftTransform);
   }

   void UpdateWheel(WheelCollider col, Transform transform)
   {
       Vector3 pos;
       Quaternion rot;

       col.GetWorldPose(out pos, out rot);

       transform.position = pos;
       transform.rotation = rot;
   }
}

```

I don' know why this, any help is appreciated.

**--UPDATE--** Image with gizmo in Local/Pivot:

# Answer
The problem here is that the wheel pivot positions are at the bottom of the wheel models. I fixed this by adding an empty game object, changing the position where it needed to be and then added the wheel model as a child of the empty game object that has the pivot right in the center, something like this:
> 1 votes

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


# Question
Title: How do I add an image and a text to a gameobject?
I did the following:

I added a canvas to main camera. I added a UI image to the canvas and named it "BackgroundImage" and made its color red and set its fill mode to "stretch / stretch". I added another UI image to the canvas, name it "ButtonBackground" and selected "Source Image" "Builtin/extras/InputFieldBackground"

I add a script named "VirtualKeyboard" to the canvas. This script has a property named "ButtonBack". I drag the sprite "ButtonBackground" into this slot.

Next, I run my script:

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

public class VirtualKeyboard : MonoBehaviour
{
      public Sprite ButtonBack;

    void Start()
    {
        Canvas canvas = GetComponent<Canvas>();

        string sName = "name1";

        GameObject key = new GameObject(sName);

        RectTransform keyRectTransform = key.AddComponent<RectTransform>();
        keyRectTransform.SetParent(canvas.transform);
        keyRectTransform.anchoredPosition = new Vector2(100,100);
        keyRectTransform.sizeDelta = new Vector2(200, 200);

        // Add Image component to the key
        Image image = key.GetComponent<Image>();
        if (image == null)
        {
            image = key.AddComponent<Image>();
        }
        image.sprite = ButtonBack;
        image.type = Image.Type.Sliced;

        // Add a Text component to the key and set its text to the current key string
        Text text = key.GetComponent<Text>();
        if (text == null)
        {
            text = key.AddComponent<Text>();
        }
        text.text = "test";
    }
}

```

"text" is null. Why is that?

The console says: Can't add 'Text' to name1 because a 'Image' is already added to the game object! A GameObject can only contain one 'Graphic' component. UnityEngine.GameObject:AddComponent\<UnityEngine.UI.Text\> () VirtualKeyboard:Start () (at Assets/VirtualKeyboard.cs:37)

However, I don't know how to solve this problem.

# Answer
> 1 votes
The error message tells you exactly what's wrong.

Each game object can only contain one `Graphic` component. Both `Image` and `Text` inherit from `Graphic` \- so only one can be drawn by a single game object.

In the Unity editor, create a new UI button using the GameObject menu (GameObject -\> Create -\> UI -\> Button). You'll see exactly how they solve this: the button object hosts the `Image` component, and it has *a child object* that hosts the `Text` component.

---
Tags: unity
---


# Question
Title: Save and load Resource failing with "Error constructing a GDScriptInstance"
I have this specific `Resource` script:

```
class_name MyDataStructure
extends Resource

@export var title: String = "Default Title"
@export var medals_per_world = {
    "world1": {
        "bronze": 0,
        "silver": 0,
        "gold": 0,
    },
    # Etc.
}

func _init(_some_title: String):
    title = _some_title

```

And I'm trying to save/load it with these methods:

```
const SAVE_DATA_PATH := "user://save_game.tres"
var _data: MyDataStructure

func _on_button_save_pressed():
    ResourceSaver.save(_data, SAVE_DATA_PATH)

func _on_button_load_pressed():
    if not ResourceLoader.exists(SAVE_DATA_PATH):
        return
    _data = load(SAVE_DATA_PATH)

```

**Saving works fine** and gives me this type of file:

```
[gd_resource type="Resource" script_class="MyDataStructure" load_steps=2 format=3]

[ext_resource type="Script" path="res://my_data_structure.gd" id="1_e2e3s"]

[resource]
script = ExtResource("1_e2e3s")
title = "Foo title"
medals_per_world = {
"world1": {
"bronze": 3,
"gold": 2,
"silver": 4
}
}

```

**Loading it fails** with this error:

> ```
> E 0:00:07:0699   root.gd:31 @ _on_button_load_pressed(): Error constructing a GDScriptInstance.
>   <C++ Error>    Method/function failed. Returning: nullptr
>   <C++ Source>   modules/gdscript/gdscript.cpp:183 @ _create_instance()
>   <Stack Trace>  root.gd:31 @ _on_button_load_pressed()
>
> ```

I recently introduced the nested dictionary `medals_per_world` so perhaps that's causing me issues?

Either way, how can I properly load such a file with the `ResourceLoader`? The fact that it saves properly suggests that loading it should also be possible? Or is my only workaround/solution to define the entire data structure with dto `Resource` scripts for each nested level if the dictionary is the cause?

I'm working with Godot 4 so can use any recently released GDScript feature if needed.

# Answer
> 5 votes
Godot will try to call your `_init` method while loading the `Resource`. But it can't because it has a non-optional parameter (Godot has no means to figure out what to pass).

Thus, a possible solution is to make it optional:

```
func _init(_some_title: String = ""):
    title = _some_title

```

Alternatively, you could remove it entirely.

---

You could also take control of how the `Resource` is loaded by implementing a `ResourceFormatLoader` which you register with `ResourceLoader.add_resource_format_loader`.

*Alternatively - in particular if you need to be able to load the `Resource` from the editor - you could be interested in implementing `EditorImportPlugin` which you register from an `EditorPlugin` using `EditorPlugin.add_import_plugin`.*

Then your implementation can use your `_init` correctly.

---

As an alternative to adding parameters to `_init` you can add static methods to build your type※:

```
static func with_title(_some_title:String) -> MyDataStructure:
    var result = MyDataStructure.new()
    result.title = _some_title
    return result

```

※: *Doing this in Godot 3.x would have required a helper class, because Godot would not resolve the name of the class while parsing the class.*

That might also improve readability of your code. For example, anybody unfamiliar with your code, and without looking up the definition, could guess that argument is a title:

```
var instance := MyDataStructure.with_title("BLAH")

```

*By the way: Godot does not support named arguments.*

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


# Question
Title: Can I contribute code to an Unreal game without running the engine on my system?
I want to get into game programming, but my system can't run Unreal Engine.

Another programmer I'm working with is using Unreal on his system, so I want to know if it's possible for me to code using Visual Studio on my system without having Unreal Engine, and still contribute to our shared project this way.

# Answer
Code is just text files. You could write Unreal engine code in anything that can write text - even your phone's SMS app if you wanted, but **the workflow would be a nightmare**.

Especially as you're first learning game development, you're going to make a lot of mistakes, and being unable to **test your work**, experiment, and observe the results without waiting on your partner will slow your learning down drastically (and impact their productivity, and possibly strain your working relationship too).

I'd recommend that you **choose a different engine or framework** for your first game - something your system *can* run. Possibly Unity or Godot, or even web game frameworks that run anywhere you can use a browser. You'll learn much faster when you can test your work in a tight iteration loop, and the fundamentals you learn about how to approach game development will be portable between engines.

If you later take on an Unreal project, it will go much smoother once you've built up experience coding in another engine, so you can anticipate many of the problems and troubleshoot others more effectively, helping to compensate for the slower iteration time if you still need to borrow someone else's system to test.
> 4 votes

# Answer
If you guys are stuck with Unreal Engine, you could start a GitHub repo with the project files, allowing both of you to upload files easily. Your friend can then upload them to Unreal Engine for testing.
> 0 votes

---
Tags: visual-studio, unreal-5
---


# Question
Title: Assistance with State Machine Event subscription error?
My aim is to create events within my various states that will broadcast to other GameObjects when to take certain actions and to send certain data without needing to reference each GameObject.

I have an Event within a concrete State deriving from a base MonoBehaviour State "GallowsBase" in my State machine called "GallowsResetEvent"/"OnGallowsResetEvent":

```
using UnityEngine;
using TMPro;

public class GallowsSetup : GallowsBase
{
    public delegate void GallowsResetEvent();
    public static event GallowsResetEvent OnGallowsResetEvent;

    SOWords _wordBank;

    public override void EnterState(GallowsStateManager _gallows)
    {
        // broadcast to observers - reset.
        OnGallowsResetEvent();
        // broadcast to observers - setup.
        // receive setup complete event
        // go to player turn state
        _gallows.SwitchState(_gallows._gallowsTurnPlayer);

    }
}

```

When I try to add a listener to the event, I receive an error CS0029 - Cannot implicitly convert type 'void' to 'GallowsSetup.OnGallowsResetEvent'

```
private void OnEnable()
{
    GallowsSetup.OnGallowsResetEvent += Reset(); //error here
}

private void Reset()
{
    _textChosenTitle.text = null;
}

```

Changing the void on the Reset method to GallowsSetup.OnGallowsResetEvent gives a couple of errors -

CS0426 The type name 'OnGallowsResetEvent' does not exist in the type 'GallowsSetup'

CS0161 'GallowsCanvas.Reset()': not all code paths return a value

I feel I hit a wall here. How can I implement decoupled events within my state machines?

# Answer
Try `GallowsSetup.OnGallowsResetEvent += Reset;`. Without the parenthesis after the method name.

`Reset()` executes the method immediately and uses the returned result in its place. The method returns nothing (aka `void`), so you get an error that void can't be converted to the expected type of the event.

`Reset` refers to the method itself as a delegate value. This allows you to store the method itself in an event so it can be executed by the event later.
> 1 votes

---
Tags: unity, events, state
---


# Question
Title: How can I override the footer buttons in Unity's UI Toolkit ListView?
In the new UI Toolkit that is shipped with Unity 2021+ there's a ListView component that can be added using the UI Builder, which has an option to enable the footer buttons.

in UXML: `show-add-remove-footer="true"`

However clicking the `+` will add a null to the list and I'd like to override that behaviour.

Adding a custom function to the button will have it triggered after Unity's default function. Is there a way to remove all registered callbacks on a button?

I tried to look for the source of this ListView class but could not find it.

# Answer
> 2 votes
As suggested by DMGregory, using `itemsAdded` resulted in a workable solution.

After creating a new "UI Toolkit \> UI Document" in a scene, and adding the below uxml as the source asset, and adding the script as a component gives the desired result.

UXML:

```
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
    <ui:ListView focusable="true" show-add-remove-footer="true" header-title="Items" show-foldout-header="true" reorderable="true" style="flex-grow: 1; background-color: rgb(210, 210, 210);" />
</ui:UXML>

```

Test.cs

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

public class test : MonoBehaviour
{
    class Item {
        public string name;
    }

    void OnEnable() {
        // Quickly setup a list of Items
        List<Item> source = new List<Item>();
        source.Add(new Item(){ name = "One" });
        source.Add(new Item(){ name = "Two" });
        source.Add(new Item(){ name = "Three" });

        // Find the listview and add functionalities
        var document = GetComponent<UIDocument>();
        var listView = document.rootVisualElement.Q<ListView>();
        listView.makeItem = () => new Label();
        listView.bindItem = (existingElement, index) => (existingElement as Label).text = $"Entry Number {index} - {source[index].name}";

        // set our list as item source
        listView.itemsSource = source;

        // since by default a null element is added to the itemsSource
        // we need to remove that in a creative manner
        listView.itemsAdded += (items) => {
            var index = items.First();
            Debug.Log($"Added: {items} - {index}");
            source.RemoveAt(index);
            source.Add(new Item(){ name = $"Random-{index}" });
        };
        listView.itemsRemoved += (items) => {
            var index = items.First();
            Debug.Log($"Removed: {items} - {index}");
        };
    }
}

```

Result:

Where the buttons at the bottom work as expected.

**UPDATE:**

A different way of achieving this would be to check for `null` items in the `bindItem` function. Which feels less hacky.

```
listView.bindItem = (e, index) => {
    if (source[index] == null) {
        source[index] = new Item(){ name = $"Random-{index}" };
    }
    (e as Label).text = $"{source[index].name}";
};

```

**Note**

If on delete you need to know which item was deleted, you need to keep a copy of the source list.

```
listView.itemsSource = new List<Item>(source);

```

As the `itemsRemoved` will trigger after it has been removed, the index that is passed would then no longer contain an item.

# Answer
> 1 votes
You do that by replacing the method stored in the delegate `makeItem` of the listview with your own method that returns the new `VisualElement` you want to appear in the list.

The example for ListView in the documentation includes an example that shows how you provide such a method while you create a new ListView via code. Keep in mind that if you do that, you should also provide an implementation of the `.bindItem` method. The `.makeItem` method creates the item element, and the `.bindItem` method is supposed to set up its data. Which will also happen on already created item elements when the player scrolls through a list.

If you want to do it with a ListView you have created as an UXML asset, that should look something like this:

```
void OnEnable() {
    var document = GetComponent<UIDocument>();
    var listView = document.rootVisualElement.Q<ListView>("myListView");
    listView.makeItem = () => {
        // your code that gets executed on making a new item.
        // Must return a VisualElement, which can be as simple or complex as you want.
        return new Label();
    };
    listView.bindItem = (existingElement, index) => {
        (existingElement as Label).text = $"Entry Number {index}";
    };
}

```

---
Tags: unity, ui-toolkit
---


title: Transforming a ray to NDC coordinates

text:
# Question
Title: Transforming a ray to NDC coordinates
I am trying to have ray tracing with a mesh using NanoRT and I want to be able to allow for a model transform on top of my view and projection transforms.

I have successfully transformed my ray from object space to NDC by computing the inverse of the view and projection matrices, but I am having some trouble to do the same when having a model transform as well. This is what I have tried:

```
glm::vec4 NDCPos      = glm::vec4((2.0f * float(mousePositionX)) / widthHeight.x - 1.0f,
                        1.0f - (2.0f * float(mousePositionY)) / widthHeight.y,
                        1.0f,
                        1.0f);
glm::mat4 inverseModel = glm::inverse(model);
glm::vec4 viewCoords   = glm::inverse(projection) * NDCPos;
viewCoords             = glm::inverse(view) * viewCoords;
glm::vec4 worldCoords  = inverseModel * glm::vec4(viewCoords.x, viewCoords.y, -1.0f, 0.0f);

glm::vec3 rayDir = glm::normalize(glm::vec3(worldCoords));
glm::vec3 rayOri = inverseModel * glm::vec4(camPos.x, camPos.y, camPos.z, 0.0f);

nanort::Ray<float> ray;
ray.org[0] = rayOri.x;
ray.org[1] = rayOri.y;
ray.org[2] = rayOri.z;

ray.dir[0] = rayDir.x;
ray.dir[1] = rayDir.y;
ray.dir[2] = rayDir.z;

float kFar = 1.0e+30f;
ray.min_t = 0.0f;
ray.max_t = kFar;

nanort::TriangleIntersector<> triangle_intersector(glm::value_ptr(modelDataVertices[0]), &indexes[0], sizeof(float) * 3);
nanort::TriangleIntersection<> isect;
bool hit = accel.Traverse(ray, triangle_intersector, &isect);
if (hit)
{
    hitPos = rayOri + rayDir * isect.t;
}

```

# Answer
> 1 votes
My issue was not having a 1.0f in the w component:

```
glm::vec3 rayOri = glm::vec3(inverseModel * glm::vec4(camPos.x, camPos.y, camPos.z, 1.0f));

```

---
Tags: c++, glm, raytracing
---


title: Why is my texture moving?

text:
# Question
Title: Why is my texture moving?
I tried sampling equirectangular texture as a reflection. It simply does not work as intended. The texture is moving with my camera in a weird manner. Here is what I tried to do.

Fragment shader:

```
#version 460 core
#extension GL_ARB_bindless_texture : require
#extension GL_ARB_gpu_shader_int64 : require
layout ( location = 0 ) out vec4 FragColor;

const float one_o_2pi = 0.1591;
const float one_o_1pi = 0.3183;

in vec3     normal;
in vec3     eye;
in vec3     frag_pos;

uniform sampler2D   tex_pref;

vec2 uv_from_vec3(vec3 t_direction)
{
    float theta = acos(t_direction.y);
    float phi = atan(t_direction.z, t_direction.x);

    float u = phi * one_o_2pi + 0.5;
    float v = theta * one_o_1pi + 0.5;

    if (phi < 0.0)
    {
        u += 1.0;
    }

    return vec2(u, v);
}

vec3 pref_env_map(vec3 w_i, float t_roughness)
{
    vec2    pref_tex_coords = uv_from_vec3(w_i);
    vec3    result = textureLod(tex_pref, pref_tex_coords, 6.0 * t_roughness).rgb;
    return  result;
}

void main( void )
{
    vec3    w_o = normalize(eye - frag_pos);
    vec3    n = normal;
    if (gl_FrontFacing)
        n = - n;
    vec3    w_i = normalize(reflect(-w_o, n));
    // The roughness is in the code, this is just a snippet
    FragColor = vec4(pref_env_map(w_i, roughness), 1.0);
}

```

Vertex shader:

<pre><code>#version 460 core

// vertex attributes
layout ( location = 0 ) in vec4 in_position_ms;
layout ( location = 1 ) in vec3 in_normal_ms;

//out vec4 outcol;

// uniform variables
//uniform mat4 P; // Model View Projection
uniform mat4 view; // Model View Projection
uniform mat4 proj; // Model View Projection
uniform vec3 uEye;

out vec3 normal;
out vec3 eye;
out vec3 frag_pos;

void main( void )
{
    mat4 P = proj * view;
    vec4 position = P * (in_position_ms);
    gl_Position = position;
    normal = in_normal_ms;
    eye = uEye;
    frag_pos = position.xyz;
}

```
</code></pre>

# Answer
> 2 votes
```
vec3    w_o = normalize(eye - frag_pos);

```

This line assumes `frag_pos` is expressed in the same space as `eye` — probably world space. (Also: note that `eye` coming from a uniform `uEye`, so you should just read the uniform directly instead of wasting an interpolator slot by passing it through as a varying/in-out variable)

```
vec4 position = P * (in_position_ms);
frag_pos = position.xyz;

```

These lines store `frag_pos` in post-projection space. That space is only valid to work with after you divide xyz by w, and the result you get is in normalized device coordinates — i.e. it's a point on the screen now, not in the 3D space of your world.

What you need to do is pass the world space position in `frag_pos` — one that has not been transformed by the view or projection matrices.

---
Tags: opengl, c++, glsl, c, vulkan
---


# Question
Title: Unity PlayMode tests - cannot find UnityEngine.InputSystem assembly
I'm trying to simulate user input in my Unity PlayMode tests. I've been reading this guide on the Unity website about adding input simulation into my tests. Specifically, it mentions I need to add the `Unity.InputSystem` and `Unity.InputSystem.TestFramework` assemblies as references in my PlayMode assembly. However, I can't find these assemblies (see image below).

I suspect I'm missing a step on bringing these assemblies into Unity to reference them, but I can't find any further documentation on this.

# Answer
> 1 votes
I've managed to resolve this issue, with some direction. I hadn't realised that the Input System test framework I was trying to use, was actually part of a package I hadn't yet installed: the new Unity Input System. Reading further back on this guide that I posted in the question, I realised there was an installation step I had missed that directed me to install the Input System package.

With this package now installed, I was able to inherit my test class from `TestInputFixture`, which handles the initialization of a clean, temporary input system. This was my setup:

```
public class MyTests : InputTestFixture
{
    private Keyboard keyboard;

    [SetUp]
    public override void Setup()
    {
        base.Setup();

        keyboard = InputSystem.AddDevice<Keyboard>();
    }
}

```

I was then able to simulate key presses in my tests:

```
[UnityTest]
public IEnumerator MyTest()
{
    Press(keyboard.escapeKey);
    Release(keyboard.escapeKey);
    yield return null;

    // ... assertions
}

```

One point to note here is that I wanted to check if the key had been pressed on that frame (not that it was being held down). This is the same as using the classic `Input.GetKeyDown(KeyCode.Escape)`. As a result, I needed to ensure my test simulated not just pressing the key down, but also releasing it back up, all within the same frame to register as being pressed on that frame.

My actual code method could then check for this scenario with the following:

```
void Update()
{
    if (Keyboard.current.escapeKey.wasPressedThisFrame)
    {
        // ... do the thing
    }
}

```

One point to note here, is that this is fine for a simple scenario like this, but only supports a single input device. The recommended approach is to actually move away from checking input manually within the `Update()` method, and instead making use of the `PlayerInput` mechanism that binds actions, input and scripts through the editor. You can read more about this here.

Thanks to @DMGregory for pointing me in the right direction.

---
Tags: unity, input, testing, unit-testing
---


title: How to implement grapple hook and swing

text:
# Question
Title: How to implement grapple hook and swing
I'm trying to make a retro style grapple hook / swing system that has a constant speed and is not based on real-life physics. Like the one in Axiom Verge, Bionic Commando (NES) and Super Metroid.

# Answer
Was able to figure it out! This works without any of Unity's built-in physics! This gets concomitant movement like in retro games.

```
    public float speed = 1f;

    public Transform hookPoint;
    public float sinTime;

    public float angle = 0;
    public Vector2 velocity;

    public float direction;
    public LineRenderer lineRenderer;

    public Texture2D texture2D;

    void Start()
    {
        lineRenderer.positionCount = 2;
        lineRenderer.SetPosition(0, transform.position);
        lineRenderer.SetPosition(1, hookPoint.position);

        lineRenderer.material.SetTexture("_MainTex", texture2D);
        SetStartingAngle();

    }

    private void SetStartingAngle()
    {
        float dx = transform.position.x - hookPoint.position.x;
        float dy = transform.position.y - hookPoint.position.y;

        angle = Mathf.Atan2(dy, dx) * Mathf.Rad2Deg;

        if (angle < 0)
            angle += 360;

        sinTime = (angle * 2) / 100;

        //Sets starting direction
        if (angle > 270)
            direction = -1;
        else
            direction = 1;
    }
    void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {
            if (radius == 0)
            {
                radius = Vector2.Distance(transform.position, hookPoint.position);
            }

            angle = (sinTime / 2 * 100);
            velocity.x = Mathf.Cos(angle * Mathf.Deg2Rad) * radius;

            //Add hookPoint Y pos to center sinWave
            velocity.y = (Mathf.Sin(angle * Mathf.Deg2Rad) * radius) +
            hookPoint.position.y;

            transform.position = velocity;
            sinTime += (speed * Time.deltaTime) * direction;

            //Ping-pongs to move in 1/2 circle
            if (angle >= 359)
                direction = -1;
            else if (angle < 180)
                direction = 1;

            //Updates line render
            lineRenderer.SetPosition(0, transform.position);
            lineRenderer.SetPosition(1, hookPoint.position);
        }
        else
        {
            radius = 0;
        }

    }
}

```
> 0 votes

---
Tags: unity, 2d, physics, game-mechanics, rope-physics
---


# Question
Title: Invalid type in utility function 'lerp'. Cannot convert argument 2 from float to Nil
Here's a declaration of *Vector2* `camera_input`. And, it comes out to be invalid. I'm using Godot 4.0.1.

Code:

```
extends CanvasLayer

@onready var camguide_y = get_parent().get_node("character_1_controller/camguide_y")
@onready var camguide_x = get_parent().get_node("character_1_controller/camguide_y/camguide_x")

var joystick_index = -1
var attack_index = -1
var s1_index = -1
var s2_index = -1
var dodge_index = -1
var camera_index = -1
var camera_input = Vector2.ZERO
var rotation_velocity_x = 0
var rotation_velocity_y = 0

func _unhandled_input(event):
    if event is InputEventScreenTouch:
        if event.pressed:
            if Input.is_action_just_pressed("joystick_action"):
                joystick_index = event.index
            elif Input.is_action_just_pressed("attack_action"):
                attack_index = event.index
            elif Input.is_action_just_pressed("s1_action"):
                s1_index = event.index
            elif Input.is_action_just_pressed("s2_action"):
                s2_index = event.index
            elif Input.is_action_just_pressed("dodge_action"):
                dodge_index = event.index
            else:
                camera_index = event.index
        else:
            if Input.is_action_just_released("joystick_action"):
                joystick_index = -1
            elif Input.is_action_just_released("attack_action"):
                attack_index = -1
            elif Input.is_action_just_released("s1_action"):
                s1_index = -1
            elif Input.is_action_just_released("s2_action"):
                s2_index = -1
            elif Input.is_action_just_released("dodge_action"):
                dodge_index = -1
            else:
                camera_index = -1
    if event is InputEventScreenDrag:
        if event.index == joystick_index:
            pass
        if event.index == camera_index:
            camera_input = event.relative

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    rotation_velocity_x = lerp(rotation_velocity_x, camera_input.x * 0.4, delta*10.0)
    rotation_velocity_y = lerp(rotation_velocity_y, camera_input.y * 0.15, delta*10.0)
    camguide_x.rotate_x(deg_to_rad(rotation_velocity_y))
    camguide_y.rotate_y(deg_to_rad(rotation_velocity_x))
    camguide_x.rotation.x = clamp(camguide_x.rotation.x, -0.5, 0.5)
    camera_input = Vector2.ZERO

```

Error message: Invalid type in utility function 'lerp'. Cannot convert argument 2 from float to Nil

# Answer
As mentioned in the lerp documentation:

> `Variant lerp ( Variant from, Variant to, Variant weight )`
>
> ...
>
> Both `from` and `to` *must be the same type*.

`camera_input.x` is a float (because that's what `Vector2.ZERO` is made up of) whereas `rotation_velocity_x` is inferred as an int (because `0` is an integer).

Try changing the declaration to:

```
var rotation_velocity_x = 0.0

```

or better yet use static typing:

```
var rotation_velocity_x : float = 0.0

```
> 1 votes

---
Tags: godot, lerp
---


# Question
Title: Accepting user input in continous game loop
I have a game loop that simply iterates through every entity and calls `entity.update()`

```
class Engine {
    protected entities: IUpdateable[]

    update() {
        GlobalTime.tick(this)
        for (let entity of this.entities) {
            entity.update()
        }
    }

```

I need to accept user input, but without requiring the game loop to pause and wait, like the following code would do

```
    update() {
        getUserInput() // will result in async-await like behavior, pausing until user input
        GlobalTime.tick(this)
        for (let entity of this.entities) {
            entity.update()
        }
    }

```

What is the standard way to implement optional asynchronous user-input with a continuous game loop? Is it just to have an `.events` array that is checked every frame, resets every frame, that the frontend can optionally append user input to?

# Answer
> Is it just to have an .events array that is checked every frame, resets every frame, that the frontend can optionally append user input to?

That would be called an "event queue", and it is a pretty common solution for input handling.

Another option is to have a data-structure that holds the current state of all inputs (which buttons are currently held down, which values you have on which analog axis...). Any system that needs to know the current input state would look in that data-structure. An architecture like that can be really convenient in game development, because you often have mechanics where some entity is supposed to behave in a certain way *while a button is being held down* (for example: "run right while the player holds d-pad right"). In that case, you can write code in an update method like this:

```
if (inputs.moveRight.ispressed) {
    position.x += speed * deltaTime;
}

```

But because most operating system APIs that deliver user-input are event-based, you usually end up writing that structure from event handlers anyway. If you are working in an multithreaded architecture where input events can be processed at any time and not just at a specific point of the game-loop, then it is usually a good idea to write their changes to a shadow-structure, and replace the actual input structure at the beginning of the update-loop. That ensures that the input state doesn't change during the update-loop, which might otherwise become a source of hard to reproduce bugs.
> 2 votes

---
Tags: software-engineering, input, game-loop
---


title: Unity texture shows UV border

text:
# Question
Title: Unity texture shows UV border
I have a photogrammetry asset whose UV is, like most photogrammetry assets, a mess.

And when I import this asset into Unity, the texture shows clear borders at the place where the UV is not connected, forming many "patches":

Compare to the same region displayed in Maya (Surface Shader):

What caused this and is there a way to fix it?

(this is in Unity 2021.3.22f1, URP, default settings)

# Answer
@DMGregory in the comment pointed out what to check and I was able to find and solve this problem.

My normal map was generated by photogrammetry software and looked like this:

In Shader Graph (since this one is using a shader graph), select normal, and in Graph Inspector, the `Fragment Normal Space` has 3 options. Mine was defaulted to `Tangent`, and after changing it to `Object`, the patches disappeared.
> 2 votes

---
Tags: unity, textures, uv-mapping
---


# Question
Title: Best way to handle collisions between moving entities on tile map?
I am developing simple 2D game. I render tiled map and several moving entities, one of which is the character controlled by a player, and other ones are NPCs that are moved by simple AI strategy - chase a character using shortest path finding algorithm (tiled map data structure contains graph property that allows entities to find paths by BFS or Dijkstra).

I am wondering how should I handle collisions between those entities. I am currently able to handle collisions between an entity and tile map objects. But the problem is when more than 1 NPCs are engaged in chasing, they can end up overlapping each other, which is not what I want to see.

I was thinking about bounding box based collision detection, but it doesn't work well with path traversing algorithm, since sometimes velocity changes result in not natural chaotic movement.

Another way is to check if tile is currently occupied by an entity and prevent movement if needed. However this lead to a problem of recreating path (graph should be copied and reduced by one node, path should be generated again)

Third option is to create some kind of relation between all NPCs to prevent collisions or change their coordinates on demand. However this is not quite scalable solution.

# Answer
> 1 votes
Sounds like you could implement a grid system where each cell contains a list of all entities currently overlapping that cell. Based on that you can do continuous collision detection and even move and slide between colliding entities and tiles so they never overlap.

It's quite an undertaking with literally many edge and corner cases to keep in mind but it can be done.

---
Tags: 2d, collision-detection, tiled
---


title: Timer event isn't working

text:
# Question
Title: Timer event isn't working
I've been using allegro for some time, and the timer event worked in all my previous projects, but I don't know what happened this time, I want to move a piece as long as the game is going, but it isn't moving at all, so the timer event isn't working, why is that? I've made sure all event sources are registered. Here is the code that reproduces the problem:-

```
int firstStuffXPos = 100;
int firstStuffYPos = 100;
ALLEGRO_EVENT_QUEUE *eventqueue;
ALLEGRO_DISPLAY *display;
ALLEGRO_TIMER *timer;
int width = 800;
int height = 600;
int FPS = 60;
 bool donePlaying = false;

class MyClass{
public:
int getXPos()
{
    return x;
}
int getYPos()
{
    return y;
}
int x;
int y;
 MyClass(int x, int y){
    this->x = x;
    this->y = y;
    stuffone;
}
ALLEGRO_BITMAP *stuffone;
};
MyClass stuff1[] = {
{ firstStuffXPos, firstStuffYPos},
};
void initialize(){
    al_init();
    if (!al_init()){
        std::cout << "Failed to initialize allegro5." << std::endl;
    }
    al_init_image_addon();
    if (!al_init_image_addon()){
        std::cout << "Failed to initialize image." << std::endl;
    }
    display = al_create_display(width, height);
    if (!display){
        std::cout << "Failed to create display." << std::endl;
    }
    al_install_keyboard();
    if (!al_install_keyboard()){
        std::cout << "Failed to install keyboard." << std::endl;
    }
    al_init_primitives_addon();

    eventqueue = al_create_event_queue();
    timer = al_create_timer(1.0 / FPS);

    al_register_event_source(eventqueue, al_get_display_event_source(display));
    al_register_event_source(eventqueue, al_get_keyboard_event_source());
    al_register_event_source(eventqueue, al_get_timer_event_source(timer));

    }
int main(){
initialize();
for (int nostuff = 0; nostuff < 1; nostuff++){
    stuff1[nostuff].stuffone = al_load_bitmap("blueblock.png");
}
    while (!donePlaying){
        al_clear_to_color(al_map_rgb(0, 0, 0));
        ALLEGRO_EVENT ev;
        al_wait_for_event(eventqueue, &ev);
        al_start_timer(timer);
        if (ev.type == ALLEGRO_EVENT_TIMER){
            firstStuffXPos += 5;
            firstStuffYPos += 5;
        }
        for (int i = 0; i < 1; i++){
            al_draw_bitmap(stuff1[i].stuffone, stuff1[i].getXPos(), stuff1[i].getYPos(), 0);
        }
        al_flip_display();
    }

    al_flip_display();
}

```

# Answer
> 0 votes
> but it isn't moving at all, so the timer event isn't working, why is that?

What makes you so sure it isn't moving *because* the timer isn't working? Try inserting a print statement in the `if (ev.type == ALLEGRO_EVENT_TIMER)` block -- I think you'll see that your timer event *is* firing.

It isn't moving because you increment `firstStuffXPos`/`firstStuffYPos`, which never actually get used. Try incrementing `stuffone[0].x`/`stuffone[0].y` instead.

As a side note, there's no need to call `al_start_timer` every time you loop, just call it once before you start your main gaime loop.

# Answer
> 1 votes
So I found your problem and it's bit me in the butt A LOT with other allegro functions. You are putting an integer into a float variable. Since you defined FPS as an interger, you must cast it as a float when setting the timer. By the way, I love allegro, but they don't overload functions and check for wrong containers in a lot of the calls, so it's kind of your responsibility to make sure you know what data type is being sent to each function. Even if you use a define up too for your FPS, unless you define it as 60.0, it may define as an integer and screw up the timer, causing the program to hang while trying to exit.

---
Tags: c++, allegro
---


# Question
Title: How can I simulate lamp flicker in a Unity shader?
I want a game object to keep its brightness (modulating `mainColor`, like `mainColor * brightness`) most of the time, but sometimes make it flicker. Something like a lamp flame that's usually steady, interspersed with short periods of chaotic turbulence before returning to full brightness.

Currently I use `smoothstep(-1,1,sin(frac(_Time.y * _Speed)))` to vary the brightness randomly during the flickering phases, but how can I stop the flickering during the stable phases?

# Answer
> 0 votes
Actually I figured it out:

```
sin(_Time.y) > -0.05 && sin(_Time.y) < 0.05
    ? smoothstep(-1,1,sin(frac(_Time.y * _Speed)))
    : 1

```

And then it will multiply `mainColor` to control main color's brightness.

---
Tags: unity, shaders, algorithm, graphic-effects
---


title: Play each scene at godot 3.1

text:
# Question
Title: Play each scene at godot 3.1
I have created a project. And I have saved 20 scenes for 20 game levels. I have designed each scene but when I hit f5 to play each scene, it shows level1 scene. I don't know what the problem is.

# Answer
If you just want to test out a given scene independently, you can use:

* `F6` to play the scene that's currently active in the editor.
* `Control+Shift+F5` to play a custom scene (brings up a selection menu).

By default both of the above should have icons in the upper right hand corner:

Otherwise, if you want to change the scene via code (for example change to level 2 after level 1 has been completed), there's an example of changing scenes in the documentation:

```
func _my_level_was_completed():
    get_tree().change_scene("res://levels/level2.tscn")

```

Note: the docs I linked are for version 3.6 stable - the most current pre 4th edition at the time of writing this answer. If you want the 3.1 version, you can find that here. In general, `change_scene` is valid for all 3.x versions of Godot; in Godot 4 you use `change_scene_to_file` instead of `change_scene`.

Note: If you already have code for changing scenes & it's not working, you'll need to edit your post to include that before anyone can attempt to troubleshoot it.
> 1 votes

---
Tags: godot, scene, scene2d
---


# Question
Title: Increment score when player touches a coin's Area2D
I have created and finished my game in Godot, but I want to add a scoring system. Specifically, I want the score to increase by 1 every time the player touches a coin. However, I am not sure how to implement this. Can someone please guide me on how many scenes I need to create and which nodes I need to use? I currently have a scene called ‘coin’ which has an Area2D node

# Answer
> 4 votes
You should not need any more scenes than you have.

I'm going to suggest to do this with a Signal Bus, although it is not the only approach.

Mainly you need to do this:

* Create an autoload with an script that has a score variable. *So you can access it from anywhere in the scene tree of your game.*

```
extends Node

var score := 0

```

You need to give a name to the autoload, for the purposes of this answer I'll call it `Board`.
* In a method connected to the body entered signal of your `Area2D` increment the variable. *I recommend using a method in a script attached to the `Area2D` itself.*

```
func _on_coin_body_entered(body) -> void:
    # ...
    Board.score += 1

```

Now, presumably, you don't just want the score to increment. You want to do something with it.

So, I'd suggest you:

* Declare a signal to notify when the score changed.

```
extends Node

signal score_changed(score)

var score := 0

```
* Then create a setter for the score variable, that emits the signal.

*Godot 3*

```
extends Node

signal score_changed(score)

var score := 0 setget set_score

func set_score(mod_value:int) -> void:
    if score == mod_value:
        return

    score = mod_value
    emit_signal("score_changed", score)

```

*Godot 4*

```
extends Node

signal score_changed(score:int)

var score := 0:
    set(mod_value):
        if score == mod_value:
            return

        score = mod_value
        score_changed.emit(score)

```
* Then you can connect to the signal from anywhere in the scene tree.

Now, what are you going to do with the score?

* Presumably you want to show it, right?

So in your UI (I suppose you have an scene for that, or you can add it to one of your scenes) you could add a `Label` and have a script that connects to the signal from the autoload, and when it gets it, it changes the text of the label.

Something like this:

*Godot 3*

```
extends Label

func _ready() -> void:
    Board.connect("score_changed", self, "_on_score_changed")

func _on_score_changed(score:int) -> void:
    text = str(score)

```

*Godot 4*

```
extends Label

func _ready() -> void:
    Board.score_changed.connect(_on_score_changed)

func _on_score_changed(score:int) -> void:
    text = str(score)

```
* Also presumably you want to store it, right?

So you can add methods to the autoload that save it or load it from storage.

I could give you the code to read and write the score as text alone in a file (you can still find that in the documentation if you want). However, usually we end up wanting to save multiple things in the file. So let me suggest to use the `ConfigFile` class, which will make INI-like files:

*Godot 3 or Godot 4*

```
const save_file := "user://saved.dat"

func load() -> void:
    var file := ConfigFile.new()
    var err := file.load(save_file)
    if err != OK:
        push_error("error loading score " + str(err))
        return

    score = int(file.get_value("Player", "score"))

func save() -> void:
    var file := ConfigFile.new()
    file.set_value("Player", "score", score)
    var err := file.save(save_file)
    if err != OK:
        push_error("error saving score " + str(err))

```

I hope you can see that this approach would work if you need to make a save file for your game, or you need to have a blackboard for the enemies to share information, or you want a configuration file, etc.

---
Tags: 2d, collision-detection, godot, scoring
---


# Question
Title: Is it better to declare a variable for new WaitForSeconds or just create each time in Unity?
Is it better to declare a variable for new WaitForSeconds or just create each time in Unity?

In other words, is A or B beter?

<pre><code>//A

IEnumerator WaitingForGodot(){
  while(!godot){
    yield return new WaitForSeconds(1f);
  }
}

// B
IEnumerator WaitingForGodot(){
  WaitForSeconds wait = new WaitForSeconds(1f);;
  while(!godot){
    yield return wait;
  }
}
```
</code></pre>

# Answer
Option B involves fewer memory allocations, since each use of `new` with a reference type has to allocate memory and track it for later garbage collection when you're done with it.

These allocations are very small and usually short-lived, so they'll tend to stay in the "Generation 0" garbage collection bucket where allocation and cleanup is relatively fast. The `IEnumerator` instance itself will tend to go here too, unless it's a long-running process; you can't avoid allocation entirely when using coroutines. You don't have to worry about this small overhead most of the time, unless you are making very heavy use of coroutines on a platform where RAM is tight and GC is slow (mobile).

You can go a step further though:

```
// C
static readonly WaitForSeconds wait = new WaitForSeconds(1f);

IEnumerator WaitingForGodot(){
  while(!godot){
    yield return wait;
  }
}

```

Now you have one memory allocation for the wait, total, across the entire lifetime of your game, no matter how many times you start this coroutine or how many frames it runs. It also slightly reduces the size of the storage needed for each coroutine's generated `IEnumerator` instance (since they no longer have to store a reference to wait — it's global).

The downside is that now the wait duration is fixed across all iterations, and you pay the construction/allocation cost even if you never actually start this coroutine at all. There's also a minor amount of namespace pollution from taking a function temporary and making it long-lived like this.
> 3 votes

# Answer
Option A is easier to read.

Premature optimization is the root of all evil. If you have performance/garbage issues, then you should revisit. But until you find a bottleneck, focus on readability and maintainability.

Also, you should use async and await instead of coroutines in my opinion.
> 1 votes

---
Tags: unity
---


title: How do I Instantiate a player prefab

text:
# Question
Title: How do I Instantiate a player prefab
I turned my player into a prefab for a endless runner game but how would i instatiate it so that the player is in the scene when the game starts without it currertly being on a seprate platform that the player then ends up jumping from to get onto the road

# Answer
> 0 votes
You would just drag the prefab into the editor. See also: https://stackoverflow.com/questions/72361621/how-to-get-a-reference-to-a-prefab-asset-in-unity

Instantiation at runtime seems also given in the docs here: https://docs.unity3d.com/Manual/InstantiatingPrefabs.html

```
public class InstantiationExample : MonoBehaviour
{
    // Reference to the Prefab. Drag a Prefab into this field in the Inspector.
    public GameObject myPrefab;

    // This script will simply instantiate the Prefab when the game starts.
    void Start()
    {
        // Instantiate at position (0, 0, 0) and zero rotation.
        Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);
    }
}

```

---
Tags: prefabs
---


title: Fastest way to draw quads in OpenGL ES?

text:
# Question
Title: Fastest way to draw quads in OpenGL ES?
I am using OpenGL ES 2.0 I have a bunch a quads to be drawn, would love to be able to have to pass only 4 vertices per quad as if I were using GL\_QUADS, but basically I just want to know the best way of drawing a bunch of separate quads.

So far what I've found I could do:

* GL\_TRIANGLES(6 vertices per quad)
* Degenerate GL\_TRIANGLE\_STRIP(6 vertices per quad)

Possibilities I've found:

* GL\_TRIANGLE\_STRIPS with a special index value that resets quad strip(this would mean 5 indexes per quad, but I don't think this is possible is OpenGL ES 2.0)

# Answer
Just use index buffer and GL\_TRIANGLES. In this case you need 4 vertices + 6 indices per quad (6 additional indices may sound large overhead but in reality it is not - once you have constructed your index buffer you don't have to touch it again). See this page for more information (search for glDrawElements)

Simple example code:

```
GLfloat vertices[] = {-1, -1, 0, // bottom left corner
                      -1,  1, 0, // top left corner
                       1,  1, 0, // top right corner
                       1, -1, 0}; // bottom right corner

GLubyte indices[] = {0,1,2, // first triangle (bottom left - top left - top right)
                     0,2,3}; // second triangle (bottom left - top right - bottom right)

glVertexPointer(3, GL_FLOAT, 0, vertices);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices);

```

Also, if you are drawing just one quad you need only 4 vertices to draw it with triangle strips (as shown in wikipedia) but I guess you already knew this.
> 40 votes

# Answer
Using index buffers isn't *necessarily* faster, as indicated in the Apple docs, "For best performance, your models should be submitted as a single unindexed triangle strip using glDrawArrays".

So, while a `GL_TRIANGLE_STRIP` will do it in 4 vertices without needing an index buffer, and you *can* use an index buffer, it's pretty lame to try to "save" repeating *2 vertices*. For this reason, *I'd suggest you draw 2 separate `GL_TRIANGLES` and repeat the 2 vertices on the diagonal*.
> 7 votes

# Answer
The big gain on desktop is to move the data into GL\_STATIC\_DRAW VBOs. Presumably this is true on iPhone's MBX GPU too.
> 1 votes

# Answer
I thought I might add that, at least with triangle lists, one might prefer to use the ordering `{ 0,1,2,0,2,3 }` over the more 'typical' ordering `{ 0,1,2,2,3,0 }` as it puts `0` as the first vertex in both triangles.

Combined with `GL_FIRST_VERTEX_CONVENTION`, this allows for the 0th vertex to dictate flat-shaded attributes for the whole quad, which is somewhat useful in cases where the whole quad can be defined by one property i.e. color.
> 1 votes

# Answer
Using `GL_TRIANGLE_FAN` for a quad uses 4 vertices, not 6.
> 0 votes

---
Tags: opengl, 3d, iphone, android, shaders
---