# Question
Title: Storing stats for multiple tiers of upgrades on an item
I have one script for all my weapons (I have 3 weapons in total) and each of these 3 weapons has 3 different tiers.

I'm currently using a method to set the values, like this:

```
public void SetTier1Value()
{
    if (weapon1IsActive == true)
    {
        damage = 6
        fireRate = 18
        etc...
    }
    if (weapon2IsActive == true)
    {
        damage = 5
        fireRate = 20
        etc...
    }
    // and like this for the rest of the weapons and tiers
}

```

All the weapons and all the tiers will have the same variables, the only difference between them are the values of their stats.

I know that the way that I'm doing stuff is over-complicating a lot.

I want to fix so in the future it's easier to add new weapons and the code in general isn't that bad to change.

What I want from this script is to be able to change the values of the weapon easily by code.

What ways can I do this?

# Answer
> 1 votes
It looks like you want to have just a single instance of your weapon class, that can morph on demand into any of your weapons at any upgrade tier. This would more conventionally be solved by having a separate instance for each weapon - say as separate prefabs - and spawning/recycling or activating/deactivating them as the player switches weapons. But if you prefer to keep this single morphable weapon, we can still make it more maintainable like so...

First I'd make a data structure that stores a snapshot of all the stats for a particular upgrade tier:

```
[System.Serializable]
public struct WeaponStats {
    public float damage;
    public float fireRate;
    // Add any other attributes of your weapon that can change with upgrades.
}

```

Then I'd create an asset that can store the set of upgrade tiers, and possibly other traits, associated with a specific weapon. This can hold an array of these stats.

```
[CreateAssetMenu(fileName = "NewWeaponProperties.asset", menuName = "Data/Weapon Properties")]
public class WeaponProperties : ScriptableObject {
    public WeaponStats[] upgradeTiers;

    // Add other stuff that distinguishes your weapon - visual, sounds, etc?
}

```

The attribute at the top lets you create instances of this class as asset files in your project folder, so you can make one for each weapon, with meaningful names.

Your weapon class can then keep track of which set of `WeaponProperties` it's currently using (ie. which weapon type is active), and what upgrade level it's currently at, from which we can deduce its current stats:

```
public class Weapon : MonoBehaviour {

    [SerializeField] WeaponProperties _properties;

    [SerializeField] int _currentUpgradeLevel;
    [SerializeField] WeaponStats _currentStats;

    public void SetUpgradeLevel(int level) {
        if (level < 0 || level >= _properties.upgradeTiers.Length) {
            Debug.LogWarning($"Tried to set weapon {name} to non-existent level {level}.");
            level = Mathf.Clamp(level, 0, _properties.upgradeTiers.Length - 1);
        }

        _currentUpgradeLevel = level;
        _currentStats = _properties.upgradeTiers[_currentUpgradeLevel];
    }

    public void SetWeaponType(WeaponProperties type, int level = -1) {
        _properties = type;
        SetUpgradeLevel(level >= 0 ? level : _currentUpgradeLevel);
    }

    void Start() {
        SetUpgradeLevel(_currentUpgradeLevel);
    }

    // ...and the rest of your weapon behaviour.
}

```

Now you can define as many upgrade levels as you want for each weapon type, and you can set them up in the inspector data, instead of hard-coding them into the weapon class individually, and recompiling anytime you want to change them. This makes it much easier to tune your data - even while the game is running - to dial in the values that feel best.

This also makes it easy to experiment with different weapon types: just create a new asset file for the new idea. Didn't work out? Just stop referencing that file, and it won't be included in your build, but you can keep it around in your project folder in case you want to come back to it later. In the meantime, this "dormant" data doesn't clutter your code like a commented-out chunk of your upgrade function.

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


# Question
Title: How to create 2D platformer maps without a game engine's editor?
I've been developing a 2D shooting platform videogame for the Sony PSP console using only the ONELua interpreter for the Lua programing language (since there is not any game engine for it). Despite its many useful modules, it doesn't come with tools to create platformers, because ONELua is not a game engine itself.

So I need to figure out how to implement my camera, maps and some other stuff myself. Since Lua is a scripting language, I've been applying best practices and an OOP approach in order to make it scalable and maintainable.

Despite researching *a lot*, all I'm finding is about Unity, GameMaker, Godot or any other already invented wheel:

1. How would you make a 2D platformer map so that it interacts with environment (other objects, enemies, etc.)?
2. Is the map represented by a matrix (kind of RPG map)?
3. The objects should be hardcoded, I mean, do they have a fixed position?

This last question is because I've read the code form another very similar project but the code has been hardcoded so I consider it as not very maintainable and scalable (since it has more than 1k lines of code in just one script), however at the end it could be hardcoded using some creational map tools, couldn't it? If so, I guess all above questions would be answered.

Based on the code that I've read, I surmise that I would put every object at a fixed position using a level editing tool, applying physics to move those physical objects and so on. Then, if the player "moves" (it would stay in the center of the screen simulating moving, just with a walking animation) then move the whole world (objects and environment) would approach the player, but I think it wouldn't be the best approach for performance.

# Answer
> 1 votes
*I have no idea about developing for Sony PSP. This answer presumes limited target hardware, and the goal of a simple 2D engine.*

---

## Budgets

*No, not money.*

Your game will have a time budget and a memory bugdet.

The memory budget is how much it can have loaded at the same time. If you load a large tilemap, that consumes your memory budget. Similarly, if you load entities, that consumes your memory budget too. Thus, smaller tilemaps leave budget for more entities, and viceversa.

The time budget is how much time you can expend updating things between frames. If the code takes too much time, then your frame rate drops. If you are applying a "the world move, the player is stationary" strategy, that takes some of your time budget. And if you update too many entities, that also takes of your time budget.

Limited hardware means small budgets. Every feature will have some cost in these budgets. Implement within what you they can afford.

---

## Tiles vs Entities

*These are guidelines to keep in mind when consider which to use.*

Giving that tiles exist in tilemaps, moving tiles is very limited (it is constrained to the grid of the tilemap). Thus, if something move, prefer using an entity. If it doesn't prefer a tile. *Assuming that tiles don't move is OK.*

Having multiple similar tiles is cheap. However, multiple entities are expensive. Thus, if something appears a lot, prefer using tiles. If it appears sparsely, you might use entities.

Having custom logic in entities is cheap. You might be able to attach logic to tiles, however they would always be loaded being expensive in memory (or if you decide to load and unload them on demand, it becomes expensive in time). This implies that having a lot of disparate logic attached to tiles is a bad idea. Thus, prefer using entities for custom logic. *Even if they don't need to move*. Only attach logic to tiles if it is very, very, common logic. *Assuming that tiles don't have logic is OK.*

---

## Tiles and The World

Because of the limited hardware, we want to only be concerned to what is present on screen, which is what we need to render. To do that we create the world with tilemaps. The simplest implementation of the tilemap is an array of tiles (this is not great for large tilemaps, but I'm assuming that the memory budget is low for large tilemaps anyway).

It is also important to know how much the player can see in tiles. Bigger tiles, means less tiles on screen. *Which is cheaper.*

These are some options that would work on low hardware:

1. We can keep a tilemap of what is on screen. The camera is stationary. And when the player reaches the edge of the screen we load and transition to a different tilemap.
2. We can keep a tilemap of what is on screen. The camera can move. When it does, we update the tilemap, moving the tiles, and loading newly revealed parts of the map from storage.
3. The tilemap does not have to be exactly what is on screen. We can have areas which are larger than what fits on screen, and only render the parts visible according to the position of the camera. When the player moves to another area, we load it as a whole.

Yes, they all work. However, they expend your budgets in different ways. For example, the first option will use less of both budgets if you need them for other things. However, if you don't, you might be able to afford something else.

---

What goes in a tile? An index. It goes to a table that has what to render (probably an offset in a texture atlas, perhaps even some means of animation), if it is passable (for physics, *or a physics layer if you can afford that feature*), and perhaps other things too. In particular, if it is the start position of an entity, so when they enter view you add their entities.

*If you want to purchase the feature of logic attached to entities, you have an entry in that table for the custom logic, you can have triggers to run it when they enter view or when an entity collides. Example: a tile that causes damage on contact.*

*Special offer*: You can have multiple tilemap render layers. You could also use them for parallax. Purchase now and receive completely free picture render layers for background and foreground.

---

I do not even know if there is a file system, nor if it is performant. If there isn't a performant file system, then hard-coding it is an option. It makes little difference if you design the map on a map editor or on paper. You need to encode it, either in a format that you code can parse, or as code directly. Just think as code as another file format.

However, you need to consider how you will query it. Will you be loading areas? It would make sense to split the world accordingly. Also, the code would have to either give you tilemps or individual tiles.

---

## Entities and Physics

Then the game can iterate over the alive entities, to perform their physics and whatever logic is necessary.

I have some special offer feature for you, purchase now:

* Keep track of which entities you updated last frame, and don't update those this frame. Or you can keep track of how far along the list of entities you managed to update, and start from there next frame. You may even assign entities to a "List A" or "List B" on creation, and update them on alternating frames. *Costs memory, saves time.*
* Do not update entities that are not outside of view. When an entities is out of view, remove it. *Costs time, saves memory.*
* Implement an Object Pool. keep a list of allocated-but-not-alive objects to be recycled. *Costs memory, saves time.*
* Limit the total maximum of alive entities. If there are already too many, you don't add more. *Costs time, saves memory.*

---

What goes in an entity? A position, a sprite (you probably want to be able to animate it, and you may want to have either multiple sprite or sprites of different sizes), an update function, and a collision function. These functions should be able to call engine methods (e.g. play a sound).

Since we are going for simple engine, you would use invisible entities (i.e. entities without sprite) to perform any additional game logic. This was a staple of early game engines.

You will also need z-ordering/y-ordering. You could either keep a sorted list of the entities by their vertical position. *Other clients that saw this product also saw*: give them a z position and sort by that. *But wait, there is more*: you could assign them render layer, you render the layers in order, and each layer keeps a sorted list.

---

The simplest to implement is discrete physics, with euler integration, and for response simply aligns the entity to the gird of the tilemap.

We don't need to think about tile-tile collisions here (any code moving tiles should handle that). We only need to worry about entity-tile and entity-entity. Simplest collision for entity-tile is to get the range of tiles that the entity touches, and query if they are passable or not. For entity-entity AABB-AABB collision would work. *Assuming that we only keep alive entities that are on screen, we don't have to worry about spase partitioning.*

If an entity collides, you call its collision function (assuming it has). *When an tile collides, you may trigger some logic attached to the tile, if you took that feature.*

*Offer for connoisseurs*: You could have the concept of physics layers and mask. Not passable tiles could be on a layer reserved for them, *or could specify a layer on the tiles*. For each entity you specify on what layer it is, and with which layers it can collide. *Should render layers also be physics layers? That makes the engine simpler, but also constraints what you can do. Since we are going for simple engine, yeah, sure. Although any layers could be considered a luxury item.*

However, you may want more complex physics in some cases. Depending on what you want on the game. For example: Do you want slopes? Do you want bouncing? Do you want moving platforms? And so on.

*Make sure to leave budget for the features the game needs. And if you have extra budget, you can afford some fancy features.*

---
Tags: 2d, maps, platformer, level-design, levels
---


# Question
Title: Deserialization of JSON from Firebase to load data
i was wondering if you could help me with an issue i have with firebase and databases! I have a class that saves variables into an array. i have managed to send that json file to firebase and i can debug it to see its correct when i load the games database but i cannot set those variables to the game. the class is like this :

```
   [System.Serializable]
   public class LevelItem
   {
       public bool unlocked;
       public int starAchieved;
   }
   [System.Serializable]
   public class LevelData
   {
       [Header("Primary Set")]
       public int lastUnlockedLevel = 0;
       public LevelItem[] levelItemArray;
   }

```

to save it to firebase i do this

```
string levels = JsonUtility.ToJson(LevelSystemManager.Instance.LevelData);
reference.Child(data).Child("Sets").Child("Art").SetValueAsync(levels);

```

and i am trying to retrieve it and set those values (lastUnlocked , star achieved , unlocked and the levelItemArray) back to the game. my other variables like difficulty work fine with this :

```
LevelSystemManager.Instance.Bundles.difficulty = int.Parse(snapshot.Child("Settings").Child("Difficulty").GetRawJsonValue());

```

but i cannot load the whole levelData class back to the game! any tips or help? when i was saving the json localy i was doing it like this to load the values

```
string levelDataString = System.IO.File.ReadAllText(Application.persistentDataPath + "/LevelData.json");
LevelData levelData = JsonUtility.FromJson<LevelData>(levelDataString);
if (levelData != null)
     {
LevelSystemManager.Instance.LevelData.levelItemArray = levelData.levelItemArray;
LevelSystemManager.Instance.LevelData.lastUnlockedLevel = levelData.lastUnlockedLevel;
}

```

but this approach wont work with firebase

i did come close i think by doing this , in which the debug does show the json in the console.

```
var json = snapshot.Child("Sets").Child("Art").GetRawJsonValue();
LevelData levelData = JsonUtility.FromJson<LevelData>(json);
Debug.Log(json);

LevelSystemManager.Instance.LevelData.levelItemArray = levelData.levelItemArray;
LevelSystemManager.Instance.LevelData.lastUnlockedLevel = levelData.lastUnlockedLevel;

```

but this gives an error ArgumentException: JSON must represent an object type. but when i do save it localy everything works out

The JSON that gets saved localy is this one

```
{"lastUnlockedLevel":1,"levelItemArray":[{"unlocked":true,"starAchieved":1},{"unlocked":true,"starAchieved":0},{"unlocked":false,"starAchieved":0},{"unlocked":false,"starAchieved":0},{"unlocked":false,"starAchieved":0},{"unlocked":false,"starAchieved":0},{"unlocked":false,"starAchieved":0},{"unlocked":false,"starAchieved":0},{"unlocked":false,"starAchieved":0},{"unlocked":false,"starAchieved":0}]}

```

and this is the one that gets saved on firebase

```
{
  "Purchases" : {
    "allsets" : 0,
    "animalSet" : 0,
    "architecture" : 0,
    "nature" : 0,
    "noAds" : 0,
    "technology" : 0,
    "vehicles" : 0
  },
  "Sets" : {
    "Art" : "{\"lastUnlockedLevel\":1,\"levelItemArray\":[{\"unlocked\":true,\"starAchieved\":3},{\"unlocked\":true,\"starAchieved\":0}]}"
  },
  "Settings" : {
    "Difficulty" : 1
  }
}

```

As you can see i do have more classes saved there which like my difficulty example work just fine . my whole issue is that i cannot load back the entire LevelData Class and set it to the games variables.Thank you!

EDIT! so far i did manage to make it load by giving the raw json to the string but this is not good for actually loading things

```
string json = snapshot.Child("Sets").Child("Art").GetRawJsonValue(); // levelDataString
LevelData levelData = JsonUtility.FromJson<LevelData>("{\"lastUnlockedLevel\":1,\"levelItemArray\":[{\"unlocked\":true,\"starAchieved\":1},{\"unlocked\":false,\"starAchieved\":1}]}");
Debug.Log(json);

LevelSystemManager.Instance.LevelData.levelItemArray = levelData.levelItemArray;
LevelSystemManager.Instance.LevelData.lastUnlockedLevel = levelData.lastUnlockedLevel;

```

I still need to be able to parse that JSON as it is and i dont know why im still getting errors when i try it like this

```
string json = snapshot.Child("Sets").Child("Art").GetRawJsonValue();
LevelData levelData = JsonUtility.FromJson<LevelData>(json);

```

# Answer
> -1 votes
Not 100% sure, but shouldn't the line

```
LevelData levelData = JsonUtility.FromJson<LevelData>(levelDataString);

```

really be

```
LevelData levelData = JsonUtility.FromJsonOverwrite<LevelData>(levelDataString);

```

i.e. `.FromJsonOverwrite` not `.FromJson`

---
Tags: unity, json
---


# Question
Title: How to get current Microphone Frequency in Godot
Let us say I want to create a singing game similar to SingStar, and for this purpose I want to get the audio pitch the microphone is getting, in real time, or as close as possible.

I know I can get audio input in Godot. Even record the microphone to a file, there is an official demo project that does that (mic\_record). I also know there are libraries that can analyze the audio.

How can I get the microphone pitch in real time?

---

*Yes, I'm answering my own question. This question is inspired on a similar one on StackOverflow, which asked for a library to do this, which lead to the question getting closed, and the asker deleted it instead of editing the question… Before I noticed. As it turns out, you don't need libraries to do this. This is a means to answer the question I believe that person should have asked.*

# Answer
---

## Getting Microphone Input

To have microphone audio input in Godot:

* Go to Project -\> Project Settings -\> General -\> Application -\> Audio and make sure "Enable Audio Input" is On.
* Go to the Audio panel (on the bottom of the Godot editor by default), and add a new Audio bus with a Record effect (`AudioEffectRecord`), enabled.
* Add an `AudioStreamPlayer` to the scene tree. Set the Stream attribute to a New `AudioStreamMicrophone`, and the Bus attribute to the Audio bus you created. We also want it to be playing, so put set the Autoplay attribute On.

If everything is working, the game should be playing whatever is listening from microphone. Once you have made sure it is working, mute the Audio bus.

*The official demo project mic\_record shows how to record and play the audio, and how to save it to a file. We don't need any of that.*

No code required.

*By the way, Godot includes other useful effects including equalizers and a pitch shifter.*

---

See also:

---

## What is Pitch?

What we refer as pitch is the audio frequency. However, is there a particular pitch for an audio signal? We need to consider that real audio is a mix of multiple frequencies.

Even an instrument playing a single node will have a fundamental frequency, and overtones which are weaker than the fundamental. (See Harmonic). Thus, we would want the stronger frequency.

---

Well, turns out we cannot get a specific frequency anyway. The best we can do is get frequency range. So pick reasonable ranges to query. Perhaps based on musical notes (you would want the nominal frequency of the note at the center of the range).

The problem is that the more certain we are of the instant in time we want to measure, the less certain we are about the frequency of the audio. Yes, that is the uncertainty principle. It emerges from the Fourier transform we need to do to get the frequencies.

*And I'm not going to explain that, instead I'll recommend the video But what is the Fourier Transform? A visual introduction. by 3Blue1Brown, and its follow-up video he more general uncertainty principle, beyond quantum. Also remember we have audio samples to work with, not a function.*

---

## Spectral Analysis

As it turns out, we don't need any library to do a Fourier Transform in Godot, because it already has the means to do an spectral analysis.

To do that add a SpectrumAnalyzer effect (`AudioEffectSpectrumAnalyzer`) to the Audio bus you want (the same with the Record effect, in this case). It will do a Fast Fourier transform for us.

You can retrieve an `AudioEffectSpectrumAnalyzerInstance` from code using `AudioServer.get_bus_effect_instance`, and call `get_magnitude_for_frequency_range` on it.

The method takes a frequency range and returns a `Vector2` (as far as I can tell - this is not documented at the time of writing - these are the left and right stereo components※, for a fair combination use the `length` of the vector) in linear energy scale (you can use `linear2db` to get decibels).

To get the stronger frequency range, we call the method on a loop changing the frequency ranges, and pick the maximum.

*The method is also useful for audio visualization.*

---

See also:

---

*※: Yes, a Fourier Transform has a real an an imaginary part. However, after having a look at the source code, I don't think that is what is going on. The source for method (here) uses a `fft_history` array. Which we see (here) converted to audio frames. Which have `l` and `r` (as defined here). Unless that means "limaginary" and "real", I think they are "left" and "right".*
> 8 votes

---
Tags: godot, audio
---


title: Any fast alternative to sine in GLSL?

text:
# Question
Title: Any fast alternative to sine in GLSL?
Should I just use the built-in sin() function or my custom sine function?
I'm concerned about performance here. I don't care about accuracy much here because I use it to just get wave effects in my shader.

The shader is for mobile platforms (OpenGL ES)

**Here's my code**

```
float customSin(float x){
   x = fract( 0.75 + x*0.159155 )*2.0 - 1.0;
   return x*x * (6.0 - 4.0*x) - 1.0;
}

```

**Here's my algorithm**

x is the input, y is the output

r = 0.75 + x/(π\*2)
a = | r- floor(r) - 0.5 |\*2
y = ( 3(a^2) - 2(a^3) )\*2 - 1

I checked the graph, and it's pretty close to the actual sine.

Which one should I go with?

# Answer
> 6 votes
ATI made an announcement that the sine / cosine instructions in their newest GPUs now requires only a single clock cycle... in 2004! Modern GPUs in fact have special function units specifically for calculating trigonometric functions.

So any hand-written sine or cosine function is unlikely to perform any better than the intrinsic sin() / cos() function, no matter how many accuracy concessions you make. They are just insanely optimized in hardware.

---
Tags: shaders, glsl, performance, opengl-es, trigonometry
---


# Question
Title: Is it a good idea to use a hash table in an ECS?
I've had an idea for optimising my ECS engine. Instead of storing components in an array, store components in a hash table as `<id> => <component>`.

This means that checking whether an entity has a particular component can now be done in O(1) rather than O(n). Just wondering whether there are any drawbacks to this approach?

Since I'm using a managed memory language, cache locality doesn't matter as much.

# Answer
If you want to know what is faster, measure. That is the engineering approach. Thus, write your code in a way that you can swap the implementation (e.g. behind an interface) and benchmark.

---

With a hash table, the selection of hash function is important. Not only the hash function may have more or less collision, but also it may take more or less time to compute.

We, of course, want a hash function that is fast and has very little collisions. Well, if the input is an integer, using an identity function (a function that just returns the input) as hash function is the fastest, and also does not have collisions.

That is one way to use an array. Just look up the entity id. That is O(1). Very easy to write, very fast code. The issue is that you need to allocate an array with as many entries as entities you may have.

That reminds me. How will the hash table grow? If it uses an array internally, it would have to allocate a new array and move the entries form the old one to the new one. Which is slow, and that is an issue.

We could solve these issues by implementing the hash table over a tree instead of an array. Usually a large branching factor is good for this use. Let us say we are using 32 bits integers for entity ids… We can have a branching factor of 256, meaning that selecting a branch requires 8 bits of the key. Then getting a leaf always takes 4 levels (8 * 4 = 32) of the tree (and yes, that is still O(1), because it does not depend on how many entries are there in the tree nor which one we want, it always 4 levels, that is constant). *Or 8 levels and branching factor of 16 (4 bits).*

*By the way, O(n) can be faster than O(1) for small n. It might make sense to use one strategy for small n, and another large n. So… Benchmark.*

---

Thus yes, use a hash table (which is an array when the hash function is the identity function, and the growing strategy is none). The details of the hash table are what matters. And to reiterate the first paragraph: benchmark.

In fact, other structures are possible. For example self-balancing binary tree (e.g. AVL or Red–black tree) would give you O(log n) performance.

---

*If cache locality were important, what you put in the hash table would not be the component, but the index of the component in an array where they are stored contiguously (instead of wherever the hash function says). So that iterating over the array of components is fast, despite of the hash table. Since cache locality is not important in your case, you can simply put the components in the hash table.*
> 6 votes

# Answer
I'd agree with Panda Pajama's advice:

> How about you **start with what you think makes the most sense**, and build from there? Optimizing too early for a very specific use case may end up backfiring -- at best, it will just make your code more difficult to read.

> It seems like this is a learning project, so even moreso, I think you should **optimize for readability**, since this is one of thousands of parts that will go into your game engine. As somebody who has written many game engines, I can assure you the first one you write will not be the last -- the things that you learn with this project will give you insights to make these types of decisions earlier in your project.

The exact way that components are stored should generally be hidden behind an API like `GetComponent` / `AddComponent` / `HasComponent` / `RemoveComponent`, so if you decide to change your storage approach later (or profile two options to test how they compare), then you should be able to change just the implementation of those methods, without breaking or modifying any code that relies on them. So you're not making an irrevocable commitment right now - you can (and, based on my experience in gamedev, probably will) change your mind later, no matter what option you pick now.

If that kind of refactoring isn't straightforward in your implementation, then improving your encapsulation might be a better priority to focus on first. Designing for maintainability often pays off in the long term.

That said, from having taught algorithms courses, I'd say you should be wary of the seduction of big-O notation. \\$O(1)\\$ can still have a substantial constant cost. For hash tables in particular, they tend to take up more space to store the keys and empty slots to keep the load factor under control, they require additional steps to hash the key, wrap it to the size of the table, and compare it to the stored key, and they randomize branch selection and memory access, which can reduce the benefit you get from processor features like caching and speculative execution (and even in a managed language, you can write code that benefits from these).

An ECS will often have just a dozen or fewer components on a single object, or of a single type. At that scale, you might well find a \\$O(n)\\$ linear probe through an array is just as fast or faster than a hash table, because your \\$n\\$ is so small.

When in doubt, *profile it*. Make two versions of `AddComponent`/`GetComponent` that you can switch between with a compiler flag, and run the same test scene or the same sequence of millions of component interactions to time whether one is significantly better for your case and usage patterns. That will be measurable proof you can trust far more than the opining of Internet strangers like us.
> 4 votes

---
Tags: software-engineering, entity-component-system
---


# Question
Title: How can I change an animated sprite's images per second from script?
Consider an `AnimatedSprite` with an animation of 9 `.png` files and a setting of 5 images per second. How can I change the number of images per second from script?

# Answer
The recommended way to vary the speed of the animation is setting the `speed_scale` attribute of the `AnimatedSprite` node. Thus, get a reference to the node and set its `speed_scale` (it is a factor). For example:

```
$AnimatedSprite.speed_scale = 1.5

```

---

It is also possible to access the `frames` attribute, which gives you a `SpriteFrames` object. Then you can get the animation speed in frames per second by calling `get_animation_speed`. For example:

```
var fps = $AnimatedSprite.frames.get_animation_speed("Animation")

```

Now, let us assume we want to set a particular number of frames per second, we could use it to compute the desired factor:

```
var sprite = $AnimatedSprite
var desired_fps = 7
var actual_fps = sprite.frames.get_animation_speed("Animation")
var factor = desired_fps / actual_fps
sprite.speed_scale = factor

```

Alternatively, we could set the animation speed in frames per second by calling `set_animation_speed`, the parameters are the animation name and the speed you want. For example:

```
var desired_fps = 7
$AnimatedSprite.frames.set_animation_speed("Animation", desired_fps)

```

Note, however, that if you modify the animation this way, it will change the speed of the animation anywhere it is used. Which is why, it is recommended to use `speed_scale` to modify the speed for a single `AnimatedSprite`.
> 3 votes

---
Tags: animation, godot
---


# Question
Title: C# Events in Unity to separate GameObject features into Components
**Broadly speaking, this is a question about how to separate my game object's code into distinct feature components that can be added and removed as needed.**

More specifically, I am trying to achieve this using C# events in Unity. But I am open to other solutions.

**Scenario:** We have enemies that have health. When their health reaches zero, they die. Some enemies (think asteroids) may spawn a number of child enemies (think smaller astroid pieces) when they die. Others however, just die.

I want to have two scripts:

* **EnemyHealth:** Tracks the enemy's health and kills the enemy when its health reaches zero.
* **EnemyChildrenSpawner:** Spawns child enemies after the enemy's death

This way, *all* enemies will have the EnemyHealth script, and *some* enemies will have the EnemyChildrenSpawner script in addition.

---

My idea is to have the EnemyHealth script raise an event when the enemy dies, and have EnemyChildrenSpawner subscribe to said event to spawn the children.

What would be the best way of achieving this?

Here's my attempt. It works. Just not sure if this is good practice, especially using the GetComponent in the second script?

EnemyHealth.cs

```
public class EnemyHealth : MonoBehaviour
{
    // The event to invoke when this enemy died
    public event EventHandler OnDied;

    // Gets called when this enemy's health reached zero
    private void Die()
    {
        // Invoke the died event
        OnDied?.Invoke(this, EventArgs.Empty);

        // Destroy this enemy
    }
}

```

EnemyChildrenSpawner.cs

public class EnemyChildrenSpawner : MonoBehaviour
{
    private void OnEnable()
    {
        GetComponent<EnemyHealth>().OnDied += SpawnChildren;
    }

    private void OnDisable()
    {
        GetComponent<EnemyHealth>().OnDied -= SpawnChildren;
    }

    private void SpawnChildren(object sender, EventArgs e)
    {
        // Spawn children
    }
}

```
</code></pre>

# Answer
> 1 votes
Myself, I would replace this with:

```
public UnityEvent OnDie;

```

Now the event will appear in the Inspector, so a designer can use the graphical interface to link up any number of different script methods to react to the health component's death.

Those components don't need to know anything about the health component, and don't need extra code added to them to attach and detach event listeners.

This makes it easy to mix and match different death behaviours without having to hard-code every possible pairing.

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


title: How to decide which Area2D is behind?

text:
# Question
Title: How to decide which Area2D is behind?
How to make an Area2D drawn after another one only in certain situations?

---

## The boat

```
+ Area2D
|_ AnimatedSprite

```

## The stone

```
+ Area2D
|_ AnimatedSprite

```

---

## Correct

## Not correct

Do I have to use 3D?

# Answer
> 1 votes
Ok, first, you are going to need to put your nodes inside a `YSort` node. And make sure it is enabled. The `YSort` node will sort the sprites by their vertical position (y-axis).

Second set the `offset` attribute of each `Sprite`. This attributes allows you to move the texture. What you want is to set it such that the origin point of the `Sprite` is along what should be "ground level" visually on the texture if that makes sense…

Here, visually:

The texture has been moved such that the origin of the `Sprite` goes where the "ground level" of the image would be, visually. *If that is a problem, you can compensate the offset with the position of the `Sprite` inside the `Area2D`. Also make sure the `CollisionShape` makes sense.*

With that setup, it should work automatically. *This could also be done manually by setting `Z Index`.*

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


# Question
Title: How can I access an OpenGl buffer from within a GLSL 330 shader?
I am currently attempting to create a simulation using OpenGl's GPU acceleration for both the simulation computations and rendering. The rendering portion of my simulation is complete and working, but I still need to create the simulation portion. To do this, I want to use transform feedback, for I am rendering as GL\_POINTS and each point needs to be moved in relation to every other point each frame. This matches nicely to a vertex shader and transform feedback abstraction. The issue comes from the fact that my input data (the initial positions of each point) is in a buffer, and each vertex shader invocation in the transform feedback render only has access to that specific entry in my buffer, while I need access to *all* entries in my buffer. How can I solve this issue?

I can't use compute shaders because I am targeting OpenGl 3.3. I have also considered taking the buffer data, copying it to the CPU, and then back to the GPU in the form of a texture, however this is likely to be incredibly inefficient, especially as I begin scaling up how many points I am working with. This is further exasperated by the fact that textures don't allow me to get pixels at integer coordinates, and passing whole numbers as floating point coordinates is likely to cause floating point error to be sufficiently significant to be a problem, especially with texture filtering (I have thousands of points for now, but that will increase to whatever my GPU can handle once I have it working).

# Answer
> 1 votes
> This is further exasperated by the fact that textures don't allow me to get pixels at integer coordinates, and passing whole numbers as floating point coordinates is likely to cause floating point error to be sufficiently significant to be a problem, especially with texture filtering (I have thousands of points for now, but that will increase to whatever my GPU can handle once I have it working).

Considering that the absolute maximum texture size you will have access to will likely be 4096x4096, you will have no problem with floating point error when it comes to accessing pixels. A 4096x4096 rgb texture will give you 16,777,216 points, which is already more than you will be able to compute in your simulation due to n^2 complexity. You should use GL\_NEAREST to be sure that there is no interpolation between texels.

Here is an example implementation for the rendering process:

Pass indices as a buffer to the vertex shader.

```
int indices [8] = [0,1,2,3,4,5,6,7];

```

Convert the index to UV coordinates.

```
int _u = index / 4096;
int _v = index % 4096;
vec2 uv = vec2(float(_u),float(_v)) / 4096.0;

```

Then, sample from the texture and convert rgb to xyz vertex coordinates. (you can also use multiple textures here if you want)

```
gl_Position = mvp * vec4(texture(tex, uv).rgb, 1.0);

```

For the simulation process, you can draw the texture to an fbo with a viewport of equal size to the texture so that 1 fragment = 1 texel = 1 vertex, and perform your simulation in the fragment shader.

# Answer
> 0 votes
The transform feedback is not simple. Here is a code to use transform feedback to read triangles. Changing it to return points should be fairly straightforward:

https://github.com/sjhalayka/opengl\_gs\_transform\_feedback

The vertex shader is:

```
#version 410 core

// Per-vertex inputs
layout (location = 0) in vec4 position;

out VS_OUT
{
    vec4 position;
} vs_out;

void main(void)
{
    vs_out.position = position;
}

```

The geometry shader is:

```
#version 430 core

layout (points) in;
layout (triangle_strip) out;
layout (max_vertices = 6) out;

out vec3 vert;

in VS_OUT
{
    vec4 position;
} gs_in[];

void main(void)
{
    vec3 vertex0 = vec3(1, 2, 3);
    vec3 vertex1 = vec3(4, 5, 6);
    vec3 vertex2 = vec3(7, 8, 9);

    vert = vertex0;
    EmitVertex();

    vert = vertex1;
    EmitVertex();

    vert = vertex2;
    EmitVertex();

    EndPrimitive();

    vertex0 = vec3(10, 11, 12);
    vertex1 = vec3(13, 14, 15);
    vertex2 = vec3(16, 17, 18);

    vert = vertex0;
    EmitVertex();

    vert = vertex1;
    EmitVertex();

    vert = vertex2;
    EmitVertex();

    EndPrimitive();
}

```

The C++ code is too long to post here.

---
Tags: opengl, physics, simulations
---


# Question
Title: Humanoid Retargetting: Number of frames in LateUpdate is not the same as frames in animation
I need to play an animation in such a way that each frame is for sure being played and not skipped.

Why? I want to transfer an animation from 1 model to another. One model is Humanoid, the other one is Generic. This way, I can "save out" the Humanoid retargetting and process it in an external animation editor later.

To transfer the animations, I need to make sure that I don't miss any frame while copying the pose to the other model.

To do that, I use a very slow animator speed like this:

```
_animator.speed = 0.01f;

```

The Unity editor says this about the animation:

To make sure that each frame is really shown / played, I have implemented my own counter. My counter however returns 43 frames and not 51 frames as the Inspector. No matter how often I repeat this process, it always return 43 frames.

What am I missing?

Thank you!

```
private void LateUpdate()
{

    float f = _animator.GetCurrentAnimatorClipInfo(0)[0].clip.length * (_animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1) * _animator.GetCurrentAnimatorClipInfo(0)[0].clip.frameRate;
    int iCurrentFrameIDInAnimationFile = (int)f;

    bool bIsNewFrame = (iCurrentFrameIDInAnimationFile != _iLastFrameIDInAnimationFile);

    if (!bIsNewFrame)
    {
        return;
    }
    else if (bIsNewFrame)
    {
        _iFrameCount += 1;
    }

    _iLastFrameIDInAnimationFile = iCurrentFrameIDInAnimationFile;

    if (_animator.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !_animator.IsInTransition(0))
    {
        //animation has finished playing
        Debug.Log("Frames: " + _iFrameCount); //this returns 43 frames. Why???
    }

```

# Answer
> 0 votes
In the chat, Anders I discussed the problem further, and he found out that Unity requires some warm up for the retargetting.

The first time around, it still misses frames.

After the first time (for playing of the animation), all works as expected.

# Answer
> 0 votes
I add a second answer since the first one is valid for others in similar situations.

Normally you don't have to calculate the frame rate as you do - since it can be done even without playing in my previous answer. However, you are trying to figure out why not all frames were playing once the animation is "done" so I think I understand what you are trying to do. Unless some other parts of your code interfere with the "\_iFrameCount", it should be the same as the number of frames in your animation - unless (and here is probably the reason), your check at the end of the LateUpdate() is not doing what you expect.

```
if (_animator.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !_animator.IsInTransition(0))
{
    //animation has finished playing
    Debug.Log("Frames: " + _iFrameCount); //this returns 43 frames. Why???
}

```

When normalizedTime is greater than 1, you have reached the end of the current animation, which can consist of several animation clips like this:

It is first when we reach the end of the second animation normalizedTime \> 1. Then, of course, why is "\_iFrameCount" less than you expect. Well, could be several reasons, for example, this:

Note that the two animations will finish, normalizedTime \> 1, before the first animation has finished (if it had not been interrupted by the second animation).

The animator could also be interrupted by some other code/event.

# Answer
> -1 votes
To calculate the number of frames in an animation, simply multiply the animation time with the framerate.

```
    AnimationClip clip = _animator.GetCurrentAnimatorClipInfo(0)[0].clip;
    float numberOfFrames = clip.length * clip.frameRate;

```

Your animation is 1.7 seconds long with a framerate of 30 which is 51 frames (1.7\*30). The playback speed of the animator does not change this value.

The tricky part is that an animation consists of a lot of keyframes, and they don't have to be evenly distributed. If your keyframes are evenly distributed, that should not be a problem, but if not it gets harder. Here is a simple animation with sprites (21 frames). Note that each keyframe is five frames apart, except the traffic light which is on frame 16.

As far as I know, you can't get information about these keyframes in run-time. You can only do it with editor-code. If you really have to know which keyframe you are, you have to add events like this:

---
Tags: unity, frame-rate
---


# Question
Title: Updating settings UI from script also triggers method to update settings from UI interaction
My application has a UI for settings which is a mixture of textboxes and scrollbars with which users can interact. I have created a class for these settings and create an object to store them. The user can also give command line arguments to apply settings from a file.

I have a function that loads this data into the UI from the object (i.e read from a file) and another function that changes object data when user make changes to the UI.

My problem is: if I load the data from file into UI, the function responsible to reflect these changes in the UI fires up but the other function also fires up because changes were made to the UI.

So what should I do to overcome this? Should I implement some kind of state mechanism that would tell code that user has made the changes, or setup some flag which will mark that the data is loaded from a file. If you can suggest some design patterns to follow?

# Answer
> 0 votes
Elaborating on my comment as an answer:

Many Unity UI components (and their Text Mesh Pro UGUI counterparts) include a `SetValueWithoutNotify` method. This lets you update the widget with a new displayed value - as though the player had entered or selected it themselves - but without invoking any `onValueChanged` events that your code might be listening for to update the data model behind the scenes.

See eg.

This way you can update the displayed state of the UI from your data model, without creating a feedback loop where the UI invokes a callback that immediately tries to write the new UI value back into the model it came from.

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


# Question
Title: How to make the automatic movement of an actor and control that it does not go off the screen?
I have an actor in a class who then I put him in the main scene, but I want the actor to move randomly, that is, now he moves to the right, then down ... but controlling that he does not leave the screen either. I have tried some ways, but in some he would not move, others would go all the way to the left and loop. I have tried this that more or less does what I had in mind, but it is not correct because the character is shaking and sooner or later ends up leaving the screen. I'm just using this library and there are many things that escape me, any help or advice would be appreciated.

```
@Override
public void act(float delta) {
    super.act(delta);
    int number= (int)(Math.random()*4+1);

    switch (numero){
        case 1: this.setX(this.getX()-delta*80);break;
        case 2: this.setY(this.getY()-delta*80);break;
        case 3: this.setX(this.getX()+delta*80);break;
        case 4: this.setY(this.getY()+delta*80);break;
    }
    Rectangle.set(this.getX(),this.getY(),this.getWidth(),this.getHeight());
}

```

# Answer
> 0 votes
There's a couple of things that stand out in your code. First, in one place you set the variable `number` to a random value between 1 & 4, but then you're switching based on a variable named `numero`. I'm guessing this is a typo, but if it's not, it's going to be a problem.

Regarding the shaking, consider how often you are calling `act()`. If it gets called every time through the game loop (from an `update()` or something similar), the result is you're picking a new direction too frequently (very likely multiple times per second). The solution to this is to keep track of how long you've been travelling in a particular direction & only pick a new direction when you've gone far enough.

As for leaving the screen, you need to add some sort of bounds checking. As originally posted, there's no code that checks to see if the actor has travelled off screen.

Here's an example of modifications that address these issues. I've included some comments to point out the reason for the various changes

```
@Override
public void act(float delta) {
    super.act(delta);

    // move in the direction of the current random heading
    switch (randomHeading){
        case 1: this.setX(this.getX()-delta*80);break;
        case 2: this.setY(this.getY()-delta*80);break;
        case 3: this.setX(this.getX()+delta*80);break;
        case 4: this.setY(this.getY()+delta*80);break;
    }

    // if needed, stop at screen boundary & clear the heading
    int maxX = Gdx.graphics.getWidth() - getWidth();
    int maxY = Gdx.graphics.getHeight() - getHeight();
    if(getX() < 0){
        setX(0);
        randomHeading = 0;
    }
    else if(getX() > maxX){
        setX(maxX);
        randomHeading = 0;
    }
    if(getY() < 0){
        setY(0);
        randomHeading = 0;
    }
    else if(getY() > maxY){
        setY(maxY);
        randomHeading = 0;
    }

    // update time spent on current heading & check if a new heading is needed
    // recall that if the actor attempted to move off screen, randomHeading was set to zero
    timeTravelled += delta;
    float maxTravelTime = 10;
    if(timeTravelled > maxTravelTime || randomHeading == 0){
        timeTravelled = 0;
        randomHeading = (int)(Math.random()*4+1);
    }

    Rectangle.set(this.getX(),this.getY(),this.getWidth(),this.getHeight());
}

```

For these changes to work, you'll need to add the following fields to your class:

```
int randomHeading
float timeTravelled

```

You will also probably want to adjust the value assigned to `maxTravelTime`.
Without the rest of your code I can't check my solution against a compiler, but hopefully this is enough to help you out.

---
Tags: libgdx, android
---


# Question
Title: Image color being changed when pygame blitting to screen
I'm working on my first game, and I decided to add some trees that twinkle to the game. For some reason when the image is blitted to the screen using pygames `blit` function it changes the color of the yellow parts of the tree where it twinkles.

Some googling led me to suspect the alpha channels could be the issue so I changed the load part of the image to use `convert_alpha()` to take care of transparency, which then displays the bottom tree correctly under a black background, but I get strange shading on the rest of the images that are being loaded prior to the trees, and as you can see, the yellow parts now have black rings around them.

I initially used these two lines of code to load the images.

```
self.sheet = pygame.image.load(filename).convert()

screen.blit(tileImage, (centered_x, centered_y))

```

**The actual image looks like this when I open it up in Paint3D**

Here is the actual class I'm using to process my sprite sheets

```
class spritesheet(object):
    def __init__(self, filename):
        try:
            self.sheet = pygame.image.load(filename).convert()
        except pygame.error as message:
            print('Unable to load spritesheet image:', filename)
            raise SystemExit(message)
    #Load a specific image from a specific rectangle
    def image_at(self, rectangle, colorkey = None):
        "Loads image from x,y,x+offset,y+offset"
        rect = pygame.Rect(rectangle)
        image = pygame.Surface(rect.size).convert()
        image.blit(self.sheet, (0, 0), rect)
        if (colorkey is not None):
            if (colorkey == -1):
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image
    # Load a whole bunch of images and return them as a list
    def images_at(self, rects, colorkey = None):
        "Loads multiple images, supply a list of coordinates"
        return [self.image_at(rect, colorkey) for rect in rects]
    # Load a whole strip of images
    def load_strip(self, rect, image_count, colorkey = None):
        "Loads a strip of images and returns them as a list"
        tups = [(rect[0]+rect[2]*x, rect[1], rect[2], rect[3])
                for x in range(image_count)]
        return self.images_at(tups, colorkey)

    def load_sheet(self,width,height,rows,image_count, colorkey = None):
        '''Loads an entire sprite sheet, assumes sprites are equally spaced, returns them as list of lists '''
        sprite_sheet = []
        for i in range(rows):
            sprite_sheet.append(self.load_strip((0, 0+i*height, width, height),image_count,colorkey))

        print('len(sprite_sheet)',len(sprite_sheet))
        return sprite_sheet

```

Any ideas what could cause this? It's not displaying the shadows of the tree either which I thought was odd, but that is a separate question I think.

**Edit** Here is a full example code. The images I'm using can be downloaded here

```
import pygame
import os
import errno
from pathlib import Path

TILEWIDTH = 143  #holds the tile width and height
TILEHEIGHT = 137
TILEHEIGHT_HALF = TILEHEIGHT /2
TILEWIDTH_HALF = TILEWIDTH /2
DEBUG = False

grass = [(0,0)]

class Enum(tuple):
    '''Allows enumerations to be defined as
       options = Enum(['COLOR','NOCOLOR'])
       Acccessing enum: options.COLOR returns 0, options.NOCOLOR returns 1
     '''
    __getattr__ = tuple.index

options = Enum(['CONVERTALPHA','CONVERT'])

class spritesheet(object):
    def __init__(self, filename,load_options=None):
        try:
            if (load_options == options.CONVERTALPHA):
                self.sheet = pygame.image.load(filename).convert_alpha()
            elif (load_options == options.CONVERT):
                self.sheet = pygame.image.load(filename).convert()
            elif (load_options == None):
                self.sheet = pygame.image.load(filename).convert()
        except pygame.error as message:
            print('Unable to load spritesheet image:', filename)
            raise SystemExit(message)
    # Load a specific image from a specific rectangle
    def image_at(self, rectangle, colorkey = None):
        "Loads image from x,y,x+offset,y+offset"
        rect = pygame.Rect(rectangle)
        image = pygame.Surface(rect.size).convert()
        image.blit(self.sheet, (0, 0), rect)
        if (colorkey is not None):
            if (colorkey == -1):
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image
    # Load a whole bunch of images and return them as a list
    def images_at(self, rects, colorkey = None):
        "Loads multiple images, supply a list of coordinates"
        return [self.image_at(rect, colorkey) for rect in rects]
    # Load a whole strip of images
    def load_strip(self, rect, image_count, colorkey = None):
        "Loads a strip of images and returns them as a list"
        tups = [(rect[0]+rect[2]*x, rect[1], rect[2], rect[3])
                for x in range(image_count)]
        return self.images_at(tups, colorkey)

    def load_sheet(self,width,height,rows,image_count, colorkey = None):
        '''Loads an entire sprite sheet, assumes sprites are equally spaced, returns them as list of lists '''
        sprite_sheet = []
        for i in range(rows):
            sprite_sheet.append(self.load_strip((0, 0+i*height, width, height),image_count,colorkey))

        print('len(sprite_sheet)',len(sprite_sheet))
        return sprite_sheet

map = [[0, 0, 0,],
        [0, 30, 0]]

def get_file_path(file_directory):
    '''
    get_file_path
    Description: Get absolute file path from current working directory, it will
                 raise a FileNotFoundError exception if the file doesn't exist

    Inputs: file_directory- filepath from running directory

    Outputs: Absolute path to file

    run_directory - Is the current run path, while file_directory is the file path
    below the current root directory.
    '''
    run_directory = os.path.dirname(__file__)
    file_path = Path(run_directory + file_directory)

    if (not os.path.isfile(file_path) ):
        raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),file_path)

    return str(file_path)

class Map():
    def __init__(self,world):
        self.map = world
        ss = spritesheet(get_file_path('/Assets/Textures/Grass-Spritesheet_Blocks.png'))
        tree_sheet = spritesheet(get_file_path('/Assets/Textures/trees_twinkle.png'),options.CONVERTALPHA)
        self.grass = ss.load_sheet(192,192,5,6,(0,0,0))
        self.trees = tree_sheet.load_sheet(192,192,1,4)

        self.init = True

        self.rect = []
        self.previous_update = False

    def render(self,screen,updatemap):
        #Only update map when player screen changes
        self.reset = False
        self.foreground = []
        if (True):#(self.init == True) or True):
            tree_width = 100
            tree_height = 100
            actual_tree_width = 175
            actual_tree_height = 182
            for row in range(0,len(self.map)):
                for col in range(0, len(self.map[row])):

                    cart_x = col * TILEWIDTH_HALF
                    cart_y = row * TILEHEIGHT_HALF
                    iso_x = (cart_x - cart_y)
                    iso_y = (cart_x + cart_y)/2
                    centered_x = screen.get_rect().centerx + iso_x
                    centered_y = screen.get_rect().centery/2 + iso_y

                    if (self.map[row][col] < 30):
                        tileImage = self.grass[grass[self.map[row][col]][0]][grass[self.map[row][col]][1]]
                    else:
                        tileImage = self.grass[grass[0][0]][grass[0][1]]
                        tileForeground = self.trees[0][0]

                        self.foreground.append({'image': self.trees[0][0], 'coordinates': (centered_x,centered_x)})

                    if (self.map[row][col] < 30):
                        screen.blit(tileImage, (centered_x, centered_y))
                    else:
                        screen.blit(tileImage, (centered_x, centered_y))
                        screen.blit(tileForeground,(centered_x, centered_y-96),special_flags=pygame.BLEND_PREMULTIPLIED)

            self.init = False

if __name__ == '__main__':
    import pygame
    from pygame.locals import ( K_w, K_s, K_a, K_d, K_UP, K_DOWN, K_ESCAPE, KEYDOWN, QUIT, )
    running = True
    pygame.init()
    screen = pygame.display.set_mode((800, 600),pygame.DOUBLEBUF)
    while running:
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    running = False
            elif event.type == QUIT:
                running = False

        worldMap = Map(map)
        worldMap.render(screen,False)
        pygame.display.update()

```

There's a colorkey option for the load\_sheet which is set to black. I've tried removing that

# Answer
For anybody else that runs into an issue like this, here is what worked for me.

Add `SRCALPHA` to the Surface you are blitting to, and use `convert_alpha()` on the surface when there is transparency.

```
image = pygame.Surface(rect.size,pygame.SRCALPHA).convert_alpha()

```

It's important to use `convert_alpha()` on the loaded image as well or it won't treat the transparency properly.

```
self.sheet = pygame.image.load(filename).convert_alpha()

```

These two things worked for me.

Now I get this when I run the code. The suggestion to use `pygame.BLEND_PREMULTIPLIED` did not correct the issue.
> 1 votes

---
Tags: python, pygame
---


# Question
Title: GameObjectRecorder clip length and frame count doesn't correlate with expectations
I have a generic animation which is 30 FPS, 1.7 seconds long and which contains 51 frames.

This is what it looks like in Unity:

And these are the frames in Blender:

I want to use this generic animation on a different model.

I can of course do this using a Humanoid Avatar and Unity's humanoid retargetting system. It works, but I don't really want my model to have a Humanoid Avatar. I have many generic animations perfectly built for just this model, so now switching to a Humanoid Avatar is against my initial decision for a generic avatar.

So what I do is to duplicate my generic model. I create a Humanoid Avatar for the duplicate.

Then I play the animation on the Humanoid model. At each LateUpdate, I copy the bone positions and rotations from the Humanoid model to the Generic model. And I use a GameObjectRecorder to save the bone rotation and position changes to a new animation file.

When the animation has finished playing once, I save the results in an animation file.

So what I have then is the animation file for my generic model.

Now I can delete the Humanoid Avatar because I used it just as a middle man.

However, the resulting animation plays much slower than the original animation.

Unity states that the animation contains 83 frames and is 2:23 seconds long.

I don't see what the problem is.

The GameObjectRecorder that I'm using to capture the animation provides the methode TakeSnapshot(dt).

"dt" means the milliseconds that it should forward the new animation.

How do I calculate "dt"?

I know that the original clip is 1.7 seconds long and plays at 30 fps.

So the duration between 2 frames should (in my opinion) be: 1.7 / 30 = 0,0567.

However, when I call \_Recorder.TakeSnapshot(0,056f) at each call, it results in this weird duration and frame count.

What I did next was to take note of the frame written by the recorder.

I use a simple counter:

```
_iCountOfHowManyFramesWhereWrittenToAnimationFile += 1;
_Recorder.TakeSnapshot(_fDurationOf1Frame);

```

When the animation has played once, I output the number of frames and the duration:

```
Debug.Log("Actually written to animation file: " +
_iCountOfHowManyFramesWhereWrittenToAnimationFile + " duration: " +
_Recorder.currentTime);// how many frames were written to the animation?

```

Result: Actually written to animation file: 51 duration: 2,833332

This confuses me: Why is my file with 51 frames longer than the other animation which also contains 51 frames? It must be because I have miscalculated the duration, but I don't see what the duration should be in order.

I thought that the duration between 2 frames was

```
fDurationBetween2Frames = AnimationClip.length / AnimationClip.frameRate;

```

But obviously that is wrong.

Here is the code that I'm using to transfer the animation from Humanoid to Generic, if anybody wants to know.

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

public class TransferAnimation : MonoBehaviour
{
    public Transform HumanoidModelWhoseAnimationWillBeCopiedToThisModel;
    private Animator _animator;
    private int _iLastFrameIDInAnimation = -1;
    private int _iCount = 0;
    private int _iFrameCount = 0;

    private int _iCountSequentFramesWhichWouldBeFatal = 0;
    private int _iLastCountWithNewAnimationID = 0;
    public AnimationClip ClipInWhichTransferredAnimationWillBeSavedAsGeneric;
    private float _iNumberOfFramesInClip;
    private GameObjectRecorder _Recorder;

    private bool _bReturn = false;

    private float _fFPS = -1;

    private int _iCountOfHowManyFramesWhereWrittenToAnimationFile = 0;

    private float _fDurationOf1Frame;

    void Start()
    {
        _Recorder = new GameObjectRecorder(gameObject);

        _animator = HumanoidModelWhoseAnimationWillBeCopiedToThisModel.gameObject.GetComponent<Animator>();

        AnimationClip nClip = _animator.GetCurrentAnimatorClipInfo(0)[0].clip;
        _iNumberOfFramesInClip = (int)(nClip.length * nClip.frameRate);

        _fFPS = nClip.frameRate;

        _fDurationOf1Frame = nClip.length / nClip.frameRate;

        _animator.enabled = true;
        pRestart();
    }

    private void pRestart()
    {
        _iCountOfHowManyFramesWhereWrittenToAnimationFile = 0;
        _iCount = 0;
        _bReturn = false;
        _iLastFrameIDInAnimation = -1;
        _iCountSequentFramesWhichWouldBeFatal = 0;
        _iFrameCount = 0;

        _animator.Rebind();
        _animator.Update(0f);

        ClipInWhichTransferredAnimationWillBeSavedAsGeneric.ClearCurves();

        _Recorder = new GameObjectRecorder(gameObject);
        // Bind all the Transforms on the GameObject and all its children.
        _Recorder.BindComponentsOfType<Transform>(gameObject, true);
    }
    private void LateUpdate()
    {
        if (_bReturn)
        {
            Debug.Break();//should not happen. Script should be deactivated
        }

        if (!_animator.enabled)
        {
            return;
        }

        List<Transform> nMyTransforms = new List<Transform>();
        GetAllChildren(this.transform, ref nMyTransforms);

        List<Transform> nHumanoidTransforms = new List<Transform>();
        GetAllChildren(HumanoidModelWhoseAnimationWillBeCopiedToThisModel, ref nHumanoidTransforms);

        //we also need to process the main transform, not only its bones
        transform.localRotation = HumanoidModelWhoseAnimationWillBeCopiedToThisModel.localRotation;
        transform.position = HumanoidModelWhoseAnimationWillBeCopiedToThisModel.position;//auch die position ist wichtig!!! z. B. wenn sich jemand duckt beim zielen!!
        Undo.RecordObject(HumanoidModelWhoseAnimationWillBeCopiedToThisModel, "Inspector"); //Bone rotations done by a script are not recorded. Is there a trick to record these bone rotations via script anyways? For example using something like (pseudo-code) this? -> Undo.RecordObject(nTargetTransform, "Inspector");

        float f = _animator.GetCurrentAnimatorClipInfo(0)[0].clip.length * (_animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1) * _animator.GetCurrentAnimatorClipInfo(0)[0].clip.frameRate;
        int iCurrentFrameIDInAnimation = (int)f;

        bool bIsNewFrame = (iCurrentFrameIDInAnimation != _iLastFrameIDInAnimation);

        _iCount += 1;

        if (!bIsNewFrame)
        {
            return;
        }
        else if (bIsNewFrame)
        {
            if (_iCount == (_iLastCountWithNewAnimationID - 1))
            {
                _iCountSequentFramesWhichWouldBeFatal += 1;// das wäre schlecht!!!!
            }
            _iFrameCount += 1;
            _iLastCountWithNewAnimationID = _iCount;
        }

        _iLastFrameIDInAnimation = iCurrentFrameIDInAnimation;

        foreach (Transform nHumanoidTransform in nHumanoidTransforms)
        {
            foreach (Transform nMyGenericTransform in nMyTransforms)
            {
                if (nHumanoidTransform.name == nMyGenericTransform.name)
                {

                    nMyGenericTransform.localRotation = nHumanoidTransform.localRotation;
                    nMyGenericTransform.position = nHumanoidTransform.position;//auch die position ist wichtig!!! z. B. wenn sich jemand duckt beim zielen!!

                    Undo.RecordObject(nHumanoidTransform, "Inspector"); //Bone rotations done by a script are not recorded. Is there a trick to record these bone rotations via script anyways? For example using something like (pseudo-code) this? -> Undo.RecordObject(nTargetTransform, "Inspector");

                    break;
                }
            }
        }

        _iCountOfHowManyFramesWhereWrittenToAnimationFile += 1;
        _Recorder.TakeSnapshot(_fDurationOf1Frame);

        float fCurTime = _Recorder.currentTime;
        float fExpecteded = ((_iCountOfHowManyFramesWhereWrittenToAnimationFile - 1) * _fDurationOf1Frame);

        Debug.Log("Frames: " + _iFrameCount + ", recorder cur time: " + fCurTime.ToString() + " vs " + fExpecteded.ToString() + "\n");

        if (_animator.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !_animator.IsInTransition(0))
        {
            //animation has finished playing
            if ((_iFrameCount - 1) == _iNumberOfFramesInClip)//wir müssen -1 machen, weil wir ja oben noch eines draufgeben
            {
                //alles ok :-)
                if (_Recorder.isRecording)
                {
                    // Save the recorded session to the clip.
                    _Recorder.SaveToClip(ClipInWhichTransferredAnimationWillBeSavedAsGeneric, _fFPS);
                    Debug.Log("Actually written to animation file: " + _iCountOfHowManyFramesWhereWrittenToAnimationFile + " duration: " + _Recorder.currentTime);// how many frames were written to the animation?
                    AssetDatabase.SaveAssets();//save out!!!!!!!!!!! Else, Unity only writes the animation to file when it quits
                    gameObject.SetActive(false);//disable this script
                    UnityEditor.EditorApplication.isPlaying = false;
                }
            }
            else
            {
                Debug.Log("Frames: " + _iFrameCount + "\n");
                //fatal error: unity didnt play all frames. Try again
                _Recorder.ResetRecording();
                pRestart();
            }
        }
    }

    public static void GetAllChildren(Transform parent, ref List<Transform> transforms)
    {
        foreach (Transform t in parent)
        {
            transforms.Add(t);
            GetAllChildren(t, ref transforms);
        }
    }
}

```

# Answer
I found the problem.

I have calculated the duration between 2 frames wrong.

It should be

```
 _fDurationOf1Frame = nClip.length / _iNumberOfFramesInClip;

```

I inititally thought that fps should be taken into account, but that is not so.
> 0 votes

---
Tags: unity, animation
---


# Question
Title: How do I calculate the duration between 2 frames in an animation file
I want to find out the duration between 2 frames in animation file.

Is the following correct?

```
fDurationBetween2Frames = AnimationClip.length / AnimationClip.frameRate;

```

Thank you.

# Answer
```
fDurationBetween2Frames = AnimationClip.length / NumberOfFrames;

```
> 1 votes

---
Tags: unity, animation
---


# Question
Title: How do I set the Foot IK property of an animator state by code?
I would like to set Foot IK to enabled via code, but I can't find how.

Which type is "Foot IK" a part of?

# Answer
> 1 votes
It looks like you want AnimatorState.iKOnFeet.

You can navigate to an `AnimatorState` from an `AnimatorController` by...

1. Using AnimatorContoller.layers to navigate the layers in the control graph.
2. Using AnimatorControllerLayer.stateMachine to access the state machine for the selected layer.
3. Using AnimatorStateMachine.states to navigate the states present in this state machine.

---
Tags: unity, animation, inverse-kinematics
---


# Question
Title: How can we generate 3D architecture in a racing game's background procedurally with respect/similar to the real world?
In the last few days, I jumped into searching is there a conventional/convenient way to build 3D architecture quickly, most likely by some accessory software like CityEngine, BIGEMAP, or google maps' Maps SDK for Unity.

However, I couldn't figure out the *most suitable* solution that typically suits the requirement of "generate 3D architecture models by the racing road which is **referencing the real world map**", or just simply "**build a massive amount** of 3D architecture models", *efficiently and handily*.

I want to achieve buildings similar to those seen in Need For Speed and Asphalt. Their buildings in the scene are *quite outstanding* to me.

How can I generate buildings similar to this?

# Answer
CityEngine is one of many tools used to make *Need For Speed*. EA didn't use CityEngine as a start-to-finish solution. It sped up their development by reducing time spent on certain tasks so it could be reinvested elsewhere:

> Game artists aren’t looking for a one-button procedural solution. Instead, they’re interested in procedural methods that help with tedious tasks and provide results that adjust to gaming constraints. Procedural methods should free artists to spend time creating and polishing, rather than performing mundane, repetitive, and time-consuming tasks

In terms of using CityEngine efficiently:

> Effective use of the CityEngine, and indeed almost any urban-modeling tool, requires familiarity with architecture. You should begin by acquiring a good understanding of basic building elements such as windows, doors, columns, pilasters, quoins, gates, roofs, cornices, arches, walls, and ornaments. We recommend examining one to three architecture books with labeled illustrations of these elements. One of the best is by Köpf and Binding, but unfortunately it’s available only in German. A similar book is a Visual Dictionary of Architecture

From there, EA identified their typical high level work flow as follows:

* Design idea/concept
* Analyze design and parameters
* Create elements and textures
* Encode design rules
* Add stochastic behavior
* Generate models

Notice that CityEngine is only used at the last step. It can be used to build a massive amount of 3D architectural content efficiently and handily. But doing so is contextual relative to the time and work spent prior to that step.

For information about how CityEngine was used in *Need For Speed*, I recommend reading Procedural Methods for Urban Modeling Tutorial Procedural Urban Modeling in Practice. The paper's co-authors includes two staffers from EA that worked on the *Need For Speed* series and the cofounder of Procedural Inc (developer of CityEngine). The quoted text blocks are from that paper.
> 1 votes

# Answer
AFAIK they achieve this by

**Parameterized Procedural Placement**

They create a workflow where you create a handful assets in this case building floors and they procedurally tweak the parameters such as Floor count,size,tint and custom props such as air conditioning outside of the buildings.

I once a saw a video about ubisoft creating a procedural assasins creed city.They premade a bunch of houses and spread them randomly.

You should desing a workflow where you control how your building floors are stacked on each other and how each floor has its own specific unique props.

**This is what i would do**

* I would decide what a building floor means to me.These would be my parameters: IsGroundFloor?, width and height of the floor, how many windows, a balcony?, general tint color of the floor material and unique set of models.(Such as vegatation, flowers, air conditioning or a satallite dish perhaps?).
* I would decide how many floors should a building has.Define the minimum and the maximum
* I would decide what will be the floor independent objects such as fire escape ladder which starts from ground to the top of the building, some garden? or fences?

with these parameters one can create wide range of different buildings considering you feed your procedural workflow with enough assets
> 0 votes

---
Tags: procedural-generation, models, level-design, racing
---


# Question
Title: How can I change the speed flag for random or not random at run time?
This method is being called by Update()

```
private void SpeedUpdater()
    {
        if (changeSpeedOnce == false)
        {
            foreach (WaypointsFollower follower in waypointsFollowers)
            {
                if (randomSpeed)
                {
                    follower.speed = Random.Range(minRandomSpeed, maxRandomSpeed);
                }
                else
                {
                    follower.speed = speed;
                }
            }

            changeSpeedOnce = true;
        }
    }

```

I'm using the changeSpeedOnce flag helper to assign the speed to the followers once either random or the constant speed. but then when the game is running changeSpeedOnce is true and if I want to change the randomSpeed flag again I need somehow somewhere to set the changeSpeedOnce to be false again.

I don't want to use a button or an input key for that but using the randomSpeed flag.

# Answer
> 0 votes
The solution is to use the third bool flag.

The variable currentSpeedState , using this variable to record the current randomSpeed state if it has changed and then to set the changeSpeedOnce flag to false again.

In the Start :

```
currentSpeedState = randomSpeed;

```

Then in the SpeedUpdater :

```
private void SpeedUpdater()
        {
            if (changeSpeedOnce == false)
            {
                foreach (WaypointsFollower follower in waypointsFollowers)
                {
                    if (randomSpeed)
                    {
                        follower.speed = Random.Range(minRandomSpeed, maxRandomSpeed);
                    }
                    else
                    {
                        follower.speed = speed;
                    }
                }

                changeSpeedOnce = true;
            }

            if(currentSpeedState != randomSpeed)
            {
                changeSpeedOnce = false;

                currentSpeedState = randomSpeed;
            }
        }

```

And the full script :

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

public class Waypoints : MonoBehaviour
{
    [Header("Objects To Move")]
    public Transform objectToMovePrefab;
    public int numberOfObjectsToMove = 1;

    [Header("Speed Settings")]
    public float speed;
    public bool randomSpeed = false;
    public float minRandomSpeed = 1;
    public float maxRandomSpeed = 100;
    private bool changeSpeedOnce = false;
    private bool currentSpeedState;

    [Header("Waypoints")]
    [SerializeField] private List<Transform> waypoints;

    [Header("Delay")]
    public float delay = 3;
    public bool randomDelay = false;
    public float minRandomDelay = 0.3f;
    public float maxRandomDelay = 5;

    [Header("LineRenderer")]
    public LineRenderer lineRenderer;
    private List<Vector3> lineRendererPositions = new List<Vector3>();

    [Header("Cinemachine Cameras")]
    public CinemachineVirtualCamera virtualCamera;

    private List<WaypointsFollower> waypointsFollowers = new List<WaypointsFollower>();

    private void Start()
    {
        currentSpeedState = randomSpeed;

        for (int i = 0; i < numberOfObjectsToMove; i++)
        {
            var parent = GameObject.Find("Moving Object Parent");
            var objectToMove = Instantiate(objectToMovePrefab, parent.transform);
            objectToMove.name = "Platfrom";

            waypointsFollowers.Add(objectToMove.GetComponent<WaypointsFollower>());
        }

        virtualCamera.Follow = waypointsFollowers[0].gameObject.transform;
        virtualCamera.LookAt = waypointsFollowers[0].gameObject.transform;

        SpeedUpdater();

        StartCoroutine(SendObjectstomoveWithDelay());
    }

    private void Update()
    {
        GetLinePointsInWorldSpace();

        SpeedUpdater();
    }

    public int Count => waypoints.Count;
    public Vector3 GetWaypoint(int index)
    {
        return waypoints[index].position;
    }

    IEnumerator SendObjectstomoveWithDelay()
    {
        {
            foreach (WaypointsFollower follower in waypointsFollowers)
            {
                if (randomDelay)
                {
                    delay = Random.Range(minRandomDelay, maxRandomDelay);
                }

                yield return new WaitForSeconds(delay);

                follower.go = true;
            }
        }
    }

    private void SpeedUpdater()
    {
        if (changeSpeedOnce == false)
        {
            foreach (WaypointsFollower follower in waypointsFollowers)
            {
                if (randomSpeed)
                {
                    follower.speed = Random.Range(minRandomSpeed, maxRandomSpeed);
                }
                else
                {
                    follower.speed = speed;
                }
            }

            changeSpeedOnce = true;
        }

        if(currentSpeedState != randomSpeed)
        {
            changeSpeedOnce = false;

            currentSpeedState = randomSpeed;
        }
    }

    List<Vector3> GetLinePointsInWorldSpace()
    {
        lineRendererPositions = new Vector3[lineRenderer.positionCount].ToList();
        //Get the positions which are shown in the inspector
        lineRenderer.GetPositions(lineRendererPositions.ToArray());

        //the points returned are in world space
        return lineRendererPositions;
    }
}

```

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


# Question
Title: Unexpected Result On Coroutines Called From Another Script
So I performed tests on calling coroutines from another script. I want to understand why the results aren't the expected behavior in one of the test case, and unfortunately the one that I needed to use (as it is more dynamic).

**Tests:**

```
// TEST 1: Running coroutines from passed IEnumerator
m_Tester.StartCoroutine(1);

// TEST 2: Running coroutines in this script through a delegate
m_TesterByFunc.StartCoroutineByFunc(1);

// TEST 3: Running coroutines by starting them publicly via this script
m_TesterByCasting.StartCoroutineByCasting(1);

```

The idea is I'd like to call coroutines from another script - in this case, from a plain class. And I'm expecting that my coroutines would run normally. However, the problem is when passing IEnumerator to the Tester class, along with the owning Monobehavior object, then starting the coroutines from it (Tester class) only worked once. Calling StartCoroutine from CoroutineTest via a delegate function or publicly worked as intended.

I'm not sure if anyone has encountered this but I'd love to know why I'm getting the unexpected result particularly for Test #1.

* Is there a problem with passing IEnumerator and caching them in the class and the reason why it only works once? Is it not passed by reference?

Please see the test scripts below.

**Script 1:**

```
public class Tester
{
    public delegate void Function();

    private MonoBehaviour m_Owner;
    private Function m_F1;
    private Function m_F2;
    private IEnumerator m_One;
    private IEnumerator m_Two;

    public Tester (MonoBehaviour owner)
    {
        m_Owner = owner;
    }

    public Tester(MonoBehaviour owner, IEnumerator one, IEnumerator two)
    {
        m_Owner = owner;
        m_One = one;
        m_Two = two;
    }

    public Tester(MonoBehaviour owner, Function f1, Function f2)
    {
        m_Owner = owner;
        m_F1 = f1;
        m_F2 = f2;
    }

    public void StartCoroutine(int index)
    {
        if (index == 0)
        {
            m_Owner.StopCoroutine(m_Two);
            m_Owner.StartCoroutine(m_One);
        }

        if (index == 1)
        {
            m_Owner.StopCoroutine(m_One);
            m_Owner.StartCoroutine(m_Two);
        }
    }

    public void StartCoroutineByFunc(int index)
    {
        if (index == 0)
        {
            m_F1();
        }

        if (index == 1)
        {
            m_F2();
        }
    }

    public void StartCoroutineByCasting(int index)
    {
        var test = (m_Owner as CoroutineTest);

        if (index == 0)
        {
            test.StopCoroutine(test._TestTwoByCasting());
            test.StartCoroutine(test._TestOneByCasting());
        }

        if (index == 1)
        {
            test.StopCoroutine(test._TestOneByCasting());
            test.StartCoroutine(test._TestTwoByCasting());
        }
    }
}

```

**Script 2:** Attach to a game object in the scene

```
public class CoroutineTest : MonoBehaviour
{
    private Tester m_Tester;
    private Tester m_TesterByFunc;
    private Tester m_TesterByCasting;

    private void Awake()
    {
        m_Tester = new Tester(this, _TestOne(), _TestTwo());
        m_TesterByFunc = new Tester(this, TestOneByFunc, TestTwoByFunc);
        m_TesterByCasting = new Tester(this);
    }

    private void OnEnable()
    {
        // TEST 1: Running coroutines from passed IEnumerator
        m_Tester.StartCoroutine(1);

        // TEST 2: Running coroutines in this script through a delegate
        m_TesterByFunc.StartCoroutineByFunc(1);

        // TEST 3: Running coroutines by starting them publicly via this script
        m_TesterByCasting.StartCoroutineByCasting(1);
    }

    public IEnumerator _TestOne()
    {
        Debug.Log("Test one");

        yield return new WaitForSeconds(3f);

        m_Tester.StartCoroutine(1);
    }

    public IEnumerator _TestTwo()
    {
        Debug.Log("Test two");

        yield return new WaitForSeconds(3f);

        m_Tester.StartCoroutine(0);
    }

    private void TestOneByFunc()
    {
        StopCoroutine(_TestTwoByFunc());
        StartCoroutine(_TestOneByFunc());
    }

    private void TestTwoByFunc()
    {
        StopCoroutine(_TestOneByFunc());
        StartCoroutine(_TestTwoByFunc());
    }

    private IEnumerator _TestOneByFunc()
    {
        Debug.Log("Test one by func");

        yield return new WaitForSeconds(3f);

        m_TesterByFunc.StartCoroutineByFunc(1);
    }

    private IEnumerator _TestTwoByFunc()
    {
        Debug.Log("Test two by func");

        yield return new WaitForSeconds(3f);

        m_TesterByFunc.StartCoroutineByFunc(0);
    }

    public IEnumerator _TestOneByCasting()
    {
        Debug.Log("Test one by casting");

        yield return new WaitForSeconds(3f);

        m_TesterByCasting.StartCoroutineByCasting(1);
    }

    public IEnumerator _TestTwoByCasting()
    {
        Debug.Log("Test two by casting");

        yield return new WaitForSeconds(3f);

        m_TesterByCasting.StartCoroutineByCasting(0);
    }
}

```

Thanks!

# Answer
> 0 votes
Okay, so after a few experiments I have found a solution to my issue. I just needed to create an IEnumerator delegate and pass that instead.

```
public delegate IEnumerator ICoroutine();

public ICoroutine m_One;
public ICoroutine m_Two;

public Tester(MonoBehaviour owner, ICoroutine one, ICoroutine two)
{
    ...
}

```

then update the calls to,

```
m_Owner.StartCoroutine(m_One());

```

and

```
m_Owner.StartCoroutine(m_Two());

```

Calling it as you would call it normally in the same script. It now works as intended.

Thanks to @Nikaas, I was reminded about enumerators getting renewed when called via delegates or methods.

# Answer
> 0 votes
You can think of IEnumerator as a counter/sequence. It has an internal state to what position it reached. In the case of unity coroutines it is a sequence of waiting times. When you run it once you gone through the full sequence and it is at its end. I have not tested it but likely you can call Reset() on the enumerator before passing it again to StartCoroutine. BTW this makes me think that you should be careful to not run the same enumerator in parallel with itself. In the case of delegates a new enumerator is created each time you start a coroutine (or maybe even some unity magic to avoid the garbage).

---
Tags: unity, coroutines
---


# Question
Title: Elegantly exposing properties in Unity inspector
There are various game objects in my scene that share some common characteristics, so I created an interface, like so:

```
public interface IHasLimitedRangeOfMotionAlongZAxis
{
    float MinimumZ { get; }
    float MaximumZ { get; }
}

```

For certain types that implement this interface, I would like `MinimumZ` and `MaximumZ` to be publicly assignable in the Unity inspector. Therefore, I would like to be able to expose these properties in Unity.

I am aware that one approach is to write C# scripts in the `Editor` folder to implement an `ExposePropertyAttribute` (see here).

However, this approach is unsatisfactory for two reasons:

1. My solution is not co-located with my `Assets` folder. I write my code in a separate solution, and then use `pdb2mdb.exe` to import my scripts into my Unity scenes. (The reason for doing this is to avail myself of C# language features introduced beyond C# 4.0, which nonetheless target .NET Framework 3.5.)
2. I shall have to create a custom editor for every single type that implements the interface with publicly assignable properties. This leads to a lot of boilerplate code.

Is there a more elegant approach than adding private backing fields with the `SerializeField` attribute for all of my public properties?

# Answer
> 2 votes
You can use Auto-Implemented Property Field-Targeted Attributes to expose properties in the inspector. You still have to use `SerializeField` but you don't need to write the backing field manually anymore.

```
[field: SerializeField]
public Transform Ball { get; set; }

```

---

This is only supported in newer versions of Unity that support C# 7.3.

*Clarification:* By newer versions of Unity, I mean any version of Unity that supported the .NET 4.6 runtime (I think). The documentation does not exist for all versions, but it has been supported since at least Unity 2018.4 *\[source\]*.

# Answer
> 1 votes
AFAIK at the moment there aren't solutions different from using `[SerializeField]` on the private fields of the property or implementing some editor code that exposes properties like the one you linked.

# Answer
> 0 votes
> I would like `MinimumZ` and `MaximumZ` to be publicly assignable in the Unity inspector.

This is not possible. You've declared these properties as read only.

> ```
> float MinimumZ { get; } //no setter
> float MaximumZ { get; }
>
> ```

No matter what inspector options exist or are possible, or even might be possible for Interface types, you've explicitly denied writing to these properties.

The only option you have is using `[SerializeField]` on the private backing object.

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


# Question
Title: Is it better to load all of the scene at once or load small parts of it as the player moves?
I want to create a lot of detail in my game but I don’t want to kill the frame rate tracking all the models and movements (like all the grass). Will loading them in pieces save the frame rate or will constantly loading and unloading models with every step negate any benefits of loading in pieces? I want to only load what the player will see at that moment and nothing else until the player either moves the camera or walks. I also want to know if loading a scene on Unity uses the gpu or the cpu?

# Answer
> 4 votes
When your game scene becomes so large that you run into performance and/or memory problems, then it can make sense to divide your world into separate scenes and only load those around the player. By loading a scene with `LoadSceneMode.Additive` you can load the content of a scene into a current scene, so both scenes coexist at the same time. And when you use `SceneManager.LoadSceneAsync`, then the loading will happen on a background thread, so the player won't notice any hiccups while scenes are being loaded. The drawback is that under some circumstances, the player might move so fast that they manage to move into a scene before a scene is loaded, which can cause a myriad of problems (like falling through the not-yet-spawned floor or walking through a not-yet-spawned wall). So it can make sense to keep the `AsyncOperation` object returned by that method and check whether it has loaded.

So for loading a scene in the background:

```
var loadOperation = SceneManager.LoadSceneAsync(newScene, LoadSceneMode.Additive);

```

When you want to unload the content of a scene you loaded additively but don't need anymore, then you use `SceneManager.UnloadSceneAsync`. You might also want to use the option `UnloadSceneOptions.UnloadAllEmbeddedSceneObjects`. This option ensures that any assets which are no longer needed will also be removed from memory:

```
SceneManager.UnloadSceneAsync(oldScene, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects);

```

# Answer
> 1 votes
You most likely will not run into that problem. If you're doing a personal project, my gut feeling is that if you are having performance problems in your level then you're probably facing more issues with LOD optimization or bad shaders/lighting. Unity should be plenty powerful for what you're envisioning.

However, It definitely depends on just how visually involved you're talking about.If you DO wind up seeing dropped frames, here are methods I would suggest:

1.) Cull the backsides of your geometry. HL2 is a good example of this. Look at their maps and it looks like they're all cardboard cutouts. But in game, they felt like whole city blocks even back in the early 2000s.

2.) Use LODs to lower the detail of out of focus or far away items. This is the Unity Manual page for the LOD Component: https://docs.unity3d.com/Manual/LevelOfDetail.html

3.) After that, I would recommend something akin to Unreal's level streaming. I'll admit, I put this one last because I haven't done this directly in Unity. But the premise is that instead of trying to dynamically cull and render objects as the player's FOV changes, use triggers to dynamically load/unload whole sections of the map. If they go down the elevator, you can cull the floor they just left for example.

Edit: Came across this post today, seemed relevant: http://victor.madtriangles.com/code%20experiment/2020/06/12/post-ue4-perf\_guide.html

---
Tags: unity, 3d, textures, performance, loading
---


title: counting coins after a certain time

text:
# Question
Title: counting coins after a certain time
I am beginner in unity . and now i am trying to write my first game. the game is includes appear random coins in random place on the screen , after passing a certain amount of time.(one coin will be appear and then after for example 2 seconds it will be destroyed and the other coins will be appear in another place ). there is a counter which calculate the number of click on coins which appear in scene and counting number of clicks on screen The coin is a prefab .Now i need to count the number of coins that will be disappear after certain amount of time.

can someone help me how i can write the code.

# Answer
I'm assuming you mean that you want to count the number of coins that was not clicked after some period of time, and that you want to destroy them?

If that is the case, then if you have a script `Coin` for example on your prefab. One way to count the remaining coins is by `FindObjectsOfType<Coin>()`. This will return an array objects in the scene that has `Coin` component attached. You can use the `Length` property to get the number of coins and do whatever you need to do with it.

```
var coins = FindObjectsOfType<Coin>();
Debug.log($"Coins left: {coins.Length}");

```

If you want to destroy those coins then you can loop the array.

```
foreach (var coin in coins)
{
    Destroy(coin.gameObject);
}

```

Is this what you're asking for?

Also, just a side note since you're a beginner. At some point in the future you might need to research about the concept of object pooling. This will help a lot in terms of performance if you are instantiating lots of objects in the scene, and making them disappear, and then show again. In pooling, instead of completely destroying the game object, you just disable them and reuse them later. Instantiating lots of objects is expensive.
> 1 votes

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


# Question
Title: Does collision between two Area2D work differently than collision with Rigidbody2D?
Consider a `Main.tscn` with:

### (1) a player:

```
+ Player extends Area2D
|_ AnimatedSprite
|_ CollisionShape2D

```

The player has:

```
func _on_Player_body_entered(body):
    hide()

```

---

### (2) a falling rock:

```
+ Rock extends RigidBody2D
|_ AnimatedSprite
|_ CollisionShape2D

```

---

### (3) a trap:

```
+ Trap extends Area2D
|_ AnimatedSprite
|_ CollisionShape2D

```

---

The collision between Player and falling Rock (Area2D vs RigidBody2D) makes the player disappear as expected. While, the collision between Player and Trap (Area2D vs Area2D) does nothing. Is it expected?

# Answer
> Does collision between two Area2D work differently than collision with Rigidbody2D

Yes.

> the collision between Player and Trap (Area2D vs Area2D) does nothing. Is it expected?

Yes.

---

We have three main `PhysicsBody2D` types:

* `StaticBody2D`: Intended to not move. If you move it by code it causes no collision response (if you want to move it, it is easier to use `KinematicBody2D` instead). And it does not provide collision response for things colliding into it (handle those collision on things that can collide into it).
* `KinematicBody2D`: Intended for you to move it from code. Movement can cause collisions. You are supposed to handle collision response from code.
* `RigidBody2D`: Intended to be moved by physics. You can apply forces to change the way it moves, but ultimately physics moves it (to move it directly make sure to set the `mode` as needed or you will be fighting the physics system, an that is a potential source of glitches). Godot handle collision response by default.

The type `Area2D` is not in that list because it is not a physics body. Instead both `Area2D` and `PhysicsBody2D` are both `CollisionObject2D`.

A consequence is that the `"body_entered"` signal in `Area2D`, will detect `StaticBody2D`, `KinematicBody2D`, `RigidBody2D` but not other `Area2D`.

It is possible to detect overlapping between `Area2D` by using `get_overlapping_areas`.

---

However, the intended way to do things is to:

1. Make the player avatar a `KinematicBody2D`. *The icon of `KinematicBody2D` should be a clue.*
2. Put the collision logic on the `Area2D`.

That is, the trap (`Area2D`) would detect the player avatar (`KinematicBody2D`) and act on it.

That leaves the question of how to handle the rock (`RigidBody2D`) collision with the player avatar (`KinematicBody2D`). Well, `RigidBody2D` also has a `"body_entered"` signal that you can use for that.

I also mentioned that you can handle collision in your `KinematicBody2D`, that would be with `move_and_collide` or `get_slide_collision`. However, note those are meant to handle collisions are result of the motion of the `KinematicBody2D`. Thus, when a `RigidBody2D` (which is handled by physics) hits the `KinematicBody2D`, you probably want to handle that on the `RigidBody2D`.

*Another advantage of placing the collision response logic on the objects that the player avatar can collide with, is that the player avatar code is not aware of them. As a consequence it is easier to extend the logic of the game by adding more things that response to collision with the player avatar.*

---

More complex collision logic can be archived by having `Area2D` as child of a `KinematicBody2D` or using `RayCast2D`.

---

*Note: `"body_entered"` will also handle collision with tile with collision shapes from a tilemap even though a tilemap is not a physic body.*
> 6 votes

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