# Question
Title: Pygame bullet firerate not working sometimes
i have made this bullet class but i have a problem with the firerate. Sometimes i'm not able to shoot even when the little delay (700ms) between the two shots has ended. I guess it's due to the pygame.time.set\_timer(). Anyways i'm looking for a quick solution because i wanna move on to work on another part of this game.

```
...

class Singlebullet(object):

    def __init__(self):
        self.img = pygame.image.load(r'C:\Users\Salem\Documents\MyGame1\bullet.png')
        self.state = 'ready'
        self.speed = 0
        self.firerate = 700

    def shoot(self):
        if current_bullet_type == 'single':
            if self.state == 'ready':
                self.x = myplane.x + 71
                self.y = myplane.y
            if self.state == 'fire':
                self.speed = -13
            for event in events:
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    if event.key == pygame.K_SPACE:
                        self.state = 'fire'
                        pygame.time.set_timer(pygame.USEREVENT+1, self.firerate)
                if event.type == pygame.USEREVENT+1:
                    self.state = 'ready'
            MyScrollingScreen.blit(self.img, (self.x, self.y))
            self.y += self.speed
s1 = Singlebullet()
...
while running:
    ...
    s1.shoot()
    ...

```

# Answer
So, i realized that i was missusing the `pygame.time.set_timer()` function. In fact, this resulted in making me able to shoot the bullet only when the timer resets itself, but i wasn't able to shoot when the countdown timer starts again. Then i added the condition that the bullet should be in ready state before starting/restarting the timer (now, the timer won't be restarted unless the bullet's state is set to 'ready' and i click the space button):

```
for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and self.state == 'ready':
                    self.state = 'fire'
                    pygame.time.set_timer(pygame.USEREVENT+1, self.firerate)
            if event.type == pygame.USEREVENT+1:
                self.state = 'ready'

```

And i have also removed the `if event.type == pygame.KEYUP` as it was absolutely useless.
> 1 votes

---
Tags: python, pygame, oop
---


# Question
Title: How to make a moving platform in Godot not be affected by collisions?
I am trying to make a moving platform in Godot (for a 2D platform game, but I suspect the issue would be similar in 3D).

Basically, both my player and my platform are KinematicBody2D, and they move via the `move_and_slide()` method. The documentation says:

> You can use this to make moving or rotating platforms, or to make nodes push other nodes.

This seems to fit my use case. However, when the player collides with the platform, the latter will be affected. For example, if the player stands on top of the platform, it will slowly start going down. I don't want that, I want the platform to move in a fixed fashion no matter what is throw at it (and if the player stands in the path of the platform for example, the player should be pushed).

How can I solve this? I was thinking about using a StaticBody2D for the platform, but the documentation says:

> A StaticBody2D is a body that is not intended to move.

So I am not sure if this is the correct solution. It seems that the `move_and_slide()` method has some additional parameters, such as `infinite_inertia`, but the documentation is not very clear to me as to what they do exactly.

# Answer
Use the collision layer and mask settings. Put the player and platform on separate layers. Using the mask settings of each node, have the platform affect the player, but don't have the player affect the platform.

Are you sure you need to move-and-slide the platform? You could tween its position between two points or have it follow a path. Then it could be a RigidBody2D in kinematic mode.
> 1 votes

---
Tags: physics, platformer, godot
---


# Question
Title: How do collision meshes work in games like Zelda on the N64?
I was recently reading about the technology of Ocarina of Time/Majoras Mask and discovered that world collision is done using a single triangle mesh (vertices, normals, etc) for an entire area. There are also no signs of preprocessed spatial partitioning methods in that data structure.

**What algorithms exist for performing character collision on a similar arbitrary triangle mesh fast enough to run on a platform like the N64?**

Quake is a contemporary game with a similar feature that came to mind. I understand Quake brush collision works by subdividing an AABB with planes. If a point is in the AABB and behind all the planes there is a collision. However, this method only works using a bunch of individual convex objects to make up a collision scene.

Zelda data structure details Here:

http://wiki.spinout182.com/w/Zelda\_64:\_Collision\_Format http://zeldaspeedruns.com/oot/generalknowledge/zelda-64-engine

**EDIT** \- I don't need to know the real method used by the real game, Zelda is an example. I am looking for a method of achieving a similar effect under similar hardware constraints.

# Answer
> 5 votes
**EDIT**:

This project decompiled Mario 64 and contains the source for collision.

Taking tigoru's advice. I instead searched for how the technique is done in Mario 64. (Zelda's engine is a direct derivative).

I found that this document was mentioned in Mario 64 discussions several times.

I read through the paper and it describes an algorithm that would solve this problem. It works in a similar way to sweeping ellipses in quake, but is built around triangle soup, rather than brush/plane soup.

> The algorithm presented in this paper handles collision detection against arbitrary meshes stored as a so-called polygon soup. When a collision is detected the algorithm will slide the moving entity along the obstacles as it is typically seen in 3d computer games. The moving entity is approximated with an ellipsoid which gives a fairly tight fit for most humanoid or animal shapes.

The algorithm also solves a lot of performance problems:

> Personally I haven’t had any performance problems with it and one also has to remember that there are two “early out” points in the function which actually kicks in quite often. Here are some statistics: I walked around a few minutes in an ERA test map which consisted of both a terrain (build from a heightmap) and polygon meshes such as houses, stairs etc. In total 1.1 million triangles were sent to the function over the whole test period and of those approximately 40% were detected to be backfacing and thus skipped1. Of the remaining 700.000 triangles 65% were able to exit early from the function after just a few cheap tests to calculate the time values t0 and t1. Of those triangles that didn’t exit early most had to perform the sweep test but a few could skip the sweep because a collision against the inside of the triangle were detected. All in all only about 20% of the triangles being sent to the function had to actually be checked for collision against the inside or edge of the triangle and thus payed the full price for the rather long function.

# Answer
> 3 votes
I'd be surprised if they don't pre-process that list of polygons on load into a spatial data structure. It could be as simple as a uniform 2D grid over the world, or something more complicated like a k-d tree.

That would allow you to rapidly find a short list of the polygons which are close to a point of interest, and you can then test each one to see if you're colliding.

Any modern physics engine should easily handle a static mesh of collision polygons efficiently by using some form of spatial subdivision. For example check out the btBvhTriangleMeshShape that bullet has.

# Answer
> 1 votes
The correct answer, based on the decompiled source code, is that a 16 x 16 spatial grid is used, dividing each level into 256 lists of surfaces that cross into the space and are candidates for collision depending on the space Mario occupies, which is a single point in space between his feet.

Object to object collisions use cylinder to cylinder collision checking with each object having only a defined cylinder height, cylinder radius and cylinder Y offset.

Object to surface collisions use point to rectangle collision detection. The single point is between Mario's feet, and it is logically checked 50 units from walls, 160 units from ceilings and 0 units to floors. Surface classification is based on Y projection of the normal vector only. To realize this, flat planes that make up walls are assumed to have width 50 during the collision testing, ceilings have depth 160, and so on. Per each game frame, up to 30 frames per second, four tests are performed at even intervals between Mario's initial position and his final position between the frame. This minimizes the chances of large velocities allowing him to break through walls when frames are dropped.

---
Tags: 3d, collision-detection, performance
---


title: How to make sound fx follow the player?

text:
# Question
Title: How to make sound fx follow the player?
Here is the setup:

```
> KinematicBody2D (Player)
- > Camera2D
- > Node2D (SoundFX)
- - > Timer (1 sec)
- - > AudioStreamPlayer2D (Beep)

```

It works fine at the beginning of the scene, but the sound fades out when the player moves away. Whyt is that and how to fix it?

I have tried to make the `AudioStreamPlayer2D` a child of a `CanvasLayer` node, without success.

# Answer
To have sound without attenuation, the simple solution is to use `AudioStreamPlayer` instead of `AudioStreamPlayer2D`.

The `AudioStreamPlayer2D` node is a `AudioStreamPlayer` with a 2D position. The maximum distance and attenuation curve controls how strong it sounds based on its distance to the screen center. The horizontal offset from the center of the screen is used for panning.

*And sadly, there isn't a `Listener2D` (no such node exist), that we could place on the Player. `AudioStreamPlayer2D` always work with the screen center.*

Of course, given the scene tree, I'd expect the `AudioStreamPlayer2D` to stay on the center of the screen. However, if the Player is moving away from the center of the screen (which depends on how the `Camera2D` moves) or if the `AudioStreamPlayer2D` is moving relative to it, then you would have attenuation.

Thus, for a solution using `AudioStreamPlayer2D`, I'd suggest to make it child of the current `Camera2D`, so that it is centered on the screen (regardless of whether or not the player moves away from the center of the screen)… As long as you don't change current `Camera2D`, or move the `AudioStreamPlayer2D` relative to it.

For a more complex scenario, let us say you want the `AudioStreamPlayer2D` centered on the screen when the current `Camera2D` is the one on the Player, but centered on the Player when you are using another camera. To do that, we can put a script on the `AudioStreamPlayer2D` to move it. Give it the `NodePath` of the `Camera2D` and the Player. The script will check if the `Camera2D` is current, and if it is, set its own global position to match the `Camera2D`. If it isn't, then set its won global position to match the Player. *Note that this requires to always unset the current `Camera2D` when you set a new one.*
> 2 votes

---
Tags: camera, godot, sound-effects
---


# Question
Title: Unity Cloud Build: Corrupted reffernces. Reimport All Assets possible?
When references in scenes or prefabs are missing, usually a reimport all fixes all issues. But when those problems occur in a cloud build that get's its data from a git repository the solution seems much harder. The AssetDatabase API allows for a reimport in a prebuild script:

```
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;

class Reimporter : IPreprocessBuildWithReport {

    public int callbackOrder { get { return 0; } }
    public void OnPreprocessBuild(BuildReport report) {
        AssetDatabase.ImportAsset("Assets", ImportAssetOptions.ImportRecursive);
    }
}

```

But the `UnityEditor` libary isn't accessible in a cloud build. Is there a way to fix missing references in a cloud build or trigger a reimport via a pre build script or something similar?

PS: Local builds after a fresh checkout of the github project do not have this issue, and only Cloud builds suffer from these missing references. Maybe someone knows the root of the issue and how to overcome it, so that none of these hacky solutions would be required.

# Answer
The solution is very simple: Next to the the regular "build" button in the start build dropdown there's a "clean build". This fixed all of our problems.

It seemes to have the same effect as a local "reimport all".

The solution was found here.
> 1 votes

---
Tags: unity
---


# Question
Title: How to trigger OnMouseX events on Kinematic Rigidbody2D object with a different collider than one used for collisions?
I have a use-case where I have an object with a Collider2D and a Kinematic RigidBody2D in order to do Kinematic movement.

However, I also want to be able to select/hover that object with a OnMouseDown/OnMouseEnter/etc, using a larger collider than I would use for the kinematic movement.

My current attempt at a solution is to have Physics-related scripts/rigidbody2d/collider2d as the top level game object, and to have a child object, with a larger collider2D which will respond to OnMouseX events.

In order to ignore OnMouseX events on the parent, I'm putting it into its own `user_ignore_raycasts` layer (I need it as its own layer for the layer collision matrix). I'm also putting the child in its own `user_use_raycasts` layer.

I'm passing that into a script that sets MainCamera's event mask:

```
using UnityEngine;

[RequireComponent(typeof(Camera))]
public class CameraEventMasker : MonoBehaviour
{
    [SerializeField]
    private LayerMask cameraEventMask;

    // Start is called before the first frame update
    void Awake()
    {
        GetComponent<Camera>().eventMask = cameraEventMask;
    }
}

```

What I notice is that OnMouseX events on the child will work IF the RigidBody2D on the parent is deleted...however, if the RigidBody2D is there, I won't receive any events. Anyone know why this is the case, and if there are other workarounds or solutions?

# Answer
My 3d game objects often would have multiple colliders - one on the parent for selecting/clicking, and others on children for such things as vision (detecting enemies), for detecting range, etc.

For clicking/selecting I use *Physics.Raycast*.

**Similarly this should work for your 2d project:**

you write this script in your *Update()* function.

```
    if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
    {
        Vector3 origin0 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hitn = Physics2D.Raycast(new Vector2(origin0.x, origin0.y), Vector2.zero, Mathf.Infinity, layerMask);

        if (hitn.collider != null)
        {
            Debug.Log("I clicked on: " + hitn.transform.name);
        }
    }

```

This script shoots 2D ray at mouse click (or touch) point and if it detects 2D collider, returns it.

Note the variable *layerMask*. You can create public variable layerMask and add to it layers which you want to be 'clickable' - other layers will be ignored. Thus you can have a game object with one 'clickable' 2d collider, and in children you can have as much colliders as you want doing other things - just put those children in other layer (or layers).

```
public LayerMask layerMask;

```
> 1 votes

---
Tags: unity
---


# Question
Title: How to get light level (brightness) of a particular location?
I'm making a 2D top-down survival game similar to `Rimworld`, I'm trying to emulate a day-night system.

Many features depend on whether any tile is light (or dark) enough, based on time of day or other light sources such as torches, so I'm wondering if there's an easy way to detect how much light there is on a certain tile without making a whole system that tracks light on a per-tile level (or maybe the latter option is better)?

I am using `Unity 2020.3.6f1` and the `URP`, which means I'm going to be using the 'new' 2D lights.

EXAMPLE: When it's nighttime, I'm going to disable the global light (sun) so those tiles will be pitch black. When it's daytime, the global light will have an intensity of 1 so that tile will have 100% brightness (look normal). When it's nighttime, but there's a torch, the tile where the torch is sitting on will have 100% brightness, and that will slowly fade to 0% over a span of 5 tiles.

Making a system that updates every single tile in the game with information about the light level seems pretty expensive. Is there a way we can observe a block "graphically", or in other words, literally look at the pixel on the screen, and determine it's alpha value to check for light level?

Any suggestion is super welcome.

**EDIT:** Every tile does not need to know its brightness every frame, but they do need to know it less often. Some examples are:

* A plant checking every couple of frames to see if it can grow
* A character checking every couple of frames to see if he's in the dark (and if he is, he needs to start panicking)

More importantly, I need my characters to make decisions based on light amount. For an example, if there is a job that needs to be done at a certain location, a character should first check the light level of that location before going to do it.

# Answer
Sorry I am not bringing "graphical" solution. But as you said every suggestion is welcome.

So this should work also:

A script which is run on each torch, not each tile. Your torch reach is 5 tiles. So that is 5 tile radius. That means that one torch has to update 88 tiles. 88 calculations is not that expensive.

If torch is moving: You can achieve this by simply using Unity 2d circle collider. When new tiles enter collider you add them to the list, when tile leaves the collider you remove it from the list.

Then iterate through this list and check the distance from torch and tile and change its 'lightness' according to distance. And you do not need to run this calculation every frame. Use *InvokeRepeating* or *Coroutines* to shoot it every half a second or so.

You do not like Unity colliders? Fine, create 'grid data structure' - basically give each tile some sort of 'address', then update it in your torch based on its speed and moving direction. Then based on current tile address find its nearest neighbors and set their 'lightness' to max. Then find further neighbors and set their 'lightness'. Do it until 5 tile distance.

**-- EDIT --** I think based on your comments and edits I now understand what is your situation , and what are you asking.

**Your situation (and solution) is like this:**

You can get rid idea of tiles all together. To solve this think that tiles just do not exist. What you really have is: several objects that need to know level of 'lightness'. A player, several plants, maybe few random cats. So write a script(s) that updates only these objects.

**For light source 'sun' -** use a simple timer (either a *Coroutine* or *InvokeRepeating*) and set global variable *dayLight* to different values based on daytime. Throughout a day this timer should tick only 10-20 times, setting the *dayLight* from 0 to 10, and when day fades - back from 10 to 0;

**For your objects - player, plants, cats -** create timer that fires function every few seconds or a bit more (or less) frequently. When fired this function first should check variable *dayLight*, then if day light is insufficient check a distance to nearest light source - a torch. To do this have all tourches in a global list, and iterate this list checking distance to each one. Or if you do not like lists, you can just use Unity 2d colliders to know that this cat or player entered 'torch area', then just check distance to it.
> 1 votes

---
Tags: unity, 2d, lighting, shadows
---


# Question
Title: How to display the counter in pygame.time.set_timer?
in pygame, we use `pygame.time.set_timer()` to repeatedly create an event. This function takes 2 arguments : the event type and the delay time after which the event occurs in milliseconds. For my case, that delay time is the reload time. So, i'm looking for a way to display that reload time on the screen. This is what i tried :

```
...
pygame.time.set_timer(pygame.USEREVENT+1, time)
...
reload_time = myfont.render(time, True, 'black')
myscreen.blit(reload_time, (670, 650))
...
pygame.display.flip()

```

This resulted in displaying the time delay value forever (it's not decreasing or resetting) So what should i do?

# Answer
> 1 votes
This is expected as `time` is passed "by value" (you *copy* the content of the variable "into the function").

Perhaps you need to change your approach to "timer" as there appears to be no equivalent to "get\_timer" to get the time left before the event is fired.

I'm not exactly sure how your whole game is developed, but you probably need to track the time yourself so that you can check the time left.

I'm not fluent in pygame, but, based on your previous question and pygame's documentation, perhaps something like this would work:

```
...

class Singlebullet(object):

    def __init__(self):
        self.img = pygame.image.load(r'C:\Users\Salem\Documents\MyGame1\bullet.png')
        self.state = 'ready'
        self.speed = 0
        self.firerate = 700 # assuming ms
        # this is new:
        self.bullet_time_left = self.firerate
        self.clock = pygame.time.Clock()

    def shoot(self):
        if current_bullet_type == 'single':
            if self.state == 'ready':
                self.x = myplane.x + 71
                self.y = myplane.y
            elif self.state == 'fire': # use elif instead of if
                self.speed = -13

            for event in events:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE and self.state == 'ready':
                        self.clock = pygame.time.Clock()
                        self.bullet_time_left = self.firerate
                        self.state = 'fire'

            delay = self.clock.tick()
            if self.state == 'fire':
                self.bullet_time_left -= delay
                if self.bullet_time_left <= 0:
                    self.bullet_time_left = self.firerate
                    self.state = 'ready'
                else:
                    reload_time = myfont.render(self.bullet_time_left, True, 'black')
                    MyScrollingScreen.blit(reload_time, (670, 650))

            MyScrollingScreen.blit(self.img, (self.x, self.y))

            self.y += self.speed
s1 = Singlebullet()
...
while running:
    ...
    s1.shoot()
    ...

```

That's the gist of it. You start a "Clock" when you fire the bullet; each update, you "update" it via it's tick() method to check how much time has passed since the last "tick()". You remove that time from the "time left"; once that counter gets below 0, you know that you're done and should clean it up. You have access to the time left so you can use it to update your label.

You'll probably want to rearrange some of what I wrote to suit your needs.

---

As I mentioned, I'm not fluent with pygame, and so maybe someone else has a better approach to propose.

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


title: Delta Time FPS with SDL 2 in C++

text:
# Question
Title: Delta Time FPS with SDL 2 in C++
I have tried achieving a good delta time and fps counter over the last few days, read and watched a lot about it, but still can't seem to get it to work.

Here is an example:

```
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>

int main(int argc, char* argv[]) {

    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        printf("error initializing SDL: %s\n", SDL_GetError());
    }

    SDL_Window* window = SDL_CreateWindow("Title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 900, SDL_WINDOW_SHOWN);

    if (!window) {
        printf("error creating window: %s\n", SDL_GetError());
    }

    Uint32 renderFlags = SDL_RENDERER_ACCELERATED;
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, renderFlags);
    if (!renderer) {
        printf("error creating renderer");
        SDL_DestroyWindow(window);
        SDL_Quit();
    }

    SDL_Surface* surface = IMG_Load("dot.bmp");

    if (!surface) {
        printf("Error creating surface: %s\n", SDL_GetError());
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
    }

    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
    SDL_FreeSurface(surface);
    if (!texture) {
        printf("error creating texture: %s\n", SDL_GetError());
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
    }

    SDL_Rect dest;

    dest.x = 0;
    dest.y = 0;

    SDL_QueryTexture(texture, NULL, NULL, &dest.w, &dest.h);

    Uint64 NOW = SDL_GetPerformanceCounter();
    Uint64 LAST = 0;
    double deltaTime = 0;

    while (true) {
        LAST = NOW;
        NOW = SDL_GetPerformanceCounter();
        deltaTime = (double)((NOW - LAST) / (double)SDL_GetPerformanceFrequency());

        SDL_RenderClear(renderer);

        dest.x += 50 * deltaTime;
        dest.y += 50 * deltaTime;

        SDL_RenderCopy(renderer, texture, NULL, &dest);

        SDL_RenderPresent(renderer);

        std::cout << "Delta Time: " << deltaTime << std::endl;
        std::cout << "FPS: " << 60.0 - deltaTime << std::endl;

        SDL_Delay(1000.0f / (60.0 - deltaTime));
    }

    return 0;
}

```

I used the suggestion from this post: How to calculate delta time with SDL?

I print out "delta time" and "FPS" to the console and, while the deltaTime is slightly different each time, the FPS is stable 60 (which is the same value that I use in SDL\_Delay to calculate delay in ms). But the test image is clearly moving not smoothly, it stutters and moves at inconsistent speed, and I can't understand why.

Please help me understand what I am doing wrong. I just can't understand it even after looking through many examples.

# Answer
I use a loop based on https://gafferongames.com/post/fix\_your\_timestep/
It renders as fast as possible and only updates when enough time has passed. This keeps your update code incredibly simple because you can assume a preset amount of time has passed. In the update function you cache the last state and calculate the new state, in the render function you calculate an interpolated state based on how much time is left which determines "where" in between the two states you're rendering. Then you render that interpolated state.

```
namespace Time {
    using namespace std::chrono;

    // get current time
    inline auto now() {
        return high_resolution_clock::now();
    }

    // get t as milliseconds
    inline auto step(const unsigned long long int t) {
        return milliseconds(t);
    }

    // get t as nanoseconds
    inline auto lag(const unsigned long long int t) {
        using namespace std::chrono_literals;
        return nanoseconds(0ns) + step(t);
    }

    // get delta time
    inline auto delta(const time_point<high_resolution_clock>& t0) {
        return duration_cast<nanoseconds>(now() - t0);
    }
}

int run(unsigned long long int t) {
    // update step in milliseconds
    const auto step = Time::step(t);
    // update step in nanoseconds
    const float step_ns = (float) step.count() * 1000000;
    // init lag exactly at step to force the first update cycle
    auto lag = Time::lag(step.count());
    // current time
    auto t0 = Time::now();
    while (true) {
        while (lag >= step) {
            //update(t);
            lag -= step;
        }
        auto alpha = (float) lag.count() / step_ns;
        //render(alpha);
        // update lag and current time
        lag += Time::delta(t0);
        t0 = Time::now();
    }
    return 0;
}

```

Say you have an object at `0,0`. Moving it horizontally across the screen at an intended speed of 10 units per millisecond is easy as:

```
update(unsigned long long int) {
    laststate = newstate;
    newstate.obj.x += (10 * t);`
}
render(float alpha) {
    auto objX = laststate.obj.x + ((newstate.obj.x - laststate.obj.x) * alpha);
    auto objY = laststate.obj.y + ((newstate.obj.y - laststate.obj.y) * alpha);
    // render the object using the interpolated x and y
}

```

The interpolation calculation can vary from property to property, so don't put it in the render function like I did here, but create a new state object based on the two cached states and the alpha value. This is just an example.
> 1 votes

---
Tags: c++, sdl2, timestep, deltatime
---


title: How to reset AnimatedSprite?

text:
# Question
Title: How to reset AnimatedSprite?
In Godot v2, it seems that `AnimatedSprite` had a method `set_frame()` see here.

But in v3, this method does not seem to exist anymore. Only 3 methods are available see here:

```
bool is_playing ()

void play (String anim="", bool backwards=false )

void stop ()

```

What is the way to reset an animation in Godot 3?

# Answer
Just set the `frame` property of the `AnimatedSprite`.
> 2 votes

---
Tags: animation, godot
---


# Question
Title: How to make an object covers a specific distance before moving in other direction for same distance?
Suppose there is a small tile and I want an object to move on x axis on that tile back and forth. How can I make that object in that specific tile. My code is :

```
 Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
    rb.velocity = new Vector2(-3f, 0);
}

```

As of now object moves left but I want it to start moving right and not go of the tile.

# Answer
There are two ways to do it:

1. To move object little by little every frame. I use this method to move units in my RTS game. In order to stop at wanted point I check every frame the distance left to target point, and if distance is small enough I stop the game object. In order to run code every frame write it in Update() function. To move little by little write small code into your Update() function:

```
if (shouldMove==true)
{
  transform.Translate(directionVector* speed);
}

```

To check distance between two points I use:

```
Vector3.Distance(transform.position, positionOfTarget)

```

To stop moving just set variable *shoudMove* to false.

2. Second method is to give objects rigid body velocity as you did. You need to do it only once so no need to put it in Update() function. But in order to stop you will still need to check distance as I wrote in previous option. When you need to stop - just set velocity to zero.
> 0 votes

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


# Question
Title: Unity - Where are Asset Store assets downloaded on Mac?
I'm on a Mac, running Unity 2021.1.5f1 Personal, and am trying to remove an asset I downloaded using Package Manager.

So for the asset in question, I want Unity to have to download the package again, from the Asset Store, to my local mac. That option is currently unavailable, because I have downloaded it in the past.

I've tried deleting the contents of these folders, to remove the downloaded file, but still no "download" option shows up next to the asset.

* ~/Library/Unity/Asset Store/Cache
* ~/Library/Unity/cache
* MY\_PROJECT/Library/PackageCache
* I also tried clearing the cache in Preferences | Gi Cache
* I looked in the docs for Asset Store cache, and the closest I found was this link

# Answer
> 1 votes
On a Mac, this is where Unity was downloading all it's Asset Store packages:

```
~/Library/Unity/Asset Store-5.x/

```

I then searched for the name of the plugin, found it, and removed it's folder

e.g

```
# find bad plugin
$ grep -r BadPlugin *

```

after doing this, the download option appeared again, and I could download the asset again from the asset server.

---
Tags: unity, assets
---


# Question
Title: Full screen to windowed screen workaround causing segmentation fault in pygame
I'm having an issue that causes the window bar to appear above the screen when jumping between full-screen and windowed mode. Did some googling on the issue and it turns out it's actually a pygame bug, **here**

So I implemented the fix, and ended up hitting up against another issue where I get a segmentation fault from pygame.

When I delete this line  `pygame.display.quit()` the segmentation fault goes away, but so does the workaround. So it's not really a fix.

**Error 1**

Error depends on whether I use `pygame.quit()` or the display quit above.

*Fatal Python error: pygame\_parachute: (pygame parachute) Segmentation Fault Python runtime state: initialized*

I ended up with even a different error when I tried to create a little example program for this question

**Error 2**

*self.txt\_surface = self.FONT.render(" ", True, self.color) pygame.error:*

*Text has zero width*

But let's focus on the first one. I enabled faulthandler on python which has helped me narrow down what line is causing the issue, and I narrowed it down to these few lines. After following back the error I found a problem with my textBox class, further found these offending lines.

```
def draw(self, screen):
    # Blit the text
    self.__hitkey__()
    roundedEdgeNum = 5
    pygame.draw.rect(screen, self.backgroundColor, self.rectBackground, 0,roundedEdgeNum)
    screen.blit(self.txt_surface, (self.rect.x+2, self.rect.y+2))

    pygame.draw.rect(screen, self.color, self.rect, 1,roundedEdgeNum)

```

What am I doing wrong with these draw and blit functions that causes an issue? I'm a little stumped on this one. Here is a full code example you can run to reproduce the issue. Thanks for any help! I really appreciate this community.

p.s. I know I'm mixing tkinter with a homegrown textbox, and I could just use a well tested GUI, but I spent a few days getting this text box to work the way I wanted it too, and so I want to use the code.

**Code Reproducing Issue**

```
import pygame
import tkinter
import os
import faulthandler
faulthandler.enable()

COLOR_INACTIVE = pygame.Color((128,128,128))
COLOR_ACTIVE = pygame.Color((0,0,0))
BACKGROUND_ACTIVE = (255,255,255)
BACKGROUND_INACTIVE = ((230,230,230))

class InputBox:

    def __init__(self, screen,x, y, w, h, text=''):
        self.screen = screen
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.LIGHT_GREY = (180,180,180)
        self.textBackground = (255,255,255)
        self.outershadowWidth = 2
        self.outershadowHeight = 2
        self.shadowWidth = 2
        self.shadowHeight = 2
        self.xoffset = 1
        self.yoffset = 1
        self.shadowRect = pygame.Rect(x+self.xoffset ,y+self.yoffset ,w-self.shadowWidth,h-self.shadowHeight)
        self.shadowRectOuter = pygame.Rect(x-self.xoffset ,y-self.yoffset ,w+self.shadowWidth,h+self.shadowHeight)
        self.rect = pygame.Rect(x, y, w, h)
        self.rectBackground = pygame.Rect(x+1,y+1,w-1,h-1)
        self.color = COLOR_INACTIVE
        self.backgroundColor = BACKGROUND_INACTIVE
        self.text = text
        self.textCopy = ''
        self.FONT = pygame.font.SysFont("cambriacambriamath", 16)
        self.txt_surface = self.FONT.render(text, True, self.color)
        self.active = False
        self.font_size = 18
        self.cursor_color=(0, 0, 1)
        self.cursor_surface = pygame.Surface((int(self.font_size / 40 + 1), self.font_size-2))
        self.cursor_surface.fill(self.cursor_color)
        self.textBackgroundSurface = pygame.Surface((self.w, self.h))
        self.cursor_position    = len("")  # Inside text
        self.cursor_visible     = True  # Switches every self.cursor_switch_ms ms
        self.cursor_switch_ms   = 500
        self.cursor_ms_counter  = 0
        self.max_string_length  = 100
        self.keydown            = False
        self.backspaceDelay     = 100
        self.timer              = 0
        self.keyTimer           = 0
        self.backspaceTimer     = 0
        self.clock = pygame.time.Clock()
        self.wipeTextOnReturn = False
        self.countWipe        = 0

        self.screen_resolution = self.getScreenResolution()
        self.nonFullScreenSize=(int(self.screen_resolution[0]/2.0),int(self.screen_resolution[1]/2.0))
        self.fullscreen = True
        self.setScreenResolution()

    def handle_event(self,events):
        for event in events:
            if event.type == pygame.MOUSEBUTTONDOWN:
                # If the user clicked on the input_box rect.
                if self.rect.collidepoint(event.pos):
                    # Toggle the active variable.
                    self.active = not self.active
                else:
                    self.active = False
                # Change the current color of the input box.
                self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
                self.backgroundColor = BACKGROUND_ACTIVE if self.active else BACKGROUND_INACTIVE
            if event.type == pygame.KEYDOWN:
                if self.active:
                    if event.key == pygame.K_RETURN:
                        self.textCopy = self.text
                        self.text = ''
                    else:
                        if ((len(self.text) < self.max_string_length) or (self.max_string_length == -1)):
                            if (event.unicode.isnumeric() or event.unicode == 'x'):
                                # If no special key is pressed, add unicode of key to text
                                self.text = self.text[:self.cursor_position] + event.unicode + self.text[self.cursor_position:]
                                self.cursor_position = len(self.text)  # Some are empty, e.g. K_UP
                    if (event.key == pygame.K_BACKSPACE):
                        self.text = self.text[:-1]
                        # Subtract one from cursor_pos, but do not go below zero:
                        self.cursor_position = max(self.cursor_position - 1, 0)
                        self.keydown         = True
                    if (event.key == pygame.K_LEFT):
                        if (self.cursor_position > 0):
                            self.cursor_position = self.cursor_position - 1
                    if (event.key == pygame.K_RIGHT):
                        # Add one to cursor_pos, but do not exceed len(text)
                        if (self.cursor_position < len(self.text)):
                            self.cursor_position = self.cursor_position + 1

            if event.type == pygame.KEYUP:
                self.keydown          = False
                self.backspaceTimer   = 0
                self.timer            = 0
                self.keyTimer         = 0

        #Handles backspace helddown, alternative to putting extra events on queue or using set_repeat
        #Putting set_repeat(1,30) in a program using this will mess up the event queue
        if (self.keydown == True):
            self.backspaceTimer += self.clock.get_time()
            self.timer += 1
            if (self.backspaceTimer >= self.backspaceDelay and (self.timer == 10)):
                self.text = self.text[:-1]
                #Subtract one from cursor_pos, but do not go below zero:
                self.cursor_position = max(self.cursor_position - 1, 0)
                self.timer = 0

        #Get key states
        key_states = pygame.key.get_pressed()

        if (key_states[pygame.K_END]):
            self.cursor_position = len(self.text)

        if (key_states[pygame.K_HOME]):
            self.cursor_position = 0

        # Re-render the text.
        if (self.active and self.text == ""):
            self.txt_surface = self.FONT.render(" ", True, self.color)
        else:
            self.txt_surface = self.FONT.render(self.text, True, self.color)

        # Update self.cursor_visible
        self.cursor_ms_counter += self.clock.get_time()
        if (self.cursor_ms_counter >= self.cursor_switch_ms):
            self.cursor_ms_counter %= self.cursor_switch_ms
            self.cursor_visible = not self.cursor_visible

        if self.cursor_visible:
            cursor_y_pos = self.FONT.size(self.text[:self.cursor_position])[0]
            # Without this, the cursor is invisible when self.cursor_position > 0:
            if (self.cursor_position > 0):
                if (cursor_y_pos > 0):
                    cursor_y_pos -= self.cursor_surface.get_width()
            self.txt_surface.blit(self.cursor_surface, (cursor_y_pos, 2))

        self.update()

        self.draw(self.screen)

        self.clock.tick()

    def update(self):
        # Resize the box if the text is too long.
        width = max(200, self.txt_surface.get_width()+10)
        self.rect.w            = width
        self.shadowRect.w      = width-self.shadowWidth
        self.shadowRectOuter.w = width+self.shadowWidth
        self.rectBackground.w  = width-self.shadowWidth

    def draw(self, screen):
        # Blit the text
        self.__hitkey__()
        roundedEdgeNum = 5
        pygame.draw.rect(screen, self.backgroundColor, self.rectBackground, 0,roundedEdgeNum)
        screen.blit(self.txt_surface, (self.rect.x+2, self.rect.y+2))

        pygame.draw.rect(screen, self.color, self.rect, 1,roundedEdgeNum)

    def setScreenResolution(self):

        self.fullscreen = not self.fullscreen

        if (self.fullscreen):
            self.screen = pygame.display.set_mode(self.screen_resolution, pygame.FULLSCREEN,0)
        else:
            pygame.quit() # ???
            pygame.init() # ???
            os.environ['SDL_VIDEO_WINDOW_POS'] = str(100)+ "," + str(100)
            #os.environ['SDL_VIDEO_CENTERED'] = '1'

            self.screen = pygame.display.set_mode(self.nonFullScreenSize,pygame.RESIZABLE,0)

        pygame.display.update()

    def __hitkey__(self):
        '''Handle key events '''
        key_states = pygame.key.get_pressed()
        if (key_states[pygame.K_F3]):
            if (self.keyStateCounter == 0):
                self.setScreenResolution()
            self.keyStateCounter += 1
        if (not key_states[pygame.K_F3]):
            self.keyStateCounter = 0

    def getScreenResolution(self):
        """
        Workaround to get the size of the current screen in a multi-screen setup.

        Returns:
            geometry (str): The standard tkinter geometry string.
                [width]x[height]+[left]+[top]
        """
        root = tkinter.Tk()
        root.update_idletasks()
        root.attributes('-fullscreen', True)
        root.state('iconic')
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        root.destroy()

        return (screen_width,screen_height)

def main():
    screen = pygame.display.set_mode((640, 480))
    pygame.init()
    input_box1 = InputBox(screen,100, 100, 140, 32)

    done = False

    while not done:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                done = True

        stuff = input_box1.handle_event(events)

        pygame.display.flip()

if __name__ == '__main__':
    main()
    pygame.quit()

```

# Answer
> 1 votes
The answer lies in this line here `stuff = input_box1.handle_event(events)`

The screen that was initially passed to handle\_events, but once pygame.quit() is called the screen variable in input\_box1 was not updated.

Changing the function to pass in the new screen surface fixed the issue.

---
Tags: python, pygame, sdl2
---


# Question
Title: Why Query Only fires OnComponentHit? It supposes to fires only Overlap events
I've just started to develop with Unreal Engine 4.26.2 and I've been for five days trying to understand how collision works.

I'm developing a Pong game, and I'm trying to make that the **Ball** bounces with the **Paddle**.

The **Ball** class has a `UProjectileMovementComponent` to move it and the **Paddle** will be controlled by the player with a `UPawnMovementComponent` custom class. So, both will move.

These are my two classes:

Ball:

```
ABall::ABall()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    VisualComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualComp"));
    CollisionComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("CollComp"));

    static ConstructorHelpers::FObjectFinder<UStaticMesh> VisualAsset(TEXT("/Game/Geometry/Meshes/Ball_mesh.Ball_mesh"));

    if (VisualAsset.Succeeded())
    {
        VisualComponent->SetStaticMesh(VisualAsset.Object);
        VisualComponent->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f));
        VisualComponent->SetWorldScale3D(FVector(1.0f));

        FBoxSphereBounds Bounds = VisualAsset.Object->ExtendedBounds;

        CollisionComponent->SetRelativeLocation(Bounds.Origin);
        CollisionComponent->SetBoxExtent(Bounds.BoxExtent);
    }

    RootComponent = CollisionComponent;
    VisualComponent->SetupAttachment(CollisionComponent);

    VisualComponent->SetCollisionProfileName(TEXT("NoCollision"));
    CollisionComponent->SetCollisionProfileName(TEXT("Projectile"));
    CollisionComponent->OnComponentHit.AddDynamic(this, &ABall::OnHit);

    // Use this component to drive this ball's movement.
    ProjectileMovementComponent = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileMovementComponent"));
    ProjectileMovementComponent->SetUpdatedComponent(CollisionComponent);
    ProjectileMovementComponent->InitialSpeed = 0.0f;
    ProjectileMovementComponent->MaxSpeed = 90.0f;
    ProjectileMovementComponent->bRotationFollowsVelocity = false;
    ProjectileMovementComponent->bShouldBounce = true;
    ProjectileMovementComponent->Bounciness = 0.3f;
    ProjectileMovementComponent->ProjectileGravityScale = 0.0f;

}

```

Paddle:

```
APaddle::APaddle()
{
    // Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    // Set this pawn to be controlled by the lowest-numbered player
    AutoPossessPlayer = EAutoReceiveInput::Player0;

    CollisionComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("CollComp"));
    VisualComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualComp"));

    RootComponent = CollisionComponent;

    // Set up CollisionComponent as parent of VisualComponent;
    VisualComponent->SetupAttachment(CollisionComponent);

    VisualComponent->BodyInstance.SetCollisionProfileName("NoCollision");
    CollisionComponent->BodyInstance.SetCollisionProfileName("Pawn");

    // Initialize paddle velocity.
    CurrentVelocity.Z = 0.0f;

    // Create an instance of our movement component, and tell it to update our root component.
    OurMovementComponent = CreateDefaultSubobject<UPaddlePawnMovementComponent>(TEXT("CustomMovementComponent"));
    OurMovementComponent->UpdatedComponent = RootComponent;

}

```

Both classes have a `UBoxComponent` as a collision component and a `Static Mesh` as a Visual Component. The Static Mesh uses `NoCollision` Preset and Collision Component uses Pawn in the Paddle and `Projectile` (custom preset) in the Ball.

Projectile Preset is:

And Projectile Object Type is:

I have tried a lot of combinations and the only one that works is when both classes, have, at least, **Query only** selected.

I think that **Query only** is used to trigger **Overlap** events but if I don't select it, `OnComponentHit` won't trigger.

Is there anything wrong with my code or am I wrong about **Query Only** and what it does?

# Answer
> 0 votes
These kinds of questions raise little interest here.

I found the answer in the book "Game Development Projects With Unreal Engine: Learn to Build Your First Games and Bring Your Ideas to Life Using UE4 and C ++". And the answer is:

It is correct. *Query only* is related to collision events and whether objects will bock each other's movement. So yes, I'm using the right *Collision enabled* property to block, and also it is the right *Collision enabled* property to detect overlapping also.

---
Tags: c++, collision-detection, unreal-4
---


# Question
Title: How can I get the Selector dialog to include my prefabs
When setting a variable for an object in Unity, for built-in types there is an option on the right-hand side to bring up a dialog that lists the possible values that can be chosen for that variable, for example when selecting a Sprite for a Sprite Renderer:

Is it possible, and if so what do I need to do, to have that list populated with the prefabs within my project?

In this example, there are a number of Item prefabs (both inside and outside the Resources folder if that makes a difference), however they do not appear in that dialog. Is there an attribute I am missing that needs to be specified on the Item class, or something else to enable this?

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

public class Item : MonoBehaviour, IIdentifiable, IFilterable
{
    [SerializeField]
    private int IdField;
    [SerializeField]
    private bool ActiveField;

    public int Id => IdField;
    public bool Active => ActiveField;
}

public class ItemRandomiser : MonoBehaviour, IWeightedObject
{
    [SerializeField]
    private List<string> NamesField;
    [SerializeField]
    private List<Item> ItemTemplatesField;
}

```

# Answer
> 3 votes
Your `Item` is not an asset, it's a component. That dialog shows ASSETS of its type.

If you change `List<Item>` to `List<GameObject>`, you will see all the prefab assets in your project.

Or instead if you change `Item` from being a `MonoBehaviour` to being a `ScriptableObject`, then that dialog will show all the `Item` assets you created in your project.

---
Tags: unity
---


title: Collider for Unity Line Renderer

text:
# Question
Title: Collider for Unity Line Renderer
I have several line renderers that are using as gas pipelines. A user can select one end of the pipe and attach it to one connector. Now the problem is some pipes (line renderer) are overlapping and penetrating with each other. Is there any way to avoid penetration using colliders so they look realistic?

# Answer
Yes It can be done, it requires a bit manipulation with vectors.

LineRenderer has start and finish, capsule colider has height,and all features of its transform. OK lets convert LineRenderer data to capsule collider!

The steps are as follows:

1. LineRenderer has start and finish coordinates - get them by using LineRenderer.GetPosition(0) and LineRenderer.GetPosition(1). So now you know where line starts and ends. Lets call them *startPos* and *endPos*.
2. lets find out height of CapsuleCollider. To do that just subtract:

```
Vector3 dir = endPos-startPos;  ///---this is vector that points from starting point to finish point
float height = dir.magnitude;

```

now we have height!

3. Lets get the middle point of this line. To do this you halve the vector and add startPos vector to it:

```
 Vector3 dir2 = dir * 0.5f;
 Vector3 centerCoord = startPos + dir2;

```

we got the center of line!

4. Lets get the all 3 angles - the rotation of the line:

```
 float angleWithZ =Vector3.Angle(dir,new Vector3(0,0,1));
 float angleWithY =Vector3.Angle(dir,new Vector3(0,1,0));
 float angleWithX =Vector3.Angle(dir,new Vector3(1,0,0));

```

We have all the angles!

5. Now just use an empty game object - (if unchecked "use world space" then child to parent and a brother of your line), set its position to our centerCoord , add capsule collider, set its height,(dont forget to zero its center) and rotate this transform according our angles!
6. write all this into neat script, add it to Update() function (or coroutine) and colliders will position themselves automatically!

Below is the picture of result I got - collider is nicely positioned around pink lineRenderer:
> 1 votes

---
Tags: unity, physics, line-renderer
---


# Question
Title: Get all images from peristent data path and save them to a Texture2D array
So i managed to make a working script that downloads images from firebase in this situation and saves them to Application.persistentDataPath. Now what i would like help in doing is getting all those images "\*jpg" and assigning them to a Texture2D array for later use.

So far i have mananged to open one of those images by name and assign it to a single texture.

```
    public Texture2D image;

 private void Awake()
    {
        string dirname = "levelNature";
        string path = Application.persistentDataPath + "/" + dirname + "/" + "nameofImage.jpg";

        LoadSprite(fileName);

    }

    private void LoadSprite(string path)
    {
        if (string.IsNullOrEmpty(path))
            Debug.Log("null or empty");

        if (File.Exists(path))
        {
            byte[] bytes = File.ReadAllBytes(path);
            Texture2D texture = new Texture2D(1024, 1024, TextureFormat.RGB24, false);
            texture.LoadImage(bytes);
            image = texture;
            Debug.Log("success");
        }
    }

```

With just one image i can assign it to a texture but since later on in the gameplay i'm using a texture2d array to assign those images to the gameplay , which now are set through the inspector , i would like to load all images in a particular folder to a Texture2D array which later on i will be using to show each image index in a specific level.

I did try it out like this but it isn't successful.

```
    public Texture2D[] source;

        var fileNames = Directory.GetFiles(Application.persistentDataPath + "/" + dirname + "/" + "*.jpg");

        source = new Texture2D[fileNames.Length];
        int index = 0;
        foreach (var fileName in fileNames)
        {
            source[index] = LoadSprite(fileName); // i get the error here that it cant convert void to texture2D
            index++;
        }

```

Hopefully once all images are loaded i could see in that array in the inspector all the images and then use that for the rest of the game. Thank you!

# Answer
> 0 votes
You declared your `LoadSprite` method as a `void` method, meaning it never returns any value to the caller.

But then you tried to use it like it was going to give a return value:

```
source[index] = LoadSprite(fileName);

```

This says "Take the return value from `LoadSprite` and assign it to my `source` array in slot `index`". But `LoadSprite` doesn't ever provide a return value, so this is nonsense, and your compiler is rightly telling you that you've written nonsense it can't do anything useful with.

It looks like you wanted to write a method something like this:

```
private Texture2D LoadTextureFromPath(string path)
{
    if (string.IsNullOrEmpty(path)) {
        Debug.LogError("Texture path is null or empty");
        return null;
    }

    if (!File.Exists(path))
    {
        Debug.LogError($"File not found: {path}");
        return null;
    }

    byte[] bytes = File.ReadAllBytes(path);
    Texture2D texture = new Texture2D(1024, 1024, TextureFormat.RGB24, false);
    texture.LoadImage(bytes);
    Debug.Log("success");

    return texture;
}

```

See how the method now has type `Texture2D`, not `void`, and we actually return a texture at the end? Now this line makes sense:

```
source[index] = LoadTextureFromPath(fileName);

```

---
Tags: unity, textures
---


# Question
Title: What would be the best way to implement a multi-directional "board game" movement system?
I'm pretty new to game dev, and can't figure out how to do this, even though it is probably really easy. If you need more reference, look up some gameplay of the Wii game Dokapon Kingdom, that's the kind of system I'm trying to create. I also made a picture to help you better understand my dilemma. Thank you all so much in advance!

# Answer
> 5 votes
## The MapNode class

I would represent each node on the map with an own gameObject which gets a MonoBehaviour I would name `MapNode`. That class would have four variables representing its neighbors:

```
public MapNode upNeighbor;
public MapNode rightNeighbor;
public MapNode downNeighbor;
public MapNode leftNeighbor;

```

Another option might be to make those a `public MapNode[] neighbors`, as this allows *any* number of neighbors in *any* direction. So when you want to add diagonal or 3d connections, you could do that. But as long as all connections are in cardinal directions, that might just overcomplicate this.

For a first proof-of-concept I would populate those neighbors manually in the inspector. But in the long run I might write some code to set up those connections automatically, either at runtime or at design time through a bunch of handy editor script.

This turns the whole network of map nodes into a graph. This is a prerequisite for a lot of neat things. Like route finding, for example. But what matters now it that it tells you what move options a game piece has when they are on a given tile.

## The GamePiece class

The `GamePiece` would be a MonoBehavior for any game object which moves from `MapNode` to `MapNode`. The player might be one of such objects, but there might be a lot more in your game which exhibit this behavior. So I would not call it "Player".

This class has the purpose to move the gameObject towards the tile it is supposed to be. In order to do that, it needs 3 properties:

* The `moveSpeed` with which it moves between nodes (could be made a `static` if you want it to be the same for everything)
* The `currentNode` where it is supposed to be (keep in mind that it might not be there *yet*)
* Whether or not it `IsMoving` to the node its supposed to be (as opposed to being already there).

The Update-method then would have two jobs:

* Move the object a bit closer to its currentNode, taking moveSpeed and deltaTime into account. The new position can be calculated with the handy utility method `Vector3.MoveTowards`.
* Determine if it reached the destination and change `isMoving` accordingly.

This class could look like this:

```
public class GamePiece : MonoBehaviour {
    public float moveSpeed = 10.0f; // units per second
    public bool isMoving{ get; private set; }
    public MapNode currentNode;

    private void Update() {
         transform.position = Vector3.MoveTowards(transform.position, currentNode.transform.position, moveSpeed * Time.deltaTime);
         isMoving = transform.position != currentNode.transform.position;
    }
}

```

To make the character move to a different node, just set `currentNode` to the node you want it to move to. Check `isMoving` to determine if its moving or stationary.

## Adding player input

This example uses the classic AWSD control scheme. This is not a very good solution. In a real game, you would want those keys to be rebindable, support different input devices, etc.. If you want to do it properly from the start, then you might want to look at the new input system. But how to do *proper* input handling in Unity goes beyond the scope of this answer. So here is a script which is sufficient as a proof of concept. I am doing this as a separate script `PlayerInput`, because not every `GamePiece` would be player-controlled:

```
public class PlayerInput : MonoBehaviour {
    private GamePiece myGamePiece;

    private void Start() {
        myGamePiece = GetComponent<GamePiece>();
    }

    private void Update() {
        if (!myGamePiece.isMoving && myGamePiece.currentNode != null) {
            if (Input.GetKeyDown(KeyCode.W))  {
                MoveToNode(myGamePiece.currentNode.upNeighbor);
            }
            if (Input.GetKeyDown(KeyCode.A))  {
                MoveToNode(myGamePiece.currentNode.leftNeighbor);
            }
            if (Input.GetKeyDown(KeyCode.S))  {
                MoveToNode(myGamePiece.currentNode.downNeighbor);
            }
            if (Input.GetKeyDown(KeyCode.D))  {
                MoveToNode(myGamePiece.currentNode.rightNeighbor);
            }
        }
    }

    private void MoveToNode(MapNode node) {
        if (node != null) {
            myGamePiece.currentNode = node;
        }
    }
}

```

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


# Question
Title: Is it better to connect signals in source code or with the IDE feature?
In Godot IDE, what are the advantages and the caveats of using the visual IDE to connect signals to listerners instead of doing this:

```
var state: bool

onready var countdown: Timer = $Countdown

func _ready() -> void:
    state = true
    countdown.connect("end", self, "_toggle")

func _toggle() -> void:
    state = not state

```

# Answer
> 5 votes
## Abstract

* Should the connection be persisted? No: Connect from code.
* Should the connection happen on load? No: Connect from code.
* Should the connection be removed on runtime? Yes: Connect from code.
* Should the connection include a node made on runtime? Yes: Connect from code.
* Are you writing GDScript? No: Connect from code, or use GDScript as glue.

On a reusable asset:

* Should the connection always be there for the asset to work? Yes: Connect from code. No: Connect from the IDE (giving the flexibility to the designer), unless you have one of the reasons above for the asset to connect from code.

Not on a reusable asset: If you have one of the reasons to connect from code, then connect from code. Otherwise, convenience triumphs, which I guess means connecting from IDE.

---

I will echo that there is no "better" way. They serve different purposes, and there are gray areas.

We could similarly ask what is better between creating nodes from code on creating them in the IDE. The intuition is that you make in from code if it is dynamic. And a similar intuition would apply to connecting signals.

---

If anything using the IDE will favor a designer workflow over a programmer workflow.

The designer and the programmer can be the same person, taking both roles. The distinction I want to make is on the kind of problems being solved. For the purposes of this answer, let us say that the programmer is creating the pieces that come together to make the game, and the designer is placing those pieces together.

Dividing the roles that way, we have:

* The person on a designer role can rely on the connections made on the IDE to be there (they are persisted, and are made effective early when loading the nodes). Also connections made on the IDE give flexibility to the designer (they can be connected in different ways to fit the needs of the game or scenario).
* However, for the person on a programmer role, making connection from code is more flexible (they have more control over when the connection happens, and can be made to node created from code). And connections made from the IDE are "optional" (they are a way to give more options to the designer).

But let us talk about differences…

---

## Persisting connections

First of all, connections made in the IDE are persisted in the scene file. Or, rather, I should say the IDE will not create not persisted connections.

From code you can decide to use or not to use the `CONNECT_PERSIST` flag. Which could be useful, for example from a tool script (e.g. an addon) to add connection that are later saved by the editor.

Although you probably don't want to do that from the same node being connected, since that code will run again, attempting to re-do the connection.

You can, by the way, save a scene file from GDScript:

```
var packed_scene = PackedScene.new()
packed_scene.pack(get_node("node_path"))
ResourceSaver.save("res://file_path.tscn", packed_scene)

```

**Addendum**: If you want children to be saved along with it, set their `owner` property.

Let this be a reminder that the Godot IDE is made on Godot. *It is dogfooding.* Although it uses the C++ API instead of the GDScript one, GDScript surfaces a lot of the same functionality used to create the IDE.

Thus, we can argue making connections from the IDE is a convenience. *See note at the end.*

---

## Controlling when the connection is made

Second, since IDE connections are persisted, you don't have control over when they happen. *I have gone over the way nodes are loaded here, I just updated it to include signal connection*. Connections happen before parenting. To be more precise, they happen outside the scene tree, before `NOTIFICATION_PARENTED` (and thus before `onready` variables and before Godot calls `_ready`), but after Godot calls `_init`, runs custom setters.

With code, you can do the connection whenever it is necessary. Thus, using connection from code gives you extra flexibility.

---

I will remind you that signals are also used with `yield`. See Coroutines and signals.

---

## Removing connection on runtime

To remove a connection on runtime, it must be done from code. The IDE has no such functionality.

Your code should not rely on a connection made from IDE being there (you could, for example, remove the connection from the IDE and forget to update the code).

However, it could be intentional, that you can a connection may or may not be there, and if it is there, you want to remove it. IN which case, make sure to check `is_connected`.

Otherwise, I would suggest to create connection that will be removed on the same script that removes it.

---

## Connect to nodes created from code

If you create a node from code, it will not show in the IDE, because the node only exist in runtime. And thus, the only way to connect to its signals is from code.

---

## Not GDScript

Connecting from the IDE works flawlessly with GDScript, but not so much with other languages. Depending on the language, you may not have the option, or the IDE might do the wrong thing (C#).

Thus I would not connect a signal from the IDE to a script in another language. Instead I would either connect it from code in that other language, or connect it from the IDE to GDScript, and from there call into the script in that other language.

In fact, I recommend to use GDScript as glue between Godot and other languages. So GDScript will export variables, connect signals, and call into script written with other languages.

---

## Creating a reusable asset (Editable children)

Doing the connections in code means that you know how the scene will be put together when used.

That is, if you are making an asset to be reused, either by yourself or a third party, the code can make less assumptions about the scene where it is used. And it would be inconvenient to require modifying the code to write what to connect. It is a better workflow to simply expose the signals and let the person on the designer role (which could be the same person) connect things as necessary from the IDE.

---

What can you take for granted from your asset anyway?

If you are using a script/class, you cannot take any assumptions about the scene tree.

If it is an scene you are reusing, you can take for granted the child nodes it has. But never something outside of the scene. That should lead you to the methodology described in Node communication (the right way), which is summarized as "Call down, signal up".

---

Sometimes it is hard to surface all the relevant options in the root of a scene. Leading us to include the scene, and enabling "Editable Children" in the editor, which will let override the properties of the scene or add new nodes (but not remove).

You should not remove or modify through a scene added with "Editable Children" because the change is taking effect on the original scene.

However, you can add or remove connection made in the IDE. That means that by making the connection in the IDE, you can support scenarios where the connection should not be there.

Thus, for connections attached to a reusable scene, consider: Would the asset work without the connection? Are the scenarios where not having the connection is preferable? In those cases prefer using the IDE to make connection (unless the connection must be made in a way that is only possible from code, in which case you may want to expose the option by other means). Otherwise, make the connection from code.

---

**Note**: The connection dialog was improved for Godot 3.2, which is good, but it could be better. See Reworked and more capable ConnectDialog. Due to the current limitations of the dialog, its convenience might not be convenient enough.

# Answer
> 2 votes
There is no right method, but there are pros and cons. Them main one I think, is that if you connect them in code it is easier for most people to keep track of the connection and the function call at the same time. However connecting them with the editor can be more visual to some people, and your code more readable depending on how you look at it.

---
Tags: godot, events, gdscript
---


# Question
Title: How do you make objects be pushed away from you?
like pain from naruto, I wanna be able to press a button and be able to push objects

here's my push method

```
 void DoPush()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, pushRadius);

        foreach (Collider pushedObject in colliders)
        {
            if (pushedObject.CompareTag("Enemy"))
            {
                Rigidbody pushedBody = pushedObject.GetComponent<Rigidbody>();

                pushedBody.AddForce(-transform.forward * 500, ForceMode.Force);

            }
        }

    }

```

the problem with this method is when I go behind the objects I push, they go towards me

# Answer
> 1 votes
You are pushing your object in the reverse direction you are facing.

Try:

```
void DoPush()
{
    Collider[] colliders = Physics.OverlapSphere(transform.position, pushRadius);

    foreach (Collider pushedObject in colliders)
    {
        if (pushedObject.CompareTag("Enemy"))
        {
            Rigidbody pushedBody = pushedObject.GetComponent<Rigidbody>();

            // Get direction from your postion toward the object you wish to push
            var direction = pushedBody.transform.position - transform.position;

            // Normalization is important, to have constant unit!
            pushedBody.AddForce(direction.normalized * 500, ForceMode.Force);

        }
    }

}

```

---
Tags: unity, physics
---


# Question
Title: Directx11 create Texture2D using subresourceData
I'm trying to create immutable texture in d3d11 so I want to use subresourceData, every tutorial on textures creates them with 2nd argument being null and after that updates subresource but I want to create it using the 2nd argument. This code works:

```
hResult = m_device->CreateTexture2D(&textureDesc, NULL, &m_cubeTexture);
if (FAILED(hResult)) {
    return false;
}

int rowPitch = textureWidth * 4;
m_deviceContext->UpdateSubresource(m_cubeTexture, 0, NULL, &(decodedTexture[0]), rowPitch, rowPitch * textureHeight);

```

And this does not:

```
int rowPitch = textureWidth * 4;
D3D11_SUBRESOURCE_DATA tSData;
tSData.pSysMem = &(decodedTexture[0]);
tSData.SysMemPitch = rowPitch;
tSData.SysMemSlicePitch = rowPitch * textureHeight;

hResult = m_device->CreateTexture2D(&textureDesc, &tSData, &m_cubeTexture);
if (FAILED(hResult)) {
    return false;
}

```

DirectX11 debug layer outputs this:

```
D3D11 ERROR: ID3D11Device::CreateTexture2D: pInitialData[3].SysMemPitch cannot be 0 [ STATE_CREATION ERROR #100: CREATETEXTURE2D_INVALIDINITIALDATA]
D3D11 ERROR: ID3D11Device::CreateTexture2D: pInitialData[5].pSysMem cannot be NULL. [ STATE_CREATION ERROR #100: CREATETEXTURE2D_INVALIDINITIALDATA]

```

Which I don't understand since it's not even an array and texture array size is set to 1

# Answer
> 1 votes
When you create texture as D3D11\_USAGE\_IMMUTABLE set MipLevels to 1.

```
D3D11_TEXTURE2D_DESC textureDesc= {};
textureDesc.Width= textureWidth;
textureDesc.Height= textureHeight;
textureDesc.MipLevels= 1; /// !!!
textureDesc.ArraySize= 1;
textureDesc.Format= DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.SampleDesc.Count= 1;
textureDesc.Usage= D3D11_USAGE_IMMUTABLE;
textureDesc.BindFlags= D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags= 0;
textureDesc.MiscFlags= 0;

D3D11_SUBRESOURCE_DATA tSData= {};
tSData.pSysMem = &(decodedTexture[0]);
tSData.SysMemPitch = rowPitch;
tSData.SysMemSlicePitch = 0;

hResult= m_device->CreateTexture2D( &textureDesc, &tSData, &m_cubeTexture);

```

Have in mind that if you create D3D11\_USAGE\_IMMUTABLE texture like this, you won't be able to call GenerateMips on it.

---
Tags: c++, textures, directx11
---


# Question
Title: Godot C++ NativeScript version not rendering multimesh instance whereas GDScript version does
I am new to Godot. I am aiming to create a RTS game with 10's of thousands of units and for it to run smoothly. So I'm looking to use GDNative C++ with the Visual Server to handle updating and moving the units and GDScript for everything else.

The following script in GDScript successfully renders a single multi mesh cube at the center of the screen.

```
extends Spatial

func _ready():

    var meshRid=preload('res://new_cubemesh.tres').get_rid()
    var multimesh = VisualServer.multimesh_create()

    VisualServer.multimesh_allocate(multimesh, 1, VisualServer.MULTIMESH_TRANSFORM_3D,
    VisualServer.MULTIMESH_COLOR_NONE, VisualServer.MULTIMESH_CUSTOM_DATA_FLOAT)
    VisualServer.multimesh_set_mesh(multimesh, meshRid)

    var instance = VisualServer.instance_create()
    var scenario = get_world().scenario

    VisualServer.instance_set_scenario(instance, scenario)
    VisualServer.instance_set_base(instance, multimesh)

```

I have implemented the alternative In GDNative (C++) and while it doesn't crash and does run the code, it does not render the cube. Camera is in correct position to observe the cube at 0,0. I've just re-purposed the GDNative C++ tutorial for now.

I really like the community here and the engine so far, so hopefully I am just misunderstanding something here and it is possible what I am trying to achieve.

Thank you for your time, c++ scripts below.

gdexample.cpp

```
#include "gdexample.h"

using namespace godot;

void GDExample::_register_methods() {
    register_method("_process", &GDExample::_process);
    register_method("_ready", &GDExample::_ready);
}

GDExample::GDExample() {
}

GDExample::~GDExample() {
    // add your cleanup here
}

void GDExample::_init() {
    // initialize any variables here
    base=5;
}

void GDExample::_ready(){

    visual = VisualServer::get_singleton();
    loader = ResourceLoader::get_singleton();

    Ref<Resource> meshResource = loader->load("res://new_cubemesh.tres");
    RID meshRid = meshResource->get_rid();

    multimesh = visual->multimesh_create();
    visual->multimesh_allocate(multimesh, 1, visual->MULTIMESH_TRANSFORM_3D, visual->MULTIMESH_COLOR_NONE, visual->MULTIMESH_CUSTOM_DATA_FLOAT);
    visual->multimesh_set_mesh(multimesh, meshRid);

    RID instance = visual->instance_create();

    Ref<World> world = get_world();
    RID scenario = world->get_scenario();

    visual->instance_set_scenario(instance, scenario);
    visual->instance_set_base(instance, multimesh);

}

void GDExample::_process(float delta) {
    return;
}

```

Let me know if you need gdexample.h or gdlibrary.cpp and I can add, the formatting gets messed up if I include them here for some reason. It's basically just the tutorial stuff though.

# Answer
> 2 votes
Got an answer! The meshResource reference needs to be kept, so just do this put

`Ref<Resource> meshResource;`

In the header file and change

`Ref<Resource> meshResource = loader->load("res://new_cubemesh.tres");`

to

`meshResource = loader->load("res://new_cubemesh.tres");`

---
Tags: c++, godot, gdscript
---


# Question
Title: Unity: Opacity over Distance with Surface Shaders
I want to tweak the alpha value based on the distance to the camera. But I see no way of passing the vertex position on to the surface function using surface shaders. Not a problem with frag shader.

It's for fading out vegetation and creating LOD systems.

```
Shader "asdf" {
SubShader {
    CGPROGRAM
    #pragma surface surf StandardSpecular alphatest:_Cutoff addshadow vertex:vert

    struct v2f {
        float4 pos : TEXCOORD1;
    };

    struct Input {
        float2 uv_Maintex;
    };

    v2f vert (inout appdata_base v) {
        v2f o;
        o.pos = mul(unity_ObjectToWorld, v.vertex);
        return o;
    }

    void surf (Input IN, inout SurfaceOutputStandardSpecular o) {
        //Need vertex or pixel distance here:
        //float dist = length(v2f.pos.xyz - _WorldSpaceCameraPos.xyz);
        //o.Alpha = saturate(50/dist);
    }
    ENDCG
}
}

```

# Answer
Just ask for `worldPos` in your `Input` structure (as documented here):

```
struct Input {
    float2 uv_Maintex;
    float3 worldPos;
};

void surf (Input IN, inout SurfaceOutputStandardSpecular o) {
    float dist = length(IN.worldPos - _WorldSpaceCameraPos.xyz);
    o.Alpha = saturate(50/dist);
}

```
> 1 votes

---
Tags: unity, shaders, surface-shader
---


# Question
Title: How to create a re-usable layout of text fields that can be bound to in world space?
Current tools:

* Unity 2020.3.2f1 (Win10)
* UI Builder preview package

My end-goal is to do the following:

1. At varying intervals, change values for many data objects in the background, such as prices, resources, demand, supply, etc.
2. Display those values in a flat table/list (as they change) in world space to the player, e.g. on a TV screen (or a transparent panel hovering above it, etc.)
3. Have the ability to apply that layout (and its bindings) to another world space object of a different size, e.g. on a smaller or wider TV screen

Imagine an office with 15 desks, all with 3 monitors showing the same data feeds and changing statistics, *except the monitors were all different shapes and sizes*. How could you avoid building all 45 monitor layouts individually, and binding to each field separately? So my question is:

**What is the "right" way to build a re-usable UI (ideally with UXML/USS), display it in world space, and have the ability to update the text in that layout?**

I thought that UI Builder + UXML/USS would be the answer, but I am having trouble parsing how my end goal would be accomplished using that (or if that is even an appropriate use case for UI Builder). Fields that are displayed using UIDocuments are not exposed in the Hierarchy, and can't be dragged onto a script's input in the Inspector, for example. I'm able to project a UXML/USS layout onto a texture =\> material =\> object, but I'm not sure how to bind to the fields within the layout:

The screenshot above is my latest attempt, a POC of a live timer (on the right) manually being updated (using a TextMeshPro field, works great), and the yellow panel to the left is a UXML/USS layout pasted onto a texture/material that's applied to a panel (in a canvas). On the *far* left is that same layout being used as a HUD, just to confirm it works the same as the floating panel. In-game, this data will not be part of the HUD, it will only be in world space. As a POC, I have been trying unsuccessfully to get the timer value from the gray panel to bind to the "should be time" text in the UXML.

So, should I just bite the bullet and build each layout by hand using game objects (such as in the gray panel)? Or am I halfway there with the UXML and just misunderstanding how UIDocuments work? Or is there a new smarter way of doing this I haven't heard of yet? Not looking for a full code example or anything, just a push in the right direction.

# Answer
> 1 votes
One very easy way is to only use one text renderer (e.g. TextMeshPro) in each place that you want to display text, and format all the text you want to display into a single multi-line string.

```
StringBuilder sb = new StringBuilder();

//...

public void RefreshText() {
    sb.Clear();
    foreach (var keyValuePair in fields) {
        sb.AppendLine($"<b>{keyValuePair.Key}</b>: {keyValuePair.Value}");
    }
    textField.text = sb.ToString();
}

```

This approach works well if all of the text changes at once. It can be needlessly expensive if only small parts of the text change. For example, if you have 25 fields you want to display, but only one field changes regularly, it's inefficient to rebuild the string and re-render all of the text when that one field changes. If you have 25 fields that each change once per second, it's not inefficient to combine them into one string because they all change at once anyway.

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


# Question
Title: How to round/smooth the path of an object/sprite that orbits around another object?
Below is a code that defines the values that cause the sprite to start at the top of the object being orbited:

**Create Event:**

```
ballSin=1;
ballCos=0;

ballSinMode=true;
ballCosMode=false;

```

Below is a code that modifies the values started in the previous code so that the sprite starts to rotate / orbit the object in a counterclockwise direction:

**Step Event:**

```
if(ballSinMode){
    ballSin-=0.05;

    if(ballSin==-1){
        ballSinMode=false;
    }
}else{
    ballSin+=0.05;

    if(ballSin==1){
        ballSinMode=true;
    }
}

if(ballCosMode){
    ballCos+=0.05;

    if(ballCos==1){
        ballCosMode=false;
    }
}else{
    ballCos-=0.05;

    if(ballCos==-1){
        ballCosMode=true;
    }
}

```

**Draw Event:**

```
draw_sprite(Sprite7,0,x+(75*ballCos),y+(-75*ballSin));

```

**The object/sprite moves correctly, but the movement occurs as follows:**

**The movement I would like the object/sprite to perform:**

I don't know why the object makes a straight movement. For me it would tend to always keep the same distance from the reference point (position of the object in the center). Since the movement is not circular, it does not. I would like to know why and how to make him move in the desired way.

> OBS - Using the program's "path" feature is out of the question.

# Answer
> 0 votes
The ballSin and ballCos basically says "move across the x/y axis", it's rather a misleading variable name. Because sin and cos has no relation with just the x and y axis. So be aware to not confuse yourself with it.

I've found some possible solution through a quick search, maybe you should try this out:

The Events below are meant for the red ball object, the `square` variable means the square object.

Create Event:

```
radius = point_distance(square.x, square.y, x, y);
phase = point_direction(square.x, square.y, x, y);

```

Step Event:

```
phase += 5; //you can change this to alter the speed/direction
x = square.x + radius * dcos(phase);
y = square.y - radius * dsin(phase);

```

Draw Event:

```
draw_sprite(Sprite7,0,x,y);

```

(Keep in mind that you should do an `instance_exists(square)` before checking for the object, else it'll crash.)

Source at: https://forum.yoyogames.com/index.php?threads/how-can-i-rotate-3-objects-around-a-central-point.11360/post-73795

---
Tags: game-maker
---


# Question
Title: Read actor instance's text variable for widget when triggered on different objects
What I'm trying to do: (a 'long story version' is linked in comment below)

(and another user example is hyperlinked in comment below - i couldn't post over 8 images and/or links in this first comment\*) (there are other similar user questions elsewhere I know)

Short story: I'm trying to make a widget that is triggered by an actor blueprint, and I want the widget to display different text that reflects the public-variable-text edits I make in the editor.

**My latest progress includes actors that are titled somewhat according to the hyperlinked user case above** so, I have a "door\_trigger" and a "doorWidget". I have altered the pin connections so much that I am just going to copy and paste all my screen shots below.

I got to change text asset DoorName by making a public variable called "name," as you'll see. I can make the trigger show this text on screen and have it disappear when the user leaves the trigger actor, **BUT EVERY INSTANCE ALSO SHOWS THIS TEXT VALUE, EVEN THOUGH I CHANGE IT**

In the screenshots (some in comment following too) you'll see the text "3" appear on screen, and it does this for all three of the dummy boxes I made; notice how the second box is supposed to show "dd" (I was just typing random filler content).

ALL HELP SO APPRECIATED!!!!! Thank you!!!

# Answer
A more efficient and clear way to do this is to use DataTables, instead of setting the name of each door, you can have an ID for each door and when the Player enters the collision, you can get the information of that door from the DataTable using that door's unique ID and display it on screen, this way you can be sure that every door has its unique ID which won't mess up the information you would like to display on screen.

Anyway, I believe that the reason why your code isn't working is because of the code after the "Get All Actors of class" node that you're using on the "Event Construct" node in the DoorWidget Blueprint, can you please try to use the "Print String" node in order to debug your code, that way you can efficiently debug and trace the values and how they're changing while your code is executing. Best of Luck!
> 1 votes

# Answer
The reason that this isn't working here is that you're looping through all the triggers but you're only setting the Name reference once the loop is completed so it's only pulling the information from the last found trigger. This will also happen if you move the pin to the Loop Body, unless you find a way to use a boolean to match up the correct trigger.

There are various ways to do what you're trying to do to get the trigger without booleans or the Loop Body.

The easiest is probably to use your existing door\_trig BP variable in the widget blueprint, click the options to make it public and Expose on Spawn. In the Door Trigger blueprint, refresh or recreate the Create Widget node and you'll see your a new pin to plug in to. Create a reference to Self and plug this in to the pin.

This will pass in the reference of the trigger to the widget so you don't need to get all the actors or loop through them. The reference will be there immediately.
> 0 votes

---
Tags: unreal-4, text, blueprints
---


# Question
Title: How to implement pixel art lighting as in the game Project Eastward?
Project Eastward Lighting Demo

Can somebody point me to the right direction as to how this lighting is done to recreate this lighting effect?

The game is 2D but uses a 3D lighting system.

# Answer
> 0 votes
The Unity Lightweight Render Pipeline recently got a couple neat additions for 2d lighting. Among them are:

* Normal mapping on 2d sprites, which can give objects a 3d impression with moving light sources
* HDR bloom
* 2d realtime shadows
* Lit areas in arbitrary shapes, either defined by polygons ("Freeform Light") or by textures ("Sprite Light")

Keep in mind that all of these features are only available in a project using the Universal Render Pipeline, not in build-in or HDRP.

A quick walkthrough of all the features is in this video by Unity Technologies. Detailed information on this subject can be found in the documentation.

One thing it can not do (AFAIK) which seems to happen in the video posted in the question is some pseudo-3d displacement of lit areas. But that displacement seems to be pretty inconsistent in that demo video, so that might not be too much of a drawback.

# Answer
> 0 votes
You can try this asset from Asset Store \[Disclamair: I am *NOT* affinity of it's author\]:

https://assetstore.unity.com/packages/tools/particles-effects/smart-lighting-2d-112535

---
Tags: unity, 2d, 3d, lighting, pixel-art
---


# Question
Title: How to avoid wagon wheel illusion of a rotating gun barrel reversing direction?
I didn't know which forum to post this in, but I'm going to try here first. I am making a shotgun with 3 barrels which spin. However, I also want it to have kickback in the animation, but every time I add that recoil it breaks the animation, making a strange wagon-wheel style illusion. No matter what I try, it always reappears once I add the recoil. Here is the animation:

Here is how the animation is supposed to be perceived, with the barrels spinning in one direction:

But this is what I often see when I look at it, where it seems to snap backwards one step:

It may be a bit hard to see, but if you look at it long enough it will flip between the two, similar to that animation of a ballerina which can be spinning in either direction. I have tried having it only spin when it is down, only spin when it is up, changing the interpolation of the spinning and of the recoil, everything I can think of, but none of it works.

How do I solve this problem? Can I stop the optical illusion while keeping the recoil?

# Answer
The illusion is caused by partial ambiguity in visual cues for depth. The brain perceives some hints about the dimensionality of the image & infers a rotation in a given direction. But some of the hints are ambiguous and allow for a competing interpretation. When this happens, our perception 'flip flops', creating the illusion that image has changed direction.

One of the strongest depth cues is shading. The current image looks relatively flat, which means that we must use relative size to infer depth. Adding some shading to the image may restore enough depth cueing to reduce the illusion:

According to this research paper, the rotational bias is sensitive to viewing angle, as illustrated in their abstract:

So one possible fix would be to try adjust the angle of the gun such that the far end is further away from the viewer:

Finally, your current motion is a slide along the Z axis coupled with a rotation about the Z axis. Additional motion may help break the illusion. Specifically, try making the animation of the gun buck up and down my rotating along an X axis near to the viewer. To do this, the far end of the gun would dip down or up (depending on your preferences) before returning to its original position.

Adding these individually or in some combination may help.
> 2 votes

---
Tags: animation
---


title: How can I reduce this code?

text:
# Question
Title: How can I reduce this code?
Could you help me to reduce this code as much as possible?

```
public GameObject[] TextPage;

public void Skin0()
{
    foreach (GameObject go in TextPage)
    {
        go.SetActive(false);
    }
    TextPage[0].SetActive(true);
}
public void Skin1()
{
    foreach (GameObject go in TextPage)
    {
        go.SetActive(false);
    }
    TextPage[1].SetActive(true);
}
public void Skin2()
{
    foreach (GameObject go in TextPage)
    {
        go.SetActive(false);
    }
    TextPage[2].SetActive(true);
}

```

# Answer
> 2 votes
Rather than use a separate method for each entry that you might activate, pass the index of the entry you want to activate:

```
public void ActivateSkin(int index)
{
    for (int i = 0; i < TextPage.Length; i++)
        TextPage[i].SetActive(i == index);
}

```

This will iterate over the entire `TexpPage` array. For each entry, its position is compared to `index`.
If the position is the same (that is to say, if `i == index` evaluates to true), then `SetActive()` will be set to true & if it is not, it will be set to false.

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


# Question
Title: What does Polygon2D's polygons property do?
Godot `Polygon2D` class has a `polygons` property of type `Array`. The documentation -at the time of writing- does not say what it does. Adding something to it makes the `Polygon2D` disappear. *Which I would find hard to believe to be the purpose of this property, not only an `Array` is excessive, but we have `visible` for that.*

I have found a question on reddit: What does a polygon2D's polygons property do? Which has a single reply saying -among other things- that "it doesn't really do anything".

Is it true that it doesn't really do anything? If it does something, what does `Polygon2D`'s `polygons` actually property do?

---

*And I can't reply on an archived question on Reddit, so I'm answering here. Yes, this is me answering my own question. again.*

# Answer
> 3 votes
If we venture down to the Godot source code, on `Polygon_2d.cpp` we find how `polygons` is used (here).

Godot expects the array to contain arrays of integers. Reading the code we can also figure out that they are indexes (0 based) for the points.

So, let us try that. We create a `Polygon2D` on the editor, give it a set of points, and then in the `polygons` property we add `PoolIntArray` elements (Using a regular `Array` and adding `int` values also works). On each we add the indexes for the points.

Here I placed points in a grid, and created a couple polygons using the `polygons` property:

*I placed the odd rows are left to right, and even rows are right to left, just because it was easy.*

As we can see the single `Polygon2D` node is capable of representing multiple polygons created from the same set of points. The `polygons` property of `Polygon2D` specifies the lists of indexes that make up those polygons. That's what the `Polygon2D`'s `polygons` property does.

When we set something to it, the `Polygon2D` disappears because it will not longer create a single polygon loopings the points in the `polygon` property. Instead the `polygons` property specifies the indexes for the points to create multiple polygons. And, of course, setting anything invalid results in nothing visible.

---

It is worth noting that the property is just specified as "Array". The type system does not tell an array of what (it is `Variant`, actually). And the editor will let you add elements to the `Array` that are not valid for this property. Which fails silently (there is no warning or error message).

However, if I add valid arrays of integers, and in them I set negative number, I get an error.

---

Also worth noting is that they are actually drawn as separate polygons. Here I have made some overlapping polygons and gave them some alpha transparency:

*I used alpha on the `Polygon2D` color for that screenshot. However, using alpha on modulate has the same result.*

As you can see the overlapping area appears more opaque.

---
Tags: 2d, godot
---


# Question
Title: What is the difference between libraries like C++/PDCurses and SFML?
I have read that PDCurses is a library that can be used to create 2D games however SFML is also a library but they are not in the same category I presume according to what I have read:

"The system terminal is a part of your operating system which allows communicating with the computer using text. If you choose to do this, it is also a good idea to use a library — but now, you use a library for creating programs working in the terminal, rather than a game library. Here, the most popular choice is Curses"

Can somebody explain the difference?

# Answer
Curses is for text, SFML for pixels.

PDCurses is a library specifically for creating text-based pseudo-graphical interfaces which visualize everything using fixed-width characters. You can use if for games like the original NetHack:

Or the more recent Dwarf Fortress:  (although neither of those projects actually uses Curses anymore. They both switched to sprite-based libraries which simulate the look of Curses console applications).

SFML, on the other hand, is a library which allows you (among other features) to load sprites from image files and place those image sprites on the screen. This makes it a feasible option for 2d games which look like they were made after 1990.
> 0 votes

---
Tags: c++, 2d
---


# Question
Title: Why are my Player Input Unity Events started twice?
I'm using the (new) "Input System" package and the "Player Input" component on my player prefab like this:

```
public class Player : MonoBehaviour
{
    [UsedImplicitly]
    public void Fire(InputAction.CallbackContext context)
    {
        if (!context.started) return;
        Debug.Log($"Fire!");
    }
}

```

The odd thing is, this method is invoked twice with `context.started == true`. What am I missing here? Why is the method invoked twice?

A minimal working example to reproduce the behaviour can be found on GitHub.

**EDIT**

The player joins automatically through the "Player Input Manager":

# Answer
> 1 votes
I tried to reproduce this issue by creating a brand-new project with the Input System and using your sample code. Nothing changed, but I can definitely suggest a workaround for this.

While using the *Player Input Manager* led me to the same results as yours, just spawning the *Player* prefab via custom code (or adding it to the scene beforehand) worked just fine. The `Fire()` callback was being called once only when the mouse button was pressed, as expected. Pew pew!

According to the scripting API, the *Player Input Manager* «manages joining and leaving of players», and that's it. I think you can smoothly get rid of this component and write your own Player Manager, which deals with spawning your player prefab and toggling user input during cutscenes and stuff.

---

The behaviour you are experiencing is likely to be a bug. The new Input System is a handy alternative to the limited, built-in input manager, but it's still under development. You may report it to the Unity team as well.

---
Tags: unity
---