# Question
Title: Is there a way to display navmesh agent path in Unity?
I'm currently making a prototype for a game I plan to develop. As far as I did, I managed to set up the navigation mesh and my navmeshagents.

I would like to display the path they are following when `setDestination()` is fired.

I did some researches but didn't find anything about it.

EDIT 1 : So I instantiate an empty object with a LineRenderer and I have a line bewteen my agent and the destination. Still I've not all the points when the path has to avoid an obstacle. Furthermore, I wonder if the agent.path does reflect the real path that the agent take as I noticed that it actually follow a "smoothier" path.

Here is the code so far :

```
GameObject container = new GameObject();
container.transform.parent = agent.gameObject.transform;
LineRenderer ligne = container.AddComponent<LineRenderer>();
ligne.SetColors(Color.white,Color.white);
ligne.SetWidth(0.1f,0.1f);
//Get def material

ligne.gameObject.renderer.material.color = Color.white;
ligne.gameObject.renderer.material.shader = Shader.Find("Sprites/Default");
ligne.gameObject.AddComponent<LineScript>();
ligne.SetVertexCount(agent.path.corners.Length+1);
int i = 0;
foreach(Vector3 v in p.corners)
{
    ligne.SetPosition(i,v);
    //Debug.Log("position agent"+g.transform.position);
    //Debug.Log("position corner = "+v);
    i++;
}
ligne.SetPosition(p.corners.Length,agent.destination);
ligne.gameObject.tag = "ligne";

```

So How can I get the real coordinates my agent is going to walk throught ?

# Answer
**It's actually really simple.** First you put a line renderer component on your nav mesh agent object. If you notice, there is an array called positions. So if you attach the following script to your nav mesh agent, it will create a path between the nav mesh agent's origin and the destination.

```
var line : LineRenderer; //to hold the line Renderer
var target : Transform; //to hold the transform of the target
var agent : NavMeshAgent; //to hold the agent of this gameObject

function Start(){
    line = GetComponent(LineRenderer); //get the line renderer
    agent = GetComponent(NavMeshAgent); //get the agent
    getPath();
}

function getPath(){
    line.SetPosition(0, transform.position); //set the line's origin

    agent.SetDestination(target.position); //create the path
    yield WaitForEndOfFrame(); //wait for the path to generate

    DrawPath(agent.path);

    agent.Stop();//add this if you don't want to move the agent
}

function DrawPath(path : NavMeshPath){
    if(path.corners.Length < 2) //if the path has 1 or no corners, there is no need
        return;

    line.SetVertexCount(path.corners.Length); //set the array of positions to the amount of corners

    for(var i = 1; i < path.corners.Length; i++){
        line.SetPosition(i, path.corners[i]); //go through each corner and set that to the line renderer's position
    }
}

```

So that will create a path in the game view.

Hope this helps.
> 14 votes

# Answer
Ok I found a solution, Might not be the best but still a solution.

First, instantiate a game object with a line renderer and attach it to the agent :

```
NavMeshAgent agent = g.GetComponent<NavMeshAgent>();
agent.SetDestination (getDestination(hit.point+offset));
agent.CalculatePath(getDestination(hit.point+offset),agent.path);
GameObject container = new GameObject();
container.transform.position = agent.transform.position;
container.transform.parent = agent.gameObject.transform;

LineRenderer ligne = container.AddComponent<LineRenderer>();
ligne.SetColors(Color.white,Color.white);
ligne.SetWidth(0.1f,0.1f);
//Get def material
ligne.gameObject.renderer.material.color = Color.white;
ligne.gameObject.renderer.material.shader = Shader.Find("Sprites/Default");
ligne.gameObject.AddComponent<LineScript>();
ligne.gameObject.tag = "ligne";
ligne.enabled = false;

```

And then in the LineScript script :

```
float dist=this.transform.parent.GetComponent<NavMeshAgent>().remainingDistance;
if (dist != Mathf.Infinity && this.transform.parent.GetComponent<NavMeshAgent>().pathStatus == NavMeshPathStatus.PathComplete && this.transform.parent.GetComponent<NavMeshAgent>().remainingDistance == 0)
        Destroy (gameObject);

this.GetComponent<LineRenderer>().SetVertexCount(this.transform.parent.GetComponent<NavMeshAgent>().path.corners.Length);
int i = 0;
foreach(Vector3 v in this.transform.parent.GetComponent<NavMeshAgent>().path.corners)
{
    this.GetComponent<LineRenderer>().SetPosition(i,v);
    //Debug.Log("position agent"+g.transform.position);
    //Debug.Log("position corner = "+v);
    i++;
}
if (this.GetComponent<LineRenderer> ().enabled == false)
    this.GetComponent<LineRenderer> ().enabled = true;

```
> 2 votes

# Answer
```
using UnityEngine;
using System.Collections;

public class PathUtils : MonoBehaviour {
private NavMeshAgent agent;
private Color c = Color.white;
public void Start() {
    agent = gameObject.GetComponent<NavMeshAgent> ();
}

public void Update() {
    StartCoroutine(DrawPath(agent.path));
}

IEnumerator DrawPath(NavMeshPath path) {
    yield return new WaitForEndOfFrame();
    path = agent.path;
    if (path.corners.Length < 2)
        return;
    switch (path.status) {
    case NavMeshPathStatus.PathComplete:
            c = Color.white;
            break;
    case NavMeshPathStatus.PathInvalid:
            c = Color.red;
            break;
    case NavMeshPathStatus.PathPartial:
            c = Color.yellow;
            break;
    }

    Vector3 previousCorner = path.corners[0];

    int i = 1;
    while (i < path.corners.Length) {
        Vector3 currentCorner = path.corners[i];
        Debug.DrawLine(previousCorner, currentCorner, c);
        previousCorner = currentCorner;
        i++;
    }

}
}

```

Edit: I had problems achieving this goal because the `path.corner` numbers were wrong. You have to wait until `EndOfFrame` otherwise you get an incomplete path.
> 2 votes

# Answer
This is a really easy way to render the actual path of `NavMeshAgents` (but note that these Gizmos are only drawn in the Scene windows, not the actual Game window).

Use `OnDrawGizmos`!

It's a really useful method you can fill out on any `MonoBehaviour`, and it gets called automatically, just like `Start` and `Update`, if it exists in your script.

```
private void OnDrawGizmos()
    {
        if (agent.destination != null)
        {
            Gizmos.color = Color.white;
            {
                // Draw lines joining each path corner
                Vector3[] pathCorners = agent.path.corners;

                for (int i = 0; i < pathCorners.Length - 1; i++)
                {
                    Gizmos.DrawLine(pathCorners[i], pathCorners[i + 1]);
                }

            }
        }
    }

```

Just make sure you provide a reference to your agent.

=====

Here's some other examples of things you can do with `OnDrawGizmos`:

You can do things like:

* draw a cube marker at the agent's destination point.
* draw a line from your agent to their destination.

```
private void OnDrawGizmos()
    {
        if (agent.destination != null)
            {
                Gizmos.color = Color.magenta;
                Gizmos.DrawCube(agent.destination, new Vector3(0.2f, 0.6f, 0.2f));
                Gizmos.DrawLine(agent.destination, transform.position + (Vector3.up * 1.5f));
            }
     }

```

What I like about it is that it's very quick and easy to add, as you don't need to deal with game objects or components. Just draw these things straight to the scene window without much fluffing around.

But again, if you want these things to appear in Game view, you'll need to do something else!
> 1 votes

---
Tags: unity, path-finding
---


# Question
Title: Why do my axis mappings to remap the MoveForward and MoveRight keys not seem to have any effect in-game on Unreal Editor 4.27.2?
Since I have an azerty keyboard instead of a qwerty one I'm trying to remap wasd to zqsd for the in-game playing in Unreal Editor 4.27.2.

I've started a new blank c++ project with starter content. Then I went to Project Settings -\> Engine - Input -\> Axis Mappings.

This is what my new axis mappings look like:

However, no matter what, when clicking Play, the camera movements will only respond to wasd and completely ignore the axis mappings which I put there. I build, compiled and tried restarting the editor but to no avail. What am I missing?

# Answer
You haven't created anything for the program to inhabit. Whether this is a pawn or a character, you need something in your Game Mode -\> Default Pawn Class, otherwise what you're moving around is just the level camera.
> 0 votes

# Answer
Eazy way, you can go to your character detail settings, search 'auto possess player', then change to player0.
> 0 votes

---
Tags: unreal-4, input, unreal, axis
---


# Question
Title: What is the best way to handle more bone weights than allowed in code?
I am currently attempting to incorporate animated models in my game engine, using Assimp to load the models. I can load and render the static model just fine, but when I try to enable the animation, it basically explodes. I can tell the animation is there and running smoothly, though something isn't working properly.

I have many things to explore in solving the issues at hand, but one in particular is troubling: The code is written to handle 4 bone weights, mostly because it appears to be fairly standard and is easy to pass to the shader. But the model has more than 4 weights per vertex.

So my question is this: What is the best way to handle having more bone weights than the code/shader can handle? Should I run through all the weights and pick the top 4 and adjust them to add up to 1? I could probably code for more weights, but then where does it end?

# Answer
So I actually went with an "all of the above" solution to this, and it works perfectly. I went with keeping the top 8 weights and normalize them to 1. This was a good idea anyway, because I found that the weights aren't normalized to 1 in many models.
> 0 votes

---
Tags: directx11, skeletal-animation, assimp
---


# Question
Title: Increased CPU usage when rendering sprites
I'm creating a game in modern OpenGL, C++ but I'm having problems with optimization. Whenever I render the sprites the CPU usage starts to increase.

Code:

```
void GameController::Render() {
    shaders.Use();
    glBindVertexArray(vao);

    for (const auto& layers : chuncks) {
        for (const auto& layer : layers) {
            const bool isVisible =
                (layer.position.x + layer.size.x >= camera->pixelRect.min().x) &&
                (layer.position.x - layer.size.x <= camera->pixelRect.max().x) &&
                (layer.position.y + layer.size.y >= camera->pixelRect.min().y) &&
                (layer.position.y - layer.size.y <= camera->pixelRect.max().y);

            if (isVisible) {
                textures[layer.id - 1]->Usage(GL_TEXTURE0);

                shaders.SetUniform("textureSampler", 0);
                shaders.SetUniform("projection", camera->projectionMatrix);
                shaders.SetUniform("translate", layer.position);
                shaders.SetUniform("scale", layer.size);

                glDrawArrays(GL_QUADS, 0, 4);

                textures[layer.id - 1]->Unused();
            }
        }
    }
    glBindVertexArray(0);
    shaders.Unuse();
}

```

CPU usage is starting to get unusually high. I've thought about implementing separate threads, one for updating and one for rendering, but I don't know if it will be efficient.

# Answer
> 3 votes
Without refactoring the code the first thing would be to avoid repeatedly setting uniforms that don't change such as:

```
shaders.SetUniform("textureSampler", 0);
shaders.SetUniform("projection", camera->projectionMatrix);

```

And put those outside the loop after the shader is selected.

---

But to really fix the performance issue you need to write all sprites to a VBO rather than issue a draw call for each single sprite, either pre-calculate the position & scale or write them as vertex attribute for the vertex shader to calculate, and let the GPU deal with clipping.

You will also need to put all your individual sprite textures into a single texture atlas (or multiple if they won't fit) you can also use texture arrays for more options https://www.khronos.org/opengl/wiki/Array\_Texture

If you have under 100 million quads you can easily let a modern GPU clip them out and still reach 60 fps. Entirely deleting the isVisible check. Frustum culling is only worth doing on the CPU for entire level section batches for 2D sprites.

You can use **Instancing** to write the **position** and **scale** to a separate VBO that will repeat 4 (or 6 for 2 triangles) times so you only need to write each value once.

```
glVertexAttribDivisor(x, 6);

```

This way you can reduce the amount of data transferred to the GPU each frame by making the updated VBO smaller.

See the official OpenGL site for more : https://www.khronos.org/opengl/wiki/Vertex\_Specification

glDrawElementsInstanced - https://registry.khronos.org/OpenGL-Refpages/gl4/html/glDrawElementsInstanced.xhtml

glDrawArraysInstanced - https://registry.khronos.org/OpenGL-Refpages/gl4/html/glDrawArraysInstanced.xhtml

These functions are specifically meant to draw multiple copies of identical (or similar) objects efficiently.

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


# Question
Title: How do I mix an image with a specified color?
I have some images of static objects using per-pixel alpha (trees, rocks) for a background. In order to make them look a bit more natural, I want to create some kind of atmospheric fog, which means the farther away the object is, the more bluish tint it has.

I have the RGB color of a fog \[108, 119, 135\] (which appears to be a color of my image if it is totally far away) and I need to mix this color with my image somehow depending on the object's specified distance (which I'm mapping to percentage of fog).

If I had to mix solid colors, I'd just find the difference between the original color and 100% fog color, multiply this by the distance percentage, and subtract this from the original color. E.g. I have a value 208 in original red channel, and to make it 30% foggy I do `208-(208-108)*0.3 = 178`.

But I have no clue how to do this with an image that has per-pixel alpha. Blitting original image and then fog color with solid transparency doesn't work because I'd get a square of color over my image instead of respecting the shape of the image's alpha.

# Answer
> 2 votes
Code:

```
import sys, pygame

def create_image_surface_with_fog(img,fog_color,fog_rate):
    _,_,w,h = img.get_rect()
    img_color = [(1-fog_rate) * 255] * 3
    fog_color = [x*fog_rate for x in fog_color]
    new_surface = pygame.Surface((w,h), pygame.SRCALPHA, 32)
    new_surface.blit(img,img.get_rect())
    new_surface.fill(img_color,img.get_rect(),special_flags=pygame.BLEND_MULT)
    new_surface.fill(fog_color,img.get_rect(),special_flags=pygame.BLEND_RGB_ADD)
    return new_surface

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((640, 480))

    character_img = pygame.image.load("character.png")
    background_img = pygame.image.load("background.png")

    fog_color = (108, 119, 135)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()

        screen.fill((0, 0, 0))
        screen.blit(background_img,background_img.get_rect())

        character_surface = create_image_surface_with_fog(character_img,fog_color,0.5)
        screen.blit(character_surface, (0, 0))

        pygame.display.flip()

```

Result when fog\_rate= `0, 0.5, 1`:

Explain:

The smallest unit in which color blend occurs is the `pygame.Surface`. If you want it to respect the alpha of the original image, you need to draw the original image onto a separate surface. Then draw this surface to the screen surface:

```
def create_image_surface_with_fog(img,fog_color,fog_rate):
    new_surface = pygame.Surface((w,h), pygame.SRCALPHA, 32)
    ...
    return new_surface
character_surface = create_image_surface_with_fog(character_img,fog_color,1)
screen.blit(character_surface, (0, 0))

```

For color mixing calculations, the calculation formula can be reorganized to reduce the number of drawings:

```
208-(208-108)*0.3 = (1-0.3)*208 + 0.3*108

```

So we only need to draw the original image once, `BLEND_MULT` once, and `BLEND_RGB_ADD` once:

```
new_surface.blit(img,img.get_rect())
new_surface.fill(img_color,img.get_rect(),special_flags=pygame.BLEND_MULT)
new_surface.fill(fog_color,img.get_rect(),special_flags=pygame.BLEND_RGB_ADD)

```

---
Tags: python, pygame, color, blending, fog
---


title: Why won't my bullets shoot?

text:
# Question
Title: Why won't my bullets shoot?
I am making a top-down shooter in Unity (following a Brackeys tutorial for the top-down shooting mechanic). When I press the left mouse button a bullet prefab spawns, as it should, however there is no force applied to the bullet. As you will be able to see in the code, I have applied force to the bullet, I am not sure why it won't work. Any ideas guys? Thank you in advance!

This is my shooting script:

```
#region Variables
// floats
private float bulletForce = 130f;

// bools

// rigidbodies
private Rigidbody2D rb = null;

// transforms
public Transform firePoint = null;

// game objects
public GameObject bulletPrefab = null;
private GameObject bullet = null;
#endregion
#region Awake
// called before the script is initialised
private void Awake()
{

}
#endregion
#region Update
// called ever frame - used for checking for input
private void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        Shoot();
    }
}
#endregion
#region FixedUpdate
// called at a fixed time - every 0.2 seconds - used for physics
private void FixedUpdate()
{

}
#endregion
#region Method - Shoot
// method to spawn bullet prefab and shoot bullet
private void Shoot()
{
    // spawn the bullet prefab at the position of fire point and rotate the prefab bullet to match the rotation of the player - name this newly created bullet by storing it in variable named bullet
    bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
    // store rigidbody on bullet game object in rb variable
    rb = bullet.GetComponent<Rigidbody2D>();
    // add force to the bullet - impulse makes the bullet fly straight away - also in this line of code i get the angle offset variable from the player controller script
    rb.AddForce((firePoint.forward * gameObject.GetComponent<PlayerController>().angleOffset) *  bulletForce, ForceMode2D.Impulse);
}
#endregion

```

}

This is my PlayerController script:

```
#region Variables
// floats
private float moveSpeed = 10f;
private float angle = 0f;
public float angleOffset = 270f;

// bools

// rigidbodies
private Rigidbody2D rb = null;

// vector2s
private Vector2 movement = Vector2.zero;
private Vector2 mousePos = Vector2.zero;
private Vector2 lookDirection = Vector2.zero;

// cameras
public Camera cam = null;
#endregion
#region Awake
// called before the script is initialised
private void Awake()
{
    // store rigidbody component in rb variable
    rb = GetComponent<Rigidbody2D>();
}
#endregion
#region Update
// called ever frame - used for checking for input
private void Update()
{
    // listen for horizontal input from the player - a and d or left arrow key and right arrow key
    movement.x = Input.GetAxis("Horizontal");
    // listen for vertical input from the player - w and s or up arrow key and down arrow key
    movement.y = Input.GetAxis("Vertical");

    // find the mouse position, then convert the pixel position to world point and store that in a variable
    mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
#endregion
#region FixedUpdate
// called at a fixed time - every 0.2 seconds - used for physics
private void FixedUpdate()
{
    // move the player to the desired position - fixed delta time happens every time fixed update is called
    rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);

    // find the direction the player needs to look by subtracting two vectors from each other
    lookDirection = mousePos - rb.position;
    // this finds the angle needed to calculate where the player should look then converts it to degrees
    angle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg - angleOffset;
    // rotate the player using the above maths
    rb.rotation = angle;
}
#endregion

```

}

The bullet just spawns Infront of the sprite and doesn't move.

# Answer
> 2 votes
It should have been .up instead of forward, because forward is for 3D. Then `*-1` because I want it to go in the opposite direction.

---
Tags: unity, 2d, shooter, shoot-em-up, top-down
---


# Question
Title: How to make redirected player movement respond to same key?
I have a 2d game (Godot 4) with different rooms with portals to go between them, and some portals redirect the direction of the player while still holding the same key. I have *that* working so far, but when I release the key, it keeps moving in the redirected direction. How can I make sure the player stops when it's supposed to?

Movement:

```
if Input.is_action_just_pressed("left"):
    velocity.x = -1
    $Sprite2D.flip_h = false
elif Input.is_action_just_pressed("right"):
    velocity.x = 1
    $Sprite2D.flip_h = true
if Input.is_action_just_released("left"):
    velocity.x = max(velocity.x,0)
if Input.is_action_just_released("right"):
    velocity.x = min(velocity.x,0)

if Input.is_action_just_pressed("up"):
    velocity.y = -1
elif Input.is_action_just_pressed("down"):
    velocity.y = 1
if Input.is_action_just_released("up"):
    velocity.y = max(velocity.y,0)
if Input.is_action_just_released("down"):
    velocity.y = min(velocity.y,0)

```

Warp between rooms:

```
func warp(real_dir,dir): # ULDR
    var odd = dir % 2 == 1

    var vpos = position
    var off = -2*MARGIN
    var offw = SIZE - 2*MARGIN

    var diff = player.position - (position + Vector2(SIZE/2,SIZE/2))
    player.position = diff.rotated((real_dir - dir) * PI/2) + position + Vector2(SIZE/2,SIZE/2)

    if dir >= 2:
        off = SIZE + 2*MARGIN
        offw = 2*MARGIN

    if odd:
        vpos = Vector2(vpos.y,vpos.x)
        player.position = Vector2(player.position.y,player.position.x)

    if warps[dir] == "":
        player.position.y = vpos.y + off
    else:
        var level_pos = locate_level(warps[dir])
        if odd:
            level_pos = Vector2(level_pos.y,level_pos.x)
        player.position.x += level_pos.x - vpos.x
        player.position.y = level_pos.y + offw

    if odd:
        player.position = Vector2(player.position.y,player.position.x)

    player.velocity = player.velocity.rotated((real_dir - dir) * PI/2)

    player_inside = not warps[dir] == name

```

# Answer
Not tested, but you could try looking at which keys the player is pressing when they're warping and setting the velocity x/y values to 0 when they're released depending on how much the movement is rotated.

For example, if the player is holding the "right" key when going into the right portal and it rotates it to go up, you could link releasing the "right" key with resetting the y velocity.

Also, if you're going diagonally, you could record two values, like "up" and "right", and then link them to resetting the x and y velocities. However, if you rotate 180 degrees (PI radians), then the axes will remain the same.

Hope this helps!
> 2 votes

---
Tags: 2d, movement, input, godot-4
---


# Question
Title: Euler Angle X is wrong after using Quaternion.LookRotation
I have an direction that I want the local player hub & camera to rotate at. The game handles this by using euler angles which Y represents the hub rotation on the horizontal axis & X represents the camera rotation on the vertical axis.

The min-max range for vertical is -88 to 88 & min-max range for horizontal is 0 to 360

Here is the code I am using the create euler angles that will look onto the direction

```
Vector2 CalcEuler(Vector3 dst, Vector3 src)
{
    //dst is target position, src is maincamera position
    Quaternion quat = Quaternion.LookRotation((dst -
                                            src), Vector3.right);
    Vector3 euler = quat.get_eulerAngles();
    return { euler.y, euler.x };
}

```

the horizontal axis(euler.y) returned from CalcEuler is perfect and rotates the hub to lock onto the specified direction. However the vertical axis(euler.x) returned from CalcEuler only works if the direction.Y value is the same as src.Y. If it isnt then itll shoot up into really high numbers past 200 and even sometimes at 359.99.

What could I be doing wrong?

EDIT: I found something some guy did on github for his rotation. After doing Quaternion.Lookrotation he did this

```
euler.x = (src.y < dst.y) ? (-360.f + euler.x) : euler.x;

```

however this does not change anything for me

SOLVED: Both answers fix the problem

# Answer
If you want to enforce angular limits, keep it in terms of angles from the start. Don't count on an automatic conversion from quaternions to Euler angles to give you angles in a specific range, because there are many Euler angle triplets corresponding to any one quaternion, and any mapping we pick will be wrong for at least one use case.

```
public static Vector2 GetClampedEuler(Vector3 lookTarget, Vector3 lookOrigin, float maxPitch) {
    Vector3 direction = (lookTarget - lookOrigin).normalized;

    // Get rotation in horizontal plane in range -180...180
    float yaw = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
    // Remap to 0...360
    if (yaw < 0f) yaw += 360f;

    // Get angle below horizontal in range -90...90
    float pitch = Mathf.Asin(-direction.y) * Mathf.Rad2Deg;

    // Enforce pitch limits
    return new Vector2(yaw, Mathf.Clamp(pitch, -maxPitch, maxPitch));
}

```
> 1 votes

# Answer
If you want to isolate the heading of a look direction then zero out the up and use the atan2 function directly.

```
vector3 dir = dst - src;
heading = atan2(dir.y, dir.x); //assuming the up/down is along z and 0 heading is along x, swap axis as appropriate
pitch = atan2(hypot(dir.x, dir.y), dir.z);

```

Though you will need to take care when hypot(dir.x, dir.y) is very small, aka when the pitch angle would exceed the bounds.

Though frankly I dislike computing back to angles using the arctan/arccos just to be put into a rotate which will put it straight into a cos and sin.

instead you can just pass the look direction directly through to whatever does the rotating hand have it figure out the correct transform operation based on just `(dst - src).normalized()`
> 0 votes

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


title: How does the VisibilityEnabler work?

text:
# Question
Title: How does the VisibilityEnabler work?
I'm confused about the use of the Visibility enabler node in Godot. I've read the documentation and tried it out both stand-alone and as a child without success.

I set the parent to print a `String` during its `_process` function. Despite adding the enabler, it continued to print despite being off screen.

How do I set it up so that It actually disables anything?

# Answer
I think what you disabled was the canvas visibility. That just disables the render's process for the nodes and its childs. If you really want to stop the `_process(delta)` method. You must find the Stop property, which by default is **inherited**, and set it to **stop**.

You can also stop the call of process by setting `set_process` to false through the script.
> 2 votes

# Answer
Read the documentation on `VisibilityEnabler` again:

> The VisibilityEnabler will disable RigidBody and AnimationPlayer nodes when they are not visible. It will only affect other nodes within the same scene as the VisibilityEnabler itself.

It has nothing to do with `_process`.

---

If you want to disable `_process`, you can use `set_process(false)` on whatever `Node` you want to disable it (you can also disable other methods), which you might do from a script attached to a `VisibilityNotifier` handling its own signals.

*Sadly we cannot fully disable a script in Godot 3.x. In Godot 4.x you would use `process_mode` for that. The equivalent of `process_mode` in Godot 3.x is `pause_mode` but there isn't an option to always stop (The "Stop" option makes the `Node` stop when the scene tree is `paused`).*

---

For reference in Godot 4 the role of `VisibilityEnabler` is taken by `VisibleOnScreenEnabler3D`, and the role of `VisibilityNotifier` is taken by `VisibleOnScreenNotifier3D`, and of course there are 2D counterparts as well.

*Yes, I see this is an old question.*
> 1 votes

---
Tags: godot, documentation, visibility-determination
---


# Question
Title: Test if a point is inside a 3D cuboid, given the 8 corner positions, through code
I'm trying to find to obtain if a point, let's call it "v" is inside a cuboid which every corner position named P1 to P8

I am trying to achieve this and in fact found some answers in some other stacks, i'll place them here:

https://math.stackexchange.com/questions/923932/test-if-a-point-is-inside-a-3d-cuboid?rq=1

https://math.stackexchange.com/questions/4497343/point-in-irregular-3d-cuboid?noredirect=1&lq=1

https://math.stackexchange.com/questions/1472049/check-if-a-point-is-inside-a-rectangular-shaped-area-3d?rq=1

The thing is, i'm not too keen in mathematics so i'm kinda lost in this one, could some of you answer me which one of those is better and how to write it code-wise?

Any languaje will do, but csharp would be appreciated, i'm trying to learning to read this ecuations but i'm kinda lost and i don't know where to start, i also apreciate if you take the time to explain in human terms what that maths are doing.

I also found this question: fast 3d point -\> cuboid volume intersection test

But i'm kinda looking for something more practical than doesn't vanish in the future of the internet to have here, in the StackExchange for future reference.

If this exist somewhere in this stack or somewhere else, i would love to hear where.

Thank you

# Answer
If you can guarantee that the 8 points form a prism with pairs of opposite faces parallel (even if the corners aren't perpendicular), then we can simplify this significantly.

We'll construct a transformation matrix that maps a standardized cube to this prism, then invert that matrix, and check if the test point transformed by that matrix lies inside the standard cube.

We'll make a 3x3 matrix M whose columns are:

* P4 - P1 (width)
* P5 - P1 (height)
* P2 - P1 (depth)

You can confirm that taking any point in the cube formed by three coordinates in the range 0...1 and multiplying it by this matrix then adding P1 gives you a point in your original prism.

Then we can invert the matrix (use the matrix inverse function of whatever C# vector library you're using) and multiply your test point minus P1 by this inverse. If the test point were inside the prism, the output will have all three coordinates in the range 0...1 (with 0 and 1 being the outer faces). Otherwise, the point is outside the prism.

The advantage of this route is you can compute the inverse just once each time the prism is transformed, then re-use it to test many points against it cheaply. Each test is just one vector subtraction, three dot products, and six float comparisons.

Here's a C#-style example, assuming a sufficiently friendly vector math and matrix API:

```
public struct Cuboid {

    Matrix3x3 _matrix;
    Matrix3x3 _inverse;
    Vector3 _corner;

    // You can use 8 named arguments instead of an array,
    // I just got tired of typing on my phone.
    public Cuboid(Vector3[] points) {
       _corner = points[0];
       _matrix = new Matrix3x3(
                   points[3] - points[0], // left column
                   points[4] - points[0], // middle column
                   points[1] - points[0]  // right column
        );
        _inverse = _matrix.inverse;
    }

    public bool Contains(Vector3 point) {
        // Remap point into "standard cube space".
        Vector3 standard = _inverse * (point - _corner);

        // Check if the remapped point lands inside
        // the 0...1 range of the standard cube.
        return (standard.x >= 0) & (standard.x <= 1)
             & (standard.y >= 0) & (standard.y <= 1)
             & (standard.z >= 0) & (standard.z <= 1);
    }

}

```

Note that even storing the matrix and inverse (for scale/rotation/skew) plus a corner (for translation), this data structure is still more compact (21 floats) than storing all 8 corner points (24 floats) and you can still extract all 8 corner points on demand. E.g. `point[1] = _corner + _matrix.columns[1]`

This method does not work if your 8-vertex object is not an affine transformation of a cube (i.e. if one of its faces is not a plane quadrilateral / not parallel to its opposite face).
> 0 votes

---
Tags: collision-detection, mathematics, position
---


# Question
Title: Custom Mesh with single texture - suspected uv issues
I created a script that allows me to change my meshes configuration while the app is running. I don't know meshes all that well and am running into issues with texturing. How do I need to set my uv's so that my texture shows correctly? There's likely other issues too so please bear with me.

*custom 10x10 mesh is on the left, standard plane right*

*script*

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

public class UpMesh : MonoBehaviour
{
    public int width = 1;
    public int height = 1;

    private Vector2 _lastSize = Vector2.zero;
    private Mesh mesh;

    private void Start() {
        _lastSize.x = width;
        _lastSize.y = height;
    }

    void OnValidate() {
        if(Application.isPlaying != true) return;
        if(width == _lastSize.x && height == _lastSize.y) return;

        MakeMesh();
    }

    void MakeMesh() {

        mesh = GetComponent<MeshFilter> ().mesh;

        Vector3[] vertices = new Vector3[4 * width * height];
        Vector4[] tangents = new Vector4[4 * width * height];
        Vector2[] uv = new Vector2[4 * width * height];
        int[] triangles = new int[6 * width * height];

        var uvH = 1f / height;
        var uvW = 1f / width;

        for(int col = 0; col < width; ++col) {
            for(int row = 0; row < height; ++row) {
                int index = row * width + col;
                float x = transform.position.x - width/2;
                float y = transform.position.y;
                float z = transform.position.z + height/2;

                vertices[index*4 + 0] = new(x + col,         y,     z - row);
                vertices[index*4 + 1] = new(x + col+1,       y,     z - row);
                vertices[index*4 + 2] = new(x + col+1,       y,     z - row-1);
                vertices[index*4 + 3] = new(x + col,         y,     z - row-1);

                tangents[index*4 + 0] = new(1f, 0f, 0f, -1f);
                tangents[index*4 + 1] = new(1f, 0f, 0f, -1f);
                tangents[index*4 + 2] = new(1f, 0f, 0f, -1f);
                tangents[index*4 + 3] = new(1f, 0f, 0f, -1f);

                uv[index*4 + 0] = new(col + col*uvW + uvW,        row + row*uvH);
                uv[index*4 + 1] = new(col + col*uvW,              row + row*uvH);
                uv[index*4 + 2] = new(col + col*uvW,              row + row*uvH + uvH);
                uv[index*4 + 3] = new(col + col*uvW + uvW,        row + row*uvH + uvH);

                triangles[index*6 + 0] = index*4 + 0;
                triangles[index*6 + 1] = index*4 + 1;
                triangles[index*6 + 2] = index*4 + 2;
                triangles[index*6 + 3] = index*4 + 0;
                triangles[index*6 + 4] = index*4 + 2;
                triangles[index*6 + 5] = index*4 + 3;
            }
        }

        mesh.Clear ();
        mesh.vertices = vertices;
        mesh.tangents = tangents;
        mesh.triangles = triangles;
        mesh.uv = uv;
        // mesh.Optimize ();
        // mesh.RecalculateNormals ();

        Debug.Log($"MAKE {height}x{width} v{vertices.Length} t{triangles.Length}");

    }
}

```

*texture*

# Answer
> 2 votes
Here's how to get rid of both the duplicated vertices and the reversed UVs:

```
mesh = GetComponent<MeshFilter> ().mesh;

// "Fencepost" math: one post for each span, plus one at the end.
int vertexCount = (width + 1) * (height + 1);
Vector3[] vertices = new Vector3[vertexCount];
Vector2[] uv = new Vector2[vertexCount];

int[] triangles = new int[6 * width * height];

var uvH = 1f / height;
var uvW = 1f / width;

// Position of vertex zero, at the "top left".
Vector3 corner = transform.position;
corner.x -= width/2f;
corner.z += height/2f;

// First, make the vertices.
int v = 0;
for(int col = 0; col <= width; ++col) {
    Vector3 vertex = corner;
    vertex.x += col;

    for(int row = 0; row <= height; ++row) {
        vertex.z = corner.z - row;

        vertices[v] = vertex;
        uv[v] = new(col*uvW, 1f - row*uvH);
        v++;
    }
}

// Second, sequence the vertices into triangles.
int t = 0;
int stride = height + 1;
for (int col = 0; col < width; col++) {
    // This is the index of the vertex in the top-left corner of this quad.
    int tBase = col * stride;
    for (int row = 0; row < height; row++) {

        // Top-right triangle:
        triangles[t++] = tBase;               // Top-left
        triangles[t++] = tBase + stride;      // Top-right (one column over)
        triangles[t++] = tBase + stride + 1;  // Bottom-right

        // Bottom-left triangle:
        triangles[t++] = tBase;               // Top-left
        triangles[t++] = tBase + stride + 1;  // Bottom-right
        triangles[t++] = tBase + 1;           // Bottom-left
    }
}

```

The backwards UVs were coming from the fact that you were moving the 1st and 4th vertex of each quad to the right, but moving the UVs of the 2nd and 3rd vertex to the right, instead of the 1st and 4th to match the positions, effectively mirroring the texture chunk shown within each quad.

---
Tags: unity, mesh, uv-mapping
---


# Question
Title: Bouncing balls miss collisions, bounce the wrong direction, of lose momentum on one axis when hitting a corner
I am making a 2D game where balls bounce from the edges of the screen, However, there seem to be two types of issues with this kind of bounce method, and every tutorial I checked uses the same method. Even though these issues happen rarely in the game, I created the exact moment they happen, you can see both issues in the video. https://streamable.com/g6fj4u

1. Sometimes, the objects do not recognize the collision between each other, and even if they do, they bounce in the wrong direction.
2. When colliding with the corner, object loses momentum and moves alongside one of the edges

This is the code I am using;

```
private void Awake()
{
    _transform = transform;
    _rigidBody2D = GetComponent<Rigidbody2D>();

    _rigidBody2D.velocity = _moveDirection * _speed;
}

private void FixedUpdate()
{
    _previousVelocity = _rigidBody2D.velocity;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    Vector2 normal = collision.GetContact(0).normal;
    Vector2 reflection = Vector2.Reflect(_previousVelocity, normal).normalized;

    _rigidBody2D.velocity = reflection * _speed;
}

```

# Answer
It appears that your code is fighting with the physics engine about who gets to control the velocity vectors of the balls.

When there is a collision between two rigidbodies, then the Unity physics engine will do the same thing you are doing here: Resolve the collision by calculating the new velocity vectors of the involved rigidbodies. By trying to take its job without telling it, you are confusing the physics engine.

Possible approaches to this problem are:

* Don't try to handle collisions in code. Leave collision resolution completely to the physics engine. You can tweak the collision behavior by assigning a Physics Material 2D to the rigidbodies of the balls and the walls.
* Don't let the physics engine handle the movement. Set the "Body Type" of the Rigidbody 2D components to "Kinematic", so the physics engine is no longer responsible for controlling their movement, and implement your own movement code in `FixedUpdate`.
> 3 votes

# Answer
These issues can be solved by calculating the average normal, instead of the first collision normal.

```
private void HandleCollision(Collision2D collision)
{
    int contactCount = collision.GetContacts(_contacts);
    Vector2 normal = Vector2.zero;

    for (var i = 0; i < contactCount; ++i)
    {
        Vector2 contactNormal = _contacts[i].normal;

        if (Vector2.Dot(_previousVelocity, contactNormal) > 0f)
            continue;

        normal += contactNormal;
    }

    if (normal == Vector2.zero)
        return;

    Vector2 reflection = Vector2.Reflect(_previousVelocity, normal).normalized;

    _rigidBody2D.velocity = reflection * _speed;
    _previousVelocity = _rigidBody2D.velocity;
}

```

There seems to be a third issue, where bounce collision does not share energy like it would in real life, this sometimes results in weird bounces when colliding with another moving object.

You can access the velocity of the collided object and take that into account while doing the calculation, however, for a simple bounce, this would be overkill. It is better to use the unity physics material instead.

We have discussed this topic in the Unity Forum, You can check it out from the link below.

https://forum.unity.com/threads/2d-bounce-has-issues-with-corners-collisions.1516451/#post-9470837
> 1 votes

---
Tags: unity, 2d, physics, collision-resolution
---


# Question
Title: How do I react to a variable having reached a certain value?
I am a new coder and im trying to learn html. i have started working on a clicker game but im trying to figure out how to give a reward when my total clicks var has reached a certain value. the reward would be one "var total-clicks" = 10 have the click value go up so each time you click after that its worth 2 clicks

```
<!DOCTYPE html>
    <html>
     <body>

<p>
    The button was clicked
    <span class="total-clicks"></span>
    times
</p>

<button id="btn1" onclick="addClick()">
    Click Me!
</button>

<script type="text/javascript">
    let clicks = 0;

    function addClick() {
        clicks = clicks + 1;
        document.querySelector('.total-clicks').textContent
            = clicks;
    }

    // Simulate click function
    function clickButton() {
        document.querySelector('#btn1').click();
    }

</script>
</body>
</html>

```

# Answer
If you want to reward the player with additional click power, then it would make sense to make that a separate variable, and use that variable instead of the constant value of `1` when you increase the click count:

```
let clicks = 0;
let click_power = 1;

function addClick() {
    clicks = clicks + click_power;

```

Now your game should still behave as before. But by turning a constant into a variable we created *the possibility* for the player's click power to change over the course of the game.

Now how do we increase the click power? Well, whenever we increase the click count of the player, we need to have some conditional code that only executes if the click count reached a certain level. We can do that with the `if` statement.

```
function addClick() {
    clicks = clicks + click_power;
    if(clicks == 10) {
        click_power = click_power + 1;
    }

```

This simple solution should increase the players click power by 1 the moment they reach 10 clicks. This works for now, but could lead to problems down the road. What if we add more than one way to increase the click power? And what if the player does that before reaching the 10 click threshold? In that case it is possible that `clicks` jumps from `9` right to `11`. It would never be exactly equals to `10`. So the reward for reaching 10 would get skipped. How do we solve that?

Well we could try to increase it when the player reached *or exceeded* 10 clicks:

```
    if(clicks >= 10) {
        click_power = click_power + 1;
    }

```

But this causes another problem. Now the player gets the reward *every time* they click the button after 10 clicks. We have to somehow memorize that the player already received the reward. We can do that with a 3rd variable that keeps track of whether or not the player received the reward and only give it to the player when he hasn't received it yet:

```
let clicks = 0;
let click_power = 1;
let reward_received = false;

function addClick() {
    clicks = clicks + click_power;
    if(clicks >= 10 && reward_received == false) {
        click_power = click_power + 1;
        reward_received = true;
    }

```

Now the player only receives the reward if two conditions are true: They reached or exceeded 10 clicks **and** they didn't receive the reward yet.

Note that if you decide to add more rewards with different conditions, then you are probably going to need a separate variable for each reward. That means you could end up with quite a lot of variables and conditions. There are ways to structure that in a better way. But that's a more advanced topic for another question.
> 1 votes

---
Tags: javascript, html
---


# Question
Title: How to move in 3D space in first person mode?
I have a Camera with Vector3 and also the camera has an angle.

If I use this:

```
hero.position.x += speedX;
hero.position.z += speedZ;

```

works great but as soon as I rotate the camera the "hero" still goes in the same direction. So if I press button W I want the hero to go the way the camera is looking.

I've also tried:

```
hero.position.x += Math.sin(hero.rotation*3.1415/180) * speedX;
hero.position.z += Math.cos(hero.rotation*3.1415/180) * speedZ;

```

But it wont work and I just can walk in a line.

So how do I move in 3D space in first person mode?

# Answer
You need to find a vector that points in the direction the camera is looking and then multiply this vector by your forward movement speed.

So you need to create a Matrix that rotates a Vector x-degrees around the Y-axis. Now I don't know what framework you're using (it just says java in your tags) so I'll just give some sample code that you need to adapt:

```
float degrees = 90; //degrees your camera is rotated along the y-axis
Vector3 forward = new Vector(0,0,-1);
forward = Vector3.Transform(forward, Matrix.CreateRotationY(MathHelper.ToRadians(degrees)));

```

Moving your player can now be done using the above forward vector

```
player.X += speed * forward.Z;
player.Y += speed * forward.Y;
player.Z += speed * forward.Z

```

Now if you're making a FPS you might also want to add strafing, this can be done easily by taking the forward vector, and rotating it another 90 degrees, you then have the 'left' vector which you can add as above the player's position where speed is 1 when 'strafe-left' is pressed, -1 when 'strafe-right' is pressed and 0 when nothing is pressed

You can also get the left vector by using the cross vector of the forward vector and the up vector (0,1,0).

*In my example x is left-right, y is up-down, z+ screen to you z- screen to 'inside' of screen.*

Edit: important note, you should always calculate a new forward vector every frame, don't re-use it and apply new rotations to the forward vector since small errors, that eventually become large errors, will creep in.
> 0 votes

# Answer
Do you have a vector to the "look" point?

If so, just increase the player position by a vector **speed\*(eyePositionToLookPoint)**

```
eyePositionToLookPoint = look - eye ;
eyePositionToLookPoint.normalize() ;
playerPos += speed*eyePositionToLookPoint ;

```

Be sure to normalize()!
> 0 votes

# Answer
Camera has it's own set of axes. You generally store any two of the three : `camFront`, `camRight` and `camUp` vectors. So, whenever you want to move your camera, you need to move it in these directions in the following way :

```
    /* update position for future use */
    cam->position = vec3_add(cam->position, vec3_mul_scalar(vec3_normalize(vec3_cross(cam->front, cam->up)), dr.x));
    cam->position = vec3_add(cam->position, vec3_mul_scalar(cam->front, dr.z));
    cam->position = vec3_add(cam->position, vec3_mul_scalar(cam->up, dr.y));

```

here `dr` is also a vector, which is the speed with which the camera is moving, more precisely it's the velocity!
> 0 votes

---
Tags: 3d, java, mathematics, algorithm, movement
---


# Question
Title: How can vertex position can be converted to fragment position?
I started learning open gl and graphics programming for a while (im using open tk as im working on c#) so i finally came across lighting where you make the ambient diffusion. Im pretty sure that you need to find the dot product between the direction between the light and the fragment position with the normal. But after a while i was puzzled on how to find the fragment position. If you look at the vertex shader here:

```
out vec3 FragPos;
out vec3 Normal;

void main()
{
    gl_Position = projection * view * model * vec4(aPos, 1.0);
    FragPos = vec3(model * vec4(aPos, 1.0));
    Normal = aNormal;
}

```

(The code is from learnOpengl) it sets the fragpos to the vec3 of each vertex position and pass it to the fragment shader. I mean fragments are the parts where it shows the objects colour right? how could vertex position could be each fragment position. I don't know if i have misunderstood things completely but after a few words in the opengl website it says

"This in variable will be interpolated from the 3 world position vectors of the triangle to form the FragPos vector that is the per-fragment world position. Now that all the required variables are set we can start the lighting calculations." i dont get this phrase.

Also this is my first time posting here so please point out any mistakes if i did any.

# Answer
> 0 votes
After the vertex shader has run for a particular group of vertices, there are a few extra stages that happen automatically before invoking the fragment shader for the resulting fragments:

1. **Primitive assembly**: this step operates on a sequence of three vertices A, B, C that are meant to form a triangle (according to your index buffer or strip/fan topology).

This is where **clipping** happens if the triangle crosses the image plane or goes outside the rasterization bounds, cutting it into triangles that stay in-bounds to avoid nasty projection errors.

This is also where we do **back face culling**, checking the winding order (when we move from A to B to C's on-screen positions, do we arc clockwise or counter-clockwise?) and discarding it if it's wound the wrong way.

Triangles ABC that survive proceed to...
2. **Rasterization**: this step figures out which pixels / fragments of the output buffer triangle ABC touches, that we should draw into in the fragment shading stage. We'll invoke the fragment shader once for each one, but we need to do a little more calculation first to figure out the inputs to use when we call that shading function.

We assign each fragment the triangle touches a barycentric coordinate (a, b, c) where a+b+c=1. A fragment exactly at the screen position of vertex A gets a=1, b=0, c=0; one exactly at vertex B gets a=0, b=1, c=0. A fragment exactly halfway between vertices A and B *in screen space* gets a=0.5, b=0.5, c=0. A fragment at the exact centroid of the triangle in screen space has a=b=c=1/3.

These can be used as blending weights to form a weighted average between properties set at the three vertices, but we need one more stage to finish the job...
3. **Interpolation**: this step is responsible for taking the values of `out` or `varying` variables set by the vertex shader, and transforming them into the input values to the fragment shader.

To do that, we (usually) need to apply perspective correction to the barycentric coordinates we have for each fragment.

The formula for this uses the screen-space barycentric coordinates a b c we sourced above, and the w component of the `gl_position` from each of A, B, and C (which tells us how far away the vertex is/how much perspective magnifies/shrinks stuff nearby):

$$\begin{bmatrix}a^\prime, & b^\prime, & c^\prime\end{bmatrix} = \frac {\begin{bmatrix}\frac a {A\_w},& \frac b {B\_w}, & \frac c {C\_w}\end{bmatrix}} {\frac a {A\_w} + \frac b {B\_w} + \frac c {C\_w}}$$

Now for each variable \\$v\\$ calculated from the vertex shader, for which we have three values from the three vertices, \\$v\_A\\$, \\$v\_B\\$, \\$v\_C\\$, we calculate a blended value that will be used as input for this fragment as:

$$v\_F = a^\prime v\_A + b^\prime v\_B + c^\prime v\_C$$

That includes the world position of the vertex that we output from the vertex shader you showed as `FragPos`. Before invoking the fragment shader, we use the formula above to calculate a blended world position for *this fragment* based on how close it is to each vertex, taking into account the depth via the w component. That then becomes the input value of `FragPos` that the fragment shader sees.

(I say "usually" above because you can choose other behaviours to achieve certain effects, like keeping the value from one "provoking" vertex constant across the whole triangle and discarding the values from the other vertices, or turning off perspective correction to do the interpolation in screen space. But perspective correction is the default and we rarely need to change it.)

So that's the gory details of how we go from a vertex position written out from the vertex shader to an intermediate fragment position read in by the fragment shader.

Does that clear up how we get per-fragment positions from the initial vertex positions?

---
Tags: opengl, shaders, opentk
---


title: Why wont my code work

text:
# Question
Title: Why wont my code work
I have just started on a new short game and i am trying to figure out how to make a reward when i reach a certain value I expect that the counter starts at zero, and each time the button is clicked it goes up by one, until it reaches 10, then the next time the button is pressed the counter should go up by 2. Instead, I find that clicking the button does not change the displayed count.

```
<!DOCTYPE html>
    <html>
     <body>

<p>
    The button was clicked
    <span class="total-clicks"></span>
    times
</p>

<button id="btn1" onclick="addClick()">
    Click Me!
</button>

<script type="text/javascript">
    let clicks = 0;
    let click_power = 1;
    let reward_recevied = false;

    function addClick() {
    clicks = clicks + click_power;
    if(clicks >= 10 && reward_received == false) {
        click_power = click_power + 1;
        reward_received = true;
    }
}
    function addClick() {
        clicks = clicks + 1;
        document.querySelector('.total-clicks').textContent
            = clicks;
    }

    // Simulate click function
    function clickButton() {
        document.querySelector('#btn1').click();
    }

        </script>
    </body>
</html>

```

# Answer
If you want to increase the first 10 times the variable clicks + 1, and after 10, clicks + 2 you need to make sure that the names of the variables in the code are `reward_received` everywhere and write the code for the `addClick()` function once.

In your code you overwrite `addClick()` function by writing it a second time.

You can view errors in your javascript if you open the HTML file in the browser by pressing `F12`.

Here is probably the code you wanted:

```
<!DOCTYPE html>
<html>
    <body>
        <p>
            The button was clicked
            <span class="total-clicks"></span>
            times
        </p>
        <button id="btn1" onclick="addClick()">
            Click Me!
        </button>
        <script type="text/javascript">
            let clicks = 0;
            let click_power = 1;
            let reward_received = false;

            function addClick() {
            clicks = clicks + click_power;
                if(clicks >= 10 && reward_received == false) {
                    click_power = click_power + 1;
                    reward_received = true;
                }
                document.querySelector('.total-clicks').textContent = clicks;
            }
        </script>
    </body>
</html>
```
> 1 votes

---
Tags: javascript, html
---


# Question
Title: How can I instantiate a prefab in a canvas and have it positioned relative to its parent?
I am trying to load, at run time, a UI prefab and have that display on a canvas. I was following the directions found on this forum. I am able to get it to load and display, but it is not showing up correctly, as shown here:

If I manually change the position in the Unity editor, at runtime, then it appears correct, as shown here.

Here's my code:

```
// load the prefab
Object subView = Resources.Load($"prefabs/Tutorial-Info");

// find the attach point (see screen shot for child hierarchy)
GameObject panel = SearchFor("Panel");
var subPanel = Instantiate(subView, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
subPanel.transform.SetParent(panel.transform, false);

```

(`SearchFor` is a function I wrote to find canvas objects by name. It is correctly returning "Panel" object. The code that function is here.)

I am not sure why the prefab instantiated at run time is not appearing where I want it to appear. What should I do?

# Answer
> 1 votes
The correct solution is to use `Instantiate` as follows:

```
Object subView = Resources.Load($"prefabs/Tutorial-Info");
GameObject panel = SearchFor("Attach");
Instantiate(subView, panel.transform);

```

The call to `SetParent` is no longer needed and `position` setting was incorrect to begin with. Please see the comments above for a little more detail on the solution.

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


title: Area2D only detecting body_exited once

text:
# Question
Title: Area2D only detecting body_exited once
I am new to game development, I am practicing by creating a pong game.

I currently have an `Area2D` set up with a signal listening for `body_exited` (the body in question being the ball), it detects the ball exiting and then resets the ball in the middle of the screen. However, it only does this once. If the ball leaves the `Area2D` again, it doesn't fire and reset.

```
extends Node2D

func _on_area_2d_body_exited(body):
    $Ball.StaticBody2D.position = Vector2(550, 325)

```

# Answer
The ball being an static body is odd... I suspect the `Area2D` is not detecting the static body at all, see the issue: Area2D does not detect moving StaticBody2D.

I would like to encourage to change the ball to be either a `CharacterBody2D` (`KinematicBody2D` in Godot 3.x) or a `RigidBody2D`. Your code should be easier to adapt to `CharacterBody2D`/`KinematicBody2D` as you can continue to move it by the same means.

The `RigidBody2D` might save you the code for the ball bouncing (you might want to remove gravity), but you need trickery to teleport it...

Teleporting a `RigidBody2D`:

```
PhysicsServer2D.body_set_state(
    rigid_body_2d.get_rid(),
    PhysicsServer2D.BODY_STATE_TRANSFORM,
    Transform2D.IDENTITY.translated(Vector2(1.0, 2.0))
)

```

*Note: If you are using Godot 3, you would use `Physics2DServer` instead of `PhysicsServer2D`.*

---

*Consider also using areas around the playing field, either using big `RectangleShape2D` or `WorldBoundaryShape2D` (which is intended for this use case).*

---

For advice on which physics body to use consider: When should I use a KinematicBody or a RigidBody for 2D platformer characters?
> 3 votes

---
Tags: 2d, collision-detection, godot, events, gdscript
---


title: Changing the type of an object in Unity

text:
# Question
Title: Changing the type of an object in Unity
I'm new in coding from zero and I have some problems with architecture of classes (project mb?). I have empty room that I need to add “equipment” to it later (change the type of room).  I already have a class with a room that contains types of rooms, but I’m not sure that this is the right solution, since the methods of different room types can be large and really different. Is it possible to somehow separate the classes of different type of room (inherit from an empty room, for example) and how to further work with them (reinitialize the room after selecting equipment?)

```
public enum RoomType
{
   None,
   FirstType,
   SecondType,
   ThirdType
}
public class Room : MonoBehaviour
{
   [SerializeField] private RoomType type = RoomType.None;
}

```

# Answer
It's very difficult to answer questions about how to architect your game when you provide so few details about the game mechanics. You mentioned that your game is similar to Fallout Shelter, so I'll think along those lines.

> Is it possible to somehow separate the classes of different type of room (inherit from an empty room, for example)

Yes, of course you can use class ***inheritance*** as with any C# application. If you aren't familiar with the concept of inheritance, you should learn about this basic principle of OOP before trying to make a game.

In brief, you could do something like this. Note that some methods are stubs with `//...` to indicate "Fill in actual code here".

```
abstract public class Room : MonoBehaviour {
    private List<Character> occupants;
    public IReadOnlyList<Character> Occupants => occupants;
    public void AddCharacter(Character character) { //... }
    public void RemoveCharacter(Character character) { //... }

    abstract public void ApplyEffect();
}

public class Generator : Room {
    [SerializeField] private float powerPerOccupant = 5.0f;
    private float currentPower;

    public float CurrentPower => currentPower;

    public void ConsumePower(float amount) { //... }

    override public void ApplyEffect() {
        currentPower = Occupants.Count * powerPerOccupant;
    }
}

public class Mine : Room {
    [Range(.01f, 1f)]
    [SerializeField] private float chancePerOccupant = .1f;
    private int currentOre;

    public float CurrentOre => currentOre;

    public void ConsumeOre(float amount) { //... }

    override public void ApplyEffect() {
        for (int i = 0; i < Occupants.Count; i++) {
            float v = Random.value;
            if (v < chancePerOccupant) currentOre += 1;
        }
    }
}

```

Alternatively, you can use ***composition*** rather than inheritance. In this case, `Room` would be a separate component rather than the base class:

```
public class Room : MonoBehaviour {
    private List<Character> occupants;
    public IReadOnlyList<Character> Occupants => occupants;
    public void AddCharacter(Character character) { //... }
    public void RemoveCharacter(Character character) { //... }
}

[RequireComponent(typeof(Room))]
abstract public class RoomFunction : MonoBehaviour {
    protected Room room;

    virtual protected void Awake() {
        room = GetComponent<Room>();
        Assert.IsNotNull(room);
    }
}

public class Generator : RoomFunction {
    [SerializeField] private float powerPerOccupant = 5.0f;
    private float currentPower;

    public float CurrentPower => currentPower;

    public void ConsumePower(float amount) { //... }

    override public void ApplyEffect() {
        currentPower = room.Occupants.Count * powerPerOccupant;
    }
}

public class Mine : RoomFunction {
    [Range(.01f, 1f)]
    [SerializeField] private float chancePerOccupant = .1f;
    private int currentOre;

    public float CurrentOre => currentOre;

    public void ConsumeOre(float amount) { //... }

    override public void ApplyEffect() {
        for (int i = 0; i < room.Occupants.Count; i++) {
            float v = Random.value;
            if (v < chancePerOccupant) currentOre += 1;
        }
    }
}

```

> how to further work with them (reinitialize the room after selecting equipment?)

Off the top of my head, there are two potential ways to approach this:

1. Create a prefab for each type of room. When the player converts an empty room into a functional room, destroy the empty room GameObject and instantiate the functional room to replace it. Then of course you will need to update any references to the room.
2. This approach only works with the *composition*-based approach. When the player converts an empty room into a functional room, add the functional room component (such as `Generator`) to the existing empty room, then instantiate any graphics that are part of the room.

Which approach is best? We can't answer that for you; it depends on both personal preference and the specific details of your game.
> 1 votes

# Answer
I'd just use RoomtypeID as a field in your room class.

You can then write a function to populate the items (equipment) in that room based on that ID.

You could store the equipment or items in the room in a list which is also a field of the room.

Here is an example of a room class from my game: (hexType is the ID and you can see a list to contain items and zombies)

```
    public class MapTile
{
    public HexNum Pos =new(0,0);    // Grid Co-ords
    public string SpriteName;       // Name of sprite to show
    public Vector3 SPos;            // World position
    public string Grid;             // String of Co-ords
    public bool Fog;                // True if tile is currently fogged of warn hidden
    public bool CanBeSearched;      // True if it can be searched
    public int HexType;             // The type of Hex it is ie "police Station"
    public int NPC_ID;              // The ID of an NPC stored here

    public List<Zombie> Zombies = new List<Zombie>(); // a list of zombies in the Tile
    public List<Item> Items = new List<Item>(); // a list of Items in the Tile

}

```
> 0 votes

---
Tags: unity, architecture
---


# Question
Title: Sprite chasing a target using move_towards_ip does not move
I'm trying to get a turtle sprite to chase a falling algae sprite utilising Pygame's inbuilt functionality. I have spent many hours reviewing questions and answers and suspect I'm missing some foundational logic as a beginner.

Below is the full code pared down to essential lines only.

No errors are displayed, yet the turtle sprite does not move.

```
import pygame
import random
from random import randint

#GLOBAL VARIABLES
BACKGROUND_COLOR = pygame.Color('black')
screen_width = 1400
screen_height = 1000
win = pygame.display.set_mode((screen_width, screen_height))
display_surface = pygame.display.get_surface()
display_rect = display_surface.get_rect()
clock = pygame.time.Clock()

class Turtle(pygame.sprite.Sprite):
    def __init__(self):
        super(Turtle, self).__init__()
        self.image = pygame.image.load('T10.png').convert_alpha()
        self.x = random.randrange(60, (screen_width - 60), 1)
        self.y = random.randrange(60, (screen_height - 60), 1)
        self.pos = pygame.Vector2(self.x, self.y)
        self.rect = self.image.get_rect()
        self.rect.x = self.x
        self.rect.y = self.y
        self.velocity = 5

    def move(self):
        self.pos.move_towards_ip(algae.pos, self.velocity)

    def update(self):
        self.move()

class Algae(pygame.sprite.Sprite):
    def __init__(self):
        super(Algae, self).__init__()
        self.width = 20
        self.height = 20
        self.surf = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        self.rect = self.surf.get_rect()
        self.x = -5
        self.y = -5
        self.pos = pygame.Vector2(self.x, self.y)
        pygame.draw.circle(self.surf, pygame.Color('green'), (10, 10), 4)
        self.list = []

pygame.init()
pygame.display.set_caption("EvoSim")

turtle = Turtle()
algae = Algae()
turtle_group = pygame.sprite.Group(turtle)
algae_group = pygame.sprite.Group(algae)
all_sprites = pygame.sprite.Group()
collide_list = pygame.sprite.Group(algae)                       #not currently in use

algae_spawn = pygame.USEREVENT + 1                              #algae spawn event
pygame.time.set_timer(algae_spawn, randint(0, 10000))           #algae spawn timer

def main():
    while True:
        clock.tick(15)
        bg = pygame.image.load('bg.png')
        win.blit(bg, (0, 0))
        turtle.rect.clamp_ip(pygame.display.get_surface().get_rect())
        turtle_group.draw(win)
        turtle_group.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == algae_spawn:      #falling algae spawn on random timer
                algae.x = random.randrange(10, win.get_width()-10)
                algae.list.append(pygame.Rect(algae.x, -20, 20, 20))
                collide_list.add(algae)

        for algae.rect in algae.list[:]:
            algae.rect.y += 1
            if algae.rect.top > win.get_height():
                algae.list.remove(algae.rect)

        for algae.rect in algae.list:
            win.blit(algae.surf, algae.rect)

        pygame.display.update()

if __name__ == '__main__':
    main()

```

# Answer
pygame.sprite.Group.draw:

> Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.

So we need to update image.rect after the image position changes:

```
    def move(self):
        self.pos.move_towards_ip(algae.pos, self.velocity)
        self.rect.x = self.pos.x
        self.rect.y = self.pos.y

```
> 1 votes

---
Tags: 2d, sprites, movement, python, pygame
---


# Question
Title: Infinite character loop when trying to play Dialogue
I am trying to make a dialogue system in Unity by following this tutorial: (29) 5 Minute DIALOGUE SYSTEM in UNITY Tutorial - YouTube. There is a slight twist to this and that is that I am triggering this conversation based on an event which is triggered when the boss is in sight. However, once the conversation starts, it just prints out the letter c endlessly and goes into an infinite loop. I’ve tried looking for the cause of this problem and using a boolean flag to indicate when the characters are being "typed" but I still can’t seem to figure it out. Any help with this is much appreciated. Here is the code for the Event/Delegate class and the Dialogue class respectively:

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

public class DialogueDelegateEvent : MonoBehaviour
{
    public delegate void BossInSight(bool inSight);

    public static event BossInSight OnBossInSight;

    //for ending the conversation:
    public delegate void ConversationComplete();
    public static event ConversationComplete OnConversationComplete;

    private static DialogueDelegateEvent instance;

    public static DialogueDelegateEvent Instance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<DialogueDelegateEvent>();
            }
            return instance;
        }
    }

    public void SetBossInSight()
    {
        OnBossInSight?.Invoke(true);
    }

    public void EndConversation()
    {
        OnConversationComplete?.Invoke();
    }
}

```

Dialogue.cs class (class responsible for playing the dialogue lines):

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

public class Dialogue : MonoBehaviour
{
    public TextMeshProUGUI textComponent;
    public string[] lines;
    public float textSpeed;

    private int index;

    private void OnEnable()
    {
        DialogueDelegateEvent.OnBossInSight += BeginConversation;
        BeginConversation(false);
    }

    private void OnDisable()
    {
        DialogueDelegateEvent.OnBossInSight -= BeginConversation;
    }

    void Start()
    {
        textComponent.text = string.Empty;
    }

    private void BeginConversation(bool inSight)
    {
        if (inSight)
        {
            Time.timeScale = 0f;
            StartDialogue();
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if(textComponent.text == lines[index])
            {
                NextLine();
            }
            else
            {
                textComponent.text = lines[index];
                StopAllCoroutines();
            }
        }
    }

    void StartDialogue()
    {
        index = 0;
        StartCoroutine(TypeLine());
    }

    IEnumerator TypeLine()
    {
        foreach (char c in lines[index].ToCharArray())
        {
            textComponent.text += c;
            yield return new WaitForSeconds(textSpeed);
        }
    }

    void NextLine()
    {
        if (index < lines.Length - 1)
        {
            index++;
            textComponent.text = string.Empty;
            StartCoroutine(TypeLine());
        }
        else
        {
            DialogueDelegateEvent.Instance.EndConversation();
            gameObject.SetActive(false);
            Time.timeScale = 1f;
        }
    }
}

```

# Answer
> once the conversation starts, it just prints out the letter c endlessly and goes into an infinite loop.

It sounds to me like that problem is probably that you keep retriggering the `BossInSight` event every frame the boss is in sight, and not just on the first frame. The result would then be that the dialog restarts every frame, which would output the first character again and again.

To solve this problem, either make sure the event only gets invoked once, that you unsubscribe the event listener after it fired once, or that your `BeginConversation` method checks if the conversation is already running, and if that's the case doesn't start it again.

---

There is also another problem here which you probably didn't realize yet. You are using coroutines with `yield return new WaitForSeconds(textSpeed)` to type out the text, but you are also setting `Time.timeScale = 0f` while the dialog is running. The timeScale also affects `WaitForSeconds` statements. So those yields won't return while the timeScale is 0. If you want the dialog to keep running while the rest of the game is paused, you probably want to use `WaitForSecondsRealtime` instead.
> 1 votes

---
Tags: unity, events, dialogue-tree, delegates
---


# Question
Title: is there a way to check if an animatorcontroller has a parameter?
With mecanim, if you try to set a parameter that doesn't exist, it logs a warning. It doesn't throw an exception or return null or anything useful like that. So if I set a parameter very often that doesn't exist, a lot of CPU time is spent logging warnings. How can I tell if a parameter exists in an animatorcontroller? It would be great if there was a method like ProceduralMaterial.HasProceduralProperty (which allows you to check if the ProceduralMaterial has the property in question).

# Answer
Simpler version, involve GC alloc on Animator.parameters, not cool for repeated call.

```
public static bool HasParameter( string paramName, Animator animator )
{
    foreach( AnimatorControllerParameter param in animator.parameters )
    {
        if( param.name == paramName )
            return true;
    }
    return false;
}

// Usage sample
public void SetFloatParamWithCheck( string paramName, float v )
{
    // animator defined elsewhere.
    Animator animator;

    if( HasParameter( animator, paramName ) )
    {
        animator.SetFloat( paramName , v );
    }
}

```

Extension version, still involve GC alloc every call.

```
public static class AnimatorHelper
{
    public static bool ContainsParam( this Animator _Anim, string _ParamName )
    {
        foreach( AnimatorControllerParameter param in _Anim.parameters )
        {
            if( param.name == _ParamName ) return true;
        }
        return false;
    }
}

// Usage sample
public void SetFloatParamWithCheck( string paramName, float v )
{
    // animator defined elsewhere.
    Animator animator;

    if( animator.ContainsParam( paramName ) )
    {
        animator.SetFloat( paramName , v );
    }
}

```

An over-engineered version. With caching and resolving parameter hash in one go. Premature optimization is evil but you will need it in (some) practice.

```
// Animator parameters query involve GC, cache it
// Animator.GetParameter( index ) might also internally use it, so no better.

Animator m_LastAnimatorCache; // Assume typically working with 1 animator, could extending to collect more cache.
Dictionary<string,int> m_AnimatorParamCache = new Dictionary<string,int>( ); // <key=paramname,value=hash>

private bool TryGetAnimatorParam( Animator animator, string paramName, out int hash )
{
    if( (m_LastAnimatorCache == null || m_LastAnimatorCache != animator) && animator != null ) // Rebuild cache
    {
        m_LastAnimatorCache = animator;
        m_AnimatorParamCache.Clear( );
        foreach( AnimatorControllerParameter param in animator.parameters )
        {
            int paramHash = Animator.StringToHash( param.name ); // could use param.nameHash property but this is clearer
            m_AnimatorParamCache.Add( param.name, paramHash );
        }
    }

    if( m_AnimatorParamCache != null && m_AnimatorParamCache.TryGetValue( paramName, out hash ) )
    {
        return true;
    }
    else
    {
        hash = 0;
        return false;
    }
}

// Usage sample
public void SetFloatParamWithCheck( string paramName, float v )
{
    // animator defined elsewhere.
    Animator animator;
    int hash;

    if( TryGetAnimatorParam( animator, paramName, out hash ) )
    {
        animator.SetFloat( hash, v );
    }
}

```
> 3 votes

# Answer
To improve upon the solutions, this is a simple animator utility class that allows you to check if the animator has a parameter or not, or safely set parameters without any warnings, it is quite fast as it uses a HashSet and Dictionary for caching the parameters and name hashes.

## Download

1. Get the script from this gist
2. Import the script into your Unity project

## Examples

Here is a quick usage snippet:

```
float speed = Mathf.Abs(this.rigidbody2D.velocity.magnitude);

// Set a parameter safely (it won't log warnings)
animator.SetFloatSafe(this.speedParameter, speed);

// Or manually check if the parameter exists
if (animator.HasParameter(this.speedParameter)) {
  animator.SetFloat(this.speedParameter, speed);
}

// Get a parameter's value safely with a default value
// The "Height" parameter here is missing in the animator and the default height value is returned instead
float defaultHeight = 10f;
float height = animator.GetFloatSafe("Height", defaultHeight);

```

Here is the complete example:

```
using UnityEngine;
using Bayat.Games.Animation.Utilities;

public class GameCharacter : MonoBehaviour {

  [Header("Animation")]
  [SerializeField]
  protected Animator animator;
  [SerializeField]
  protected string speedParameter = "Speed";

  [Header("Physics")]
  [SerializeField]
  protected new Rigidbody2D rigidbody2D;

  protected void OnEnable() {

    // Allocate caches and resources for this animator (only the first usage allocates the caches, the rest use the same caches for this animator)
    animator.AddAnimatorUsage();
  }

  protected void OnDisable() {

    // Release caches and unused resources
    animator.RemoveAnimatorUsage();
  }

  proteved void LateUpdate() {

    float speed = Mathf.Abs(this.rigidbody2D.velocity.magnitude);

    // Set a parameter safely (it won't log warnings)
    animator.SetFloatSafe(this.speedParameter, speed);

    // Or manually check if the parameter exists
    if (animator.HasParameter(this.speedParameter)) {
      animator.SetFloat(this.speedParameter, speed);
    }

    // Get a parameter's value safely with a default value
    // The "Height" parameter here is missing in the animator and the default height value is returned instead
    float defaultHeight = 10f;
    float height = animator.GetFloatSafe("Height", defaultHeight);
  }

}

```

## Resources

## License

MIT License.
> 0 votes

---
Tags: unity, mecanim
---


# Question
Title: How Do I 'Reset' my Render Texture When I Stop a Video Player?
I have a Unity VideoPlayer where I use a render texture with an audio source to play the video. `VideoPlayer.Stop` pauses the video and resets the time to 0. I want to reset the VideoPlayer back to its default after I stop the video player. I searched the Scripting API but I did not see anything obvious on how to do this. How do I do this?

# Answer
> 1 votes
I did a quick test on my machine, a quick solution to that would be to disable the `VideoPlayer` component by calling `myVideoPlayer.enabled = false`. This would stop rending the video, and render the rest of the object. If you want to re-use it you can re-enable it the same way.

You can edit the object's material to change what the object looks like when the video is off.

# Answer
> 1 votes
I ended up going on to other projects, but found myself needing a solution to this issue again. It took me a few hours, but I was able to find a solution. I wrote a script to use the render texture I wanted to reset as input.

```
public void ClearOutRenderTexture(RenderTexture renderTexture)
    {
        RenderTexture rt = RenderTexture.active;
        RenderTexture.active = renderTexture;
        GL.Clear(true, true, Color.clear);
        RenderTexture.active = rt;
    }

```

I found the solution here in the Unity forum.

# Answer
> 0 votes
You can also clear out the content of the render texture. Keep a reference of your render texture and when you stop the player you can just

```
renderTexture.Release();

```

# Answer
> 0 votes
```
[ContextMenu(nameof(Clear))]
private void Clear()
{
    if (rt != null)
    {
        var cmd = new CommandBuffer();
        cmd.SetRenderTarget(rt);
        cmd.ClearRenderTarget(true, true, Color.clear);
        Graphics.ExecuteCommandBuffer(cmd);
        cmd.Dispose();
    }
}

```

---
Tags: unity, video, rendertexture
---


# Question
Title: UI mask and elements not visible after Async scene change
i have an async loading scene system that redirects to a loading scene and then to the target scene. The function works properly although i found out that some UI elements dont work directly on scene load. For instance i have a ui bar that acts as a fill bar for objectives, (as you collect points it increments) which when i run the scene directly works fine but as soon as i load that scene async i need to manually enable the object or have it get enabled with a button press to work.

i call the loading through this function

```
Utilities.LoadSceneLoading(Utilities.Scene.GameScene, Utilities.Scene.LoadingSceneGame);

```

The actual function is this

```
  private class LoadingMono : MonoBehaviour { }

  private static Action onLoaderCallback;
  private static AsyncOperation asyncOperation;

    public static void LoaderCallback()
    {
        if (onLoaderCallback != null)
        {
            onLoaderCallback();
            onLoaderCallback = null;
        }
    }

    public static void LoadSceneLoading(Scene scene, Scene _loadingScene)
    {
        onLoaderCallback = () =>
        {
            GameObject loadingObject = new GameObject("Loading GO");
            loadingObject.AddComponent<LoadingMono>().StartCoroutine(LoadSceneAsync(scene));

        };
        SceneManager.LoadScene(_loadingScene.ToString());
    }

    private static IEnumerator LoadSceneAsync(Scene scene)
    {
        yield return null;
        asyncOperation = SceneManager.LoadSceneAsync(scene.ToString());

        while (!asyncOperation.isDone)
        {
            yield return null;
        }

    }

```

And in the loading scene i have this script that get enabled after an animation event

```
public class LoaderCallback : MonoBehaviour
{
    private bool isFirstUpdate = true;

    private void Update()
    {
        if (isFirstUpdate)
        {

            Utilities.LoaderCallback();
            isFirstUpdate = false;
        }
    }
}

```

and the object that enables it is this

```
  private void Update()
    {
        ShowScene();
    }

 void ShowScene()
    {
        if (canMove)
        {
            time -= Time.deltaTime;
            if (time <= 0)
            {
                loaderCallback.enabled = true;
            }
        }

    }

    public void EnableCallBack()
    {
        canMove = true;
    }

```

The whole process works fine as i need it to but i have those issues with the UI which for now , for the count bar , i have kind of fixed by having it inactive on start and enable it on the play button press but since i do have more elements and i dont want to have to try it out everytime i add something i would like some help in understanding why it doesnt allow the UI elements to appear! Thank you!

Edit:

basically what it doesnt show is an inverted UI mask that i have.

```
public class CutoutMaskUI : Image
{
    public override Material materialForRendering {
        get
        {
            Material material = new Material(base.materialForRendering);
            material.SetInt("_StencilComp", (int)CompareFunction.NotEqual);
            return material;
        }
    }
}

```

i have a UI element acting as a border around an image set to fill in two separate objects, the count bar and a selection bar acting like a clock going around in a circle , these two items do not render on start and if i disable them / enable them in runtime they suddenly appear.

Basicaly the red fill image doesnt get rendered in the circle and the black outline in the count bar

# Answer
> 1 votes
I was having the same problem with the inverted mask, and found this thread in Unity Forums, so I tried what styrbo suggested. But didn't work initially, then I tried changing maskable to false and back to true in the Fix Coroutine, and it worked! So, this is what I added to the CutoutMaskUI class:

```
protected override void Start()
{
    base.Start();
    StartCoroutine(Fix());
}

/// Fix for async loading scenes
private IEnumerator Fix()
{
    yield return null;
    maskable = false;
    maskable = true;
}

```

---
Tags: unity, async
---


# Question
Title: In an Entity-Component-System architecture how should my map be represented?
I'm migrating a 2D game I've been making using only SpriteKit to an ECS architecture using GameplayKit, and I'm still a bit clueless on how to achieve this. I think I got the gist of ECS, but yet, I've got no clue on how to make my game map.

For reference my map is basically a 2D grid and on each coordinate there's a possibility to exist resources, or a player unit, enemy unit, etc. It's basically a build your base, collect resources, upgrade your stuff, survive waves of enemies kind of game.

In my non-ECS implementation I basically have a Map class that's keeping references to SKSpriteNodes, and I basically just have some procedural generation going on to generate my initial resources.

How do I define my map? Should it be an `GKEntity`? I've got no clue on how exactly to represent it. Any tips that will give me a push will be very welcomed!

# Answer
> 1 votes
I see many GameplayKit examples that are more EC than ECS, which can add to confusion as they put a lot of code in entities. GameplayKit supports both approaches.

In an ECS, an entity is an aggregation of components. Components are data objects. Systems is where your logic goes. In the case of your Map, it can be an entity where you add components that make sense for the systems which need to act on it.

For example the Map would have a Renderable component because it is rendered by the Render system. A Position component for storing its x and y locations (and the Render system knows where to render it). The Map might have a Grid component that has data like tileSize, numRows, numCols, etc. That data could be used by a TerrainGenerator system to create the image of the map.

---
Tags: ios, entity-component-system, spritekit
---


# Question
Title: When/Where to use Node2d as parent vs Other Node
tl;dr = When/Where/Why use 'Node2d' as the parent vs going straight to 'Other Node'?

I have just started diving into using Godot for the first time. I completed the Your First Game official tutorial (Dodge The Creeps) and have a question my searchengine-fu hasn't yet been able to find an answer for. Links to this question being asked already and/or where I completely missed this in the docs are appreciated.

I would like to attempt my own game now and learn during the process. Something I can't seem to find an answer for is when it is appropriate to select "Node2d" when creating a new scene, versus clicking on "Other Node" and selecting what is required from there.

If I want to make a tower defense game I will need a scene to hold the 'world/map' that I make using a TileMap. The Turrets I place and the Mobs that follow the path will be their own scenes - presumably something like Sprite2D or AnimatedSprite2D

When I create these scenes (ie world.tscn, missile\_turret.tscn etc), when/where/why is it appropriate to select Node2D as the parent and then add TileMap or Sprite2D as a child, versus when should I just go straight for "Other Node" then select either TileMap or Sprite2D from the list of all nodes that comes up?

Which Node to use for certain features is part of the journey of discovery I'm looking forward to, but currently I'm mentally stunlocked with the concept of using the correct parent node.

Questions rattling in my mind currently sound like: "Do I make everything Node2D and then add the appropriate child nodes every time? That didn't seem to be the case in the tutorial" / "Do I make a "main.tscn" that uses the Node2D option as the parent and then all of my other scenes skip straight to "Other Node \> \[correct node like TileMap\]" as the parent which I then add to main.tscn?"

# Answer
tl;dr: Use the generic `Node2D`, `Node3D`, `Control` or `Node` as root, and worry about it later.

---

I should clarify that scenes in Godot are bundles of `Node`s you reuse. Which includes what you might call props, prefabs, and so on. For example, an enemy unit might be an scene.

---

When you are creating a new scene Godot will ask you if you want to use `Node2D`, `Node3D`, `Control` (user interface), or "Other" (which lets you pick, but defaults to `Node`).

*By the way, there is another way to make an scene worth noting: you can pick a child and then use the option "Save Branch as Scene" from the context menu of the Scene dock. The option will allow you to create a new scene with that node as root and with its children, and in your current scene you will end up with an instance of the new scene.*

Please be aware that what you pick as root of the scene is not final. You can use the "Change Type..." option you find in the context menu on the Scene dock to change it. Or you can use the "Make Scene Root" option from the same menu to promote a child to root of the scene.

Thus: you don't need to overthink this ahead of time.

Having a generic `Node2D`, `Node3D`, `Control` as root and then having more specific child might be a little overhead but usually not something to worry about.

The stronger argument is how you will use the instances of the scene. As Godot is not very good it easing access to scene internals. *Note: the "Editable Children" option from the context menu in the Scene dock will allow you to see, add and edit the children of the instantiated scene.*

You might find that as your scenes become complex it might not be clear which node should be root, but regardless of which you pick you need code to reach other nodes. In that situation it makes sense to use a generic root and give it an script that eases access to what you need where you instantiate it.

---

What I do is start with the generic `Node2D`, `Node3D`, `Control`, or just `Node` if none of those make sense. Then add children of specific types. And if it makes sense to make any of them the root, I'll use the "Make Scene Root" option. Of if it makes sense to make some of them a new scene I'll use the "Save Branch as Scene" option.

---

I'll describe something more advanced here...

As you know, you can change the scenes with scene tree methods (e.g `get_tree().change_scene_to_file(…)`)… I don't do that at all. Using those requires using autoloads to keep data from one scene to the other, and it is an obstacle to make scene transitions (you can take control of the process by using an autoload that does the right thing).

Instead, I find it is easier to make main scene root a `Control` or a `Node`. Then I can use `ViewportContainer` or `CanvasLayer` to separate the game world from the UI. And I would create game world scenes of type `Node2D` or `Node3D` depending the game. In the main scene I would add a script with code to switch game world scenes, or load and unload multiple at the same time (e.g. have the world loads as you explore), and I would use background loading (`ResourceLoader.load_threaded_request`) to avoid hiccups.

So my answer for the main scene is: neither `Node2D` nor something more specific like `TileMap`.
> 2 votes

# Answer
In general, there's not necessarily a right answer for selecting one over the other in Godot. There's probably a measurable typically negligible performance impact to adding an extra layer of indirection in the scenes. But to my in mind, selecting one over the other is largely a matter of selecting the relationships that make it easier to manage the complexity of developing the game.

To me, using the primary "idea" as the parent node type is represents an "is a" type relationship whereas including one node as a child of another represents the "has a" relationship (also known as composition). And keep in mind that `TileMap` and `Sprite2D` (and any other node of the 2D category that I bothered to look up) inherit from `Node2D`. Since they are already specialized versions on `Node2D`, they have a built in "is a" type relationship with Node2D.

In Godot, I almost always lead with the main idea of a thing to select the "is a" relationship for the parent node. For the player and enemies I used `KinematicBody2D`, for hit boxes and hurt boxes I used `Area2D` and so forth because that's how I think of them. The player isn't 2d node with a kinematic body attached to it, it is the kinematic body. This also saves me the the extra mental overhead of needing to dig an extra layer into everything to get what I need. By that I mean since the player is a `KinematicBody2D` I can call `move_and_slide(..)` directly. If I used the "has a" relationship I would need to first "get" the `KinematicBody2D` that belonged to the player.

Sometimes though there's not a clear idea. Usually this happens for more abstract concepts that are a collection of things, none of which is more the main idea than the others. An example might be an explosion effect consisting of a sound, sprite & animation player. None of those parts better represents the idea of the explosion effect more than others. So in that case I used a `Node2D` and added the other nodes as children. Another example is the "main" or "world" scene. It's more a collection of stuff than it is the embodiment of one particular thing or idea. For that I would use `Node` because it doesn't need the position, rotation, etc that comes with `Node2D`.

Disclaimer: I've only used GDScript with Godot. One of the other bindings might lead me to a more composition heavy design as that's tended to be my preference with other engines / frameworks.
> 1 votes

---
Tags: godot, scene-graph, hierarchy
---


title: Reward System For HTML Game

text:
# Question
Title: Reward System For HTML Game
i am new to coding and have started a little clicker game and right now im working on a reward system for when the players click amout reaches a certain value. i have figured out how to make one reward but im trying to figure out how to make multiple. I want the value of each click using the click\_power var to go up by 2 each time. this is my code so far. '''

The button was clicked times

Click Me! let clicks = 0; let click\_power = 1; let reward\_received = false;
```
        function addClick() {
        clicks = clicks + click_power;
            if(clicks >= 10 && reward_received == false) {
                click_power = click_power + 1;
                reward_received = true;
            }
            document.querySelector('.total-clicks').textContent = clicks;
        }
    </script>
</body>

```

im trying to use the "reward\_received" var using boolean telling if its true or false. every time i try to make a new reward i use reward\_received1/2/3 ect.but when i run it, it will only do the reward with the highest required amount. please help and make it make since for a beginner. Thank you for your efforts.

# Answer
This is the same as checking for adding a life for a given score.

The key is to change the check value each time it is achieved.

Here are two possible implementations:

## Implementation 1

Add another variable `var next_reward = 10;`

```
function addClick() {
  clicks = clicks + click_power;
  if(clicks >= next_reward) {
      click_power = click_power + 1;
      next_reward = next_reward + 10; // or any formula your like
  }

```

## Implementation 2

To use an array instead define two variables:

```
var reward_index =0;
var next_reward = {10,30,500};

```

```
function addClick() {
  clicks = clicks + click_power;

// check for end of the array
  if(reward_index < next_reward.length)
    if(clicks >= next_reward[reward_index]) {
      click_power = click_power + 1;
      reward_index = reward_index + 1;
    }
    // optional
    else {
      reward_index = next_reward.length -1; //set last element to ...
      next_reward[next_reward.length -1] = next_reward[next_reward.length -1] * 100; // or any formula your like
    }

```

Exclude the else if no rewards are needed after the array is exhausted.
> 0 votes

---
Tags: html, clicker
---