title: Context-based Steering

text:
# Question
Title: Context-based Steering
I added context-based steering functionality to my 2d sideview free-roam shoot-'em-up game. Essentially enemy units emit raycasts eventually towards every direction, I determine interest and danger values, calculate the sum total of all vector and move the entity that way.

However, this fails somewhat quickly in the following situation:

Enemy is wandering (there is a position that is essentially its `moveTarget`, which gives a high interest) around, eventually one of the (8) casts hits the player. The player is a DANGER value so the entity is supposed to move away from the player. A vector is calculated that is essentially a vector opposite the direction to the player, so indeed the entity accelerates AWAY from the player FOR A FRAME. However, next frame, by pure chance, no raycast is hitting the player, so the entity returns to its old course essentially getting close to the player (who sits along its wander target). This happens for 10 or 20 frames, until by pure chance of the 8 casts again hits the player and we again, for a single frame, move away from the player.

How do you solve this? Just tuning up the amount of casts from 8 to 180 would work, but with 16 or 32 casts there will still be plenty of frames when the rays don't hit the player, and hence the entity sees no need to "back off".

# Answer
> 1 votes
It sounds like the problem stems from conflicting goals. Specifically, the AI has an attraction toward a goal, a repulsion from the player and trying to resolve the two by moving *directly* away from the player results in an oscillating behavior.

Abstractly, the solution is to move away from the player in a way that prevents (or at least reduces) the chance that future movements will put the AI back into the same situation. Here are a few ways to could implement this:

After raycasting, select the ray that moves closest to the goal without intersecting the player. This represents a daring or risk taking AI - it will avoid the player to move toward the goal, but it will do as little as possible to avoid the player.

You can make a somewhat more cautious AI by adding a region of avoidance around the player. The AI will do what it can to move toward the goal, but it will skirt further away from the player when doing so. While it's common to use a bounding square or circle for the region of avoidance, it might be worth considering other shapes. For example, if your game physics accounts for momentum, you might bias the avoidance region to be larger in front of the player's direction of travel. The resulting AI would be more likely to attempt to dart just behind the player & less likely to move directly into the player's path. A similar modification could also be made to avoid weapons.

For a very risk averse AI, instead of moving directly away from the player, select an avoidance vector that somewhat less than 180°. This will likely result in some oscillation as the AI may need approach the goal a few times, but by biasing its avoidance off the centerline from the player, it should eventually manage to navigate around the player. Note that while you can randomize the bias, keep in mind that if the bias is too small & changes too frequently, it's more likely to make back to back moves that effectively cancel each other out.

A final observation: any simple steering behavior has limitations. For example, the player could move in a way that herds the AI into some other danger. This isn't necessarily bad from a design perspective though - sometimes part of finding the fun is giving the player opportunities to predict what the AI is likely to do and outsmart the game.

---
Tags: 2d, ai, steering-behaviors
---


# Question
Title: does texture image format matter for opengl 2?
So, from what I gathered, rendering engines take common image formats like PNG or JPG and convert them into their favored formats, such as Targa or DDS.

Does it mean that using the already converted texture format directly results in faster render times?

# Answer
As I explain in another answer, GPUs cannot read PNG or JPG, full stop. Those formats just do not provide the random access functionality we need for rendering, where we need to be able to map instantly from "texture coordinate (0.2, 0.7)" to "here is the memory address of the data for that specific texel" without scanning through all of the image data before that point in the stream to find it.

Anything that loads a PNG or JPG first decompresses it to a GPU-readable format, then displays that format. So you don't gain a per-frame speed advantage/disadvantage versus using dedicated GPU formats, because you *are* using a dedicated GPU format no matter what you do.

Where storing your images in GPU-ready formats like DDS can help is that you don't need to take time to decompress it on load — you can dump bits straight from the disc/network into VRAM and use them directly, without any transcoding. This can save time when booting the game, loading levels, or streaming content, and give you more predictable memory layouts (more of a concern on embedded systems like older consoles).

The other advantage is that you can take time offline to compress textures into a smaller format while preserving image quality. Not smaller compared to JPG/PNG usually (they're *really good* at compressing, while GPU formats usually aren't, due to the random access limitation), but smaller than the GPU version you'd get if you just did the most naive transcode.

By default, most libraries/APIs will decompress PNG/JPG images to uncompressed RGBA8 for use on the GPU: that's 8 bits for each of four colour channels, adding up to 32 bits per pixel. By contrast, some DDS formats can get down to 4 bits per pixel — one eighth the size — at the cost of image quality or giving up colour channels you might not need for certain textures.

The smaller size (vs raw RGBA8) both helps save on the game's video memory demands, so you can fit more textures/etc. in memory at once or load/stream content faster, and reduces the bandwidth demands of sampling the texture, which can give you a performance boost during rendering.

But you can get that benefit from JPG/PNG too if your transcoding step re-compresses them into one of these more packed GPU formats instead of uncompressed RGBA8. The difference is that if you do this compression offline and save the GPU-ready DDS asset to later load in game, you can use a slow compressor that maximizes the visual quality available for a given format. You don't care if it takes a while, since it can run on your build machine overnight without adding to loading times for players.

Doing it on load when transcoding from JPG/PNG, you usually go for a fast compressor that might not make optimal choices, and it's too late for the designer to fiddle with format and compression settings to find the right trade-off for each image. So you more often have to fall back on less compressed GPU formats if you're loading from JPG/PNG at runtime.
> 1 votes

---
Tags: opengl-es2
---


# Question
Title: How to inspect/modify the runtime state of a node in the Godot editor?
I'm thinking of something similar to Unity, where GameObjects have their boot state and their runtime state, where you can change the runtime state in the editor during game play.

Godot is a distinctly different, but in some ways similar, engine. I'm wondering if I can take a node and monitor, or tweak, its parameters during gameplay, like I can in Unity? I'm having a hard time finding information on this.

# Answer
> 6 votes
You can do so, although Godot's behavior is slightly different to Unity and I'd suggest trying it in a small test project before you unintentionally change an actual working project.

The functionality you're looking for is hidden in the Scene Tree inspector of the editor, i.e. the "Scene" tab. Once your project is running and the editor is connected, it will show two new buttons/tabs right above the scene tree:

* **Local** shows your editor state, i.e. your boot state. You can change everything while the project is running and values will be adjusted immediately (this also includes changes within the editor's main view, e.g. modifying tile maps).
* **Remote** shows your the project's running scene tree/state. You can select and modify the nodes in this tree, which is your runtime state. Note that your main editor window will always stay in the *Local* state, but if you click on any node in the Remote scene tree, your Node Inspector will show the selected node.

I've recorded a short clip from an experimental project of mine to demonstrate this (don't mind Samus Aran running around, this is just for testing instead of developer art).

**Note:** The inspector will only show exported variables. In Godot 3.x, you do this by preceding them with the keyword `export`. The GDScript exports documentation has more information and a lengthy example of the various options. Fortunately, most of the time one of these two is good enough:

```
export var some_variable_name = 5
export(int) var some_variable_name

```

You would replace `some_variable_name` with your actual variable name and depending on which version you go with, either replace `5` with your reasonable starting value or replace `int` with your actual type being used.

In Godot 4, you use the `@export` keyword instead. The documentation for that version can be found here.

# Answer
> 1 votes
I believe they are asking if you can edit in the editor at runtime like Unity does. Unity plays the runtime back in the editor and the game window at the same time, and you can change things like you would in the editor during play testing. So, no, that isn't how Godot does it's play-testing mode. You can only edit in the inspector and the editor doesn't reflect the runtime and game preview doesn't change the editor view in real-time.

# Answer
> 0 votes
I'm not familiar with Unity's workflow, but from your description it sounds like a GDScript export will do what you want. From the official description:

> In Godot, class members can be exported. This means their value gets saved along with the resource (such as the scene) they're attached to. They will also be available for editing in the property editor. Exporting is done by using the `export` keyword:
>
> ```
> extends Button
>
> export var number = 5 # Value will be saved and visible in the property editor.
>
> ```
>
> An exported variable must be initialized to a constant expression or have an export hint in the form of an argument to the `export` keyword (see the Examples section below).
>
> One of the fundamental benefits of exporting member variables is to have them visible and editable in the editor. This way, artists and game designers can modify values that later influence how the program runs ...

The official documentation (linked at the start of the answer) has a lengthy example of the various options - so lengthy that it may be discouraging. Fortunately, most of the time one of these two is good enough:

```
export var some_variable_name = 5
export(int) var some_variable_name

```

You would replace `some_variable_name` with your actual variable name and depending on which version you go with, either replace `5` with your reasonable starting value or replace `int` with your actual type being used.

---
Tags: godot, gameobject, editors
---


# Question
Title: How can I prevent my ball from slowing down when it makes contact with the corners of colliders
I'm trying to make a game where the player has to destroy blocks. But when the player collides with the corners of the blocks, the player's velocity slows down, or even stops.

How can I ignore the corners and keep a constant momentum?

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

public class Player : MonoBehaviour
{
    private Rigidbody2D rb;
    public float horizontalSpeed = 5f;
    public float verticalSpeed = 7f;
    public float sideBounceForce = 10f;

    float horizontalInput;

    public bool isLaunched = false;
    public bool isGameStart = false;
    public bool isDead = false;

    public AudioSource sfxCollide;
    public AudioSource sfxDied;

    public TextMeshProUGUI scoreText;
    public TextMeshProUGUI highScoreText;
    private int score = 0;
    private int highScore = 0;

    private SpriteRenderer playerRenderer;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        playerRenderer = GetComponent<SpriteRenderer>();

        highScore = PlayerPrefs.GetInt("HighScore", 0);
        UpdateHighScoreText();
    }

    private void FixedUpdate()
    {
        BallsMovement();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        sfxCollide.Play();
        [![enter image description here][1]][1]
    }

    public void DestroyChildren(GameObject children)
    {
        Destroy(children);
    }

    void BallsMovement()
    {
        if (!isLaunched && Input.GetKeyDown(KeyCode.Space))
        {
            isGameStart = true;

            LaunchBall();

            return;
        }

        horizontalInput = Input.GetAxis("Horizontal");

        // Calculate the horizontal movement
        Vector2 horizontalMovement = new Vector2(horizontalInput * horizontalSpeed, rb.velocity.y);

        // Apply the horizontal movement to the ball's rigidbody
        rb.velocity = horizontalMovement;
    }

    private void LaunchBall()
    {
        rb.AddForce(Vector2.up * verticalSpeed, ForceMode2D.Impulse);
        isLaunched = true;
    }

    public bool IsGameStarted()
    {
        return isGameStart;
    }

    public Sprite GetPlayerSprite()
    {
        return playerRenderer.sprite;
    }

    public void IncreaseScore()
    {
        score++;
        UpdateScoreText();

        if (score > highScore)
        {
            highScore = score;
            UpdateHighScoreText();
            PlayerPrefs.SetInt("HighScore", highScore);
        }
    }

    private void UpdateScoreText()
    {
        scoreText.text = "Score: " + score.ToString();
    }

    private void UpdateHighScoreText()
    {
        highScoreText.text = "High Score: " + highScore.ToString();
    }
}

```

# Answer
I think instead of using collision, you should tick the `isTrigger` checkbox on the box's collider, and use `OnTriggerEnter2D` to destroy the box.

You want to destroy the box, but in your way you have to hit the box first, which make player slower.

With trigger colliders, the collision does not deflect or slow the player, but you can still detect the collision to destroy the box.
> 2 votes

---
Tags: unity, c#, physics, collision-resolution
---


title: Smooth loading screen between scenes

text:
# Question
Title: Smooth loading screen between scenes
I created a loading screen to display a loading animation as the next scene is loading. I load the next scene asynchronously with:

```
yield return SceneManager.LoadSceneAsync(scene,LoadSceneMode.Additive);

```

And also set `Application.backgroundLoadingPriority = ThreadPriority.Low;`, but the behaviour is still the same as a regular level load.

Am I missing something?

Expected behaviour:

* Exit level, and fade out.
* Loading screen appears.
* Once load is done, fade loading screen out.
* Fade in next scene.

What is happening:

* Exit level, and fade out.
* Loading screen appears, frozen
* Suddenly new scene fades in.

Once the load starts, the game just frezees, like with a regular Scene load.

I read that you have to set `allowSceneActivation = false`, so you can fade the loading screen out, and then set it to `true` to let unity finish loading, but this completelly freezes my game, like the async operation never finishes loading.

# Answer
> 23 votes
When you load an scene with `SceneManager.LoadSceneAsync()` there are actually two things happening:

* The gameObjects of the scene are loaded into memory.
* Then the whole scene is enabled. All Awake() and Start() callbacks will be called for the objects in the scene.

The second step, enabling the scene, is what actually freezes unity, because unity is running all those initialization callbacks in your scripts in a single cycle.

Indeed setting `SceneManager.LoadSceneAsync().allowSceneActivation` to `false` will make the async operation to complete only the first step of the process, and will wait until it's set to `true` to begin the second part of the process.

But if you set `allowSceneActivation` to `false` and yield on the callback like this, you will freeze your game for good:

```
AsyncOperation AO = SceneManager.LoadSceneAsync(scene,LoadSceneMode.Additive);
AO.allowSceneActivation = false;
yield return AO;

//Fade the loading screen out here

AO.allowSceneActivation = true;

```

Why? Because you are telling the Async operation to not proceed with the second step of the scene load, so the operation will never be completed.

If you want to know when the first part of the operation is ready, to then proceed with the second one, you have to rely on `AsyncOperation.progress`. This value will stop at `0.9f` once it's waiting for the `allowSceneActivation` flag.

It should be something like this:

```
AsyncOperation AO = SceneManager.LoadSceneAsync(scene,LoadSceneMode.Additive);
AO.allowSceneActivation = false;
while(AO.progress < 0.9f)
{
    yield return null
}

//Fade the loading screen out here

AO.allowSceneActivation = true;

```

If you want the scene activation to not freeze your game, then you should keep your Awake and Start callbacks to a minimun, and initialize your scripts in a coroutine through several cycles.

# Answer
> 0 votes
I had the exact same issue in Unity 5.6, and had already tried adding in the yield statements. It was the LoadSceneAsync itself that was blocking the main thread of Unity and preventing the current scene from nicely showing any loading progress.

It would seem to be a bug in Unity as far as I can tell. When my scene was less complex my code worked great, smooth transition. Once it got larger, Unity blocked the thread for about 6 seconds, all the while the game sits as 'not responding' despite the operation supposedly being "async"

The way I solved the issue was to look at my lighting. There have been massive bugs in the past with lighting and this feature. So I went through my objects, and found I had a spotlight on one object (even though it was disabled...)

I deleted the spotlight, and hooray! Scene loads async properly! No locking!

# Answer
> 0 votes
While Leo's answer above is more thorough I'd like to add one more important detail: LoadSceneAsync is not truly asynchronous when run in Editor Play Mode. Unity's behaviour for asynchronous loading differs between Editor and built Player, making it difficult to reason about and test such smooth loading experiences in Editor Play Mode.

---
Tags: unity, multithreading, loading, preload, scenemanager
---


# Question
Title: why when i press "A" i go up but its supposed to go left?
```
//KeyHandler.java
package Main;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyHandler implements KeyListener{
    public boolean upPressed, downPressed, leftPressed, rightPressed;

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {

     int code = e.getKeyCode ();

     if (code == KeyEvent.VK_W){
            upPressed =true;
     }
     if (code == KeyEvent.VK_S){
            downPressed = true;
     }
     if (code == KeyEvent.VK_A){
            leftPressed = true;
     }
     if (code == KeyEvent.VK_D){
            rightPressed = true;
     }
  };
    @Override
    public void keyReleased(KeyEvent e) {
    int code = e.getKeyCode();

      if (code == KeyEvent.VK_W){
            upPressed = false;
      }
     if (code == KeyEvent.VK_S){
            downPressed = false;
      }
     if (code == KeyEvent.VK_A){
            leftPressed = false;
      }
     if (code == KeyEvent.VK_D){
           rightPressed = false;
      }
   };
}

//GamePanel.java

public void update () {
        if (keyH.upPressed == true) {
            playery -= playerspeed;
        }
        else if (keyH.downPressed == true){
            playery += playerspeed;
        }
        else if (keyH.leftPressed == true){
            playery -= playerspeed;
        }
        else if (keyH.rightPressed == true) {
            playerx += playerspeed;
        }
    };

```

# Answer
> 2 votes
If you take a look at your update, you see that `playery` is used 3 times and `playerx` once.

`leftPressed` should use `playerx` instead of `playery`. This kind of error is a good practice for debugging, since you know exactly when the error is happening (when pressing left). Since the rest is working correctly, all you need to do is check carefully what is happening in your `leftPressed` condition

---
Tags: java
---


# Question
Title: Why Does Offsetting Perlin Noise Cause Zooming In To No Longer Work?
I am creating a game in which a world map is generated using Perlin noise, and then specific points in the map are rendered using higher resolution Perlin noise. I am trying to do this by zooming in on specific points of the map, therefore rendering them at a high resolution (by dividing by a larger number in my Perlin calculations)

This works exactly as intended, up until I try to offset the Perlin noise from the center. As soon as this is done, zooming in no longer works-- When you zoom in, random noise is produced. I have ensured that the offset is remaining consistent, so it isn't that.

I have a feeling I'm misunderstanding something about how Perlin noise works, here. The following code works fine.

```
public void Generate()
{
    var perlin = new Perlin();

    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            TileBase tile = GetTile((1d + perlin.NoiseOctaves(
                 (double)(x - 50) / scale.value,
                 (double)(y - 50) / scale.value,
                 0.5d, 10, lacunarity.value, 1 - persistence.value)) / 2d);
            tilemap.SetTile(new Vector3Int(x , y, 0), tile);

        }
    }
}

```

However, as soon as I try to offset x by a constant value in order to make the noise different, it breaks the zoom-in feature.

https://gyazo.com/a741bec0ec9e509e796a70d8750cf10d Expected behavior

https://gyazo.com/d3460e3cfbf7562b0582eacfd9b0d662 Offsetted, unexpected behavior

What could be going wrong? Am I misunderstanding something with Perlin noise? Any help is much appreciated!

**Edit:** The -50 in the calculation is because I am working with a 100 x 100 tile grid, and I am wanting to zoom in on the center, rather than on the bottom left corner as would be the default behavior. The offset code would look like this:

```
public void Generate()
{
    var perlin = new Perlin();

    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            TileBase tile = GetTile((1d + perlin.NoiseOctaves(
                 (double)(x - 50 + offsetX) / scale.value,
                 (double)(y - 50 + offsetX) / scale.value,
                 0.5d, 10, lacunarity.value, 1 - persistence.value)) / 2d);
            tilemap.SetTile(new Vector3Int(x , y, 0), tile);

            //tilemap.SetTile(new Vector3Int(x, y, 0), );
        }
    }
}

```

With the offsets being randomly generated integers.

# Answer
The way you've written this math, the scale slider zooms in toward (0, 0). You could distribute the scale over the formula like so:

```
(x - 50 + offsetX) / scale.value
==
(x - 50) / scale.value + offsetX/scale.value

```

So the tile at the center of your map only corresponds to `(offsetX, offsetY)` when `scale.value = 1`. As you scale down / zoom in, you also translate sideways by dividing the offset.

This gets more pronounced the larger your offset value. If `offsetX` is 1000 and you reduce your scale to 0.9, now the center of your view is at 900, and you've scrolled the 950-1050 window you had previously been looking at out of view entirely. Now you see a patch of noise uncorrelated with the patch you were looking at before (which is way off to the right, out of frame), so it looks like your tiles just randomized.

To fix this, move the offset to the outside of the expression:

```
(double)((x - 50) / scale.value + offsetX)

```

Now the offset is independent of the scale.

Another factor that can come into play is aliasing. If the noise function you're sampling has detail on scales smaller than a tile, then it matters a lot where exactly within a tile your sample point lands. As you zoom, your sample point slides continuously over all those little bumps and valleys, rather than jumping across them in tile-sized intervals. That can make detail that was not apparent at one scale suddenly appear, making the tile pattern shimmer. This is a form of undersampling or spatial aliasing, and it can be solved by damping out octaves at higher frequencies than your tile spacing.
> 0 votes

---
Tags: unity, c#, procedural-generation, perlin-noise
---


# Question
Title: How can I make a 2D shader that darkens all sprites not in a certain area?
I was wondering if there was a way to make a 2D shader (or use any other method) to selectively black out areas of the screen that are not in a specific region.

I need this shader because in the game I am making, I would like the area outside of the player's current room to be obscured, except when the player is transitioning between rooms, at which time both will be visible for a while, after which the old room fades to black. You can seem a diagram of this below.

I have tried accomplishing this by simply fading in and out textures depending on which room the player is in, but the problem with this method is that if these textures overlap, while the rooms are transitioning, the areas where they do overlap will be darker than the others. Likewise, attempting to set up these textures to account for all possible room entry/exit scenarios without overlap is complicated, error prone, and time consuming. This is compounded by the fact that certain parts of the map should be visible from multiple rooms. I have also tried using a simple shader that darkens all pixels in the old room, but that doesn't work because, as mentioned before, some areas are visible in multiple rooms.

Thank you for any help you can give! I understand that this might not be a simple thing to make, and I've had a lot of trouble describing what I'm looking for, so I'm totally happy to clarify further if need be.

# Answer
> I have tried accomplishing this by simply fading in and out textures depending on which room the player is in, but the problem with this method is that if these textures overlap, while the rooms are transitioning, the areas where they do overlap will be darker than the others.

Solving this issue should solve your problem. Without seeing your code, it's difficult to give you a perfect solution, but here's a possible solution that uses `blend_disabled`, a `SubViewportContainer` (Godot 4), and z-indexing.

Create a shader whose sole job is to disable blending:

```
shader_type canvas_item;
render_mode blend_disabled;

```

Attach that shader to your shadow textures (for this example, I'm using ColorRects). This will prevent overlapping textures from having a "darker" color.

Make your shadow textures children of a `SubViewport` (which in turn will be a child of a `SubViewportContainer`). Set the size of the viewport to be the same as the size of your game.

This will "enable" blending again, so that the shadow texture can blend with your room textures.

Update your game logic to set the z-index of each shadow texture whenever the player changes rooms, with a high value if the player is in the room and a low value if the player is not. This example is inefficient but conveys the meaning:

```
for shadow_texture in shadow_textures:
    if contains_player(shadow_texture):
        shadow_texture.z_index = 1
    else:
        shadow_texture.z_index = 0

```

This will ensure that the room(s) the player is currently in is not darkened by any overlapping textures that belong to another overlapping room.

Here is a clip of this example with ColorRects, treating the mouse as the player and controlling the "thickness" of that shadow with the ColorRect's alpha channel:
> 3 votes

---
Tags: shaders, rendering, godot
---


title: falling and clipping through terrain

text:
# Question
Title: falling and clipping through terrain
I found this bug in many big games and never expected to find it in my small game. Basically, while running around carelessly, you suddenly clip through the terrain and fall endlessly.

I momentarily fixed it by putting water below the terrain. So, after a while, you fall into a giant pool of water and can /unstuck without needing to die due to this stupid bug.

I also doubled the collision for the static body. The collision was created using Godot's "create trimesh static body" button on the viewport.

Doubling the collisions seems to have helped, and as of now, the problem appears to be solved... but isn't there a better method?

Because what if I didn't completely fix the problem? What if I made it so rare that I'm just not gonna encounter it until it's too late, do I have to add 3, 4 ,5 or even more collisions just to be sure?

My terran is very low poly so it doesn't really matter that i have to add 5 collisions or more, but it's just not right.

**extra details**

the player's max speed is 31 miles or 50 km per hour, has a cube for the legs collision and another cube for the torso collision

the terrain is made in blender from a flat plane that was distorted into a landscape.

the player clips throu terrain even when in the middle of the mesh so doesn't matter if it's the edge between two connected terrains.

the collision was applied automatically by godot.

# Answer
> 2 votes
**Introduction to how physic engines work**

The way most physics engines out there work including GodotPhysics and Bullet is like this※:

1. Move the objects first.
2. Then check if they are breaking some constraint (including collisions and joints).
3. Then move the objects so they are not breaking the constraints.

Since moving the objects so they are not breaking the constraints they were breaking might result in breaking other constraints, in practice the second and third steps are done multiple times. *With a hard cap in how many times it will repeat them, as to avoid and infinite loop. If the hard cap is exceded, it might result in objects stuck inside of each other. In Godot you can configure the hard cap, search for "solver iterations" in Project Setting.*

*You, of course, do not see the intermediary steps of this process.*

*You can also imagine that if the character were moving fast enough, it would move to the other side of the terrain in a single step and never collide with it. That phenomenon is known tunneling.*

And yes, this is virtually every physics engine, not just Godot's one.

※: Barring continuous collision detection (which is only available for `RigidBody`(`2D`) in Godot, btw).

---

**How does the physic engine end up pushing the character down the terrain**

As you know, we want the player character to be moving downwards according to gravity, so it collides with the ground. Now think about how that happens...

* First the player character moves down, so it is clipping the terrain.
* Then Godot sees that it is colliding.
* So Godot pushes the player character outside of the terrain.

And now you can imagine how this goes wrong: It pushes the player character out the wrong direction.

Why would it do that?

While I can argue that modern physics engines have all they need to figure out from where the objects were moving before they collided and push them out in that direction... In practice many physics engine push the objects the way that it is closer. *Because this requires less computations, and thus it means they can handle more collisions in the same time.*

*I don't know if in Godot having multiple colliders in the character would make it more likely to get pushed the wrong direction.*

*You might try switching between GodotPhysics and Bullet to see which handles this situation better.*

Having thin terrain makes this more likely. Because your character would be partially on both sides of the terrain when it is colliding with it.

*Regardless how unlikely it might be, it only has to go wrong once for the character to clip through the terrain, so we want the chance to be zero.*

---

**Solution with extra colliders**

Duplicating the collider gives you a second chance that the player character will be pushed the correct way. *And, assuming you place the duplicated collider slightly lower, it has even better chances.*

If you want to fix this with with extra colliders, consider using a `WorldBoundaryShape3D` which is often used for infinite impassable walls for the boundary of your game world. The `WorldBoundaryShape3D` acts as if it had infinite thickness, it will only ever push in the same direction.

---

**Solution with terrain thickness**

Another solution is to give thickness to the terrain. And this is also the solution for clipping through other things where you can't afford a `WorldBoundaryShape3D` (e.g. walls).

Any thickness would minimize the problem simply because when clipping the amount of the characters would sticks out the other side would be less than the same situation with a thin collider... But tunneling and almost tunneling (moving mostly to the other side and getting pushed that way) might still be possible at high enough speeds.

So, to completely fix this using thickness, you want:

1. Set a terminal speed (not just for falling, for everything). So you limit the velocity magnitud at which your character moves to that terminal speed.
2. Compute which distance the player character would move in a single physics step at that terminal speed.
3. Make the thickness of any physical obstacle greater than that distance. *My advice is to use the double of the distance as minimum thickness. Although it should not be necessary assuming the character size is significantly greater than the computed distance. I rather not have to think about it.*

So, how much time is a physics step? First of all, you have how many physics frame per second happen (which is in Project Settings under "physics/common/physics\_ticks\_per\_second") and second you have how many physics steps it will do per frame (which is in Project Settings under "physics/common/max\_physics\_steps\_per\_frame").

By default, we would have that each physics frame is `1/60 of a second`. And each frame has 8 steps, so each step is `1/8` of that. So each step is a `1/(60*8) of a second` that is `1/480 of a second` or `0.002083333333 s`.

And I'm advising to double it, following that advice we can assume it is the double of the time, so `0.004166666666 s`... And let us round that up to `0.005 s` (which is fine since we are defining a minimum threshold).

So you take your terminal speed multiply it by `0.005 s` and you have your minimum thickness.

*If you changed the defaults so physics steps are longer, then you need to recalculate because this thickness might no longer be safe. But if you made the physics steps shorter, then the minimum thickness would be lower, meaning that whatever thickness you were using is till fine.*

For example, for a terminal velocity of `14 m/s` the minimum thickness is `0.07 m`, and for a more realistic terminal velocity of `60 m/s` it is `0.3 m`.

*I also want to note that there is another reason to have a minimum thickness to things - not just terrain - and that is light leaking. And that might be larger than what you need for physics.*

---

**About the seam between colliders**

By the way, in the seam where colliders meet, you might have the situation where pushing the character out of one collider pushes it into the other... And that ultimately might result in pushing the character the wrong way.

You would solve that by having the colliders overlap... Which you can accomplish by making the colliders larger, or by adding extra colliders in the seams.

However, this problem is less common in Godot and other engines where collision shapes have a non-zero extra margin, because that makes it so that aligning the meshes result in colliders slightly overlap in practice.

---
Tags: collision-detection, godot-3
---


# Question
Title: How to create skeletal animation data for a skirt?
Please think of this in an engine-agnostic way first, and then we can talk about specific engines.

In my game, I have a 3D character which is wearing a hakama (think of it as a long pleated skirt). This character will be doing a lot of dancing, which I'm getting a lot of motion capture data for. This is how my character is rigged right now (view from Unity):

This character has a standard 3D Studio Max humanoid rig, plus a bunch of bones for the "dangling" stuff such as the skirt, the sleeves, the long hair and other parts.

Unfortunately, motion capture can only give me data for the humanoid part, not for the additional parts, so I need a way to animate these. For now, let's focus on the hakama (skirt). I have a few ways of doing this:

1. Removing the additional bones, and rig the cloth directly to the leg bones: This is my last resort, but one that I'd like to avoid, as the hakama will move directly with the legs as if it were a tight fit, losing a lot of realism.
2. Keep the bones and animate them manually. There are just too many frames and too many characters for it to feasible to do this manually, so this is out of the question.
3. Simulate the leg and cloth interaction in some way. Fortunately, the dancing is static (just for cutscenes), so I can do this offline, export the resulting bone transforms for each frame, and apply this to the character during playback.

Since Unity has a pretty mature physics engine, I am trying to hack an offline physics simulation that exports the resulting bone transforms for each frame, which I can then playback in real time in the actual game (which by the way is not Unity-based). So far, the sleeves and hair have shown some pretty good results, but the hakama is much more difficult, and I haven't gotten it to work even close to decently.

I have tried:

* Setting colliders in the legs and the skirt, so when the legs push the skirt, the skirt moves. I can set a bunch of joints to set some constraints, but setting a correct shape and position for the skirt colliders is not trivial, since the leg colliders eventually find a hole between the skirt colliders, which leads to the leg intersecting with the skirt.
* Instead of colliders, set spring joints between the leg bones and the skirt bones. Unfortunately, springs don't have a concept of "pushing" vs "pulling", and I can visualize a lot of cases where the simulation will lead to the leg intersecting the skirt.

Notice that I can't use Unity's cloth simulator, since this acts on polygons directly, and I need to be able to export the results of the simulation in terms of bone matrices.

It's not mandatory to use Unity. I just need to find a way to simulate the leg-cloth interaction and export the results in a series of bone transforms.

Any ideas on how to solve this problem?

# Answer
Revisiting this problem five years later to post the solution that I found.

In general, it's not really possible to get good results with skeletal animation. The cloth doesn't really move in a way that can be meaningfully represented as a skeletal animation.

Instead, and over-simplifying things, I ended up simulating the cloth offline with a semi-custom solution, and getting the actual vertex positions for each vertex for each frame of the animation. I then replay this when rendering the game.

It's a lot of data, but with some aggressive quantization, it was possible to get the data to a manageable size.

If there is something to learn from this, is that skeletal animation is meant for skeleton-like structures, and cloth is not like this.
> 0 votes

# Answer
I know you said engine agnostic, but I can only tell you what I know... I don't know Unity, but Unreal Engine has the ability to apply physics simulation to bones. But it's not going to look like cloth if you're going that route. Its best used for things like pony tails, or pauldrons on armour...things that just need to shake a little. The only way it will look like cloth is to either do a physics simulation on the mesh (I don't understand why you say you can't) or to hand-animate it which would be brutally hard.

You also say a few confusing things. You say "Fortunately, the dancing is static". Static means unmoving, and by definition if they're dancing, they're not unmoving. Do you mean they're just dancing on spot? You also say doing it offline - Maybe this is a Unity term. Do you mean a pre-rendered sequence as opposed to a real-time simulation?
> 0 votes

---
Tags: physics, 3d, skeletal-animation, skinning
---


title: How does a bot know who is an enemy?

text:
# Question
Title: How does a bot know who is an enemy?
How does a bot know who is an enemy if "enemy" encompasses not only one player, which can be just hardcoded?

For example, in Warcraft 3, we can have two bot teams with faction alliances and they will treat each other as enemies.

What is the mechanism that chooses who is an ally and who is an enemy?

I suppose there is some `Map<Team, List< Units >>` and every bot is assigned some `Team` by default at the start, and when bot `sees` someone and that unit is not in the bot's team it means it is an enemy? But here is no place for allies.

**Edit**: So I am working on 2d Farm Game and I plan to add another enemy to me fraction and some enemies for all fractions.
Currently I don't have any NPC but later I want to have some units that can gather resources/kill enemies. So I was thinking that there is no difference between my units and enemy units.So there should be some rules that define that this bot treats another bot as ally or an enemy.

**PS**: The reason I started thinking about that was that I started working on inventory and understood that ideally there should be no difference between me and an npc who gathered a particular resource, so there should be some way to add a resource to same inventory by player controlled character and a bot. This led me thinking that the same should be true for another team, the code should be the same. There shouldn't be `FriendlyBot` and `EnemyBot`.Just Bot script for example and some script that assigns team id and later using this team id bot will interact with an inventory.

It seems to me that two topics are pretty close to each other as both need a structure that would allow me to organize bots into teams and inventory belongs to the whole team.

# Answer
> 1 votes
Unity has tags and Godot has Groups.

you can put the player into group/tag "player" and the enemy AI will know who is the player.

or use Team1/Team2/Team3

or maybe use `"playerID_insert_number_here"` for npcs that follow specific players in an online game.

Alternatively you can use `GameObject.Find("insert objsect to find")` in unity or `get.node("insert node to find")` in godot but this last method usually doesn't work for multiplayer games

in other game engines or if you are not using a game engine, you could probably just use variables inside the player script like creating an area around the enemy with code and basically saying

```
if anything touches the area:
  proceed:
  if anything in the area has method/variable "player"
     proceed:
else :
    enemy AI does whatever it should do when no players are around

```

and you can make as many if/else statements as needed for all the states the AI has, maybe put them into functions() and call each function when needed or use switch case but I've never used switch case so i don't know. But people more expert than me say the less nested if-else statements you use, the better.

Anyway you always rather use tags and groups since it easily works in multiplayer and it's the most performing one becase no area is created around the enemy.

one area can be unnoticeable, but get 20 enemies and that's 20 areas around them... each one needs to get update every single frame.

I personally found incredible performance boosts by not using areas.

# Answer
> 0 votes
In addition to what Cei mentioned, you can accomplish this in Unity by creating a sphere around the object you wish to detect enemies or players as i demonstrate below ,however this system has the disadvantage that enemies may be able to detect you without seeing you. If you were to make the next GTA, it would be unreal so another approach to this issue is make the enemy cast a ray while patrolling around the map

```
private void Detect()
{

    Collider[] detectedColliders = Physics.OverlapSphere(transform.position, raduis){

        for (int i = 0; i < detectedColliders.Length; i++)
        {

            if (detectedColliders[i].CompareTag("Player")){

                if (!HasTarget)
                {
                    // Do what ever you want the enemy/npc to do

                    HasTarget = true;
                }

            }
            else
            {
                // Idle
            }

        }

    }

}

```

---
Tags: unity, ai, game-mechanics
---


title: Unity vs Unreal Engine

text:
# Question
Title: Unity vs Unreal Engine
I am beginner in VR development.

Which game engine is better between Unity and Unreal Engine?

I am thinking to pick Unreal Engine as it has better graphics.

Do you think in the future, Unity will have better graphics than Unreal Engine?

Thank you.

# Answer
Game engines don't have "better" or "worse" graphics, the graphics depend on which rendering software you are using and how good of an artist you are.

**Unity vs Unreal**

Unity is advertised to everyone, Unreal engine is advertised to professional artists and clueless beginners.

So if you have no skills you will find more tutorials for unity because more people use it, but you will also have to learn more stuff.

If you are an artist but not a programmer, you can make decent games with unreal without thouching much code, at most you'll just copy and paste free or stolen code you find on the internet when blueprints don't get you there.

and if you have no skills at all but got a big bank for a big computer and a lot of assets that you can buy from the market, unreal is made especially for you.

That's why Unreal Engine got kind of an infamy for being used by a lot of talentless scammers, especially on kickstarter.com because people using it either already are professionals making big games or are completely clueless dreamers/scammers trying o resell you free assets or stuff they got from the unreal engine market and call their game "the new big thing"
> -1 votes

---
Tags: unity
---


# Question
Title: Most but not all quads appear corrupted when passing matrix and colour using VBO for instanced rendering
I was trying to batch quads with the same texture and blend mode into the single draw call using `glDrawElementsInstanced`. As long as I use just a position, texture coordinates, and projection matrix as inputs to my shader, everything works just fine. But if I add color as another input to the shader, storing it in at the `instancesVBO`, triangles are getting "corrupted", and most of the quads I\`m trying to render are rendered wrong. What is interesting, not all of them are.

My `instancedVBO` setup is as follows:

```
        glGenBuffers(1, &instanceMatrixVBO);
        glBindBuffer(GL_ARRAY_BUFFER, instanceMatrixVBO);
        glBufferData(GL_ARRAY_BUFFER, MAX_BATCH_SIZE * sizeof(QuadData), nullptr, GL_STATIC_DRAW);

        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)0);
        glEnableVertexAttribArray(3);
        glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(sizeof(glm::vec4)));
        glEnableVertexAttribArray(4);
        glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(2 * sizeof(glm::vec4)));
        glEnableVertexAttribArray(5);
        glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(3 * sizeof(glm::vec4)));
        glEnableVertexAttribArray(5);
        glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), (void*)(4 * sizeof(glm::vec4)));
        glEnableVertexAttribArray(6);

        glVertexAttribDivisor(2, 1);
        glVertexAttribDivisor(3, 1);
        glVertexAttribDivisor(4, 1);
        glVertexAttribDivisor(5, 1);
        glVertexAttribDivisor(6, 1);

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindVertexArray(0);

```

QuadData:

```
        struct QuadData
        {
            glm::mat4 position;
            glm::vec4 color;
        };

```

VBO data update:

```
    glBindBuffer(GL_ARRAY_BUFFER, instanceMatrixVBO);

    glBufferSubData(GL_ARRAY_BUFFER, 0, std::min(m_test_batch.size(), MAX_BATCH_SIZE) * (sizeof(QuadData)), m_test_batch.data());

    glBindBuffer(GL_ARRAY_BUFFER, 0);

```

`MAX_BATCH_SIZE` is a constexpr set to 100 000, and, as far as I know, is not exceeded at any point.

The shader, as far as I know, works just fine, but just in case:

```
    const char *vertexShaderSource = ""
        "#version 330 core\n"
        "\n"
        "layout (location = 0) in vec3 aPos;\n"
        "layout (location = 1) in vec2 aTexCoord;\n"
        "layout (location = 6) in vec4 aColor;\n"
        "layout (location = 2) in mat4 aTransformMatrix;\n"
        ""
        "out vec2 oTexCoord;\n"
        "out vec4 oColor;\n"
        "\n"
        "uniform mat4 uModel;\n"
        "\n"
        "void main()\n"
        "{\n"
        "   gl_Position = aTransformMatrix * vec4(aPos, 1.0);\n"
        "   oColor = aColor;"
        "   oTexCoord = aTexCoord;"
        "}\0";

```

# Answer
Your attribute pointers do not match the layout of the data you're buffering.

The `stride` parameter specifies how many bytes to step forward to get from the start of data for element 1 to the start of data for element 2, and so on. Your code claims that's 64 bytes for the first 4 attributes (`sizeof(glm::mat4)`) but only 16 bytes for the last attribute (`sizeof(glm::vec4)`), so that already doesn't make sense. The second colour will be read from inside the block of data for the first position.

In fact, both these numbers are wrong, because your data is an array of this structure:

```
struct QuadData
{
    glm::mat4 position;  // 64 bytes
    glm::vec4 color;     // 16 bytes
};

```

That's 64+16 = 80 bytes. (Assuming no padding/alignment between subsequent entries - double-check that, as I'm not deeply familiar with those alignment rules).

That means the second entry in your array of `QuadData` comes 80 bytes after the first, and your strides provided in `glVertexAttribPointer` need to reflect that spacing.

Without this, the position tries to step forward by only `sizeof(glm::mat4)` (64 bytes), and starts reading the second quad's position out of the data for the first quad's colour, because that's what's in the 64th-68th bytes of the data stream. It keeps trying to read colours in the position attribute until the 6th quad it draws, which lines up correctly with the data for the 5th quad (at 20 * 16 = 320 bytes along the buffer). This is why you see some quads (about 1 in 5) drawn approximately correctly while others are horribly corrupted.
> 0 votes

---
Tags: opengl, opengl-es, vbo, instancing
---


# Question
Title: How to disable a layer in a Tilemap's collision mask via code?
I have a tilemap in Godot 4.1 and I have defined a physics layer for a tileset, but I cannot figure out how to disable a layer in collision mask in code.

I already found out that I should get tileset first and I used this code to set a collision mask to interact with player:

```
tileset.set_physics_layer_collision_mask(0,2)

```

But the problem is I don't know how to disable it?

# Answer
> 1 votes
You should be able to set an empty mask.

Here you are setting the mask of the layer 0 to the value 2 (which has only one bit set):

```
tileset.set_physics_layer_collision_mask(0,2)

```

Similarly, you can set it 0 so no bit is set:

```
tileset.set_physics_layer_collision_mask(0,0)

```

Or you could set some other value if you need to.

---
Tags: physics, tilemap, godot-4, layers
---


# Question
Title: How do I find and replace text with regex in Godot?
The way to find and replace text in javascript from regex is like so:

```
"ab".replace(/./g, (match) => match + "&");
// outputs: a&b&

```

What is the equivalent function or functions in gdscript?

# Answer
In Godot we use the `RegEx` class, and it has a `sub` method to replace matches, however it does not take a callback. *`Callable`s are relatively recent addition in Godot, and many APIs has not been updated to use them.* That does not mean we can't do it.

Furthermore, we cannot specify global (`g`) when compiling the `RegEx` (Godot does not support the delimiter and modifier syntax). However the `g` modifier means it will not stop on one match... Which is what `search_all` will do. So we build our code on top of it.

The method `search_all` returns an `Array` of `RegExMatch` from which we can get the start and end indexes of each match... To replace the text we can use `get_slice` and build a new `String` from the pieces (No, Godot does not have an equivalent of `splice`). And since the replacement might not have the same length, the indexes would be wrong after the first replacement... So, we will keep track of an offset to make it work.

This is working Godot 4 code:

```
var subject := "ab"
var pattern := "."
var callback := func(text:String) -> String: return text + "&"

var regex := RegEx.new()
regex.compile(pattern)

var regex_matches := regex.search_all(subject)
var offset := 0
for regex_match in regex_matches:
    var start := regex_match.get_start()
    var end := regex_match.get_end()
    var length := end - start
    var text := subject.substr(start + offset, length)
    var replacement := str(callback.call(text))
    subject = (
        subject.substr(0, start + offset)
        + replacement
        + subject.substr(end + offset)
    )
    offset += replacement.length() - text.length()

prints(subject)

```

Output:

```
a&b&

```

*For Godot 3, we cannot write an inline anonymous method like I did for `callback` above. And Godot 3 didn't have typed `Array`s, so we cannot infer the type of `regex_match` thus some implicit typing won't work (I mean you would have to use `=` instead of `:=`).*

---

**Addendum**:

For your case, you could use a capture group in your pattern (i.e. `"(.)"`) so you can use a backreference in `sub`. Which results in less code - assuming you can express the replacement you want in this form.

This is working code (it should work in both Godot 3 and Godot 4):

```
var subject := "ab"
var pattern := "(.)"

var regex = RegEx.new()
regex.compile(pattern)

subject = regex.sub(subject, "$1&", true)

prints(subject)

```

Output:

```
a&b&

```

Note that I'm passing `true` as third parameter of `sub`, that is telling it to replace all matches, without it the output is `a&b` (i.e. it only replaces the first match).
> 2 votes

# Answer
Based off the awesome answer by @Theraot, here's a utility function which can be added to an autoload script.

```
func str_replace(target: String, regex: RegEx, cb: Callable) -> String:
    var out = ""
    var last_pos = 0
    for regex_match in regex.search_all(target):
        var start := regex_match.get_start()
        out += target.substr(last_pos, start - last_pos)
        out += str(cb.call(regex_match.get_string()))
        last_pos = regex_match.get_end()

    out += target.substr(last_pos)
    return out

```

Usage:

```
# outputs: "alad"
print(Globals.str_replace(
    "abcd",
    RegEx.create_from_string("bc"),
    func(text: String): return "la"
))

```
> 2 votes

---
Tags: godot
---


# Question
Title: How Can I Make a Silhouette Shader When an Object is Behind Another Object in Godot 4
I've been trying to replicate the effect created in this guide (https://www.gdquest.com/tutorial/godot/shaders/silhouette-2d/) in Godot 4, but I haven't had any luck.

The problem seems to be that in Godot 4, Color values are bound from 0 to 1, rather than being unbounded like in Godot 3. The issue is that this makes it very hard to determine when the mask is visible because you cannot give the mask a non-standard color value.

One solution I had tried was checking if the screen color matched the texture color, but this was a no-go as a) my game has 2d lighting that affects color and b) my game has a pretty consistent color palette, leading to "false positives".

I was wondering if there was a different/better method to achieve this effect. Thank you for any help you can give!

EDIT: I'm adding a minimal repro of my code here.

# Answer
> 1 votes
You've run into the problem that you can't generally share information between shaders - shaders have very limited output functionality. If shading the silhouette in screen space no longer works due to clamping in Godot 4 and unpredictable colors in your scene, I'd suggest **shading the silhouette on the foreground nodes themselves** (instead of on a character node). **It's more annoying**, since you have to apply the shader to every single (drawable) foreground node, but it will do exactly what you want.

To achieve this, we'll create a shader that takes the current character sprite and its game location *in screen space*. Similar to the GDQuest tutorial, we'll combine a solid color with the foreground texture based on the transparency of the character sprite - if it's transparent, we'll use the foreground texture, if not, the solid color. The math for this is a bit gnarly.

```
shader_type canvas_item;

// vec4(top_left_x, top_left_y, bottom_right_x, bottom_right_y)
uniform vec4 range;
// the sprite texture, which is being used as a mask in this shader
uniform sampler2D mask_texture;

void fragment() {
    vec4 texture_color = texture(TEXTURE, UV);
    // get the alpha channel of the mask based on the screen coordinates
    // (we have no access to game coordinates in shaders)
    // clamp so that we don't access data outside of the mask
    float mask_alpha = texture(mask_texture, vec2(clamp((SCREEN_UV.x - range.x) / (range.z - range.x), 0.0, 1.0), clamp((SCREEN_UV.y - range.y) / (range.w - range.y), 0.0, 1.0))).a;
    // set the alpha of this node's texture opposite to that of the mask
    texture_color.a = 1.0 - mask_alpha;
    // combine the node's texture and the silhouette color (white in this case)
    COLOR = vec4(1.0, 1.0, 1.0, 1.0) * mask_alpha + texture_color;
}

```

The current character sprite can be a `ViewportTexture`, just like the one set up in the GDQuest tutorial you linked. But for the character bounds, we need to make sure that the character's screen space location is up-to-date on every frame. We can do that with some custom logic in our game loop. Again, the math isn't pretty.

```
func _process(_delta):
    // get information on the viewport ("camera") and the character
    var viewport_scale := get_viewport_transform().get_scale()
    var viewport_size := get_viewport_rect().size
    var character_origin := ($Character as Node2D).get_global_transform_with_canvas().get_origin()
    var character_rect := ($Character/Sprite as Sprite2D).get_rect()
    // calculate the bounds of the character sprite
    var rect = Rect2(character_origin + (character_rect.position * viewport_scale), character_rect.size * viewport_scale)
    // normalise the bounds to screen space (a float between 0 and 1)
    var topleft = rect.position / viewport_size
    var bottomright = rect.end / viewport_size
    var range = Vector4(topleft.x, topleft.y, bottomright.x, bottomright.y)
    // update the shader
    (($Foreground as Sprite2D).material as ShaderMaterial).set_shader_parameter('range', range)

```

This creates an effect like this:

Here is a link to a sample project \- you can move the character with the arrow keys to see how the silhouette changes.

Be warned that this is a rough implementation and will likely require some cleanup to work with your game. Camera attributes, screen settings, viewport usage, and more could change how the math needs to work to calculate screen space positions.

---
Tags: 2d, shaders, godot-4
---


# Question
Title: Move object continuously along y with optional movement along x
I am looking for a sensible way to continuously move an object downwards with constant speed while moving left or right by some amount x when the user presses the left or right arrow keys.

Basically, movement should look like this:

```
|
|
V Right Arrow  Key pressed
    |
    |
    |
    V Right Arrow key pressed
        |
        |
        |
        V Left Arrow Key pressed
    |
    |
    |
    V

```

The movement on the x-axis should be smooth, i.e. it shouldn't jump from one spot to the next, but rather move to a **specified** x-coordinate slowly.

What I am having trouble with is moving along the x axis independently of the y-axis.

I have another project where I handled movement towards a certain goal with `Vector2.MoveTowards`

```
void Update()
{
    float step = 1 * Time.deltaTime;
    transform.position = Vector2.MoveTowards(transform.position, movementTarget, step);
}

```

I would use this by setting the object's `movementTarget`

But this doesn't lend itself to my current requirements because, when I set the `movementTarget`, I need to specify a y component, which leads the object's velocity on the direction to become zero once the movementTarget is reached, but I need the object to move continuously along the y-axis.

Basically, I am looking for a hypthetical method Vector2.MoveTowards that only takes an x-input.

I'm not sure if I'm making myself clear, so please ask questions if more information is needed.

# Answer
> 2 votes
Can you use `Mathf.MoveTowards`?

I believe it would be something like this:

```
var position = transform.position;
var step = velocity * Time.deltaTime;

position.x = Mathf.MoveTowards(position.x, targetX, step.x);
position.y = position.y + step.y;

transform.position = position;

```

*Assuming you have a `velocity` vector, and `velocity.x` is positive (so `step.X` is also positive).*

You would, of course, have to pick the `targetX` when you get the input. Perhaps something like this:

```
targetX = (direction + Mathf.Floor(transform.position.x / snap)) * snap;

```

*Where `snap` is the non-zero horizontal step, and `direction` is `-1.0f` or `1.0f`.*

I don't know if you want to impose a minimum and maximum `targetX`. If you do, you might use `Mathf.Clamp`.

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


# Question
Title: Issues with implementing shadow mapping produces weird results
This is my first attempt in implementing shadow mapping. I am using right hand coordinate system and my projection matrices are producing z values from 0 to 1. I've decided first to use orthogonal projection matrix for shadows:

```
mat4 LightProj = Ortho(-10, 10, -10, 10, -10, 20);
mat4 LightView = LookAt(-4, 4, -2);

```

This is how I produce my data for shadows. Vertex Shader:

```
mat4 Bias = mat4
    (0.5, 0.0, 0.0, 0.0,
     0.0, 0.5, 0.0, 0.0,
     0.0, 0.0, 1.0, 0.0,
     0.5, 0.5, 0.0, 1.0
     );
    Out.ShadowPos  = Bias * WorldUpdate.LightProj * WorldUpdate.LightView * Out.Pos;

```

Fragment shader:

```
float GetShadow(vec4 PositionInLightSpace, vec3 Normal, vec3 LightDir)
{
    float  Bias = 0.0; //05; //max(0.05 * (1.0 - dot(Normal, LightDir)), 0.005);
    vec3   ProjPos     = PositionInLightSpace.xyz / PositionInLightSpace.w;
    float  ShadowDepth = texture(ShadowMap, ProjPos.xy).x;
    float  ObjectDepth = ProjPos.z;
    float  Result      = (ObjectDepth - Bias) > ShadowDepth ? 0.0 : 1.0;
    return Result;
}

    float Shadow  = GetShadow(In.ShadowPos, Normal, LightDir);
    vec3 Ambient  = vec3(1.0, 1.0, 1.0) * 0.2;

    OutputColor = vec4(Ambient + Shadow * Light, 1.0) * In.Col;

```

At first glance everything looks fine. Even generated shadow map:  But the results looks really way off the correct solution:  How can I solve this issue? Thanks in advance

# Answer
So, as I was using vulkan, it should be like this:

```
mat4 Bias = mat4
    (0.5,  0.0, 0.0, 0.0,
     0.0, -0.5, 0.0, 0.0,
     0.0,  0.0, 1.0, 0.0,
     0.5,  0.5, 0.0, 1.0);

```

The thing is that in vulkan everything being rendered from bottom to top and therefor in my renderer Y is reversed. That's it.
> 0 votes

---
Tags: glsl, shadows, shadow-mapping, vulkan
---


# Question
Title: How come serverless functions are so much more expensive than a VPS hosting my PHP API?
I'm working on an online turn-based game. I will have a server, but it will be used strictly for storing match data and relaying it to the match's participants (or spectators). For simplicity, no game logic will be processed in the server and the participants will be the ones to decide the legality of the enemy's moves etc.

---

My backend cloud knowledge is limited. I can work fine with PHP and MySQL, so I can technically make a PHP API, host it, and have the players poll it via HTTP requests every few seconds to get updates on the match (or upload commands). The PHP script will always open a MySQL connection, do one or two small queries and return a tiny bit of JSON-formatted data. To summarize, I believe that a single request would take at most 2 seconds to complete, and the output will be usually less than 100 bytes.

Given this fact, I figured I could perhaps try one of those serverless cloud functions services, like Azure's. It sounds just perfect for my kind of scenario.

For this project, I am estimating at most 100 users playing a match **at any given time**. And given the way the game is designed, they should probably poll data every two seconds. So `100 * 30 * 24 * 60 * 30 = ~130M` executions per month. With Azure, that could be around $540 monthly just to support about 100 players.

This got me thinking, what if I just host the PHP API and MySQL database in a normal VPS, like GoDaddy's perhaps? Their cheapest option is about $50 a month. They don't meter the number of requests, concurrent users or bandwidth used (my usage is pretty low anyway, less than 15GB monthly).

So my question is, how come a 'serverless function' service is massively more expensive than just using a normal VPS to host my PHP API? Is there a catch that I may be missing?

---

Naturally it's all about testing - I should try both of them, but I figured someone has been through this already, or perhaps there is something obvious I am missing.

# Answer
If you want only managing database, you can use shared hosting pack. You don't need Bare metal or VPS cloud server. Serverless function or aws Lambda servers developed for instant processing and not being used for a long time. It would be very costly to run them continuously and shut them back down.
> 0 votes

# Answer
With those serverless APIs, you are paying for much more than just traffic and computing resources. You are paying for:

* Scalability. Suddenly have several orders of magnitude more requests because the game became a viral hit? No problem. Adding a couple instances just takes a couple clicks, or can even be automatized via APIs.
* Global availability. Companies like Amazon, Microsoft or Google have datacenters around the globe. This allows you to provide short latency times to your players no matter where they are. Renting your own servers all around the world from all kinds of local companies *might* be possible, but could turn into an administrative nightmare.
* Platform as a service. You might be able to save a lot of development and administration hours by using their existing services instead of first setting up your server and then creating your own API from scratch in PHP. And person-hours are money!

These factors might or might not matter to you. If you are strapped for cash, then going the "do it yourself" route with a private virtual server might be a viable alternative. And another advantage is that you avoid the vendor lock-in you have with a proprietary PaaS solution.
> 0 votes

---
Tags: multiplayer, php, mysql, cloud-computing
---


# Question
Title: Attempt to call missing method - Lua (Roblox studio)
I am trying to develop a game in Roblox and I have am cannot call a method on a class that I created. I have added my steps below. I am certain the path to the model is correct and I think I have created everything as I should.

I have created the following model

```
local PlayerLeagueUpdateModel = { }
PlayerLeagueUpdateModel.__index = PlayerLeagueUpdateModel

function PlayerLeagueUpdateModel.new(playerKey: StringValue)
    local self = setmetatable({ }, PlayerLeagueUpdateModel)
    self.PlayerKey = playerKey
    return self
end

function PlayerLeagueUpdateModel:GetPlayerKey()
    return self.PlayerKey
end

return PlayerLeagueUpdateModel

```

In a separate file I create a new instance of this model and I call GetPlayerKey(). Then print the result. It prints the expected value. I have provided the code below. I then fire a bindable event.

```
local playerLeagueUpdateModel = PlayerLeagueUpdateModel.new(playerKey)

local playerKey = playerLeagueUpdateModel:GetPlayerKey()
print(playerKey)

PlayerBindableEvent:Fire(saveEventType, player, playerLeagueUpdateModel)

```

I have a script watching for this bindable event. The script is provided below

```
local function HandlePlayerActiveInLeagueUpdate(eventType: EventTypes, player: Player, playerLeagueUpdateModel: PlayerLeagueUpdateModel)
    local playerKey = playerLeagueUpdateModel:GetPlayerKey()
    print(playerKey)

    PlayerDataManager.UpdatePlayerLeagueData(player, playerLeagueUpdateModel)
end

```

When I call playerLeagueUpdateModel:GetPlayerKey() I get the following error message

> attempt to call missing method 'GetPlayerKey' of table

What am I doing wrong?

# Answer
> 1 votes
its supposed to be local playerKey = playerLeagueUpdateModel.GetPlayerKey()

with a dot

---
Tags: lua, roblox
---


# Question
Title: How to check if player actually went through a trigger area and didn't just touch it?
I'm trying to make a racing game that measures your distance from the center-line of the road. To do this I need to check on which part of the road the player is, so the calculation is correct. (If it is a turn or a straight road.)

I made a trigger wall between road-parts, but for the trigger to work correctly I need to know if player actually drove through the trigger or just touched it and backed-off. Because if you activate the trigger and don't end up on the other side, then you changed the road calculation method without changing the road you are on.

I've tried making a small cube at the player location, reducing the width of the trigger and then setting only cube and trigger to interact on the separate layer. It failed as with average speed the trigger didn't detect the cube. (Cube is a part of player cart, so you can't assign to it rigid body as it just falls-off)

I'm trying to think of geometrical solution, but I have no idea how to generalize it. In short I'd need to draw a line through a middle of trigger area along the separating axis and check if OnTriggerEnter player is on one side and OnTriggerExit is on the other side of the trigger.

I'd appreciate any help.

# Answer
> 2 votes
Here's one way you can do this, using dot products to check how far the vehicle is from the center of the trigger's transform along the trigger's z axis (blue arrow in the local transform gizmo).

To perform well, the trigger should be at least one vehicle length thick, or thicker if your vehicles are very fast, so they don't tunnel past it in a single frame. Align the trigger so its local z+ axis points "forward" along the track.

```
public class Checkpoint : MonoBehaviour {

    // Identifier for "this" part of the track - maybe you have a component for that?
    public int trackSegment;

    // Reference to checkpoint "behind" this one for when going backwards.
    public Checkpoint previous;

    // Track which side a vehicle was on when it entered the trigger.
    List<Vehicle> _enteredFromRear;
    List<Vehicle> _enderedFromFront;

    // Gets the distance in world units along the checkpoint's z+ axis (blue arrow)
    // that the vehicle is in front of the checkpoint (negative for behind).
    float GetForwardDistance(Vehicle vehicle) {
        var toVehicle = vehicle.transform.position - transform.position;
        return Vector3.Dot(toVehicle, transform.forward);
    }

    // When a vehicle enters the trigger, record which side it entered from.
    void OnTriggerEnter(Collider other) {
        // Ignore collisions not from vehicles (use physics layers to exclude these completely)
        if (!other.rigidbody.TryGetComponent(out Vehicle vehicle))
            return;

        // Ignore repeated entries from vehicles with multiple colliders.
        if (_enteredFromRear.Contains(vehicle) || _enteredFromFront.Contains(vehicle))
            return;

        if (GetForwardDistance(vehicle) <= 0) {
            _enteredFromRear.Add(vehicle);
        } else {
            _enteredFromFront.Add(vehicle);
        }
    }

    // When a vehicle exits the trigger, check whether it left from the
    // opposite side it entered, and update its track segment if so.
    void OnTriggerExit(Collider other) {
        // Again, filtering with physics layers saves redundant calls.
        if (!other.rigidbody.TryGetComponent(out Vehicle vehicle))
            return;

        if (GetForwardDistance(vehicle) > 0) {
            // If we left from the front, and entered from the back...
            if (CheckCrossing(vehicle, _enteredFromRear, _enteredFromFront)
                vehicle.OnEnterTrackSegment(trackSegment);
        } else {
            // If we left from the back, and entered from the front...
            if (CheckCrossing(vehicle, _enteredFromFront, _enteredFromRear)
                vehicle.OnEnterTrackSegment(previous.trackSegment);
        }
    }

    // Checks whether vehicle came from the "cross" side (true)
    // or the "reverse" side (false), and removes the vehicle from that list.
    bool CheckCrossing(Vehicle vehicle, List<Vehicle> cross, List<Vehicle> reverse) {
        int index = cross.IndexOf(vehicle);

        if (index < 0) {
            reverse.Remove(vehicle);
            return false;
        }

        cross.RemoveAt(index);
        return true;
    }
}

```

# Answer
> 1 votes
If you want to know if the car is within a race track segment, then don't use OnTriggerEnter. Create a trigger area that covers **the whole** track segment, and use `OnTriggerStay`.

This method will get called every frame while the car's collider intersects the collider of the area. So you can use it to set the current segment the car is in, which you then use (right there or in another script) to do your distance calculation.

However, there is a slight problem with this method: When the car is on the edge of two track segments, its collider will intersect both of them. That means it will trigger the OnTriggerStay methods of both colliders in the same frame. This might or might not be a problem for you, depending on what you are doing, how you are doing it and why you are doing it. If that's not acceptable for you, then I have a completely different approach for you:

Still have colliders that cover the whole track segments, but don't use trigger events, use `Physics.OverlapSphere`. Use this method from the car with its `transform.position` to detect the colliders of the race track its center is currently in. This method returns not one but an array of colliers. This array might contain more than one collider even for a sphere with radius 0 in case two track segments overlap. In that case it would be prudent to just pick the first one. Also, this method is unaware of which gameObject called it, so it is possible for an object to detect *its own* collider with it as well. To avoid that, put all the race tracks with their colliders on a separate physics layer, and use a layer mask in your OverlapSphere call so the method detects only colliders.

---
Tags: unity, geometry, racing
---


# Question
Title: "Subdividing" a quad with uneven side divisions?
I'm trying to generate an arbitrary quad mesh with each side having a different, arbitrary number of vertices, ideally with a fairly evenly-size distribution of triangles making up the final mesh, similar to a normal quad subdivision. I haven't been able to find any algorithms for generating such a shape, but Delauney triangulation looks like it might be helpful if I could figure out how to evenly distribute the interior vertices. Is there an algorithm for such triangulation?

# Answer
I'm not already aware of an algorithm that solves this problem, but if I had to write one, here is what I would try.

1. Let `n_u` = (top vertex count + bottom vertex count) / 2 - 2.
2. Let `n_v` = (left vertex count + right vertex count) / 2 - 2.
3. Generate interior points in a `n_u` × `n_v` rectangular grid.

By taking the mean of the edge counts, the difference between the interior triangle size and the edge triangle size is minimized, which should avoid overly skinny triangles. Of course, it could be tweaked downward to trade off density match for lower total triangle count.

It might be more efficient in triangle count to smoothly interpolate from one edge's vertex count to the other, but that reopens the question of how to place the points. Perhaps it could be treated as a *dithering* (of point presence or absence) on a grid as fine as the finest edge subdivision?
> 0 votes

---
Tags: mesh, triangulation
---


# Question
Title: Physics.OverlapBox not detecting 2D collider objects
I have a 2D game with several square objects (*tiles*) that each have a BoxCollider2D and a kinematic Rigidbody2D. I want to detect when one tile is located to the right of another tile, such as to prevent movement in that direction. All the tiles are on the default layer (layer 0). To detect if there is a tile to the right of the current tile, I use `Physics.OverlapBox`, but for some reason, it never detecs any object (tile) in the OverlapBox, even though the visual gizmo in red which represents the OverlapBox clearly overlaps it.

This should trigger the line `Debug.Log("intersected")`, as specified below, but it doesn't.

My code is as follows:

```
void Update()
{
    rightSpacePosition = new Vector2(activeTile.transform.position.x + fBlockSize, activeTile.transform.position.y);
    Collider[] intersectingBox = Physics.OverlapBox(rightSpacePosition, new Vector2(0.5f * fBlockSize, 0.5f * fBlockSize), Quaternion.identity);
    if (intersectingBox.Length != 0)
    {
        Debug.Log("intersected")
    }
}

```

I have also tried specifying the layer with

```
Collider[] intersectingBox = Physics.OverlapBox(rightSpacePosition, new Vector2(0.5f * fBlockSize, 0.5f * fBlockSize), Quaternion.identity, 0);

```

and

```
Collider[] intersectingBox = Physics.OverlapBox(rightSpacePosition, new Vector2(0.5f * fBlockSize, 0.5f * fBlockSize), Quaternion.identity, 1<<0);

```

In order to visually debug, I also draw a wirecube

```
void OnDrawGizmos()
{
    Gizmos.color = Color.red;
    Gizmos.DrawWireCube(rightSpacePosition, new Vector3(fBlockSize, fBlockSize));
}

```

Also, here are the settings of the Rigidbody2D and BoxCollider2D

# Answer
In my case, using Physics**2D**.OverlapBoxAll fixed the issue
> 0 votes

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


# Question
Title: Class in a class in Godot, how do you access things from the containing class?
I have a class inside a class. I would like the inner class to be able to access functions from the outer class. Something like what's below:

```
@onready var my_label = $MarginContainer/Panel/Label

func display_text(text: String):
    my_label.set_text(text)

class DialogueSession
    var num = 1
    func show_next():
         display_text("the next number is:" + num++)

```

I get the error:

> Error: Function display\_text() not found in base self

How can I achieve this code structuring?

# Answer
> 1 votes
One way is to pass `self` into the `DialogueSession._init()`, like so:

```
@onready var my_label = $MarginContainer/Panel/Label

func display_text(text: String):
    my_label.set_text(text)

func create_dialogue_session():
    return DialogueSession.new(self)

class DialogueSession:
    var container_class
    _init(c_c):
        container_class = c_c

    func show_next():
         container_class.display_text("the next number is:" + num++)

```

I do not believe this is likely to be the best way

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


# Question
Title: Pressing two buttons on Android with same thumb touch. UI Event Triggers not working
NOTE: See bottom of the question as I have managed to use a workaround which works to press the two buttons at once on Android (thanks to Douglas Potestas help)

I've struggled with this in the past and got it working. But its been a long time since I have used raycasts and I have mostly forgotten. Quick summary before people tell me to use `OnPointerEnter` etc is that on all of my Android games using pointer events you cannot press the two buttons (eg. imaging a NES gamepad pressing A and B with the same thumb like when you play Mario or something). You cannot slide the thumb to press both it only registers the first button hit, and this is not adequate for most of my game ideas.

Basically, I want to check if the thumb is over any amount of buttons at every frame of the game loop.

So I have this very basic code which I hoped would work, but the hit only returns anything if it hits a physical game object such as Cube or Capsule.

I want it to return if it hits a UI Image/Panel/Button (it matters not which one really).

I've tried adding 2D box collider and a 3D cube collider both as trigger and not trigger and made sure they're big enough. I've tagged the image/button. I've checked the "Raycast Target" box. Here is update loop of my OnScreenControlManager.cs

```
     void Update () {
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit;
         float rayLength = Mathf.Infinity;

         if (Physics.Raycast(ray, out hit, rayLength))
         {
             Debug.Log("hit coll = " + hit.collider.tag);
             if (hit.collider.tag == "LeftButton")
             {
                 Debug.Log("hit coll = " + hit.collider.tag);
             }
         }
     }

```

I definitely had this working about a year ago in Unity 5. I'm now using Unity 2017, hope that isn't anything to do with it.

Have also tried Physics2d.Raycast:

```
private void Update()
{
    RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

    if (hit.collider != null)
    {
        Debug.Log("Target tag: " + hit.collider.tag);
    }
}

```

Solution which works using new Rects and the Overlaps method. (Note , you cannot use this if the buttons are small and close together

```
public class OnScreenController : MonoBehaviour
{

    Rect touchRect;
    public float touchRectExtents;

    Bounds buttonLeftBounds;
    public GameObject buttonLeft;
    Rect buttonLeftRect;

    Bounds buttonABounds;
    public GameObject buttonA;
    Rect buttonARect;

    Bounds buttonBBounds;
    public GameObject buttonB;
    Rect buttonBRect;

    public Text aPressed, bPressed;

    private void Start()
    {
        buttonLeftBounds = buttonLeft.GetComponent<Collider2D>().bounds;

        buttonABounds = buttonA.GetComponent<Collider2D>().bounds;
        buttonBBounds = buttonB.GetComponent<Collider2D>().bounds;
    }

    private void Update()
    {
        touchRect = new Rect(Input.mousePosition.x - touchRectExtents, Input.mousePosition.y - touchRectExtents, touchRectExtents * 2, touchRectExtents * 2);

        buttonLeftRect = new Rect(buttonLeftBounds.center.x - buttonLeftBounds.extents.x, buttonLeftBounds.center.y + buttonLeftBounds.extents.y, buttonLeftBounds.size.x, buttonLeftBounds.size.y);

        buttonARect = new Rect(buttonABounds.center.x - buttonABounds.extents.x, buttonABounds.center.y + buttonABounds.extents.y, buttonABounds.size.x, buttonABounds.size.y);
        buttonBRect = new Rect(buttonBBounds.center.x - buttonBBounds.extents.x, buttonBBounds.center.y + buttonBBounds.extents.y, buttonBBounds.size.x, buttonBBounds.size.y);

        if (touchRect.Overlaps(buttonLeftRect))
        {
            Debug.Log(" LEFT PRESSED");
        }
        if (touchRect.Overlaps(buttonARect))
        {
            aPressed.text = "A PRESSED";
        }
        else
        {
            aPressed.text = "A NOT PRESSED";
        }

        if (touchRect.Overlaps(buttonBRect))
        {
            bPressed.text = "B PRESSED";
        }
        else
        {
            bPressed.text = "B NOT PRESSED";
        }
    }
}

```

EDIT: Still doesn't work :\[ although I can now press the two buttons at once with the same touch, I need to add a way to check for other touches. For example if I am using the D-Pad with left thumb, this code doesn't even detect the hit on the buttons because `Mouse.inputPosition` is still over at the D-Pad.

# Answer
> 3 votes
I faced the same issue and found some other solution that could solve it, so probably it will be helpful for someone. Used unity version: 2022.2.
First of all, I need to say that I’m using input actions (new input system), not an input manager.

My input actions look like this:

You also should have an EventSystem on your Project Hierarchy. Probably you already have one if you add a Canvas or some UI element. I need to mention that I didn’t change an EventSystem or its properties, except just applying `Input System UI Input Module`, so it looks like this:

My Canvas has a `DPad` GameObject with 4 buttons (up, left, right and down).

`DPad` object has a `DPadController` script as a component.

```
public class DPadController : MonoBehaviour
{
    [SerializeField] private EventSystem eventSystem;

    private GameObject _lastPressedButton;
    private Dictionary<string, GameObject> _customPointerUpEventCalls;

    public void Awake()
    {
        _customPointerUpEventCalls = new Dictionary<string, GameObject>();
    }

    public void PointerDown(GameObject pressedButton)
    {
        _lastPressedButton = pressedButton;
    }

    public void PointerEnter(GameObject pressedButton)
    {
        if (!_lastPressedButton)
        {
            return;
        }

        _customPointerUpEventCalls.TryAdd(_lastPressedButton.name, _lastPressedButton);
        ExecuteEvents.Execute(_lastPressedButton,
            new PointerEventData(eventSystem), ExecuteEvents.pointerUpHandler);
        ExecuteEvents.Execute(pressedButton,
            new PointerEventData(eventSystem), ExecuteEvents.pointerDownHandler);
        _lastPressedButton = pressedButton;
    }

    public void PointerUp(GameObject pressedButton)
    {
        if (_customPointerUpEventCalls.ContainsKey(pressedButton.name))
        {
            // remove and do nothing because we already called 'up event' earlier in PointerEnter
            _customPointerUpEventCalls.Remove(pressedButton.name);
            return;
        }

        if (!_lastPressedButton)
        {
            return;
        }
        _customPointerUpEventCalls.TryAdd(_lastPressedButton.name, _lastPressedButton);
        ExecuteEvents.Execute(_lastPressedButton,
            new PointerEventData(eventSystem), ExecuteEvents.pointerUpHandler);
        _lastPressedButton = null;
    }
}

```

As you see, you would need to attach `EventSystem` to an appropriate variable in UnityEditor. In this script, methods are just ordinary methods (not events) and are called from `DPadButtonController` script. In `DPadController` we are saving the last pressed button in ‘PointerDown’ method and if we enter some new button area (during the already pressed event) then we explicitly call `PointerUp` event on the last pressed button, mark it as our own custom event invocation and call `PointerDown` on the newly entered button. We need to mark custom event invocation; otherwise, the `PointerUp` method will be called indefinitely.

Each of the movement buttons has a `DPadButtonController` script as a component.

```
public class DPadButtonController : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler
{
    [SerializeField] private GameObject dpadControllerObject;
    private DPadController _dpadController;

    public void Awake()
    {
        _dpadController = dpadControllerObject.GetComponent<DPadController>();
    }

    public void Start()
    {
        // to make buttons clickable only where image is
        GetComponent<Image>().alphaHitTestMinimumThreshold = 0.1f
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        _dpadController.PointerDown(gameObject);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        _dpadController.PointerUp(gameObject);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        _dpadController.PointerEnter(gameObject);
    }
}

```

In order for the `DPadButtonController` script to work, you would need to attach the `DPad` GameObject to an appropriate variable in UnityEditor. And here we have only `DPadController`’s method invocations.

In my case, I need one button to stop working and another to start working during the same thumb touch. But the provided solution could be easily adapted for the case presented in the question.

I hope this was helpful.

# Answer
> 1 votes
You probably want Rect.Overlap()

It allows you to check if one rect overlaps another rect.

So you would want to have a rect for the players touch. Which you can crate using the position and radius of Input.Gettouch(). Then do a fingerRect.Overlap(aButtonRect) instead physics.raycast.

If you are only trying to do a specific point instead of an area you can use Rect.Contains().

Which would look something like AbuttonRect.Contains(Input.mouseposition)

---
Tags: unity, android, gui, input, touch
---


# Question
Title: Platformer Sprite is inside of a Solid Sprite
My platformer sprite in Construct 2 works normally aside from it not colliding correctly with platform sprites that are solid, as it goes through them until the platform is not quite halfway up the platformer sprite, and I cannot figure out why.

# Answer
Solved - Had to edit collision box polygons, this was not explained in the tutorial I am using.
> 0 votes

---
Tags: collision-detection, sprites, construct-2
---


title: Rain particle system scale

text:
# Question
Title: Rain particle system scale
I'm using a rain particle system and using cone a radius to scale it.

My question is what is the best way to make the rain particle covering the entire map?

And does increasing the rate over time affect performance? And is it necessary to increase it when increasing the radius?

# Answer
The larger the area of your particle system, the more particles you'll need to have alive in that volume at any given time for it to look appropriately dense/full.

Every one of those particles has a cost.

Each raindrop costs processing time to animate it each frame, bandwidth to upload its vertices for rendering, vertex shading time to transform it to the screen (even the ones off-screen need to be transformed to find out whether they *could* be on-screen), and rasterization, shading, and blending costs for the few that actually end up visible on screen.

You'll also pay a lot of overdraw this way. If you want to render a heavy sleet with dense sheets of rain out into the distance, drawing it one raindrop at a time means you end up drawing over the same pixels again and again, adding very little visible difference with each pass, and devouring your GPU's fill rate budget.

Instead, it's helpful to use a camera-centric approach. The player only *sees* raindrops near the camera, so let's only spend time simulating and drawing those ones

Have a small-ish particle system positioned nearby in front of the camera, and co-moving with it, so that it always fills the field of view. Simulate the particles in world space, so that you can still walk past them as they fall, rather than the rain seeming to stay glued to you as you move.

If your movement speed is fast, you may need to teleport trailing particles from behind you back in front of you to keep the density consistent - otherwise you can outrun the rain: the emitter hasn't had enough time to drop rain in the new region you've moved into. I had to do this to simulate space dust for a fast-moving spaceship, poking into the particle system's particle buffer to reposition them manually. Your raindrop shader can fade drops to transparent just before this repositioning distance, so the player never sees rain just pop in/out of existence this way.

You can render more distant rain with a second particle system farther out with a simpler shader, or a full-screen quad that uses an animated shader effect to imitate dense, distant rain with a single shading and blending pass, instead of transforming and layering thousands of individual raindrop meshes. This makes it easier to dial the weather all the way up to hurricane intensity where visibility drops off, without murdering your framerate. Instead it acts more like a textured screenspace fog, with roughly constant rendering cost regardless of droplet density or draw distance. It won't parallax exactly correctly, but that's what the nearby particle rain is for, to sell the illusion where the player can see it best.

Games will often use a similar screen-space effect to render very close raindrops / ones splashing on the camera itself (if having a "physical" camera is part of your game's aesthetic). Rendering close, medium, and far rain effects separately like this helps you focus each layer's effects on what looks best at that distance, so you don't pay for beautiful refractions that are only visible up-close when you're rendering "filler" sleet a city block away.

You can see in this Reddit post that Starfield uses this layered local particles trick: there's a sparse rain within a span of a few meters of the player, and a dense rain just around their head (where the game camera usually sits):
> 1 votes

---
Tags: unity, particles, effects
---