title: lag spikes and low fps

text:
# Question
Title: lag spikes and low fps
fighting up to two dozen enemies at once the game runs perfeclty smooth...

30 enemies and the game starts to go from the 300-480 fps down to 30-180.... 60 enemies and all attacking at once...the game goes down to 4-12 fps

now it is time to think about performance.

it is a 3D game, godot 3.5.1 with action combat mechanics.

the lag spikes mostly happens when all enemies are attacking, so it has something to do with the damage logic... which is basically a back and fort between the player script to check for defense and the enemy script to check for damage...and 1 box shaped hitbox that is activated on certain frames when enemies play their attacking animations but I don't know if I can make it anymuch simpler than that so it must be something lese.

when they enemies are just minding their own business and are not in fighting mode... the game runs decently well.

so what are the first things I can do to raise that performance when a bunch of enemies all go ammassing against you? I mean they will probably kill you since they can stun lock you, 60 vs 1 and even bees can kill a dude... but at least you will die with a good performance.

# Answer
> 3 votes
Before I start, a note on terminology: I'll be calling "agent" to any non-player entity that does things in the world. They include enemies, but the term "agent" is not limited to enemies, it applies also - for example - to companion characters.

And about performance in general: before we look into doing things faster (i.e. porting to C# or C++), we should look into doing things less often, which is what this answer focuses on... But you should also consider doing less. If ultimately you need to cap the number of enemies in the world, then design around that.

---

**Chase performance**

I presume the agents figure out how to much to go to the player, or whatever target they have, each frame. You want to change that, so that only one agent figures out the direction per frame, and the rest just keep going the same direction they were going (which is likely to be approximately correct, unless the target - e.g. the player - is a lot faster than the enemies).

---

**Attack performance**

On one hand, you don't want to process multiple attacks the same frame. Another way to put it is that you will give the player invulnerable frames (even if it is only the same frame of the attack). So only the first attack to connect in a frame gets processed and others are discarded.

On the other, you might need to limit how many enemies can attack at the same time... Before it gets to collision checks... That is: the enemies take turns to attack.

It does not have to be one by one, for example, you could have at most 5 enemies attempting to attack at the same time. And the others do not have to be idle... They can even play attack animations, but they will not harm the player (not because the player is invulnerable and code returns early, but because their collisions are disabled and so the code for them never runs).

Smoke and mirrors I say.

---

**AI director**

This all suggest that instead of having a back and forth between player and enemy scripts, before doing anything, you want to centralize the logic. There must be some central code that decides who can update their path, and who gets to attack.

The place where you centralize the logic has a name: It is the AI director.

Traditionally the AI director... Directs. It tells the agents what to do. And most of its operation is asynchronous. A second approach is also possible: have each agent report their intention, and the director tells them if they are allowed or not to proceed. I believe that for you it is easier to refactor your code into that second approach. *And you might then refactor into the traditional approach if you need to.*

**Note**: Also traditionally the AI also handles spawning enemies, and dynamic difficulty... It does not have to. There are no hard rules. It is your game. But, if you have code to spawn enemies, that might be a good place to implement - or at least connect - your AI director. Otherwise, I suggest to start with a new autoload.

Having an AI director will ease experimenting (e.g. what happens if the enemies don't attack at all? what happens if only a few of them chase? etc.). And that is what I would suggest you do: implement an AI director (it does not have to be a complex one, just one that does as much as you need), and experiment with it, to try to find a balance between performance and game-play.

---
Tags: 3d, performance, opengl-es2, godot-3
---


# Question
Title: How can i keep a constant grid position relative to transform.ChildCount
I need to manage the index positions in a `GridLayoutGroup` and keep it consistent with the `childCount` of the group it belongs to.

The Grid has a fixed `ConstraintCount`(3) and can be increased or decreased by 3 (it adds a row). The index can also be modified (+1, -1) so that its value within the transform group changes. I initially wrote the code

```
        destTank = top.transform.childCount - 2;

```

which works well, it keeps my index `destTank`  always to be on the top/middle position of the grid even when the grid changes, but it doesn't take in consideration the index variations. as result an index of 9 in a 3x3 grid will become 5 in a 3x2 grid but i need it to be 6. In other terms if the position on the grid is, let's say, on the top/left corner of the grid it should also be in the top/left corner in a smaller grid, not in the top/center position.

to solve this i wrote something like that

```
        destTank = top.transform.childCount - (top.transform.childCount - destTank);

```

but it's not working because the value of `destTank` is always changing and gives me weird results. I tried a lot of different combinations of values, even tried to divide the `childCount` by the `contraintCount` to obtain a ratio (1,2,3) corresponding to the rows number and use it somehow as a delta to obtain my index but nothing worked. Maybe I'm just messing up the syntax when writing the math operations. Anyone can help me solve the puzzle? Here's the full code:

```
    private void Positions()
{
    var rows = top.transform.childCount - 3;

    destTank = top.transform.childCount - (top.transform.childCount - destTank);
    destHealer = center.transform.childCount - 2; // (center.transform.childCount / GLG_center.constraintCount);
    destDpsMR = right.transform.childCount - 1;
    destDpsML = left.transform.childCount - 1;
    destDpsRR = bottomR.transform.childCount - 1;
    destDpsRL = bottomL.transform.childCount - 1;

    Debug.Log(top.transform.childCount);
}

private void PositionsPlus()
{
    if (currentGroupIndex == 0)
    {
        destTank = (destTank + 1) % top.transform.childCount;
    }
    if (currentGroupIndex == 1)
    {
        destHealer = (destHealer + 1) % center.transform.childCount;
    }
    if (currentGroupIndex == 2)
    {
        destDpsMR = (destDpsMR + 1) % right.transform.childCount;
    }
    if (currentGroupIndex == 3)
    {
        destDpsML = (destDpsML + 1) % left.transform.childCount;
    }
    if (currentGroupIndex == 4)
    {
        destDpsRR = (destDpsRR + 1) % bottomR.transform.childCount;
    }
    if (currentGroupIndex == 5)
    {
        destDpsRL = (destDpsRL + 1) % bottomL.transform.childCount;
    }
}

public void CellAdd(int value)
{
    for (int i = 0; i < value; i++)
    {
        if (currentGroup.transform.childCount < 9)
        {
            Instantiate(gridCell, currentGroup.transform.position, Quaternion.Euler(90, 0, 0), currentGroup.transform);
            FloatingText("+ " + value.ToString() + " CELLS");
        }
    }
    GroupsOffset();
    Positions();
}
public void CellRemove(int value)
{
    for (int i = value; i > 0; i--)
    {
        if (currentGroup.transform.childCount > 3)
        {
            DestroyImmediate(currentGroup.transform.GetChild(i).gameObject);
            FloatingText("- " + value.ToString() + " CELLS");
        }
    }
    GroupsOffset();
    Positions();
}

```

# Answer
> 0 votes
The calculation for your second image is easy.

```
circleNumber = ((totalElements - 1) / 3) * 3 + index;

```

We are doing a simple integer division. / 3 * 3 will give you the top left number of the latest row, from there you just add the index. If your index can go higher than 2 but should wrap around (meaning index 3 should point to 6 again), you add can modify it to

```
circleNumber = ((totalElements - 1) / 3) * 3 + (index % 3);

```

---
Tags: unity, grid
---


# Question
Title: Keeping characters in-sync in network rollback environment - when player is actively changing its input
I am implementing network rollbacker in real-time action game and found out a very strange issue where local (non-master) player is moved a bit forward then back when changing input.

After narrowing it down I found this is a source of the issue:

1. Non-master player (let say at (0, 5) position) is moving forward via vector (1, 0)
2. Player decides to stop moving. It immediately stop movement locally (as prediction) and then send message to server that it wants to stop
3. As it is some time before the packet arrives, the server now thinks the player is at (1, 5) and it broadcast the information to all players
4. The packet from non-master player arrives. Server immediately goes back a few frames and re-simulates (via rollbacker), and moves character back to position (0, 5). It broadcast the information again.
5. The non-master player receives information that is should stand at (1, 5). It erroneously corrects its own position to (1, 5)
6. The second packet arrives. The non-master player goes back to the valid (0, 5)

How can I correct the algorithm so the non-master player won't be doing this leap forward/back on changing input (5th and 6th step above), when receiving incorrect correction from master due to master not knowing its local change of input?

# Answer
> 0 votes
Okay, I found the solution:

* Non-locally-predicting clients just take server value as requested
* Non-master character will follow this algorithm:

1. After change request comes from server and is mis-matching with local prediction, the object will remember current position and schedule position update within next 0.5 second
    2. If new packet arrives it will update position update request, but do not change update timer
    3. If new packet happen to match prediction, the entire correction process is cancelled
    4. When reached position update timeout (after 0.5 second) it takes position requested and add to it local delta movement happen within that 0.5 seconds

Example based on original question:

1. Packet comes with correction (1, 5). Because it is distant from current position (0, 5), the client schedules update in 0.5 seconds
2. The client starts moving up to (0, 6)
3. The new correction comes with (0, 5). The entire correction process is cancelled as the client was at (0, 5) at the moment
4. The client predicts its new position at (0, 6)

And if there is indeed a mismatch (ie. there was some event that pushed player to (1, 5) that could not be predicted locally):

1. Packet comes with correction (1, 5). Because it is distant from current position (0, 5), the client schedules update in 0.5 seconds
2. The client starts moving up to (0, 6)
3. 0.5 seconds has passed. The clients correct its position to (1, 5) + (0, 6) - (0, 5) = (1, 6)

---
Tags: networking
---


title: Input axis from keys

text:
# Question
Title: Input axis from keys
I'm making a game engine from scratch and I'm currently handling the inputs. The low level handling is done, and now I would like to provide higher level input listeners, such as axis.

I've failed to find anything online on the maths behind inputs axis, so I though I'll give this community a shot.

I have two keys binded to an axis (let's say, W and S for forward / backward movement). Each key can be in a pressed or released state. What would be the approach to create a input axis value that goes from -1 to 1, smoothly and depending on the input ?

For example, when pressing W, the axis would smoothly move from 0 to 1 over the course of several frames, and back to 0 when the key is released.

I wondered about things like gravity or springs toward 0, while applying forces towards 1 (-1) when W (S) is pressed.

If anyone is interested, here is my current code for the axis (I'm doing it in Rust)

```
/// the stand alone axis
pub struct InputAxis {
    positive: winit::event::VirtualKeyCode,
    negative: winit::event::VirtualKeyCode,
    positive_state: bool,
    negative_state: bool,
    value: f32,
    speed: f32,
    springback: f32,
}

/// update code (raw input handling is not shown here, this func is called once per frame)
pub fn update(&mut self, delta: f32) {
    // key being pressed simulate a pushing force on the axis
    if self.positive_state {
        self.value += self.speed * delta;
    }
    if self.negative_state {
        self.value -= self.speed * delta;
    }
    // spring to return the axis to 0
    let spring = -self.value * self.springback * delta;
    self.value += spring;
    // clamp the axis value
    if self.value > 1. {
        self.value = 1.;
    } else if self.value < -1. {
        self.value = -1.;
    }
}

```

The code here technically works, but does not feel good at all. The values never fully reach zero after being moved, and I can't find a consistent balance between speed and springback.

Are there any well-known models that work well out here ?

# Answer
> 1 votes
There's actually two questions above:

**Why does the code above not reach 0?**

You never reach 0 because you are just scaling the value each frame. This means that you will get increasingly smaller values but never reach 0 - you basically modeled Zeno's paradox ;)

The simplest way to fix this is to set a lower bound and set your value to 0 if it ever reaches/crosses that bound:

`value = value <= bound ? 0 : value;`

This will work but you probably want more control in shaping response to input, which leads us to the next question...

**What approach should I use for input?**

The approach you're using will work but designers are bound to want more control depending on the style of gameplay (or even the gameplay itself - maybe there's effects that modify input behavior dynamically?).

Off the top of my head I can imagine designers wanting to tweak the parameters that are associated with easing functions:

***Duration***: How long does it take for input to settle, or how "tight" do the controls feel?

***Curve***: How do the values settle? Do they glide linearly to a stop? Do they taper off slowly? etc.

In the end I don't think you're likely to find a canonical approach to input handling due to the variety of genres and control schemes out there, but IMHO easing functions seem like a good general starting point that should cover a lot of design ground.

***OLD ANSWER (TOTALLY WRONG: See comment)***

I think the issue with your code is that there's no damping, which is why your input never settles to 0. Currently there's nothing that removes energy from the system except the clamping (which only works for large values) and numerical precision (which only works for tiny values). Therefore it'll keep oscillating indefinitely. You would want to add a damping parameter (a float that is less than 1) that will scale the energy of the system down each iteration:

```
let damping = 0.99;
let spring = -self.value * self.springback * delta * damping;

```

Springs are great at modeling these kinds of things but for inputs they may not be the perfect choice. A feature of springs is that they tend to bounce (i.e. over/under-shoot their target) which can be a problem for input: you don't want your character nudging past the edge of a cliff in a platformer, or your reticle to oscillate around your target in a shooter. You might be better off using some easing function to control the smoothing of the input. Like springs these can be very finely tuned but they give you more control, which you'll likely want with something that needs to be as precise and predictable as player input.

---
Tags: input, axis
---


title: floating damage text in 3D

text:
# Question
Title: floating damage text in 3D
followed this tutorial : https://www.youtube.com/watch?v=UlvBqz8bhCo

the guy is working mostly in 2D, i tried to apply the same method but I'm hating working with UI in godot, everytime I seem to get something right, I get 100 more wrong.

the problem I'm having is that when I hit multiple enemies, only one damage indicator shows

so basically in the code the func \_ready() animates the damage indicator making it shrinks after it appears... and the self.queue\_free() deletes the damage after the animation is complete

I'm using a third person controller with a crossair, the damage shows offset to the left of the crossair, which is perfect for now... but no matter how many enemies I hit... only one damage pop up shows... even when enemies have different ammounts of defense so it should show diferent damage texts... it only ever shows the damage of the first enemy hit

the floating damage is called by the enemy when it is hit

there is the full enemy.gd code https://github.com/Ceisri/Godot-Action-Combat/blob/main/Creatures/Enemies/Enemy.gd

The player calls the function that damages the enemies with :

```
func attack():
var enemies = hitbox.get_overlapping_bodies()
for enemy in enemies:
    if enemy.has_method("onhit"):
        #enemy.hurt()
        enemy.onhit(damage)

```

which is the mirrored version of the Enemy script... , it also has the function to be damaged:

```
func onhit(damage):
$GUI/HealthBar.value = int((health / maxhealth) * 100)
health -= (damage - defense)
staggered = true

```

it basically gets the (damage) from the enemy and the (defense) from the player... the opposite happens when the enemy is being hit.

so aggressor damage - victim defense = damage caused to victim

# Answer
> 0 votes
fixed it, before no matter how many enemies you hit, the first floating damage would ovveride all the others thus only the first will show.

now it shows all damage every time someone is hit.

Solution:

-Get the screen size, divide by two to get the center

-Spawn the text at the center

But now it still overlaps

-Create an offset

-Spawn the text offset to the cursor with a random range of positions.

```
var offset = Vector2(rand_range(-20, 20), rand_range(-20, 20))
return center + offset

```

to use them in your game, just follow the tutorial and then add my part of code...

full script at : https://github.com/Ceisri/Godot-Action-Combat/blob/main/scripts/floatingtext.gd

now it can display as many damage indicators as possible, and all around the cursor, regardless of monitor size.

---
Tags: 3d, sprites, gui, combat, godot-3
---


# Question
Title: How to achieve Quake moving lava effect using OpenGL under v2.0?
On the first boss fight level you could notice how lava moves what is not a surprise for a software renderer. But according to the Quake fandom, GLQuake was released in 1997, hence OpenGL had no shader support, so how the moving lava was added? Was it some kind of a mesh grid with just some texture-mapped polys floating around? Or maybe it was still done in the 'software rendered' way?

# Answer
> 2 votes
What you need to do is to adjust the UV coordinates. Here are a couple of non-shader options for doing that:

1. Just modify the mesh on the CPU every frame. This is straightforward if you're using glTexCoord2f() etc. instead of vertex buffers.
2. Apply a transform matrix using glMatrixMode(GL\_TEXTURE). This would work for things like scrolling a texture across a mesh, but it's less flexible.

Having said all that, you could just take look at the source code: https://github.com/id-Software/Quake

---
Tags: opengl, shaders, support
---


# Question
Title: godot saving games, explain like I'm five
using this tutorial, my game crashes before opening and gives 0 errors... doesn't even tell me what's wrong.

All the code I'm using is literally just this open project: https://github.com/BirdyBirdBirbs/picokun copied and pasted. which is the same exact thing you see in the video... but for my game engine version, because the main one got updated to 4.0

In the save function I obviously changed what the save system is supposed to save to account for compatibility.

so:

```
func load(save_game: Resource):
var data: Dictionary = save_game.data[SAVE_KEY]
stats.health = data['health']
stats.energy = data['energy']
stats.maxhealth = data['maxhealth']
stats.maxenergy = data['maxenergy']

```

which is literally the same thing but using my variable names instead of theirs, like they use max\_health... and mana I use maxhealth and energy...

I've been spending days searching for tutorials on godot on how to make saving system and the internet is polluted with either useless "quick" 2-5 minute tutorials or with templates that don't explain anything at all about how the node system works, pretty much all of the methods I tried just give me crashes .

and the godot documentation assumes that I have a college degree in rocket science.

# Answer
This is nearly impossible to debug – only guess – given your small code snippet above. If the debug console doesn't include any errors, this sounds as if your actual code flow cause the engine to exit.

Either way, to me this feels as if you're overcomplicating things unnecessarily.

I no longer have version 3 installed, so this is from memory, but all you actually should have to do:

Godot's built-in class `ConfigFile` already has all the neat little tricks you're looking for in a savegame/savestate.

To use this, it should be enough to just create your own global autoload/singleton class (there should be tons of tutorials on how to enable this):

**SaveState.gd**

```
extends ConfigFile

```

This is all. Just this one line (while you can add extra functionality, if you need it, for example some checksum calculation). Register it under the global name `SaveState` (Project Settings \> Autoloads) and your objects may use it like this:

**Player.gd**

```
func _ready():
  # Load maximum health, use the current/default value as the default
  self.max_health = SaveGame.get_value('player', 'max_health', self.max_health)

```
> 1 votes

---
Tags: gui, savegame, godot-3
---


# Question
Title: Render and Process loop synchronisation with threads
I am developing an interactive visualizer for a project using Pangolin and OpenGL. The idea is as follows.

There are two threads:

| 1. Render Thread | 2. Process Thread |
| --- | --- |
| \- acquire lock and swap `dataNew` with `dataDisplay`, release lock
\- render `dataDisplay` on the window | \- read data
\- process data
\- acquire lock, copy data to `dataNew` buffer, release lock |

Sample code:

```
// Render loop
while (!pangolin::ShouldQuit()) {
  if (mDataReadDone) break;

  // ....some code.....

  /*Critical section*/
  // Can acquire lock only after mDataNew
  // is updated with new data in the process thread
  {
      std::unique_lock<std::mutex> lock(mRenderMutex);
      std::swap(mDataDisplay, mDataNew);
  } /*Critical section*/

  // .....Render mDataDisplay data.........
}

// data process loop
while (!mWindowClosed) {
  // .....Read data....

  // .....Process data....

  // ....Copy data.....
  /*Critical section*/
  {
      std::unique_lock<std::mutex> lock(mRenderMutex);
      copyDataFromPipeline(mDataNew);
  }

}

```

**Question**: In the render loop, for the `std::swap()` to happen, it has to wait till new data is filled in `mDataNew` buffer by the process thread and hence the render loop is blocked for some time. Can the render loop be blocked for some time by design in general?

**Constraint** \- In my case, I have a pause option and also a time travel option to go back in frames to debug a particular frame if something is wrong there, so I cannot miss any frames for rendering

# Answer
You can do this in a lock-free way if you set aside a third data buffer (triple buffering).

Call them:

* next to write
* most recently written
* currently rendering

and store a pointer to each.

When the process thread finishes writing freshly-processed data into `next to write`, it performs an atomic swap of the pointers to `next to write` and `most recently written`. So when the render thread looks for the latest data, it finds it via the `most recently written` pointer, and the process thread is free to write new data into the `next to write` buffer, knowing that no one else is relying on its contents.

When the rendering thread finishes rendering a frame and needs the next one, it performs an atomic swap of the pointers to `most recently written` and `currently rendering`. That keeps the data being currently used for rendering out of reach of the process thread, and releases the previously rendered data to be overwritten.

Because these two swaps are done atomically, they happen all at once - one fully after the other, never overlapping or interleaved. So you don't have to worry about one of the pointers getting duplicated/misplaced due to a race condition.

This avoids locking for a full data copy at any stage. You can see some more discussion of the implementation of such atomic pointer swaps here.

If the process thread is fast, it can process multiple data frames between renders, and the render thread will automatically pick up the latest and greatest data as fast as it can. If your process thread sometimes runs slower than your render thread, you'll want to put the render thread to sleep until the process thread finishes the next swap and wakes it - otherwise out of the box it will flip back and forth re-rendering the two most recent frames until the process thread finishes.
> 0 votes

---
Tags: c++, rendering, multithreading
---


# Question
Title: How to implement skeletal animation for Signed Distance Field models?
When animating a 3D model, we want the surface of the model to remain continuous (such that, for instance, the limbs do not seem to slide on the torso, but stay attached at their position).

In a triangle-based mesh, this is easy since the edges of mesh preserve where a limb gets attached to torso. In fact, preserving the volumetric properties becomes the tricky part, to ensure that faces don't end up intersecting each other, etc.

However, in an SDF, while the volumetric properties get preserved automatically, the surface properties do not. Instead of the character looking like a creature with stretchable skin than holds their muscles and bones inside, it looks like a cloud whose various volumes can slide in, out or around upon movement.

What are the ways that skeletal animation can be applied to Signed Distance Fields, if any? If there are none, what alternative to skeletal animation might be used to achieve same effect?

# Answer
> 0 votes
I've thought about this a lot myself and think the following problems make certain kinds of animation more difficult with sdfs than polygons:

* smoothing between sdf primitives has a lot to do with the nice features of sdf modelling, but this means that a model might start smoothing with itself undesirably as you animate it. consider a hand and fingers, all made with a series of smoothed primitives. As fingers get closer together, like a folded hand, a fist, etc, the fingers will all blend in with each other to create a new whole rather than individual fingers.
* the old "squash and stretch" traditional animation exercise. With polygons, it is trivial to elongate a ball, for example, and have it stretch easily in one direction while narrowing in another dimension to maintain volume. If you have an sdf sphere as your ball, this can be more complicated. perhaps you use non-uniform scaling to stretch the ball.. that is already undesirable as most sdf renderers stick to uniform scale (though non-uniform can be done) for mathematical reasons. the other option then is to use multiple smoothed spheres to create your stretched oval-like ball, but now you need to carefully tweak their placement and alter their sizes so the volume seems visually preserved. it's just not so useful; very hard to animate something like with all the changes you have to make at every frame compared to a basic polygonal skeleton.
* arbitrary scenes of many complex objects are hard to optimize with sdfs. With polygons, you have tried-and-true bounding hierarchies that can be automatically created at the triangle level and bounced off to a renderer, and many GPUs now handle these natively, some even create the bounding chains for you. With sdfs, if you want a rendering application to automatically handle a large number of primitive operations, the methods for doing this are not particularly obvious. demo scenes can hard-code in the bounding volumes as an optimization, but if you want to work with arbitrarily complex scenes, you can't expect someone to program this directly for every scene, especially as they start animating (nor would this be a reasonable thing to expect artists to do either). there are plenty of ways to optimize sdfs but each has its own drawbacks and can be exceptionally computationally expensive as a pre-render step in some cases (like voxel discretization) hence why marching cubes back to polygons is a clearer path to rendering efficiency, especially once sdfs start animating around.

I'd be curious what other things you've considered as ways to solve this problem?

---
Tags: animation, skeletal-animation, skinning, signed-distance-field, raymarching
---


title: Why is my Post Processing not working?

text:
# Question
Title: Why is my Post Processing not working?
I'm trying to get Post Processing working in my Unity Project, with URP enabled, but I'm not seeing it work. I've looked at a few tutorials and I've followed them exactly, but I never see any post processing happen.

Here's the inspector window for my Camera:

And here's the inspector window for my Post Processing GameObject:

# Answer
> 5 votes
URP comes with its own implementation of post processing. You cannot use the regular "Post-process Volume" or the "Post-process Layer" with the Universal Render Pipeline. You need to add a different Volume (like the one added in the image below) to add post-processing. Click "Add Component", and search for Volume to add it.

You also need to make sure the Camera has enabled Post Processing (Which you already have enabled)

I also use URP in my game, and here is a short gif with and without certain post-processing effects:

# Answer
> 0 votes
Additional info to John's answer. Make sure you check following before proceed with John's answer.

## Make sure to remove Post Proprocessing Stack V2 (PPv2)

Go into Window -\> Package Manager, Select "In Project" and search for "post processing" package like this one in the screenshot. **The PPv2 package is for built-in renderer not for URP**. You must delete it to prevent confusion.

This is common pitfall if you created your project as built-in renderer then decided to switch to specialized renderer later (URP, etc) your project might be having this package installed.

Notice that component icon from 2 packages are different:

And lastly remove your post processing profile asset if it was created with PPv2. The URP one has its own different asset and cannot be interchanged.

---
Tags: unity, unity-urp
---


# Question
Title: Coroutine delay isn't consistent on different framerates
My problem:

I am using a coroutine to add a typewriter effect to my texts, but the delay (using `yield return new WaitForSeconds();`) isn't consistent on different framerates (`Application.targetFrameRate`).

This seems to be more visible with smaller delays, as one of my texts has a delay of just 0.0005 seconds and thats where I first noticed it.

I have tried to multiply the `yield return new WaitForSeconds();` with Time.deltaTime but that didn't work.

# Answer
> 4 votes
The smallest delay that `WaitForSeconds` can give you is one frame. That's because the way it's implemented is it checks once each frame (after `Update`) whether enough time has elapsed. If so, it resumes the coroutine, and if not, it waits a whole frame before checking again.

So if you're rendering at say 60 fps, you can't get any delay shorter than 0.016667 seconds.

You can simulate more granular delays using a scheme like this:

```
IEnumerator TypeWriter(string text, float delay) {
    int charactersTyped = 0;
    float accumulatedTime = 0f;

    while (charactersTyped < text.Length) {
        // Wait till after Update calls for this frame are done.
        yield return null;
        // Add elapsed time to our accumulator.
        accumulatedTime += Time.deltaTime;

        // As long as enough time has elapsed to type another character...
        while (accumulatedTime >= delay) {
            // type one more, and deduct the delay it came with.
            charactersTyped++;
            accumulatedTime -= delay;
        }

        // Once all the typing is done for this frame, update the display.
        display.text = text.Substring(0, Mathf.Min(text.Length, charactersTyped));
    }
}

```

This will type out multiple characters in a single frame as needed to "catch up" to the amount of time that's elapsed. So if your delay is 0.0005 (half a millisecond) and your framerate is 60 fps (16.667 ms per frame), then it will race ahead 9 characters in one frame, to keep pace with the number of characters that "should have been" typed by now, had the simulation been running continuously. Since the player only sees the rendered frames anyway, this does not make the typing more jerky than it would be otherwise - the scree is just not displaying enough frames in-between to show every character being typed individually.

By retaining the `accumulatedTime` between frames, you save any "loose change" milliseconds leftover from one frame into the next, which helps avoid temporal aliasing to get a smoother typewriting animation.

# Answer
> 0 votes
```
using System.Collections;
using TMPro;
using UnityEngine;

public class TypewriterEffect : MonoBehaviour
{
    public float typingSpeed = 0.05f; // Characters per second

    private TMP_Text textComponent;
    private string fullText;
    private bool isTyping = false;

    private void Awake()
    {
        textComponent = GetComponent<TMP_Text>();
        fullText = textComponent.text;
        textComponent.text = "";
    }

    public void StartTyping()
    {
        if (!isTyping)
        {
            StartCoroutine(TypeText());
        }
    }

    private IEnumerator TypeText()
    {
        isTyping = true;
        float startTime = Time.realtimeSinceStartup;
        float elapsedTime = 0f;
        int characterIndex = 0;

        while (characterIndex < fullText.Length)
        {
            elapsedTime = Time.realtimeSinceStartup - startTime;
            int visibleCharacters = Mathf.FloorToInt(elapsedTime / typingSpeed);

            if (visibleCharacters > characterIndex)
            {
                characterIndex = visibleCharacters;
                string currentText = fullText.Substring(0, characterIndex);
                textComponent.text = currentText;
            }

            yield return null;
        }

        isTyping = false;
    }
}
```

# Answer
> -2 votes
```
using System.Collections;
using TMPro;
using UnityEngine;
public class TypewriterEffect : MonoBehaviour
{
    public float typingSpeed = 0.05f;
    private TMP_Text textComponent;
    private string fullText;
    private bool isTyping = false;
    private void Awake()
    {
        textComponent = GetComponent<TMP_Text>();
        fullText = textComponent.text;
        textComponent.text = "";
    }
    public void StartTyping()
    {
        if (!isTyping)
        {
            StartCoroutine(TypeText());
        }
    }
    private IEnumerator TypeText()
    {
        isTyping = true;
        float delay = typingSpeed;
        for (int i = 0; i <= fullText.Length; i++)
        {
            string currentText = fullText.Substring(0, i);
            textComponent.text = currentText;
            yield return new WaitForSeconds(delay);
        }
        isTyping = false;
    }
}
Bu şekilde, farklı kare hızlarında daha tutarlı bir daktilo yazma efekti elde etmelisiniz...
```

---
Tags: unity, frame-rate, coroutines, time, deltatime
---


# Question
Title: How can I hide the interior frontfaces of a portal when viewed from the outside?
I'm trying to follow This tutorial for a portal mask shader. It's an awesome effect but it comes with a couple of caveats. The shader as he designs it can only exist in a bubble, as:

1. The portal is visible through other objects (this I solved by finagling the queue order):
2. The illusion the portal creates of another space within is broken as soon as you enter:

As loading can't be perfectly instantaneous, this means when a player enters the portal, there will be a brief moment in which they are right back outside it, which I feel ruins immersion.

In order to compensate for this, I figured I would try to extrude the edges of the mask geometry, which works for the inside of the portal..

..but introduces the new problem of the front faces of the inside of the object being visible:

So what I'm hoping to achieve is a shader which:

* Occludes the PortalMask shader/object from the outside only
* Does not occlude other environment objects
* Is not itself visible

Am I asking the impossible?

# Answer
A simple trick for this is to add a second shader pass, or second material that renders before the main one.

Switch the culling mode to cull front faces and draw back faces instead. Write to the depth buffer but leave the colour buffer unchanged.

This puts an invisible occluder in front of the front faces when viewed from the side, so they don't draw through it.

The downside with this is that it will also include any transparent effects drawn after the portal, like particles. It also only works from outside the portal volume. Inside, you'll see the front faces unoccluded, even if you walked in from the side rather than through the aperture.

I think a better solution is to keep the portal flat. Make a corridor out in empty space with your portal interior effect. As soon as the camera position crosses the portal, teleport the player into the corresponding position in the corridor, so that the player doesn't see any visible cut. (You can have an imposter of the room they just left in case they turn around, obscured by magical portal effects to disguise artifacts)
> 1 votes

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


# Question
Title: Smartphone tilt calculation when using gyroscope in Unity (smartphone moving problem)
I have been trying for several days now to set up the correct behavior of the gyroscope in Unity. I want to make it so that when the smartphone is tilted, the object tilts along the z-axis. I found several variants of the code on the Internet and I managed to correctly calculate the slope and block the change in rotation when the smartphone is tilted forward or backward. But one problem remains, in which, if you pick up a smartphone and turn around its axis, the angle of rotation of the object also changes. As I understand it, this is due to the fact that in addition to the tilt, the gyroscope also calculates the change in the rotation of the smartphone in space. Here is my code:

```
public class TestInputController : MonoBehavior
{
     public Transformbg;
     private Quaternion referenceRotation;

     void Start()
     {
         input.gyro.enabled = true;
         referenceRotation = GetDeviceRotation();
     }

     private Quaternion GetDeviceRotation()
     {
         return new Quaternion(0.5f, 0.5f, -0.5f, 0.5f) * Input.gyro.attitude * new Quaternion(0, 0, 1, 0);
     }

     private float GetRollAngle(Quaternion refRotation, Quaternion currentRotation)
     {
         Quaternion eliminationOfXY = Quaternion.Inverse(Quaternion.FromToRotation(refRotation *
             Vector3.forward, currentRotation * Vector3.forward));

         Quaternion rotationZ = eliminationOfXY * currentRotation;
         return rotationZ.eulerAngles.z;
     }

     void Update()
     {
         bg.transform.rotation = Quaternion.Slerp(bg.transform.rotation,
                        Quaternion.Euler(0f, 0f, GetRollAngle(referenceRotation, GetDeviceRotation())),
                        8f * Time.deltaTime);
     }
}

```

How can you remove the dependence on the rotation of the smartphone in space and leave only the calculation of the angle of inclination to rotate the object along the z axis?

# Answer
Quaternions must have a vector length of one, so `Quaternion(0.5f, 0.5f, -0.5f, 0.5f)` is an invalid Quaternion.

Your post multiply \`new Quaternion(0, 0, 1, 0)' rotates 180 degrees about the Y axis.

Yes, Quaternion math is weird, but unless you fully understand the restrictions:

Since gimbol lock cannot affect a single angle:

```
private Quaternion GetDeviceRotation()
{
    return Quaternion.FromEuler(0,0,Input.gyro.attitude.eulerAngles.Z);//move to needed axis
}

```

Never be afraid to go back to simple Euler angles. Just don't try to rotate them.
> 0 votes

---
Tags: unity, c#, rotation, quaternion, gyroscope
---


# Question
Title: Why the camera is never looking forward direction and always looking down?
While the camera(transform) is moving between the waypoints I want that according to the CameraViewMode enum selected option is the direction the camera will look at.

The BirdsEye mode is always the view mode even if I select the Forward. I found that I can't change the camera rotation while it's moving between the waypoints , not sure if it's because there are so many waypoints and they are very close to each other less then 1 distance or becaue I want the camera rotating facing to the next waypoint each time.

This how it is now , the camera is looking at the waypoints from up to down: This is what I count as the BirdsEye view mode:

The forward view mode should be when the blue axis will be forward and not down.

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

public enum CameraViewMode
{
    BirdsEye,
    Forward
}

public class CubeSpawner : MonoBehaviour
{
    public GameObject cubePrefab;
    public LayerMask terrainLayer;
    [GapRange(0, 100, GapDisplayMode.Floats)]
    public float gap = 0f;
    public float cameraMoveSpeed = 5f;
    public float zoomSpeed = 5f;
    public float rotationSpeed = 10f;
    public List<Transform> wayPoints = new List<Transform>();
    public float waypointsMovementSpeed = 5f;
    public float waypointsRotationSpeed = 5f;
    public float cameraHeightOffset = 2f;
    public CameraViewMode viewMode = CameraViewMode.BirdsEye;

    private Vector3 lastCubePosition;
    private bool isDragging = false;
    private int currentWaypointIndex = 0;
    private bool isMoving = false;
    private bool isRotating = false;

    private void Update()
    {
        HandleCameraMovement();
        HandleCameraRotation();

        Vector3 mousePosition = Input.mousePosition;

        HandleRuntimeInput(mousePosition);

        if (Input.GetMouseButtonDown(2)) // Middle mouse button pressed
        {
            isMoving = true; // Start moving towards waypoints
        }

        if (isMoving)
        {
            MoveTowardsWaypoint();
        }
    }

    void MoveTowardsWaypoint()
    {
        if (currentWaypointIndex >= wayPoints.Count)
        {
            isMoving = false; // Reached all waypoints, stop moving
            return;
        }

        // Get the current waypoint position and rotation
        Vector3 targetPosition = wayPoints[currentWaypointIndex].position;

        if (!isRotating && currentWaypointIndex == 0)
        {
            Quaternion targetRotation;
            if (viewMode == CameraViewMode.BirdsEye)
            {
                targetRotation = Quaternion.LookRotation(Vector3.down, Vector3.up);
            }
            else
            {
                targetRotation = Quaternion.LookRotation(targetPosition - transform.position, Vector3.up);
            }

            // Rotate towards the desired direction
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);

            if (Quaternion.Angle(transform.rotation, targetRotation) < 0.01f)
            {
                isRotating = true; // Finished rotating, start moving towards the first waypoint
            }
        }
        else
        {
            Quaternion targetRotation = Quaternion.LookRotation(targetPosition - transform.position, Vector3.up);

            // Calculate the target camera position with height offset
            Vector3 targetCameraPosition = targetPosition + Vector3.up * cameraHeightOffset;

            // Move towards the target camera position
            transform.position = Vector3.MoveTowards(transform.position, targetCameraPosition, waypointsMovementSpeed * Time.deltaTime);

            // Rotate towards the waypoint rotation
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, waypointsRotationSpeed * Time.deltaTime);

            // Check if reached the current waypoint
            if (transform.position == targetCameraPosition)
            {
                currentWaypointIndex++; // Move to the next waypoint
                isRotating = false; // Reset the rotation flag
            }
        }
    }

    private void HandleRuntimeInput(Vector3 mousePosition)
    {
        if (Input.GetMouseButtonDown(0))
        {
            isDragging = true;
            Ray ray = Camera.main.ScreenPointToRay(mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hitInfo, Mathf.Infinity, terrainLayer))
            {
                lastCubePosition = hitInfo.point;
                GenerateCube(lastCubePosition);
            }
        }
        else if (Input.GetMouseButtonUp(0))
        {
            isDragging = false;
        }
        else if (isDragging && gap > 0f)
        {
            Ray ray = Camera.main.ScreenPointToRay(mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hitInfo, Mathf.Infinity, terrainLayer))
            {
                if (Vector3.Distance(hitInfo.point, lastCubePosition) >= gap)
                {
                    GenerateCubesBetween(lastCubePosition, hitInfo.point);
                    lastCubePosition = hitInfo.point;
                }
            }
        }
    }

    private void GenerateCube(Vector3 position)
    {
        float terrainHeight = Terrain.activeTerrain.SampleHeight(position);
        Vector3 cubePosition = new Vector3(position.x, terrainHeight, position.z);
        GameObject go = Instantiate(cubePrefab, cubePosition, Quaternion.identity);
        wayPoints.Add(go.transform);
    }

    private void GenerateCubesBetween(Vector3 start, Vector3 end)
    {
        float distance = Vector3.Distance(start, end);
        int numCubes = Mathf.RoundToInt(distance / gap);

        Vector3 direction = (end - start).normalized;
        float stepSize = distance / numCubes;

        for (int i = 0; i < numCubes; i++)
        {
            Vector3 position = start + direction * (i * stepSize);
            GenerateCube(position);
        }
    }

    private void HandleCameraMovement()
    {
        // Get the horizontal and vertical input
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        // Convert input to world space relative to the camera's rotation
        Vector3 moveDirection = (horizontalInput * transform.right + verticalInput * transform.forward).normalized;

        // Apply movement
        transform.position += moveDirection * cameraMoveSpeed * Time.deltaTime;
    }

    private void HandleCameraRotation()
    {
        if (Input.GetMouseButton(1))
        {
            float rotationX = Input.GetAxis("Mouse X") * rotationSpeed;
            float rotationY = Input.GetAxis("Mouse Y") * rotationSpeed;

            transform.Rotate(Vector3.up, rotationX, Space.World);
            transform.Rotate(Vector3.right, -rotationY, Space.Self);
        }
    }
}

```

# Answer
> 0 votes
The code works as intended, but your scene is not set up well.

`MoveTowardsWaypoint()` does two things depending on the current state:

* If `isRotating` is `false` and `currentWaypointIndex` is `0`, rotate the camera. (Huh? You rotate the camera when `isRotating` is false?)
* Otherwise, move the camera until it is directly above the waypoint while looking directly at the waypoint, then target the next waypoint.

You have created far too many waypoints too close together, so the next waypoint is always (almost) directly underneath the camera, so the camera is always looking down.

You should delete most of your waypoints; this will improve performance and make the camera behave the way you want it to.

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


# Question
Title: How to fix Unity UI Panel Image being replaced with an "X"?
In my Unity Game, the Image on my UI Panel got replaced with an "X" instead of the Image it is supposed to be, I tried adding a different image to the panel and making a new panel, but it still would display the image as an "X", here is an image.

# Answer
> 0 votes
enter image description here \[

---
Tags: unity, image, user-interface
---


# Question
Title: Why does ApplyRadialDamageWithFaloff applies full damage?
For some reason it applies full damage even when actor to damage is further than 100.0f from the MainDamageSphere. What can be the problem? I'm checking for damage with the usage of overriden "TakeDamage" function

**AGrenadePauncherProjectile\_CPP::OnHit**

```
void AGrenadeLauncherProjectile_CPP::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp,
                                           FVector NormalImpulse, const FHitResult& Hit)
{
    if (OtherActor != nullptr && OtherActor != this)
    {
        TArray<AActor*> ActorsToIgnore;

        /*UGameplayStatics::ApplyRadialDamageWithFalloff(OtherActor, Damage, 1.0f, Hit.ImpactPoint, 100, 400,
            1.0f, UDamageType::StaticClass(), ActorsToIgnore);*/

        ExplosionClass->Initialize(SplashRadius, 100.0f, Damage, GetTransform(), OtherActor, ActorsToIgnore, this);

        SoundSystem->PlaySoundUnsafe(*ExplosionSoundCue, GetActorLocation());
    }

    Destroy();
}

```

**UExplosion::Initialize**

```
void UExplosion::Initialize(const float& SphereRadiusValue, const float& SphereRadiusValueInner, const float& SplashDamageValue,
                            const FTransform Transform, AActor* ToDamage, TArray<AActor*> ActorsToIgnore, AActor* ProjectileActor)
{
    if (ExplosionParticleSystem)
    {
        UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ExplosionParticleSystem, Transform, true, EPSCPoolMethod::None, true);

        // decided to hardcode parameters for debug
        UGameplayStatics::ApplyRadialDamageWithFalloff(ToDamage, SplashDamageValue, 1.0f, Transform.GetLocation(), 100, 400,
                                                       1.0f, UDamageType::StaticClass(), ActorsToIgnore, ProjectileActor);
    }
}

```

**UPDATE**

As far as I can see from disassembled code, ApplyRadialDamageWithFaloff calls procedure TakeDamage that belongs to my enemy actor(which needs to be damaged) and passes base damage instead of calculating new value relying on enemy's position inside of sphere... I attach a screenshot of disassembled code where you can see that xmm6 vector register holds a m128\_f32 variable that has base damage and it moves it to xmm1(which is a register related to TakeDamage function)

So what's the problem? Why would the main function refuse to calculate new value depending on enemy ator distance from impact point?

# Answer
Just had to switch from simple `TakeDamage` to `OnTakeRadialDamage` and `OnTakePointDamage`. The problem was solved.
> 1 votes

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


title: Making holes in 3D objects (Unity)

text:
# Question
Title: Making holes in 3D objects (Unity)
How can I make a hole in an object with Unity 3D? I've something like this object and I want to make a hole in it.

# Answer
You can't. Unity does not have CSG modeling options. You're going to either:

1. construct your cylinder out of smaller parts
2. model it in another program
3. programmatically rebuild the mesh geometry at runtime. WARNING: ADVANCED TOPIC
> 6 votes

# Answer
Not directly. But there are several ways to achieve this:

1. Use a **voxel engine**. Then you can have objects that have some kind of "molecules". You can deform them in runtime.
2. Use a **runtime mesh deformation** plugin.
3. You may **build your object in parts**, and then attach them together in Unity, so you can create a hole by simply removing the part in the middle.
> 5 votes

# Answer
As of 2020, you can do this with ProBuilder's (experimental) Boolean CSG Tool.

1. Install ProBuilder in Window \> Package Manager.
2. Enable Experimental Features in Edit \> Preferences \> ProBuilder.
3. Select two PRoBuilder objects.
4. Tools \> ProBuilder \> Experimental \> Boolean
5. Change Operation to Substraction (there's also Intersection and Union, BTW) and Apply.

A new object will be created. Works great with simple shapes so far:
> 5 votes

# Answer
Maybe try **Polybrush**? Check out this tutorial right at 33:00 to see proof of concept. https://www.youtube.com/watch?v=GioRYdZbGGk

The woman in the video cuts custom shapes out of the plane. You can do it out of other objects too. Before you try it, make sure to install everything she tells you to in the beginning and learn how to **insert an edge loop** (basically a carved line) on your object at 10:05.

Personally for me, ProBuilder refused to work. I was able to load Pro Builder, but it wasn't showing my assets to add to the subtraction method. I'm using Unity 2020.1.14f1
> 0 votes

# Answer
For anyone who is wondering how to do this in 2023, you can use the package ProBuilder and use the subtraction tool to make a hole.

Source: https://www.youtube.com/watch?v=aearddXihnw
> 0 votes

---
Tags: unity, 3d
---


# Question
Title: Audio middleware unity package missing assembly references
I want to use AudioKinetic WWise middleware to implement audio to a mobile game I'm working at the moment but I'm experiencing trouble assembly references thus I'm not able to code the audio scripts I need for the game.

**Setup**

* Unity 2021.3.22f1
* Visual Studio Community 2019
* Unity development with Unity VS workload
* Wwise 2022.1.5.8242
* Wwise Unity integration 2022.1.5.8242.2798

**Packages**

* Visual Studio Editor 2.0.18
* Firebase
* Doozy UI

**Attemps to sort out the issue**

* Install the work environment from scratch
* Pull repo from scratch
* Add missing reference to the main project assembly definition as described here: Unity - Manual: Assembly definition files
* Remove all `.csproj` `.sln` files from the root folder
* Check `Building settings` platform is **Android**
* Integrate Wwise to another project -\> works fine!
* Integrate a different audio middleware **FMOD Studio** -\> didn't work either
* Regenerate files from Preferences -\> External tools regenerate project files
* Check that Visual Studio is indeed my `External script editor`
* Keep a clean console from error non-related to this issues (console has been clean always)
* Remove `manifest.json`
* Reimport project

What bothers me is that the issue happens with this specific project and I've not been able to nail down what is preventing me from using any middleware API. My last resort is to implement audio logic with Unity native audio API because I'd need to code a lot and my result is potentially more error prone than relying on APIs that having been thouroughly tested. If you are an audio person, you know how painful not being able to work with an audio middleware can be.

Does anyone have previous experience with the same issue?

**Console output**

`Error CS0234 The type or namespace name 'Event' does not exist in the namespace 'AK.Wwise' (are you missing an assembly reference?) _ai-space-shooter C:\Unity Projects\NFTCo\ai-space-shooter\Assets\_ai-space-shooter\Audio\PlayAudioEvent.cs 7 Active`

# Answer
This is not an exact answer (I haven't used Wwise), but more of a troubleshooting process that's too long to fit in a comment.

It's hard to get support for specific third-party plugins here because you're not very likely to find another user that is using the same plugin and has encountered the same issue.

For commercial plugins, it's often best to start by contacting the company that makes the plugin for technical support. It looks like Wwise charges for technical support, so you'd need to weigh the cost against the amount of time that you might save. If you don't want to pay the support cost, your second option is the Wwise community Q&A.

If you can't get answers from the web, you can try further troubleshooting on your own. You mentioned that the plugin works in a new project but not in your existing project. One way to troubleshoot this kind of issue is to copy things from the problem project into the new project one at a time, checking after each to see if the new project still works.

For example, let's say your project has several plugins besides Wwise, a few open-source libraries, and your own code and assets. Copy the first plugin into the new project, then test Wwise. If it works, copy the next plugin, then test again. Repeat with each plugin and library that you're using, then with your scripts and assets. If you copy in something and then Wwise stops working, you've found your problem and can start a more focused search for answers. If you copy all of the files over and it still works, start copying project *settings*, again testing after each step.

It's possible that after copying everything over, Wwise will still work in the new project for no apparent reason, in which case you just delete the old project and continue development using the new one.
> 0 votes

# Answer
Turns out that WWise didn't work for us this time. We replaced it with FMOD and added its main assembly reference definition manually on the inspector. Even though this was the solution, I still find value in Kevin's answer as step by step strategy to overcome problems between third party technologies and Unity.
> 0 votes

---
Tags: unity, assembly, wwise
---


# Question
Title: Fanning cards in 2D leads to cards continuing to move forever
I'm using this video as guide for my Godot 3.5 project, but for some reason the code does fan the card but also the cards keep moving and spreading forever.

The code:

```
extends Node2D

var card_count = 0
var cards_in_hand = 0
var spread_curve = preload("res://UI/resources/spread_curve.tres") as Curve
var height_curve = preload("res://UI/resources/height_curve.tres") as Curve

export var card_spread_x : float = 2.0

func _process(_delta):
    fan_cards()

func fan_cards():
    cards_in_hand = get_children()

    card_count = cards_in_hand.size()
    var hand_ratio = 0.5
    if card_count > 1:
        for card in cards_in_hand:
            hand_ratio = float(card.get_index()) / float(card_count - 1)
            var position = card.global_transform
            position.origin.x += spread_curve.interpolate(hand_ratio) * card_spread_x
            position.origin += height_curve.interpolate(hand_ratio) * Vector2.UP
            card.global_transform = position

```

I realize that the function `_process` will keep calling the `fan_Cards` function endlessly. The video doesn't say anything else about the code regarding the positioning of the cards.

**How can I stop the cards from spreading indefinitely?**

# Answer
> 2 votes
## How do cards stop

You are using two curves to achieve that: `spread_curve` and `height_curve`.

Now, the `interpolate` method is evaluating the `Curve` given a value between the `min_value` and `max_value` of the `Curve` (which by default are `0.0` and `1.0`).

That should be your target, not your step.

The code in the video goes like this (link):

```
for card in hand.get_children():
    var hand_ratio = # ...
    var destination := hand.global_transform
    destination.origin.x += spread_curve.interpolate(hand_ratio)

```

Notice it is building a `destination` variable using the `global_transform` *of the hand*.

The idea is that the process does not really stop. The code would still be running... Except that when the cards are already at the `destination` they don't move.

---

## How do cards move

It isn't clear to me what approach is used to move the cards to that `destination`. At least one clue is that the video says that the cards handle their own rotation (link), which is in the `_process` of the card.

You don't seem to be placing logic in the cards, but we can start by the `_process` of the hand.

*By the way, you are playing loose with the type of `cards_in_hand`, you initialize it as an `ìnt` (`0`) but then set it an `Array` (`get_children()`).*

I also notice you made the case of a lone card an special case, which would be to avoid a division by zero. Here is the deal: you need to separate the cards by `1/n`, but you need to offset that by half a separation. That way you don't need special cases.

*I did something similar for How can I align my troops on a battle screen?.*

The following is my take on the code:

```
extends Node2D

const spread_curve := preload("res://UI/resources/spread_curve.tres") as Curve
const height_curve := preload("res://UI/resources/height_curve.tres") as Curve

export var card_spread_x:float = 2.0
export var card_spread_y:float = 1.0
export var card_speed:float = 100.0

func _process(delta:float) -> void:
    var cards_in_hand := get_children()
    var card_count := cards_in_hand.size()
    var separation := 1.0/card_count
    var offset := separation * 0.5
    for index in card_count:
        var card := cards_in_hand[index] as Node2D
        var hand_ratio := index * separation + offset
        var destination := _compute_destination(hand_ratio)
        _move_card(card, destination, delta)

func _compute_destination(hand_ratio:float) -> Transform2D:
    var destination := global_transform
    destination.origin.x += spread_curve.interpolate(hand_ratio) * card_spread_x
    destination.origin.y += height_curve.interpolate(hand_ratio) * card_spread_y
    return destination

func _move_card(card:Node2D, destination:Transform2D, delta:float) -> void:
    var src_pos := card.global_transform.origin
    var dst_pos := destination.origin
    var max_displacement := card_speed * delta
    card.global_transform.origin = src_pos.move_toward(dst_pos, max_displacement)

```
* I have added a `card_spread_y` because why not?
* I have also added a `card_speed` because we need to define the card motion somehow.
* I have separated `_compute_destination` and `_move_card` into their own methods to keep them simple, and also to make it easier if you want to move logic to the card nodes (they can have a `destination` property, and run the code we have in `_move_card` in their own `_process` instead).

---

## How do card rotate

You are going to want rotation aren't you?

We can add one more `Curve`.

```
const angle_curve := preload("res://UI/resources/angle_curve.tres") as Curve

```

And why not another spread:

```
export var card_spread_angle:float = 1.0

```

And we got to use it to compute the destination. I'll take the opportunity to change the way we do this:

```
func _compute_destination(hand_ratio:float) -> Transform2D:
    # Compute displacement:
    var displacement := Vector2(
        spread_curve.interpolate(hand_ratio) * card_spread_x,
        height_curve.interpolate(hand_ratio) * card_spread_y
    )

    # Compute rotation
    var rotation := angle_curve.interpolate(hand_ratio) * card_spread_angle

    # Decompose the hand transform in position and rotation
    var pos := global_transform.origin
    var rot := global_transform.get_rotation()

    # Update position and rotation:
    pos += displacement
    rot += rotation

    # Compose the result
    return Transform2D(rot, pos)

```

---

And we have to move the card...

We could compute how much time does the card take to move and use that to figure out the angular speed.

In particular, if you recall that speed is distance divided by time, then we can solve for time. Then the angular speed is the angle difference divided by that time... And how much we rotate - at most - this frame is that angular speed multiplied by `delta`.

I say "at most" because you need to be careful to not overshoot.

Doing the shortest way is an extra wrinkle (we will use `wrapf` to get the shortest angle difference).

We would want to have the equivalent of `move_toward` for angles, but we don't have it (`move_toward_angle` has not been added to Godot 4 at the time of writing, much less Godot 3). So we will do it the messy way.

```
func _move_card(card:Node2D, destination:Transform2D, delta:float) -> void:
    # Decompose current transform into position and rotation
    var src_pos := card.global_transform.origin
    var src_rot := card.global_transform.get_rotation()

    # Decompose destination transform into position and rotation
    var dst_pos := destination.origin
    var dst_rot := destination.get_rotation()

    # Compute total time
    var dif_pos := dst_pos - src_pos
    var time := dif_pos / card_speed

    # Compute angular speed
    var dif_rot := wrapf(dst_rot - src_rot, -PI, PI)
    var angle_speed := abs(dif_rot) / time

    # Compute max displacement and rotation this frame:
    var delta_pos := card_speed * delta
    var delta_rot := angle_speed * delta

    # Compute new position and rotation
    var new_pos := src_pos.move_toward(dst_pos, delta_pos)
    var new_rot := src_rot + min(abs(dif_rot), delta_rot) * sign(dif_rot)

    # Compose the new transform
    card.global_transform = Transform2D(new_rot, new_pos)

```

---

## Isn't there another way?

You need to know a bit of physics and a bit of math to come up with the above solution.

Plus the speed is constant, so it takes longer for cards that are away to reach the destination. We might want predictable time. Also, some more natural speed that decelerates when reaching the destination would be nice.

Plus this seems like a common enough case, and perhaps Godot has a better way to deal with it...

---

**Using a `Tween`**

And yes, Godot has an easier way, that would be `Tween`s. This would be the approach with the old API:

You create a `Tween`

```
var tween:Tween

func _ready():
    tween = Tween.new()
    add_child(tween)

```

You define the time:

```
var time_seconds = 2.0

```

And interpolate properties:

```
tween.interpolate_property(
    card,                    # On this object
    "global_transform",      # This property
    card.global_transform,   # From this value
    destination,             # To this value
    time_seconds,            # In this time
)

```

You can also specify easing, with the two extra optional parameters, for example:

```
tween.interpolate_property(
    card,
    "global_transform",
    card.global_transform,
    destination,
    time_seconds,
    Tween.TRANS_QUAD,
    Tween.EASE_OUT
)

```

See the cheatsheet by wandomPewlin for reference.

Don't forget to call `start`:

```
tween.start()

```

---

Most of the time a `Tween` is fine. However there is push to move to the new API (which would - in theory - make migration to Godot 4 easier):

```
var tween = get_tree().create_tween()

```

---

**I'll still do my own way anyway**

This is what I want:

* Reach the target in known time.
* Smoothly stop at the target.
* Support moving targets.
* In a frame rate independent way.
* Without additional state or variables.

Given that it is a moving target and I want to reach it in known time, the speed is not constant. In fact, from reaching it in known time alone the speed is not constant (it will reach the target in the same time regardless of the starting position). This works well with the idea that I want to reach the target smoothly.

However, this is a contradiction: have no state, and smoothly reach a moving target in known time. If we don't have state we would have to resource to some formula that converges into the target... But convergence, mathematically, takes infinite time.

Ah, but this is running in a computer! At some point the distance to the target will not be representable as a floating point number. And that is not infinite time... We can compute when that is, and work out from there.

Thus, we are going to pick some concept of "distance" at which we consider that it is close enough to the target that we say it reached it (actually we will snap to it, but the gap should be too small to tell). And we are going to pick a formula that converges to the destination, and is within that "distance" of it at a known time.

Since we want frame rate independence, we want to make sure that:

```
lerp(lerp(a, b, f(t1)), b, f(t2))

```

Which is the same as:

```
lerp(a, b, f(t1 + t2))

```

The kind of functions that satisfy these criteria are exponential function.

After much experimentation, this the code I came up with:

```
func get_approach_factor(time:float, delta:float) -> float:
    const EPSILON := 0.00001
    const SCALE := 1000.0
    if is_nan(time) or time == INF:
        return 0.0

    if time < EPSILON / SCALE:
        return 1.0

    var base := pow(EPSILON, 1.0 / (time * SCALE))
    return 1.0 - pow(base, delta * SCALE)

```

You give it the total `time`, and the time elapsed this frame (`delta`), and it tells you a number from `0.0` to `1.0` that tell you how much you should approach the target (i.e. your interpolation factor).

By the way, the reason why `EPSILON` is not close to the smaller possible value, and the reason why there is a `SCALE` constant, is because we run into problems with floating point numbers (almost by definition of what we are doing). So I'm using a larger `EPSILON` and scaling down `time` by `SCALE`, under the idea that the behavior should be the same at different time scales. The values I picked work for times from a few milliseconds to a couple minutes, which I believe is fine for games.

Now you can do this (assuming `time` is a property, instead of `card_speed`):

```
func _move_card(card:Node2D, destination:Transform2D, delta:float) -> void:
    # Get the approach factor
    var factor := get_approach_factor(time, delta)

    # Interpolate the transforms
    card.global_transform = card.global_transform.interpolate_with(destination, factor)

```

---
Tags: 2d, card-game, gdscript, godot-3
---


# Question
Title: Unity Spline Animate reset the position when change the speed
I am exploring the Unity Spline package, and within the package, there is a sample scene called 'splineAnimate' where the SplineAnimate script is used to move an object along a spline. The script has a 'speed' property in the inspector. However, when I set it to a different value, the object jumps along the spline instead of smoothly increasing or decreasing its speed. This issue occurs both when I increase and decrease the speed. I have captured the behavior here.

# Answer
> 0 votes
I have found a tutorial on YouTube that explains how to write a custom script to handle animating along a spline, it is a replacement for the SplineAnimate component. It handles positive and negative changes to the speed and automatically orients the GameObject to follow the spline.

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

public class MoveAlongeSpline: MonoBehaviour
{
    public SplineContainer spline;
    public float speed = 1f;
    float distancePercentage = 0f;

    float splineLength;

    void Start()
    {
        splineLength = spline.CalculateLength();
    }

    void Update()
    {
        distancePercentage += speed * Time.deltaTime / splineLength;

        Vector3 currentPosition = spline.EvaluatePosition(distancePercentage);
        transform.position = currentPosition;

        if (distancePercentage > 1f)
        {
            distancePercentage = 0f;
        }

        Vector3 nextPosition = spline.EvaluatePosition(distancePercentage + 0.05f);
        Vector3 direction = nextPosition - currentPosition;
        transform.rotation = Quaternion.LookRotation(direction, transform.up);
    }
}

```

# Answer
> 0 votes
I think the function here teleports the object, for example it needs to go from point a to point b and it does it by teleporting... you should optimize the function by script.. instead of teleporting, you should make it drag from point a to point b

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

public class MoveAlongSpline : MonoBehaviour
{
    public SplineContainer spline;
    public float moveSpeed = 1f;
    public float rotationSpeed = 5f;

    private float currentDistance = 0f;

    void Update()
    {
        // Calculate the target position on the spline
        Vector3 targetPosition = spline.EvaluatePosition(currentDistance);

        // Move the character towards the target position on the spline
        transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);

        // Calculate the target rotation on the spline
        Vector3 targetDirection = spline.EvaluateTangent(currentDistance);

        // Rotate the character towards the target rotation on the spline
        if (targetDirection != Vector3.zero)
        {
            Quaternion targetRotation = Quaternion.LookRotation(targetDirection, transform.up);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }

        // If the end of the spline is reached, loop back to the beginning
        if (currentDistance >= 1f)
        {
            currentDistance = 0f;
        }
        else
        {
            // Adjust the movement based on the length of the spline
            float splineLength = spline.CalculateLength();
            float movement = moveSpeed * Time.deltaTime / splineLength;
            currentDistance += movement;
        }
    }
}

```

---
Tags: unity, splines
---


# Question
Title: How to fix diamond artefacts in diamond square algorithm?
I'm trying to implement the Diamond Square Algorithm. In order to do this I'm following this tutorial: Diamond Square | Procedural Generation | Game Development Tutorial

I store the height values into a 2D array and then I create a .ppm image using these values. The algorithm seems to work, but when I open the .ppm image, the result is very bad. The image has a lot of diamond artefacts. The image below shows the result:

The source code that implements the algorithm is this:

```
#include "DSSequential/DiamondSquareSEQ.h"
#include "iostream"

DiamondSquareSEQ::DiamondSquareSEQ(int NSize, float minHeightValue,
    float maxHeightValue, float randomValue) : N(NSize), minHeightValue(minHeightValue),
maxHeightValue(maxHeightValue), randomMagnitude(randomValue)
{
    //Height map size computation
    HeightMapSize = static_cast<int>(std::pow(2, N) + 1);
    HeightMap.reserve(HeightMapSize);

    //Filling of the height map
    for(int i = 0; i < HeightMapSize; i++)
    {
        for (int j = 0; j < HeightMapSize; j++)
        {
            HeightMap.emplace_back(0.0f);
        }
    }
    chunkSize = HeightMapSize - 1;
    half = 0;
    //Four corner value computation
    HeightMap[0] = randGen.GenerateFloatInARange(minHeightValue, maxHeightValue);
    HeightMap[0 * HeightMapSize + chunkSize] = randGen.GenerateFloatInARange(minHeightValue, maxHeightValue);
    HeightMap[chunkSize * HeightMapSize + 0] = randGen.GenerateFloatInARange(minHeightValue, maxHeightValue);
    HeightMap[chunkSize * HeightMapSize + chunkSize] = randGen.GenerateFloatInARange(minHeightValue, maxHeightValue);
    RunDiamondSquare();
}

void DiamondSquareSEQ::PrintMap()
{
    for (int i = 0; i < HeightMapSize; i++)
    {
        for (int j = 0; j < HeightMapSize; j++)
        {
            if (HeightMap[i * HeightMapSize + j] != 0.0f)
            {
                std::cout << HeightMap[i * HeightMapSize + j] << " ";
                continue;
            }
            std::cout << "0" << " ";
        }
        std::cout << "\n";
    }
}

std::vector<float> DiamondSquareSEQ::GetHeightMapData()
{
    return HeightMap;
}

void DiamondSquareSEQ::RunDiamondSquare()
{
    while (chunkSize > 1)
    {
        half = chunkSize / 2;
        DiamondStep();
        SquareStep();
        chunkSize /= 2;
        randomMagnitude/= 2;
    }
}

void DiamondSquareSEQ::DiamondStep()
{
    for(int i = 0; i < HeightMapSize - 1; i += chunkSize)
    {
        for(int j = 0; j < HeightMapSize - 1; j += chunkSize)
        {
            float value = 0.0f;
            const float randValue = randGen.GenerateFloat() * randomMagnitude;

            //Average computation
            value += HeightMap[i * HeightMapSize + j];
            value += HeightMap[i * HeightMapSize + (j + chunkSize)];
            value += HeightMap[(i + chunkSize) * HeightMapSize + j];
            value += HeightMap[(i + chunkSize) * HeightMapSize + (j + chunkSize)];
            value /= 4;

            value += randValue;

            HeightMap[(i + half) * HeightMapSize + (j + half)] = value;
        }
    }
}

void DiamondSquareSEQ::SquareStep()
{
    for (int i = 0; i < HeightMapSize; i += half)
    {
        for (int j = (i +half) % chunkSize; j < HeightMapSize; j += chunkSize)
        {
            float value = 0.0f;
            int count = 0;
            const float randValue = randGen.GenerateFloat() * randomMagnitude;
            int index = (i - half) * HeightMapSize + j;
            if(index >= 0)
            {
                value += HeightMap[index];
                count++;
            }

            index = i * HeightMapSize + (j - half);
            if (index >= 0)
            {
                value += HeightMap[index];
                count++;
            }

            index = half * HeightMapSize + (j + half);
            if (index < static_cast<int>(HeightMap.size()))
            {
                value += HeightMap[index];
                count++;
            }

            index = (i + half) * HeightMapSize + j;
            if (index < static_cast<int>(HeightMap.size()))
            {
                value += HeightMap[index];
                count++;
            }

            value /= count;
            value += randValue;
            HeightMap[i * HeightMapSize + j] = value;
        }
    }
}

```

How can I fix this?

# Answer
I have solved the diamonds artefacts issue. I post the solution for the future. The error was in this piece of code:

```
index = half * HeightMapSize + (j + half);
if (index < static_cast<int>(HeightMap.size()))
{
   value += HeightMap[index];
   count++;
}

```

now the correct version is this:

```
index = i * HeightMapSize + (j + half);
if (index < static_cast<int>(HeightMap.size()))
{
  value += HeightMap[index];
  count++;
}

```

In the previous version the `index` var was: `index = half * HeightMapSize + (j + half);` now is `index = i * HeightMapSize + (j + half);`. This caused the diamonds artefacts. Now the result looks better!
> 1 votes

---
Tags: c++, procedural-generation, terrain-rendering, heightmap, noise
---


title: How important is a Flip-Y Axis setting?

text:
# Question
Title: How important is a Flip-Y Axis setting?
I noticed many open-world games have a setting called Flip Y-Axis. I need to know the significance of adding a Flip Y-Axis setting, that makes it so that if you move the mouse down the camera moves up instead of down, in a 1st-person 3D open-world game.

# Answer
Flight yoke interfaces flip the y axis, why someone would use an inverted y input device for a 1st person game is beyond me.

The flip side argument is why not add it; input is scaled by multiplication anyway and the sign change has no effect on performance.
> 1 votes

---
Tags: 3d
---


# Question
Title: smoothly transition from an animation layer to the other in unity
I have two layers of animation and I'm trying to SMOOTHLY transition between these two layers when I click a button.

```
public void OnButtonClicked(){
animator.SetLayerWeight(layerIndex, 1f);
}

```

For some reasons I don't know, the animation is not smooth at all. It looks really bad when I click the button and the new animation that I'm setting its layer weight starts

# Answer
You must interpolate the `animator.SetLayerWeight` across multiple steps.

```
float LayerWeightTarget = 0;
float CurrentLayerWeightTarget = 0;
public void OnButtonClicked()
{
   LayerWeightTarget = 1f;
}
public void Update()
{
   if(CurrentLayerWeight != LayerWeightTarget)
   {
      CurrentLayerWeight = (LayerWeightTarget - CurrentLayerWeight) * 0.125f;
      // Adjust value(.125f) to your preferred speed. not linear, but fast and convergent.
      Targetanimator.SetLayerWeight(layerIndex, CurrentLayerWeight);
   }
}

```
> 0 votes

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


# Question
Title: How do i put the enemy in an idle state without breaking everything
very simple logic but my brain is fried for now, so I don't get how to ad the option for an enemy to sometimes just go idle without breaking the entire animation logic... i tried adding a randomized timer so that when the enemy is already walking randomly and there are no players around the timer will switch idle and walk on and off...but for some reason this glitched the enemy and it started rotating on itself randomly and then stopped moving completely, so here's what works for now :

```
extends KinematicBody

onready var animation = $Archer/AnimationPlayer
onready var eyes = $Eyes
onready var ray = $RayCast
var directionChangeTimer = 0.0
var directionChangeInterval = 0.0
const minChangeInterval = 3.0
const maxChangeInterval = 12.0
const turn = 32
var vertical_velocity = Vector3()
var gravity = 30
var state = walk
var target

#states list
enum {
    idle,
    chase,
    walk,
    shoot,
}

#as soon as the enemy spawns it will walk around randomly
func _ready():
    state = walk
    directionChangeInterval = rand_range(minChangeInterval, maxChangeInterval)

#if in range, the enemy will start attacking,
#if outside of range the enemy will start chasing the player
func _on_Sight_body_entered(body):
    if body.is_in_group("Player"):
        state = shoot
    else:
        state = idle

func _on_Sight_body_exited(body):
    state = chase

func changeRandomDirection():
    var randomDirection = Vector3(rand_range(-1, 1), 0, rand_range(-1, 1)).normalized()
    var lookRotation = randomDirection.angle_to(Vector3.FORWARD)
    rotate_y(lookRotation)

func getSlideVelocity():
    var forwardVector = -transform.basis.z
    return forwardVector * 4

#state machine logic
func _process(delta):
    match state:
        idle:
            animation.play("idle")
        shoot:
            animation.play("shoot")
            if target:
                eyes.look_at(target.global_transform.origin, Vector3.UP)
                rotate_y(deg2rad(eyes.rotation.y * turn))
        walk:
            animation.play("walk")
            directionChangeTimer += delta
            if directionChangeTimer >= directionChangeInterval:
                directionChangeTimer = 0.0
                directionChangeInterval = rand_range(minChangeInterval, maxChangeInterval)
                changeRandomDirection()
            move_and_slide(getSlideVelocity())
        chase:
            animation.play("walk", 0, 1.5)
            if target:
                var targetDirection = (target.global_transform.origin - global_transform.origin).normalized()
                eyes.look_at(global_transform.origin + targetDirection, Vector3.UP)
                rotate_y(deg2rad(eyes.rotation.y * turn))
                move_and_slide(targetDirection * getSlideVelocity().length())

#gravity without sliding on slopes
func _physics_process(delta):
    if not is_on_floor():
        vertical_velocity += Vector3.DOWN * gravity * 2 * delta
    else:
        vertical_velocity = -get_floor_normal() * gravity / 2.5

    move_and_slide(vertical_velocity, Vector3.UP)

#if outside of chasing range the enemy will walk randomly,
#otherwise it will chase the player
func _on_ChaseRange_body_entered(body):
    state = chase
    target = body
func _on_ChaseRange_body_exited(body):
    state = walk

```

# Answer
> 1 votes
You already have some timer logic to change the walking direction on random intervals. You could have it use a random to decide if it will change direction or switch to idle.

Something like this:

```
directionChangeTimer += delta
if directionChangeTimer >= directionChangeInterval:
    directionChangeTimer = 0.0
    directionChangeInterval = rand_range(minChangeInterval, maxChangeInterval)
    if randf() > 0.25: # 75% chance of changing direction, 25% of going idle
        changeRandomDirection()
    else:
        state = idle

```

And the same logic on the idle state could be used to change to walk. When you do the change form idle to walk you, you probably want to have it pick a walking direction.

So:

```
match state:
    idle:
        animation.play("idle")
        directionChangeTimer += delta
        if directionChangeTimer >= directionChangeInterval:
            directionChangeTimer = 0.0
            directionChangeInterval = rand_range(minChangeInterval, maxChangeInterval)
            changeRandomDirection()
            state = walk
    shoot:
        animation.play("shoot")
        if target != null:
            eyes.look_at(target.global_transform.origin, Vector3.UP)
            rotate_y(deg2rad(eyes.rotation.y * turn))
    walk:
        animation.play("walk")
        directionChangeTimer += delta
        if directionChangeTimer >= directionChangeInterval:
            directionChangeTimer = 0.0
            directionChangeInterval = rand_range(minChangeInterval, maxChangeInterval)
           if randf() > 0.75:
               changeRandomDirection()
           else:
               state = idle

        move_and_slide(getSlideVelocity())

```

Here I'm using the same time variables. I expect no issue from doing that. Although you might want to move the timer logic to a method that you can call:

```
func change_time(delta:float) -> bool:
    directionChangeTimer += delta
    if directionChangeTimer >= directionChangeInterval:
        directionChangeTimer = 0.0
        directionChangeInterval = rand_range(minChangeInterval, maxChangeInterval)
        return true

    return false

```

Then the above code would be like this:

```
match state:
    idle:
        animation.play("idle")
        if change_time(delta):
            changeRandomDirection()
            state = walk
    shoot:
        animation.play("shoot")
        if target != null:
            eyes.look_at(target.global_transform.origin, Vector3.UP)
            rotate_y(deg2rad(eyes.rotation.y * turn))
    walk:
        animation.play("walk")
        if change_time(delta):
           if randf() > 0.75:
               changeRandomDirection()
           else:
               state = idle

        move_and_slide(getSlideVelocity())

```

This is not for performance, this for making the code easier to read, and also to remove any error that might be introduced in duplicating the code, plus if you need to change that logic in the future you only need to change it in one place.

---

You say that in your attempt that it ended up "rotating on itself randomly ". Which suggests to me it was calling `changeRandomDirection` every frame. That could have been that you didn't reset the time correctly, or you didn't change the state when you should have.

---

About your edits to the question:

Yes, if `target` is an object then `if target:` and `if target != null:` are the same thing. However, if `target` is a `Node` then the variable it will not become `null` when the `Node` is freed... For that you check like this: `if is_instance_valid(target):`.

*I don't get the logic behind the changes of state for `Sight` and `ChaseRange`, but you do you.*

---

By the way, in a prior question you asked about performance. Here is something you can try: Do more in `_physics_process` and less in `_process`. I believe that calling `move_and_slide` in `_process` might be having a negative impact on the performance... In particular if your machine can run at more FPS than the `physics_ticks_per_second` (which is 60 by default), and I believe it can, then it would be trying to run `_process` at that rate, so if you move that code to `_physics_process` would result in doing it *less often*.

---
Tags: 3d, gdscript, godot-3
---


title: How can I load symbols for Composure?

text:
# Question
Title: How can I load symbols for Composure?
I'm trying to load symbols so I can use breakpoints in Composure scripts and see how they control the PostProcessing of the SceneCapture2D component (because of this problem), but breakpoints hit. I've tried cleaning and rebuilding, setting the Composure plugin's LoadingPhase to PreDefault and even editing the Windows Registry to allow for loading more Debug symbols. But none of this works because I can't find pdb files for Composure.dll, ComposureEditor.dll or ComposureLayersEditor.dll. Are these unavailable? I'd expect them to be in UE\_5.1/Engine/Plugins/Compositing/Composure/Binaris/Win64, but there's nothing there.

# Answer
> 0 votes
You must build Unreal from source and specify pdb generation.

This is an option under the Unreal Build Tool C# files for the plugin. This assumes the plugin source is available.

If it is provided compiled only, there are no symbols available, and your quest is without merit.

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


# Question
Title: How to install game with dependencies on Linux?
I am creating a game using C and some libraries. I wish to not require my users to download anything but the game as most games are self contained. What is the usual process for compiling and installing dependencies such as glfw or SDL2 locally on Linux?

# Answer
## Standalone game

For Linux, SDL suggests to download the source code, compile it, and include the relevant files as part of your game.

The main information can be found on the official site SDL2 - Installation, but here's the most relevant information:

* For the most part, you only need to deliver a `.so` file for each library you are using (for Linux). So you'd need `libSDL2.so` to be part of the project you deliver.
* SDL offers some pre-compiled packages, but I find often that doesn't include Linux, they also suggest you can compile the project from scratch, so you can enable/disable functionality that you want included.
* You can compile the library statically (so it's included in your executable and you won't need a `.so` file), but the makers of SDL advice against that. The main reason is, if you publish a game with a version of SDL, it would be possible for a user to update SDL without touching your game, and everything should just work.

To compile SDL2 (based on the link above, with minor variations) you can use the following commands:

```
git clone https://github.com/libsdl-org/SDL.git -b SDL2
cd SDL
mkdir build
cd build
../configure --prefix=my_sdl_directory
make
make install

```

This will compile the project **and install it inside `build/my_sdl_directory/`**. Inside that directory, you should be able to locate the `.so` file and also other files useful for development (like the header files). You can the make a project, compile against that library, and ship the `.so` file with it.

You can then allow users to download your project, and run it straight away without them needing to install SDL2 themselves.

## Linux Distros

It's worth mentioning if you plan to publish your game on official Linux Distros, you can pretty much declare SDL2 as a dependency, and the package manager of each distro will be able to deal with it.

The instructions are different for each distro, and more likely out of scope for this answer.
> 5 votes

# Answer
# AppImage

A possible cross-distro solution is to use AppImage format, which allows to easily bundle all your resources and dependencies into a single directly executable file needing no installation.

While it's a good idea to consult the official guide for packaging native binaries, the overall process can be summarized as follows:

1. Install dependencies using package manager of distro you're using as a build machine (e.g. apt), including header files.
2. Build your game as you normally would, taking care to specify `/usr` as installation prefix. In with CMake it might be (inside build directory)

```
cmake PATH_TO_SOURCE_DIR -GNinja -DCMAKE_INSTALL_PREFIX=/usr

```

You'll also want to make use of standard path specifications, i.e. installing binaries in `bin/`, data in `share/`, etc.. Something else you'll probably want to do is to install desktop file together with an icon for your app to ensure that AppImage desktop integration works properly.

3. Compile and install your application into a temporary directory by setting DESTDIR variable. Continuing the example above:

```
DESTDIR=/tmp/myappdir ninja -j4 install

```
4. Call `linuxdeploy` tool to produce AppImage in your current directory:

```
linuxdeploy --appdir /tmp/myappdir --output appimage

```

This will automatically include in all shared libraries that your game depends on into resulting appimage.

# Steam

If you plan to use Steam for distribution of native build of your game on Linux you should look into documentation for steam runtime, which already includes many libraries commonly used by games (which, relevantly for your question, includes SDL2 but not GLFW). I'm not very familiar with it, but the linked repository should get you started. Another official guide specifically for game developers is also available.

As for libraries that do not happen to be provided by steam runtime, GLFW3 in your case, you'll have to ship those with your game, e.g. in `lib` subfolder and point `LD_LIBRARY_PATH` at it. The latter is often done with a simple script like the following, which you configure as game's main executable:

```
#!/bin/sh
export LD_LIBRARY_PATH="${PWD}/lib"
exec bin/mygame "$@"

```
> 2 votes

# Answer
There's a way, but it's complicated.

1. **Install the oldest Linux you want to support.**

You want to build on an old Linux. Install it in Docker.

We're going to ship libraries we depend on with your application. But there are some system libraries we can't ship, like `libc` (see list below). Since we're going to depend on whatever version is installed in the system, it's better to build on a system that uses an old version, so our users have the one at least as new.
2. **Compile SDL2 yourself**.

SDL2 has a mechanism where it dynamically determines the available libraries at runtime, and uses what it can.

But, interestingly, the maintainers of at least Ubuntu's SDL2 package disable this logic. To have it, you need to compile SDL2 yourself from scratch.

* **Install dependencies.**

    Before following the usual `./configure && make` procedure, you have to install the libraries SDL2 depends on. Read the manual. If you don't do it, you'll end up with non-functional build of SDL2.
3. **Copy the right dependencies.**

You need to ship the `.so`s of the correct dependencies alongside your executable.

Run `ldd my_app` on your application to get a list of the shared libraries you depend on. From those, copy following (to two SEPARATE directories next to your executable, will explain below):

* `libgcc*`, `libstdc++*`, `libc++*` (whichever are listed in `ldd` output)

    This list was figured out experimentally; copying some other libraries causes issues. Try for yourself to be sure.

    Those are probably only needed if you installed a newer compiler than what's present by default on your old build system.
    * Any other `.so`s you built yourself, including the one for SDL2.

Note that `ldd` might suffix the printed libraries with a version, e.g. `libstdc++.so.6`. If so, you use the exact filename as printed, not stripping the version suffix. The target file can be a symlink, make sure you copy its contents rather than the link itself (but using the name of the symlink as the resulting filename).
4. **Create a runner script.**

By default, Linux apps don't search for shared libraries next to the executable. And in any case, we need libgcc/libstdc++/libc++ in a separate directory, for reasons that will be explained later.

The solution is to place a small script next to the executable, that will set the `LD_LIBRARY_PATH` environment variable before running the executable:

```
#!/usr/bin/env bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
LD_LIBRARY_PATH='$ORIGIN/foo:$ORIGIN/bar' "$SCRIPT_DIR/my_app"

```

Here `$ORIGIN` will be replaced with the name of the directory where your executable is located. Substitute `foo` and `bar` for the names of subdirectories with your libraries.
5. **Improve the runner script to automatically determine the newer library version.**

I don't have this figured out yet. The above should be enough most of the time, but if the system you're running on ships newer libstdc++ (or perhaps libgcc/libc++) than what you shipped, you can run into issues: some libraries SDL2 will load dynamically from the system might want a newer libstdc++ (the one in the system), and will break if given the old one you shipped.

The solution is to dynamically decide (in the runner script) which libraries are newer, and use them.

I'm not sure what is the best way yet. I'd probably recommend shipping a tiny executable that uses something from C++ standard library (to depend on `lib[std]c++`), try running it first. If it runs successfully, you remove the directory with libgcc/libstdc++/libc++ from `LD_LIBRARY_PATH`. If it fails, you keep that directory in the path.

---

Alternatives:

* **Appimage**

It does almost exactly the same thing we do (you need to install an old Linux to build, etc), except they package everything into one nice executable.

But they don't do the dynamic library selection, and just tell you to use an old libstdc++. See this issue. There's also this plugin which seems to do the dynamic selection thing.
* **Flatpak**

Looks promising, because all libraries your application will see will come from the flatpak runtime, which should prevent the version conflicts explained above.
* **Snap**

Similar to Flatpak, but would avoid for ideological reasons (server is closed-source, Canonical pushes it aggressively, etc).
> 0 votes

---
Tags: sdl2, c, linux, glfw, installer
---