# Question
Title: Why does this variable keep returning to its original value?
In my 2D platformer game, I'm trying to create a button that, when the player or a box is on top of it, opens a door of the same color. Here is the code for the button:

```
extends StaticBody2D

onready var is_object_on_button = false

func _on_Green_Button_Area_body_entered(body):
    is_object_on_button = true
    print("button is down")

func _on_Green_Button_Area_body_exited(body):
    is_object_on_button = false
    print("button is up")

```

Code for the door:

```
extends StaticBody2D

onready var is_object_on_button = Green_Button.is_object_on_button
onready var door_collision = $CollisionPolygon2D

func _process(delta):
    if is_object_on_button:
        door_collision.set_disabled(true)
        print("unlocked")
    else:
        door_collision.set_disabled(false)
        print("locked")

```

The button prints the right things at the right time, so I assume the button is working properly, but the door constantly stays (and prints) locked. How do I fix this?

Edit: After a bit of experimentation, I think that the problem is that is\_object\_on\_button keeps returning to whatever value its assigned at the start: If I set it to true at the onready, it stays true. I do not know how to fix this, either.

# Answer
> 1 votes
## New Answer

The underlying reason of the problem is that the autoload (singleton) script is not the same on the scenario. When the player interacts with the instance on the scenario, the green door script interacts with the instance on autload (singleton).

There are a two solutions:

**Option one: Don't use an autoload.**

Now that green button has signals (as suggested in the original answer, *kept for reference*), you can connect them directly to the green door, or doors, in the scenario from the editor.

You would no longer need to connect those signals from code if you do it from the editor, of course.

Drawback: It can get complicated to connect all the signals for large scenarios.

---

**Option two: Use a signal bus.**

For those complicated large scenarios, there is a a common pattern in Godot: the signal bus.

To do it, you create a script and put in autoload (singleton), and that script will only defines signals. Nothing more. You would then emit those signals and connect them whenever you need them (knowing that being a singleton they are always available).

Let us say your singleton is called `SignalBus` (because, of course), and it has the signals `"button_down"` and `"button_up"` then in your green button code you can do this:

```
func _on_Green_Button_Area_body_entered(body):
    SignalBus.emit_signal("button_down")
    print("button is down")

func _on_Green_Button_Area_body_exited(body):
    SignalBus.emit_signal("button_up")
    print("button is up")

```

And in your green door code, you can connect to the `SignalBus`:

```
onready var door_collision = $CollisionPolygon2D

func _ready() -> void:
    SignalBus.connect("button_down", self, "_on_button_down")
    SignalBus.connect("button_up", self, "_on_button_up")

func _on_button_down():
    door_collision.set_disabled(true)
    print("unlocked")

func _on_button_up():
    door_collision.set_disabled(false)
    print("locked")

```

And that would be connecting all the green doors to all the green button via the signal bus.

---

## Original Answer

This line:

```
onready var is_object_on_button = Green_Button.is_object_on_button

```

Is making a copy of the value when the Node enters the scene tree for the first time (just before `_ready` would run). That value never changes. The other script does not access it, nor modifies it.

Vaillancourt's advice in comments is correct, you should use `Green_Button.is_object_on_button` directly:

```
func _process(delta):
    if Green_Button.is_object_on_button:
        door_collision.set_disabled(true)
        print("unlocked")
    else:
        door_collision.set_disabled(false)
        print("locked")

```

---

You might also be interested in using signal. You can declare signals in your singleton, for example:

```
signal button_down
signal button_up

func _on_Green_Button_Area_body_entered(body):
    emit_signal("button_down")
    print("button is down")

func _on_Green_Button_Area_body_exited(body):
    emit_signal("button_up")
    print("button is up")

```

Then - given it is a singleton - you can connect to those signals anywhere from code:

```
onready var door_collision = $CollisionPolygon2D

func _ready() -> void:
    Green_Button.connect("button_down", self, "_on_button_down")
    Green_Button.connect("button_up", self, "_on_button_up")

func _on_button_down():
    door_collision.set_disabled(true)
    print("unlocked")

func _on_button_up():
    door_collision.set_disabled(false)
    print("locked")

```

See Custom signals and Connecting signals in code.

---
Tags: godot, gdscript
---


# Question
Title: Storing 2D animation frames and sharing them between objects
I store 2D animation frames in some class. But the problem is that when I want to create multiple objects for example I want to spawn explosion or enemy

```
void ExampleScene::update()
{
    if (needToSpawnEnemy())
    {
        this->objects.add(Enemy());
    }
}

```

It means that everytime I want to spawn object I will need to access TextureHolder, pass string, get texture and load or compute animation frames and any other calculations that derivered object wants. It's not problem for example with player beacuse I load it on Scene::onCreate only once during entire game but with enemy I would do this during some update function.

My likewise simplifed implementation

```
struct Animation
{
public:
    void addFrame(Rect rect);
    //The rest of implementation
private:
    std::vector<Rect> frames;
}

class AnimatedSprite
{
public:
    void addAnimation(Animation& animation);
    //The rest of implementation
private:
    std::vector<Animation> m_animations;
}

```

How do I represent objects (this is gonna be very small project which will evolve later to ECS architecture but I think my problem will not change anyway so I want to solve it already)

```
struct Context
{
    TextureHolder textureHolder;
    //The rest of stuff...
}

class Object
{
public:
    //The rest of implementation
private:
    Context* context;
    AnimatedSprite sprite;
}

class Player : public Object { //implementation }
class Enemy : public Object { //implementation }

```

And how I add animation frames

```
void Enemy::onCreate()
{
    this->sprite.setTexture(this->context->textureHolder.getTexture("assets//graphics//enemy.jpg"));

    Animation walkAnimation;
    walkAnimation.addFrame({0, 0, 64, 64});
    walkAnimation.addFrame({64, 64, 64, 64}); //etc...
    //Surely it can be changed so frames will be loaded from file on disk

    this->sprite.addAnimation(walkAnimation)
}

```

Maybe NOW it's not very big problem unless I would get animation frames from file (which I want in future). So is there any gamedev standard / pattern / another aproach for this? I was thinking to store frames in dynamic memory and somehow share that data between objects of same class but I'm getting headache of thinking how I could manage that memory. (I don't see how smart pointers would help me beacuse there could not exist any Enemy objects for some time)

```
class AnimatedSprite
{
public:
    void setAnimation(Animation* animation)
    //The rest of implementation
private:
    AnimationState* animationState;
    AnimationFrames* animationFrames;
}

```

Should first object load everything but how do I delete it? I don't know if x enemy will be last one. Or maybe should I add some methods to Object class

```
virtual void Object::loadDataFromDisk();
virtual void Object::unloadDataFromDisk();

```

But it seems to be bit clumsy. I was also thinking to use my Context class to create somewhat AnimationHolder and use it like this-\>context-\>animationHolder.getAnimation("ENEMY\_WALK"); but I'm not sure about this.
Or maybe some prefab system? TLDR; To be precise my shorter question is how to avoid loading same 2D frames data (not textures) while spawning new objects.

So any help and ideas?

# Answer
I do not know if you have a Renderer class that can store global rendering objects like textures, fonts, shaders, materials, etc. The simplest implementation with what you have right now is to have your `AnimatedSprite` class be the owner for all your animations (i.e. the one class responsible for creating/deleting them) via: `static std::map<std::string, std::unique_ptr<AnimatedSprite>> s_registry` (or, if you want to be cache friendly: `static std::vector<std::pair<std::string, std::unique_ptr<AnimatedSprite>>>`), and the entities just need to store a pointer to one of them.

As for loading, I use a custom XML format that the Animated Sprite can use to parse during loading that will automatically add it to the registry. By generalizing the XML format you can have it just be part of an entity's own XML format, when that part gets parsed, the animation is loaded into the registry and a reference to the newly created animation is added to the entity.
> 0 votes

---
Tags: c++, animation, sfml, data
---


# Question
Title: How to best apply colliders on a rough 3D shape
I have a 3D model for a level in unity. I want to add colliders to it. What is the best type of collider for this model? And,it is 3D

# Answer
> 1 votes
There really is just one realistic option, and that's a Mesh Collider. Make sure you mark the object as "Static" and enable mesh cooking on your mesh collider in order to improve performance. The alternative would be to manually create a separate Box Collider for every single wall in the level, which would be a very tedious and error-prone task.

When your level is too complex for a mesh collider because you have lots of high-detail geometry in it, then it can make sense to go back to your 3d modeling program and create a simplified version of the level mesh which you then export separately and use as the mesh for the mesh collider.

---

Oh, and just by the way: Do you know Pro Builder? This optional package for Unity allows you to create and edit levels directly in the scene editor.

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


# Question
Title: how to reference a variable in an anothere script
i have a object which sets pickedup = true on collision

```
public class IDCARD : MonoBehaviour
    {
    private bool pickedup = false;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnCollisionEnter(Collision collision)
    {
       print("k");
        pickedup = true;
        Destroy(gameObject);
    }
}

```

now i want exit script in an another object to check if pickedup == true on collison ****now what can i do pls give a brief explanation with a names i have given****

i have written your code. but i think there is some issues

# Answer
first of all, you marked the variable "pickedup" as `private`. That means it's invisible for other scripts. When you want to access it from another script, you have to mark it as `public`:

```
 private bool pickedup = true;

```

(or alternatively, you could create a getter-method or a property to access the value of a private variable, but let's stay with the most simple solution for now)

Now, when you want to read that value from another script, you need to know two additional things:

* What game object you want to get the variable from. Remember that there can be many objects in the game which have the same script but with different values.
* What script on that game object contains the variable. Remember that a gameObject can have many scripts, and each of them can have a variable `pickedup` which means something different in the context of that script.

So assuming you have **another** script on **another** gameObject which is supposed to check **this** particular value on something it collided with, you would write it like this:

```
private void OnCollisionEnter(Collision collision)
{
    // Get the gameObject we collided with
    GameObject other = collision.gameObject;
    // Obtain the IDCARD component of that object
    IDCARD idcard = other.GetComponent<IDCARD>();
    // check if that object actually has an IDCARD component, otherwise you would get a NullReferenceException error
    if (idcard != null) {
        // now we can access the public variable of this script of this gameObject
        if (idcard.pickedup) {
            /*
            ...stuff...
            */
        }
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Are there ways to limit players other than a conventional currency system or a resource system?
I'm making a 2D strategy game. I want to create something unlike the current resource management type games I regularly see tagged as strategy.

My goals are:

* To force the player to think about their decisions
* To allow for experimentation easily and without sacrificing previous progress
* To allow for multiple ways of solving problems presented in the game
* To eliminate grinding simply because it won't work in whatever system I use

In effect, I want some way to limit the player and force them to make hard decisions, without using a commonly used currency or resource/crafting system, to cut down on grinding.

However, I'm actually having a little trouble implementing this sort of idea *alongside the idea of progression.*

My original idea was to introduce a cap on how many of each type of item a player could have at any one time. In effect, this introduces some elements of an open-ended puzzle game. However, this limits progression:

* If the number of items the player can have increases over time, this means that each individual item's significance decreases over time. This has the effect of making decisions easier over the course of the game. Not what I want.
* If the items get more powerful over time, then items acquired near the start of the game have no viability later on. I would like items to be at least partially viable at any stage of the game, to increase variety and make the game less linear. It turns the game into replacing old with new.
* Only increasing the variety of items over the course of the game is a sure-fire way to lose players early if they believe they are not making progress.

My implementation is workable, but simply not good enough for my personal standards and goals.

**Is there a better way to let limits, choice and progression go hand in hand?**

I use the word "item" here not just to refer to items in game, but other things such as spells, moves, buildings, etc. that a player could acquire and use in the game.

# Answer
# No

You can not limit a player other than through resources. This is due to the fact that in game design, everything that is limiting to a player **is** a resource.

* The cards on your hand in poker
* The pieces on the board in chess
* The cross (or circle) you can place in a game of tic tac toe
* A jump in a platformer video game (timing and jump height)
* Ammo in a shooter game
* Things that the game itself calls resources, like wood, gold, etc
* Time
* Attention

***The whole point* of a game is that players decide how to spend their resources.**

With that knowledge, take another look at those examples you didn't like and analyze them more deeply. For example, look at a specific resource:

* How does it limit the player?
* What is the game protected against by limiting the player like this?
* What exactly did you not like about handling the resource?

Based on that information you can then develop a more fun alternative.
> 24 votes

# Answer
Two resources many novice game designers tend to overlook are *time* and *attention*. The player can not do everything at once and can not be everywhere at once. So they need to prioritize which problems to take care of and which problems to ignore.

This is a major factor in real-time strategy, especially on a competitive level. There is a reason why the performance of competitive RTS players is often rated in "Actions Per Minute". A player with the mental and physical dexterity to perform lots of actions quickly can beat a player who is in a superior strategic position and has more access to "real" resources.

However, focusing your game on that aspect can lead to a very stressful and hectic game experience. There are players who enjoy that kind of gameplay, but it is not everyone's cup of tea. Nevertheless, there are ways to implement these aspects in a turn-based strategy game which is played at a more leisure pace.

*Time as a resource* can be implemented in turn-based strategy by putting a hard limit on the number of actions the player can perform each turn. So the player has to decide whether they want to spend their last action on ordering the construction of a new combat unit, to reassign their workers or assign a new research goal.

*Attention as a resource* can be implemented in a turn-based strategy game by giving the player an avatar in the game world. They can only perform actions within the vicinity of their avatar, and moving their avatar to another location takes one or more turns.
> 37 votes

# Answer
> My goals are:
>
> 1. To force the player to think about their decisions
> 2. To allow for experimentation easily and without sacrificing previous progress
> 3. To allow for multiple ways of solving problems presented in the game
> 4. To eliminate grinding simply because it won't work in whatever system I use

None of these scream out "you can't have resources or currency". I think your goals are good, but your implementation of them is either flawed or oversimplified.

> 1. To force the player to think about their decisions

Resource scarcity is one of the best tools you have to drive player decisions.

Do I go in this temple to see if there's treasure, at the risk of getting hurt? Do I spend resources or take risks rescuing these people so they can join my settlement? Do I spend my unobtainium on a few awesome weapons for a few of my soldiers, or on medium armor for all of my soldiers? Should my people face short-term starvation or take the risk of eating spoiled food?

> 2. To allow for experimentation easily and without sacrificing previous progress

This really depends on the game in question.

* Builder games tend to have a "blueprint" mode where you can design something without building it, specifically so that you can experiment with designs.
* You could have a sandbox mode where players can test out the things they have unlocked
* You could allow for free reimbursement (e.g. disassemble a crafted item with 100% resources returned) for a limited time
* Your game world could include a firing range where the player gets to use all manner of weapons they don't own, but they can't take the weapons with them
* ...

> 3. To allow for multiple ways of solving problems presented in the game

I don't see how this affects whether you have currency or resources in any meaningful way.

Money don't buy happiness, and currency don't buy unobtainium if no one has unobtainium to sell. Currency buys guns and defensive armatures, but currency won't stop the bullet from hitting your unprepared soldiers.

> 4. To eliminate grinding simply because it won't work in whatever system I use

Grinding is repeated manual labor. Automation is the antithesis of grinding. Let's take two factory games as an example.

Satisfactory has unlimited resources, but it has time-capped them. An iron node will always output e.g. 120 items/min, infinitely. It only costs electrical power. This also applies to coal nodes, and coal can be converted into power. Therefore, if I have coal miners, iron miners, and all the requisite machines, I can build an infinitely operating iron smelter. I never have to look at it again, and it generates iron products for me.

Factorio does things mostly the same way, but here resources are not infinite. They are plentiful before they deplete, but they eventually do deplete. Factorio has a very developed logistical system that they want you to use, so they incentivize you to eventually need resources that are further away, which gets you to use their transportation options. This is all by design to naturally drive gameplay towards the content they have created.

You can take lessons here that work for any game. Maybe the girl you saved from bears now brings you 5 breads every day, but yesterday's bread will spoil. This is an example of how you can have a resource, have a natural cap on it (5), and limit the player (refreshes every day), without needing them to grind (the girl bakes the bread for you).

---

> If the number of items the player can have increases over time, this means that each individual item's significance decreases over time. This has the effect of making decisions easier over the course of the game.

This is only true if the resource cost of things remains a constant across the game's lifetime. Most (if not all) games tend to increase costs as time goes on.

There's also the consideration of what a player will do with a larger stack of resources. You might incentivize them to e.g. run *two* factories as opposed to one, therefore naturally increasing their resource usage while also doubling their gameplay.

> If the items get more powerful over time, then items acquired near the start of the game have no viability later on.

This is hard to answer without specifics on your game, but there are cases where new resources *supplant* older resources, and cases where new resources simply *add more options*. If the new resources are exceedingly rarer, or they have their own set of drawbacks, then the player is urged to still use the older resources where possible, just so they don't overuse their rarer resources.

For example, crafting a dagger is the same whether you're using stone, iron, gold, or veryexpensivium. But these later resources are only found later in the game, and rarer. The player has the option to hunt for rare veryexpensivium and only craft veryexpensivium daggers to make money, or to just easily collect stone and make a ton of stone daggers.

Similarly, while a Greater Health Potion is obviously better than a Lesser Health Potion, it's significantly more expensive to craft and it has a much longer cooldown period for usage. Therefore, players are advised to still use LHPs when they only need to heal a little bit.

> Simply increasing the variety of items over the course of the game is a sure-fire way to lose players early if they believe they are not making progress.

I don't quite follow. How would a progression of resource acquisition make the players believe they are not progressing? Quite the opposite, no?

This is where vertical and horizontal progression start to become relevant considerations:

* Horizontal progression means **variety**. A shotgun is different from an assault rifle is different from a sniper rifle, but they all have pros and cons. Overall, they average out at the same quality.
* Vertical progression means **improvement**. A laser shotgun does more damage than a regular shotgun. It may be harder to come by, but if you have it, it's the superior choice.
    + Horizontally, a laser shotgun is different from a laser assault rifle is different from a laser sniper rifle, but they all have pros and cons. Overall, they average out at the same quality.

Not all players are created equally. Some like horizontal progression more (so they are on par with experience players in terms of equipment, just not player skill), others like vertical progression more (so they feel like they are improving their equipment and becoming more powerful).

Which kind of progression you implement highly depends on the kind of game you have, and how you expect players to interact.

* In PVP games, vertical progression deincentivizes new players, as they cannot beat experienced players. At best, you can make "ranks" so experts do not play against newcomers.
* In single-player (or single-player-focused) games centered around expansion, vertical progression incentivizes a player to keep player, as they increase their value and amass wealth/power.
* In games centered around short-term gameplay (think: roguelikes, sports games, fighters), vertical progression is not as important as horizontal progression. There's usually a bit of both, but predominantly more horizontal progression. I.e. you unlock new fighters rather than your fighter becoming stronger than the other available fighters.

Vertical progression is generally more incentivizing in terms of single player content, but it clashes with multiplayer content when dealing with players who started at a different time but wish to play against each other.

Horizontal progression doesn't incentivize over the long term, but it does create a replayability and creativity factor that works well for short games that are meant to be played often (as opposed to a single game that is played for a long stretch).

Overgeneralized:

* Vertical =\> Singleplayer, one long savegame.
* Horizontal =\> Multiplayer *or* short games with high replayability.

> Is there a way to limit players other than a currency system or a resource system?

You've glossed over time. Now, to be clear here, I'm not referring to "microtransaction energy" systems specifically, but I am referring to a time lock. Essentially, a cooldown system.

* Maybe your smith can only craft one item per day for you.
* Maybe you have infinite potions, but they are toxic and you can't chug them all (cfr the Witcher).
* Maybe you have infinite ammo in your bag, but reloading takes a long time.
* Maybe you have infinite ammo in your gun, but it overheats.

But the main takeaway here is that it's not how you limit the player that matters. What matters is **how the player can work with those limits**.
All of these limits need a way to *massage* them. Not for players to outright bypass them, but to adjust the limit based on some actions they take.

* Paying your smith +50% for each job makes him happier to do two jobs a day.
* There's a clearing potion that lowers toxicity, sort of like coating your stomach, possibly at the cost of a decreased potion effect.
* Upgrade your gun to improve loading speed (possible at the cost of e.g. smaller clips)
* The overheating mechanic could be impacted by local weather (tropical vs arctic), or what metal the gun was made from.

The best games present you with both an obstacle, and tools to (partially) overcome that obstacle, possibly at the cost of effort to set it up. The worst games set up arbitrary limits that have no in-universe justification and create no gameplay around dealing with that limit.
> 11 votes

# Answer
**Is there a better way to let limits, choice and progression go hand in hand?**

As always in game development there is rarely a better choice, but there are often different choices with different trade offs. One technique for forcing players to make hard choices frequently used alongside progression systems is creating ***mutually exclusive options*** sometimes this is done via an intermediate currency that is usually strictly limited in quantity (e.g. skill points, upgrade ores, item slots) so that in a given point in a game you can only have enough to acquire so many.

Sometimes a you can't or don't want to limit resources strongly enough to create natural mutually exclusive options, at that point you may ultimately need a hard lockout of other options. You can have the "Flaming Sword of +1 Awesome" or the "Wicked Axe of Massive Frost" but never both; owning one inherently prevents the player from ever getting the other. This can be implement in a variety of ways may helping one NPC annoys the other, or Flaming Sword and the Frost Axe woulc cancel each other out and can't coexist.

Hard lockouts forces a very hard decision for the player if the choices are well balanced, but beware those same hard choices can also be very stressful for the player and missing out on any given option that can make them feel like their first playthrough of game is incomplete.
> 6 votes

# Answer
You could limit the number of orders the player is allowed to give in a turn/60 seconds(Not sure if your game is real time).

If you include this option, together with a currency/resource system, the twist will be that when building you also need to consider how many other units you have, and if you can control them all. And defense will often require far more options then offensive operations.

And an even more fun twist would be, if you allowed the user to use an action\*, to group units together. That way you can move the the entire group with one movement. But if units are in a group, then you can ONLY move the entire group not a single unit within the group so that is the trade off. Extra bonus for having an option for creating formations in a group.

\*The ability to create a group could also be limited to a specific number, or require an officer in the group.
> 0 votes

# Answer
Thinking outside of the box... the other answers are already pretty good. But you asked for other ways to limit players, and here are some unconventional ideas that might inspire you:

1. Make players do physical things in the real world. Thus their physical limits will cause in-game limitations. You can make the things they are required to do be directly related to the role-play of the game, or they could be unrelated and silly, just for fun. Examples are all over the map, silly just for fun would include take a drink, run around the table, do a somersault, etc. If you have a time-based game, but you are required to also do 5 jumping jacks during their turn, or roll the dice three times instead of once and mathematically figure out the average or just the highest and/or lowest roll, it will mean that they are trying their best to complete the tasks quickly to not waste their time.
2. Give the players additional responsibilities that they have to perform at different times. Again, these could be related to the role-playing of the game, but they could also be somewhat random, depending on the nature of the game. The additional responsibility could distract them from their main task and make them have to choose between the two, or else just forget or not be able to do one of them (depending on the nature of the game-play). These additional tasks could be transferred to other players through game-play, or they could be assigned at the beginning or various stages of the game.
3. Make the game items cost real items in the real world. This doesn't have to be money, it could be other items or even services. I'm not thinking about any specific type of game here, just making a recommendation that this could be a game device.

Here's a silly example, say you use common rocks or flowers or blades of grass as game elements, if I am required on my turn or maybe on other people's turns to run outside and get a limited number of items, it limits my game-play, especially if it is decided that the items should be rare items. Or maybe Joe gets 3 blades of grass, Ann gets 1 blade of grass and 2 rocks, and Mary gets a feather on their turns. Even though there are 7 objects in total, the feather could be considered of higher value because there are the least of it. You could have mathematical rules about how much things are worth related to each other. So because there is only 1 feather, it is worth 10 times the next lowest item, which is worth 10 times the next lowest item, etc. So people would just be getting random objects and hoping to either have a bunch of something or else something really rare. Could be fun

4. Similarly to my silly example above, you could have predetermined items in the game that are used for certain things, but the value of them could change similarly to what I mentioned above. So if there are 3 itemA, 2 itemB and 6 itemC out on the board right now, then itemB is worth 100 times what itemC is, and itemA is worth 1/10 of that. But if later someone uses up an itemA somehow, suddenly the value of itemA is equal to itemB and itemC is also worth more because itemA and itemB are now tied in value at 10 times what itemC is worth. So this is a market value idea based on scarcity and abundance of resources.
> 0 votes

# Answer
The game Genshin Impact employs an interesting strategy with one of the available resources called *Original Resin*. This resource is required to obtain many desirable objects in the game.

A player can hold a maximum amount of this resource at any one time, but once it is spent, it slowly regenerates on its own (taking about a day to regenerate to maximum when fully depleted). This makes it valuable (since it is the only way to obtain many desirable items), but not scarce (since it replenishes automatically).

Those who want to put the time in can spend it daily and obtain items more quickly, while those who want to play more casually will still have some available to spend whenever they do choose to use it.

It seems like this type of resource might address some of the problems you're attempting to solve:

* It forces a player to think about their decisions, since their access to the resource is limited on any given day
* It allows for experimentation, because even if they make a poor decision and "waste" the resource, it will be available again for them to try the next day.
* It eliminates grinding since the player has no control over the rate at which the resource is obtained.
> 0 votes

# Answer
One way how to implement progression is to have enough variability to enable "player learning" and "player progression" instead of the game character.

Take as an example the Breath of the Wild. The character obtains all powers at the start of the game but how to use them and combine them he discovers during the game itself. This also gives the player great feeling of accomplishment (I can do that?).

Difficult part is to always offer multiple options how to approach a situation. In 2D strategy game it would mean a lot of various interactions or powers of units and structures. I can think of C&C Generals where you could break the game by using special abilities and combination of units - like soldiers with rockets shooting from a helicopter.
> 0 votes

---
Tags: game-design, game-mechanics, strategy
---


# Question
Title: LibGDX setToRotation canceling out position
I'm working on a 3d project in Libgdx. I've got a camera flying around in 3d space, being controlled with touch. Works great, moves forward and backward, strafes, full 360 look around with no gimbal lock.

But, I want my player to be able to see what they're holding. So I've added a "hands" model instance, which I'll change out depending on what is being held. I've positioned the model in front on the camera, which works fine.

But then whenever I try to call a `transform.setToRotation`, it sets the rotation, but moves the *position* back to 0,0,0. Does anyone know why this is happening? Here's my camera update code:

```
public void updateCamera()
{
    // left right look
    camDir.set(cam.direction);
    cam.rotate(cam.up , deltaX);

    // up down
    tempVec.set(camDir.crs(cam.up), deltaY);
    cam.rotate(tempVec);
    cam.update();

    // move forward
    cam.position.add(forwardTemp.set(cam.direction).scl(deltaForward));
    cam.update();

    // strafe
    strafeTemp.set(cam.direction);
    strafeTemp.rotate(cam.up, 90);
    cam.position.add(strafeTemp.scl(deltaStrafe));
    cam.update();

    // move tool hands to match
    handPos.set(cam.position);
    handPos.add(forwardTemp.set(cam.direction).scl(1.5f));
    handInst.transform.setToTranslation(handPos);

    handInst.transform.setToRotation(cam.direction, Vector3.X);
} // end updateCamera

```

# Answer
> 0 votes
If you look at the documentation for `setToRotation` you'll see this:

> public Matrix4 setToRotation(Vector3 v1, Vector3 v2)
>
> Set the matrix to a rotation matrix between two vectors.
>
> Parameters:
>
> * v1 - The base vector
> * v2 - The target vector

Note that this does *not* say "*adds* a rotation to an existing matrix while preserving its translation, scale, and shear." It says that it *sets* (replaces) the value of the variable with a *rotation matrix* (ie. a matrix that is pure rotation and nothing else).

So the method is doing exactly what it promised to do, you're just using the wrong method for the task you want to achieve.

It looks like you want something more like:

```
// Do this first so that we rotate around our local origin/pivot.
handInst.transform.setToRotation(cam.direction, Vector3.X);

// No "To" - we're folding a translation into the existing matrix.
handInst.transform.setTranslation(handPos);

```

---
Tags: libgdx, 3d, camera
---


# Question
Title: which is more performant particles_system or animation_player
let's say I wanna make an `Aura+Thunder effect` , I can achieve the result using the `Particles System` like this vid: https://www.youtube.com/watch?v=4eMZspcU5Is , or by using `AnimationPlayer` , but which is more performant if there will be like 15 instance of the `Aura+Thunder effect` \+ other effects?

# Answer
> 2 votes
At the end it is going to depend on whether or not GPU or CPU is the bottleneck. However, the options I describe below are *roughly* sorted by decreasing chance of being the most performant option (under the possibly wrong assumption that the GPU is more powerful, and thus the CPU is likely the bottleneck). *Which is not a replacement for testing, if you really want the most performant solution.*

By the way, it also turns out to be *roughly* sorted by increasing effort to do within Godot (under the possibly wrong assumption that you find it easier to move things in the editor than writing code, and thus writing code is likely more effort).

---

**`Particles`**

Using `Particles` is *likely* the most performant way to do it, and it turns out to be the easier to do within Godot. So start there.

The `Particles` node will animate the particles on the GPU. Because of that, If you can do the effect with `Particles` it is likely to be the most performant approach.

One drawback is that it is not supported on the GLES2 backend. So make sure it is supported in the target hardware.

Also, some features are only available for `CPUParticles`. Which is the next stop.

---

**`CPUParticles`**

Assuming you had your system set up with `Particles` and you need something only available for `CPUParticles`, you can convert them! There will be a "Particles" option in the editor when the `Particles` node is selected, and under it you find "Convert to CPUParticles".

Using `CPUParticles` will minimize render calls, but it will compute all the movement on the CPU. Which means, unlike `Particles`, `CPUParticles` eat CPU time. But it also means they have less limitations.

---

**Shader Material**

Let us say that `Particles` is not good enough, and you don't want the particles to run on the CPU. You can a shot at doing what they do: Set a shader material with a `MultiMesh` (to minimize render calls) and apply displacement in the vertex function to move the instances (`MultiMeshInstance`), so that all the movement is computed on the GPU.

By the way, just the fact that `MultiMesh` and `MultiMeshInstance` are nodes is overhead.

For randomness you can use a noise texture, for example. There is a `NoiseTexture` resource type you can use.

*Use `INSTANCE_ID` and `INSTANCE_CUSTOM` built-ins in the shader language to have it distinguish the different instances. Note: `INSTANCE_ID` is not available in GLES2.*

This will take advantage of the GPU for the particle animation… And it is, of course, more work to write the shader code. *However, consider this option before `AnimationPlayer`. By the way, this option may or may not be more performant than `CPUParticles` depending on your bottleneck.*

---

**`AnimationPlayer`**

Similarly to `CPUParticles`, `AnimationPlayer` will work on the CPU. Although, `AnimationPlayer` is arguably the most powerful option *-baring using an `AnimationTree`-* it has a couple significant drawback for this use case:

1. It is not made for randomness. Every time the animation plays, it is the same.
2. It is a lot of work to setup the animation of all the particles in the editor.

Thus, I would only suggest it if you can create the particle effect in another software and import it in such way that it comes up as an `AnimationPlayer`. And even then, it would be the same every time, and it is not taking full advantage of the GPU.

*By the way, animate `MultiMeshInstance` to minimize render calls.*

Furthermore, the power of `AnimationPlayer` come from the fact that it can control other nodes. For example you can use it to play sound on cue. *Heck, it can call methods!*. Thus, if you really need an `AnimationPlayer`, you can have it control the shader parameters of the aforementioned setup, so it is only in charge of the parts you can't do from the shader.

---

**Just move things from code**

The *likely to be* less performant option is to move things from the `_process`. This is not far from what `AnimationPlayer` does (except, you know, that is core code).

But hey, Turing *and Tetris* complete language! You can take advantage of `Tween` to do interpolations. You can query physic bodies for collisions, you can play sounds, you can write to file and send requests to the network.

You can create the nodes from code, including making all the setups previously mentioned. So you can have code that creates an `AnimationPlayer` and then plays it. Which is an opportunity to introduce randomness to the `AnimationPlayer`, and also you would be setting up all the particles from code (which you may or may not find easier to do).

I said `MultiMesh` and `MultiMeshInstance` being nodes is overhead. You may have a chance at cutting that overhead by talking to the `VisualServer` directly. *In fact, this is the approach some bullet hell games has taken due to performance (plus talking to the physics server). So there is still a chance this is the most performant way to do it, but you really got to put the effort.*

---
Tags: 3d, animation, godot, particles
---


# Question
Title: Get a Vector2 Based on Object Rotation in Unity
I feel like there is an obvious answer to this but I can't find it. Is there a function in unity that gives you a Vector2 (or 3) based on the rotation of an object.

for example:

z rotation = 0 ---\> (0,-1)
z rotation = 90 --\> (1,0)
z rotation = 180 -\> (0,1)
z rotation = 270 -\> (-1,0)

I could just write this in my script the long way, but I feel like there might be a function for it in unity

# Answer
If you have an object whose transform is already rotated the way you want on the z axis (and not rotated on the x and y), then this is as simple as:

```
Vector2 direction = -transform.up;

```

Otherwise, you can construct the rotation you want and rotate the "down" vector by it:

```
Vector2 RotationToVector(float degrees) {

    Quaternion rotation = Quaternion.Euler(0, 0, degrees);
    Vector2 v = rotation * Vector3.Down;

    return v;
}

```
> 2 votes

---
Tags: unity, c#, rotation, vector
---


# Question
Title: Ray-Triangle Intersection: does the direction of the triangle normal matter?
Found an article here about ray triangle intersection: https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution

It states that D of plane Ax+By+Cz+D = 0 can be found as triangleNormal.Dot(triangleVertex). But depending on the sign of the normal, D would have a different value. Doesn't that make a difference as to which side of the origin the plane lays? Doesn't the normal of the triangle always need to face the origin for this equation to be correct?

# Answer
Remember that A, B, and C come from the normal too. So negating the normal flips the sign of all four terms, making:

$$\begin{align} (-A) x + (- B) y + (- C) z + (- D) &= 0\\ (-1)(Ax + By + Cz + D) &= 0\\ (-1) \times (-1)(Ax + By + Cz + D) &= (-1) \times 0\\ Ax + By + Cz + D &= 0 \end{align}$$

So you can see, negating the normal still gives us an equivalent equation, with all the same solutions as the original. Whether we start with \\$\vec n = (A, B, C)\\$ or \\$\vec n = (-A, -B, -C)\\$ does not alter the plane equation in any way that matters.

The direction of the normal can matter for lighting, or whether you consider the triangle "front facing" for your purposes, but does not change anything about the math for detecting the intersection.

The resource you're using contains an error, though. if \\$ \vec n = (A, B, C)\\$ is the plane normal, then \\$D = - \vec n \cdot \vec p\\$ for a point \\$\vec p\\$ in the plane. The article you linked neglects that minus sign.

Another way of thinking of this: if your normal is a unit vector, then \\$D\\$ is a *signed distance* from the plane to the origin, along the direction of the normal. If the normal points toward the origin, this signed distance is measured in the same direction as the normal, and gives a positive value. If the normal points away from the origin, then this distance is measured in the direction opposite the normal, and gives a negative value.

Meanwhile, \\$Ax + By + Cz\\$ measures a signed distance from the origin to the plane perpendicular to \\$(A, B, C)\\$ containing the point \\$(x, y, z)\\$.

Since the "from" and "to" are flipped between these two parts, the two values will have the same magnitude but opposite sign for any \\$(x, y, z)\\$ on the plane, cancelling out to the zero on the right hand side.

(If the normal is not a unit vector, the same argument applies, except now we're dealing with a scaled distance - like we measured it with a different choice of units)
> 1 votes

---
Tags: mathematics
---


# Question
Title: Spawning random items to drop from the top of the screen
I'm wondering how to make specific random objects drop. In my case, from the top of the screen.

I have 16 objects, named `recycle_items_0` through `recycle_items_15`.

```
IEnumerator CreateRoutine()
{
    while (true)
    {
        yield return new WaitForSeconds(3);
        CreateItems0();
    }
}

private void CreateItems0()
{
   Vector3 pos = Camera.main.ViewportToWorldPoint(new Vector3(UnityEngine.Random.Range(0.0f,1.0f),1.1f,0));
   pos.z = 0.0f;
   Instantiate(recycle_items_0, pos, Quaternion.identity);
}

```

# Answer
Put your 16 items into an array, then select a random element of that array.

```
// Populate this array in the inspector.
public GameObject[] _prefabs;

private void CreateRandomItem()
{
   Vector3 pos = Camera.main.ViewportToWorldPoint(new Vector3(UnityEngine.Random.Range(0.0f,1.0f),1.1f,0));
   pos.z = 0.0f;

   var prefab = _prefabs[Random.Range(0, _prefabs.Length)];

   Instantiate(prefab, pos, Quaternion.identity);
}

```

Any time you find yourself appending a number to the end of a name, stop and ask yourself, "is this a place where I should use an Array, List, or other collection instead of individually-named variables?"
> 1 votes

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


# Question
Title: Removing ads but maintaining opt-in video ads
I have a game for iOS that will show advertisements.

One form of advertisement offered is a rewarded video (a video that the user can watch *by choice*). This is actually an important aspect of the game because watching these videos allows the user to continue playing after running out of a certain resource (balls, in this case).

Now, the user can remove the advertisements via In App Purchase.

**Question:** Is there anything wrong with keeping the rewarded videos as an option for the user, even though they paid to remove ads? If I disallow the rewarded videos, the user will lose a really useful feature of the game, but I'm worried about initializing the advertisement SDK and therefore tracking users who probably think they've disabled any tracking for advertisements.

Thank you for your thoughts!

# Answer
Players are smart. When they realize that reward ads are a valuable resource to them, then they will also realize that performing an in-app purchase which takes that resource away from them would be counter-productive. Which is one less reason for them to give you that money. On the other hand, when players make the "no advertising" purchase and the game *still* compels them to watch ads, they will feel rightfully cheated.

So how do you solve that problem?

**Implement that the benefit the players received by watching the advertisement is now obtained immediately by the press of a button.**

Do you think that's too easy? Then your reward ads themselves *also* made the game too easy. It's still the exact same mechanic, after all, just with less intentionally wasting of the players' time. When adding quality-of-life features makes your game too easy, then the difficulty they removed was just fake difficulty anyway.
> 1 votes

---
Tags: game-design, ios, advertisements
---


# Question
Title: Euler Angles of Any Great Circle from hit.point of a sphere
How do you get the Euler Angles of Euler Angles of Any Great Circle that surrounds the raycast hit.point of a sphere?

# Answer
I'm going to assume you're using Unity's coordinate system and Euler angle conventions. I'm also going to assume you have a "reference" great circle model as a child of the sphere, which in its default rotation (local Euler angles 0,0,0) lies along the equator of the sphere in the local XZ plane, with its pivot at the center. I'll assume you want a set of local Euler angles that rotate this child circle model to pass through a particular hit point on its parent.

If any of these assumptions are incorrect, then let this be a lesson to include those details in your question so we don't have to guess.

First we'll transform the hit point into the sphere's local coordinates and normalize it, to eliminate the influence of the parent's transformation.

```
var localHitDirection = sphere.transform.InverseTransformPoint(hit.point).normalized;

```

Now we can make our yaw and pitch angles by converting this point into spherical coordinates in the usual way.

```
float yaw = Mathf.Atan2(localHitDirection.x, localHitDirection.z) * Mathf.Rad2Deg;

float pitch = -Mathf.Asin(localHitDirection.y) * Mathf.Raf2Deg;

```

Using these two angles will ensure the point on the great circle at (0, 0, 1) rotates to lie along the line joining the sphere's center to the hit point.

Our roll angle is a degree of freedom you get to choose. Choosing any angle -180 to +180 will spin the great circle around this line, keeping it passing through the hit point on the rotation axis while the rest of the circle sweeps around the sphere.

Once you've chosen your roll angle, you can apply your rotation as:

```
greatCircle.transform.localEulerAngles = new Vector3(pitch, yaw, roll);

```
> 1 votes

---
Tags: mathematics, euler-angles
---


# Question
Title: How to rotate the transform only on the Y?
```
private Update()
{
    // Here the transform player should rotate facing the opposite direction.
    // Determine which direction to rotate towards
    Vector3 targetDirection = targetToRotateTo.position - transform.position;

    // The step size is equal to speed times frame time.
    float singleStep = rotationSpeed * Time.deltaTime;

    // Rotate the forward vector towards the target direction by one step
    Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);

    // Draw a ray pointing at our target in
    Debug.DrawRay(transform.position, newDirection, Color.red);

    // Calculate a rotation a step closer to the target and applies rotation to this object
    transform.rotation = Quaternion.LookRotation(newDirection);
}

```

# Answer
> 1 votes
If your object always remains upright (green vector always points up), then this is as simple as zeroing out the y component of your target direction.

```
Vector3 targetDirection = targetToRotateTo.position - transform.position;
targetDirection.y = 0f;

if (targetDirection != Vector3.zero) {
    float singleStep = rotationSpeed * Time.deltaTime;

    transform.rotation = Quaternion.RotateTowards(
                            transform.rotation,
                            Quaternion.LookRotation(targetDirection),
                            singleStep);
}

```

If your vertical axis might point in an arbitrary direction, then you can use the trick I've explained a few times in past Q&A:

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


# Question
Title: Rewarded ad showresult remain finished even after you reward the player
When the user dies in game and if they watch a rewarded ad video I give them 3 health. Here is the code:

```
using System.Collections;
using UnityEngine;
using UnityEngine.Advertisements;

public class adScript : MonoBehaviour, IUnityAdsListener
{

    public string gameId = "xxxx";
    string mySurfacingId = "Rewarded_Android";
    [SerializeField] private GameObject LoadingUI = null;
    public float waitTime = 3f;
    public bool testMode = true;
    public GameObject dead;
    public GameObject player;
    public GameObject blue;

    void Start()
    {
        // Initialize the Ads service:
        Advertisement.AddListener(this);
        Advertisement.Initialize(gameId, testMode);
    }

    public void ShowInterstitialAd()
    {
        if (Advertisement.IsReady())
        {
            Advertisement.Show("Interstitial_Android");
        }
        else
        {
            Debug.LogError("Error: Ad was not able to be loaded in " + waitTime + " seconds!");
            Debug.Log("Ad didnt loaded");
        }
    }

    //private IEnumerator ShowAd()
    //{
    //    float currentTime = 0.0f;

    //    LoadingUI.SetActive(true);

    //    while (currentTime <= waitTime && !Advertisement.IsReady())
    //    {
    //        currentTime += Time.unscaledDeltaTime;

    //        yield return null;
    //    }

    //    // show the ad if it is now ready
    //    if (Advertisement.IsReady())
    //    {
    //        Advertisement.Show("Interstitial_Android");
    //    }
    //    else
    //    {
    //        Debug.LogError("Error: Ad was not able to be loaded in " + waitTime + " seconds!");
    //        Debug.Log("Ad didnt loaded");
    //    }

    //    LoadingUI.SetActive(false);
    //}
    public void ShowRewardedVideo()
    {
        // Check if UnityAds ready before calling Show method:
        if (Advertisement.IsReady(mySurfacingId))
        {
            Advertisement.Show(mySurfacingId);
        }
        else
        {
            Debug.Log("Rewarded video is not ready at the moment! Please try again later!");
        }
    }

    // Implement IUnityAdsListener interface methods:
    public void OnUnityAdsDidFinish(string surfacingId, ShowResult showResult)
    {
        // Define conditional logic for each ad completion status:
        if (showResult == ShowResult.Finished)
        {
            showResult = 0;
            healthScript.healthValue += 3;
            respawn();
            player.SetActive(true);
            dead.SetActive(false);
        }
        else if (showResult == ShowResult.Skipped)
        {

        }
        else if (showResult == ShowResult.Failed)
        {
        }
    }

    public void OnUnityAdsReady(string surfacingId)
    {
        // If the ready Ad Unit or legacy Placement is rewarded, show the ad:
        if (surfacingId == mySurfacingId)
        {
            // Optional actions to take when theAd Unit or legacy Placement becomes ready (for example, enable the rewarded ads button)
        }
    }

    public void OnUnityAdsDidError(string message)
    {
        // Log the error.
    }

    public void OnUnityAdsDidStart(string surfacingId)
    {
        // Optional actions to take when the end-users triggers an ad.
    }

    // When the object that subscribes to ad events is destroyed, remove the listener:
    public void OnDestroy()
    {
        Advertisement.RemoveListener(this);
    }

    public void respawn()
    {

        Renderer rend = player.GetComponent<Renderer>();
        TrailRenderer rend2 = player.GetComponent<TrailRenderer>();
        Collider2D col = player.GetComponent<Collider2D>();

        gameObject.transform.position = new Vector3(0, 0, 0);

        rend.enabled = true;
        rend2.enabled = true;
        col.enabled = true;
        blue.SetActive(true);
        Time.timeScale = 1;
    }

}

```

In this code dead is for the deadMenu and screen is another menu for user to click on button to continue game.

Issue is the works fine. But when I pause the game after all this than the user gets the health bonus again because the `Debug.LogWarning("showsResult");` is finished again and the above code runs again.

How to tackle it?

# Answer
> 0 votes
What happens here is that you use the same code to run the Unity ads in two different ways, but don't tell Unity that they should not behave the same.

You say that you want `ShowInterstitialAd()` to just show an ad and move on, and `ShowRewardedVideo()` show an ad and reward the player when they're done consuming it.

There is nothing currently in your code that says this, you need to tell Unity about this. When you call `Advertisement.Show()`, Unity will check what to show, show it to the player and when they're done consuming the ad, Unity will you about it. It will send the parameter you passed to `Show()` to your `OnUnityAdsDidFinish()` implementation as the first parameter: you can then check what this parameter is and act upon it; in your case, since you show the advertisement you want rewarded like this `Advertisement.Show(mySurfacingId);`, you would need something like this in `OnUnityAdsDidFinish()`:

```
    public void OnUnityAdsDidFinish(string surfacingId, ShowResult showResult)
    {
        // Define conditional logic for each ad completion status:
        if (showResult == ShowResult.Finished && surfacingId == mySurfacingId)
        {
            showResult = 0;
            healthScript.healthValue += 3;
            respawn();
            player.SetActive(true);
            dead.SetActive(false);
        }
        else if (showResult == ShowResult.Skipped)
        {

        }
        else if (showResult == ShowResult.Failed)
        {
        }
    }

```

---
Tags: unity
---


# Question
Title: UnityEditor related classes can not be referenced. Why?
I have two classes. Both of them are placed in the `editor/interface_field` folder.

```
using System;
using UnityEngine;

namespace editor.interface_field
{
    public class RequiredInterfaceAttribute : PropertyAttribute
    {
        public readonly Type type;

        public RequiredInterfaceAttribute(Type type)
        {
            this.type = type;
        }
    }
}

```

```
    using UnityEditor;
    using UnityEngine;

    namespace editor.interface_field
    {
        [CustomPropertyDrawer(typeof(RequiredInterfaceAttribute))]
        public class RequireInterfaceDrawer : PropertyDrawer
        {
            public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
            {
                if(property.propertyType == SerializedPropertyType.ObjectReference)
                {
                    var requiredAttribute = this.attribute as RequiredInterfaceAttribute;

                    EditorGUI.BeginProperty(position, label, property);

                    property.objectReferenceValue =
                        EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.type, true);

                    EditorGUI.EndProperty();
                }
                else
                {
                    var previousColor = GUI.color;
                    GUI.color = Color.red;

                    EditorGUI.LabelField(position, label, new GUIContent("Property is not a reference type"));

                    GUI.color = previousColor;
                }
            }
        }
    }

```

I have another class.

```
using editor.interface_field;
using UnityEngine;

namespace interface_user.implementations
{
    public interface IInterface {}
    public class InterfaceUser : MonoBehaviour
    {
        [SerializeField]
        [RequiredInterface(typeof(IInterface))]
        UnityEngine.Object interfaceImplementation;
    }
}

```

The `[RequiredInterface(typeof(IInterface))]` line throws the following error:

> The type or namespace name 'RequiredInterfaceAttribute' could not be found (are you missing a using directive or an assembly reference?) \[Assembly-CSharp\]csharp(CS0246)

I can not understand why does not Unity see the `RequiredInterfaceAttribute` class and how could I make it see it.

# Answer
> 1 votes
So, as #DMGregory pointed out the classes inside the `editor` folder can not be referenced by classes outside of the `editor` folder. But the classes inside the `editor` folder can easily reference classes outside the `editor` folder. Given all that here is how I solved the issue.

I created a folder named `game_editor` and moved the `RequiredInterfaceAttribute` into it. Along the way I changed the namespace from the `editor.interface_field.RequiredInterfaceAttribute` to the `game_editor.interface_field.RequiredInterfaceAttribute` and added a respective `using` to the `RequireInterfaceDrawer`.

```
using UnityEditor;
using UnityEngine;
using game_editor.interface_field;

namespace editor.interface_field
{
    [CustomPropertyDrawer(typeof(RequiredInterfaceAttribute))]
    public class RequireInterfaceDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if(property.propertyType == SerializedPropertyType.ObjectReference)
            {
                var requiredAttribute = this.attribute as RequiredInterfaceAttribute;

                EditorGUI.BeginProperty(position, label, property);

                property.objectReferenceValue =
                    EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.type, true);

                EditorGUI.EndProperty();
            }
            else
            {
                var previousColor = GUI.color;
                GUI.color = Color.red;

                EditorGUI.LabelField(position, label, new GUIContent("Property is not a reference type"));

                GUI.color = previousColor;
            }
        }
    }
}

```

```
    using System;
    using UnityEngine;

    namespace game_editor.interface_field
    {
        public class RequiredInterfaceAttribute : PropertyAttribute
        {
            public readonly Type type;

            public RequiredInterfaceAttribute(Type type)
            {
                this.type = type;
            }
        }
    }

```

---
Tags: unity, editors, interface
---


# Question
Title: Reduce bounciness of dynamic bodies in Box2D
In my 2D platformer game my player character is modeled using a Box2D dynamic body. One thing I thought feels off though is that even though the restitution of the fixture applied is zero, the player will bounce off static geometry when falling at an angle, kind of like a plastic box would perhaps, but certainly not like a body would.

There isn't really much that Box2D allows me to tweak though except for density and restitution? I noticed that playing with the density has basically no effect on how the player moves which I thought was odd too.

Are there any realistic value ranges you would recommend? It's all a bit trial and error right now for me.

# Answer
Correct me if I'm wrong, but I believe the density of fixtures will affect the mass of the body.

Anyway, the only settings that affect the "bounciness" is restitution. If changing the restitution of the box doesn't fix it, have you tried changing the restitution of the ground (or whatever the box shouldn't be bouncing off of)?

If that doesn't work, as far as I'm aware the only other solution would be to listen for collision events and add forces to counteract the bouncing. I don't recommend this, as it can be buggy, but it's possible to get decent results depending on your needs.
> 1 votes

# Answer
I had the same issue and setting linear damping to a higher value solved it for me. This has the effect of reducing the velocity after a collision, see the Box2D Damping Documentation for details.
> 1 votes

---
Tags: box2d, physics
---


# Question
Title: Add 1 to a PlayerPref float if a day has passed in Unity 2D
I'm making a daily rewards system in my Unity 2D game. For each real-life day the user logs in (not necessarily consecutive) the player earns a Reward Point. Reward Points do two things:

1. Increase the rarity of what the player may obtain from Reward Chests.
2. Increase the frequency that a player may open a Reward Chest. The frequency starts at 24 hours, and for each Reward Point, it is decreased by 24 hours. (The frequency a player earns a Reward Point is *not* increased, just the frequency that the player can open a chest.)

I am asking how to check if a day has passed since the player last opened the game, and, if they have, add 1 to a PlayerPrefs float (this float contains the amount of Reward Points). I am familiar with Time, but I'm not sure how to accomplish my goal with it.

.

# Answer
> 0 votes
Note the concerns in the comments that data stored in PlayerPrefs is easy for players to modify, and checks based on local system time can easily be cheated by changing your system clock. If you don't mind this reward being cheated, that's fine - just be aware that it will happen.

If you want to make this harder to cheat, you can spin up a cheap server and database. Make a web request to the server to ask for the reward point value. The server will receive the request, and check this player's row in the database, updating it based on the server time, then send the result back. That puts the clock and storage outside the player's reach.

That said, if you're happy with a cheatable local version, you can do something a bit like this:

```
// Store the keys to read/write in PlayerPrefs as constants, so we don't make typos.
const string DAY_LAST_PLAYED_ID = "DayLastPlayed";
const string DAYS_PLAYED_ID = "DaysPlayed";

// Keep track of how many days we've played before today.
// Zero for the whole first day of play, one on the second, two on the third...
int _previousDaysPlayedCount;

// Helper method to decode a timestamp from a string we stored in PlayerPrefs.
bool TryReadDate(string text, out System.DateTime date) {
    return System.DateTime.TryParseExact(text, "O",
               System.Globalization.CultureInfo.InvariantCulture,
               System.Globalization.DateTimeStyles.RoundtripKind, out date);
}

// Helper method to encode a timestamp into PlayerPrefs,
// and save it to disc so it's not lost if we close unexpectedly.
void RecordPlayDay(System.DateTime date) {
    PlayerPrefs.SetString(DAY_LAST_PLAYED_ID,
                date.ToString("O", System.Globalization.CultureInfo.InvariantCulture));
    PlayerPrefs.Save();
}

// Call this function when your game starts up or regains focus,
// or at intervals during play to credit a day roll-over mid-session.
void UpdateDaysPlayed() {
    // Refresh our day played count from the stored value,
    // or use zero if this is our day and we haven't written it yet.
    _previousDaysPlayedCount = PlayerPrefs.GetInt(DAYS_PLAYED_ID, 0);

    var today = System.DateTime.Now.ToUniversalTime();

    // Get our saved timestamp from the last day we played, and try to parse it.
    var lastPlayString = PlayerPrefs.GetString(DAY_LAST_PLAYED_ID, "");
    System.DateTime lastPlayDate = default;

    if (string.IsNullOrWhiteSpace(lastPlayString)
        || !TryReadDate(lastPlayString, out lastPlayDate)) {
        // If we didn't have a valid date saved, then this is our first day.
        // Write that info as a starting point to compare to later.
        RecordPlayDay(today);
    } else {
        // If we do have a valid date saved from last time,
        // compare it to the current time. If the difference is at least
        // 24 hours, then we're playing on a new day.
        var difference = today - lastPlayDate;
        if (difference.TotalHours >= 24.0) {
            // It's a new day! Increment our count and save that information.
            _previousDaysPlayedCount++;
            PlayerPrefs.SetInt(DAYS_PLAYED_ID, _previousDaysPlayedCount);
            RecordPlayDay(today);
        }
    }
}

```

Note that we only update the saved timestamp when it's been a full 24 hours since our last timestamp. That way if you play frequent short sessions multiple times a day, you don't keep kicking the threshold forward without ever ticking it over.

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


# Question
Title: How do I know when the app is launched, loses focus and gets focus again on mobile?
I searched in Unity Documentation but there are no information. I'd like to know which methods is called and what it returns in the following scenarios on Android:

* App initially starts
* App goes in the background
* App is brought forward after being in the background

As for IOs I know that the scenarios should be the following:

* App initially starts:

OnApplicationFocus(true) is called
* App goes in the background:

OnApplicationFocus(false) is called

OnApplicationPause(true) is called
* App is brought forward after being in the background:

OnApplicationPause(false) is called

OnApplicationFocus(true) is called

# Answer
> 4 votes
The following snippet calls EnterApplication() and ExitApplication(), for you to implement yourself. It works in Editor, on Android, and on iOS, consistently. The methods are called when the application launches, backgrounds, resumes, and closes.

```
#if UNITY_IOS || UNITY_EDITOR
    private void OnApplicationFocus(bool focus)
    {
        if (focus)
        {
            EnterApplication();
        }
        else
        {
            ExitApplication();
        }
    }
#endif

#if UNITY_ANDROID || UNITY_EDITOR
    private void OnApplicationPause(bool pause)
    {
        if (pause)
        {
            ExitApplication();
        }
        else
        {
            EnterApplication();
        }
    }
#endif

```

If I remember right, in Editor, there is a minor inconsistency, although I cannot remember what. I wrote this code a while back, and thought it would be useful - although, I cannot exactly remember how it works.

# Answer
> 1 votes
In Android, there are **Activities**. When your app starts, some Activity is launched. You can get its state from few methods. In your case:

> onCreate() - activity is just created
>
> onPause() - another activity comes foreground
>
> onResume() - user returns to activity

You can check **Activity lifecycle** in this image:

Note that android apps can have more than one activity. So for example onPause() doesn't always mean app went to background, since another activity could be launched and the first one is paused.

Docs:
https://developer.android.com/reference/android/app/Activity.html

https://developer.android.com/training/basics/activity-lifecycle/index.html

# Answer
> 0 votes
Ok; I've never done Oculus development but I stumbled upon their Unity lifecycle documentation while researching the same question, figured I'd post it here as one more step towards solving the mystery. From there (see original page for full details; I'm intentionally filtering this down to standard Unity messages only):

> ## HMD unmount and mount with a delay
>
> When a user removes the HMD, then puts it back on at a later time (~10 seconds or more):
>
> * When HMD is removed
>     + ... after ~10 seconds: `OnApplicationPause(true)`
> * When HMD is replaced
>     + `OnApplicationPause(false)`
>
> ## HMD exits Guardian tracked space
>
> The user’s HMD exits the defined play area
>
> * `OnApplicationFocus(false)`
> * `OnApplicationPause(true)`
>
> HMD returns to play area
>
> * `OnApplicationFocus(true)`
> * `OnApplicationPause(false)`
> * ...
>
> ## Power button is pressed to turn off the display
>
> * `OnApplicationPause(true)`
>
> ## Power button is pressed to turn on the display
>
> * `OnApplicationPause(false)`
> * ...
>
> ## Oculus button is pressed to open the System UI
>
> * `OnApplicationFocus(false)`
> * `OnApplicationPause(true)`
>
> User selects “resume”
>
> * `OnApplicationFocus(true)`
> * `OnApplicationPause(false)`

Also, it might be worth noting that that page has an "Application Start" section that *doesn't* mention any of the standard messages, so I'm not sure if that's a documentation error or if focus / pause events just aren't sent initially:

> ## Application start
>
> When the application is initialized -
>
> * `HMDAcquired`
> * `HMDMounted`
> * `VrFocusAcquired`
> * `TrackingAcquired`

Both the Rift and the Quest have the same behavior, according to those docs. I do not, however, know if any of that is also covered by the new XR plugin system for AR/VR platforms.

Hopefully that helps.

---
Tags: unity, android, ios
---


# Question
Title: Why when increasing the speed it's getting to the max speed but in fact it's not the max speed ? why it's not getting to the value 1 but to 0.999999?
A bit long post but both scripts are connected and working together.

The speed is a parameter in Animator that moves between 0 and 1.

At this speed I'm using first the SlowDown function to slow down smooth the "Forward" to 0 then the transform is stopped.

Then I'm trying to speed up back the transform by increasing the "Forward" value from 0 to 1 :

```
if (startRotatingBack && turnBack)
                {
                    ThirdPersonUserControl.stop = false;

                    float target = 1.0f;
                    float delta = target - current;
                    delta *= Time.deltaTime;
                    current += delta;
                    playerAnimator.SetFloat("Forward", current);
                    currentSpeed = playerAnimator.GetFloat("Forward").ToString();
                }

```

I can see when increasing the "Forward" back to 1 that it's getting very close to 1 it's getting to the value 0.999999 I'm not sure why it's not getting to 1 but this is not the problem yet.

When it's getting to the value 0.999999 and the transform is moving now fast again it's still not moving as fast as before slowing it down to 0 before slow down to 0 it was moving much faster and now when increasing it back 1 or to 0.999999 it's not moving the same speed as before.

Not that it matters I think if the speed is 0.999999 or 1 but I wonder why it's not getting to 1 when increasing the "Forward" parameter.

To make it reach the speed as before I must pressing the W key the value is 0.999999 but only if I press the W key holding W it will reach then the speed as before at the start before slowing down.

using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityStandardAssets.Characters.ThirdPerson;

```
public class PlayerSpaceshipAreaColliding : MonoBehaviour
{
    public float rotationSpeed =250;
    public float movingSpeed;
    public float secondsToRotate;
    public GameObject uiSceneText;
    public TextMeshProUGUI textMeshProUGUI;
    public Transform targetToRotateTo;

    private float timeElapsed = 0;
    private float lerpDuration = 3;
    private float startValue = 1;
    private float endValue = 0;
    private float valueToLerp = 0;
    private Animator playerAnimator;
    private bool exitSpaceShipSurroundingArea = false;
    private bool slowd = true;
    private bool startRotatingBack = false;
    private bool displayText = true;
    private bool turnBack = true;

    public float damping = 10;
    private float current = 0.0f;
    public string currentSpeed;

    // Start is called before the first frame update
    void Start()
    {
        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (exitSpaceShipSurroundingArea)
        {
            if (slowd)
                SlowDown();

            if (playerAnimator.GetFloat("Forward") == 0)
            {
                slowd = false;

                if (displayText)
                {
                    uiSceneText.SetActive(true);

                    if (textMeshProUGUI.text != "")
                        textMeshProUGUI.text = "";

                    textMeshProUGUI.text = "I can see something very far in the distance, but it's too long to walk by foot.";
                    StartCoroutine(UITextWait());
                    displayText = false;
                }
            }

            if (startRotatingBack && turnBack)
            {
                ThirdPersonUserControl.stop = false;

                float target = 1.0f;
                float delta = target - current;
                delta *= Time.deltaTime;
                current += delta;
                playerAnimator.SetFloat("Forward", current);
                currentSpeed = playerAnimator.GetFloat("Forward").ToString();
            }
        }
    }

    IEnumerator UITextWait()
    {
        yield return new WaitForSeconds(5f);

        textMeshProUGUI.text = "";
        uiSceneText.SetActive(false);
        startRotatingBack = true;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            slowd = true;
            exitSpaceShipSurroundingArea = false;
            Debug.Log("Entered Spaceship Area !");
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            ThirdPersonUserControl.stop = true;
            exitSpaceShipSurroundingArea = true;
            Debug.Log("Exited Spaceship Area !");
        }
    }

    private void SlowDown()
    {
        if (timeElapsed < lerpDuration)
        {
            valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
            playerAnimator.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;
        }

        playerAnimator.SetFloat("Forward", valueToLerp);
        valueToLerp = 0;
    }
}

```

This script is where I'm using the keys for the movements including the W key as to move the transform forward faster :

```
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

namespace UnityStandardAssets.Characters.ThirdPerson
{
    [RequireComponent(typeof(ThirdPersonCharacter))]
    public class ThirdPersonUserControl : MonoBehaviour
    {
        private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object
        private Transform m_Cam;                  // A reference to the main camera in the scenes transform
        private Vector3 m_CamForward;             // The current forward direction of the camera
        private Vector3 m_Move;
        private bool m_Jump;                      // the world-relative desired move direction, calculated from the camForward and user input.

        public static bool stop = false;

        private void Start()
        {
            // get the transform of the main camera
            if (Camera.main != null)
            {
                m_Cam = Camera.main.transform;
            }
            else
            {
                Debug.LogWarning(
                    "Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
                // we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
            }

            // get the third person character ( this should never be null due to require component )
            m_Character = GetComponent<ThirdPersonCharacter>();
        }

        private void Update()
        {
            if (!m_Jump)
            {
                m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
            }
        }

        // Fixed update is called in sync with physics
        private void FixedUpdate()
        {
            if (stop == false)
            {
                // read inputs
                float h = CrossPlatformInputManager.GetAxis("Horizontal");
                float v = CrossPlatformInputManager.GetAxis("Vertical");
                bool crouch = Input.GetKey(KeyCode.C);

                // calculate move direction to pass to character
                if (m_Cam != null)
                {
                    // calculate camera relative direction to move:
                    m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
                    m_Move = v * m_CamForward + h * m_Cam.right;
                }
                else
                {
                    // we use world-relative directions in the case of no main camera
                    m_Move = v * Vector3.forward + h * Vector3.right;
                }
#if !MOBILE_INPUT
                // walk speed multiplier
                if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
#endif

                // pass all parameters to the character control script
                m_Character.Move(m_Move, crouch, m_Jump);
                m_Jump = false;
            }
        }
    }
}

```

# Answer
> 1 votes
Ask Zeno.

More seriously, you can plug your formulas into a spreadsheet to see for yourself:

As `current` gets closer to `target`, `delta` gets closer to zero (and multiplying by deltaTime makes it smaller still, but does not actually help make this calculation framerate independent). So you add less and less of an increment every frame, making slower and slower progress.

After 42 frames at 60 fps, you've made it halfway to the target, but after another 42 frames, you're still only 75% of the way there (you crossed only half of the remaining half), and another 42 frames later you're only 87.5% of the way there (you crossed only half of the remaining quarter).

If you keep taking these 42-frame steps, each covering only half the remaining distance, you'd need an infinite number of such steps to actually reach your destination - otherwise after a step of size x you'd always still have another x distance left to go. At least, that would be the case with unlimited-precision real numbers.

But computers don't have unlimited precision, so you hit an even harder wall. Single-precision floating point numbers have 23 bits of mantissa. That means that close to our target of 1.0, we can only represent numbers in increments of \\$2^{-23}\\$, or about 0.000 000 119 209.

If the increment we try to add to `current` is less than half that number, \\$2^{-24}\\$ or 0.000 000 059 604, then it doesn't take us far enough to round to the next representable number, and `current` stays the same after the addition - it's like we added zero. At that point, our progress stalls completely.

That happens by around frame 748, or about 12 seconds of running this code at 60 fps.

To avoid this problem, you can try using `Mathf.MoveTowards` instead, something like this:

```
const float secondsToMaxSpeed = 2f;
const float acceleration = 1f/secondsToMaxSpeed;

current = Mathf.MoveTowards(current, 1.0f, acceleration * Time.deltaTime);

```

This gives a linear increase in speed, instead of the exponential decay you had before, and will reach 1.0 exactly in the number of seconds you set. It's also correctly adjusted for the framerate, so you'll get consistent behaviour across different devices.

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


# Question
Title: RNG random numbers/preset payout rate contradiction
Taking a casino slot machine for example: How can the probability of a payout TRULY be random with a preset payout rate?

If a casino has slots programmed to a specific rate or percentage of payout, how can probability of winning by RNG generated slot symbols TRULY be “random” while simultaneously being pre set by the controller?

What am I missing - Does the preset payout rate not contradict the simple and fundamental premise of random winning?

The moment preset payout rates are programmed, fundamentally you lose all chance (pun intended) of generating anything random.

# Answer
> 3 votes
Consider that I can "program" a six-sided die to a payout rate of...

* 0%, by designating that no sides win
* 16.67%, by designating that only a 6 wins
* 33.33%, by designating that a 5 or higher wins
* 50.00%, by designating that a 4 or higher wins
* 66.67%, by designating that a 3 or higher wins
* 83.33%, by designating that a 2 or higher wins
* 100%, by designating that all sides win

Does that mean I've reduced the randomness of the die by deciding which sides I'll count as a win?

No. And yet I can mathematically show that the overall win rate will tend toward the number I chose over large numbers of trials.

Real games have many more internal states than just the six faces of a die, so the percentages can be tuned to much finer increments. But the core idea remains: given a source of randomness that can put the system into each one of these states with some known probability, we can compute the overall probability of winning (or the expected value paid to the player on average) by summing over the probability of each winning state (multiplied by its payout value).

The trick here is that the win rate is an *average* of a large population of samples. We can know a great deal about the overall behaviour of a stochastic system in the long term, when all the antics of the RNG are smeared together over millions of runs, even if we can say nothing about how the next roll of the die will fall.

Of course, the exact degree of unpredictability depends on the quality of our source of randomness. But even with an RNG source as pure as radioactive decay, we can still reason precisely about the long-term rates of particular occurrences, despite the randomness of each sequential outcome.

It's sometimes misunderstood that this means probability itself has some kind of memory or agency. That if a coin comes up tails "too many" times, Lady Luck will notice and start tipping the scales in favour of heads in order to balance it out and hit her 50% target. This is known as the Gambler's Fallacy. If this were true, then it really would make things "less random". If we'd observed a number of tails flips in the past, we could use that to make better predictions that the next flip might come up heads.

But that's not what happens. It's not unusual, for instance, for difference between the number of observations of some event and its expected number of occurrences according to the probability to actually grow over time, rather than shrink back to zero. So how do the overall rates still approach the theoretical calculations anyway, even if one event doesn't "catch up"? It's the growth of the denominator that does it:

* 9 heads out of 20 flips is 1 behind what we'd expect, for a 10% error.
* 95 heads out of 200 is 5 behind what we'd expect (5x more), for only a 5% error (half as much)
* 975 heads out of 2000 is 25 behind what we'd expect (5x more again), for only a 2.5% error (half again)

This is how we can get more and more confident about the range of the overall results we expect to see over an interval as we increase the number of trials, even without any ability to predict the result of a particular trial.

---
Tags: mathematics, random, probability
---


# Question
Title: What server architecture should I use for matchmaking in Node.js?
I'm making a board game in which users register for a game which will start at fixed time and users can register till the start of the game. My initial idea was to use it with socket.io(connection sets up when user opens up the app and use same socket for gameplay) with Redis adapter and fire start game event from outside the context of sockets (using redis adapter and separate process). But my friend suggested to use ws with in-memory state management(for making stateless and not use socket.io for performance) and use polling for showing registering tournaments. Can you please help me with if I'm missing out anything ?

# Answer
> 2 votes
There are several options to use. I'll go through some of them here.

## Stateless vs Stateful

### Stateless server

Stateless servers do not hold any state by themselves. When an event happens (a request or a message from network arrives) the server fetches data from a database using data from the event (player ID, message ID, etc), processes the request and then possibly sends a response.

The state is not stored primarily in the server's memory and will not be lost if the server is rebooted. This allows easy scaling for multiple users as all the data is stored elsewhere and can be fetched by any server instance.

Fetching the data every time from a database adds delays and is not in general well-suited for fast-paced real-time games. But it works really well for game lobby features such as matchmaking and user management. This delay can be reduced a little bit by using a common cache server like Redis.

### Stateful server

This type of server manages the state by itself in the server's own memory. For example it may hold the current game state which is lost if the server is rebooted, unless the server is allowed to gracefully quit and save it's state to disk or database.

Scaling up for more concurrent users who need to interact with each other is harder as it would require the servers to transfer data between each other through P2P or a database or other means. In general this approach supports best serving a small group of users that need to interact with each other.

As stateful server stores the data in it's memory, it is well-suited for fast-paced gameplay with relatively short sessions. These types of servers are also often started up and shut down on demand as the amount of total players in the game requires.

### Redis

Redis is a database that can be used for in-memory caching before fetching from the actual database. It does save data to disk periodically, but it is not guaranteed to keep the data safe. If you want to keep data safe, something else is recommended as a database. For short-term usage this is a great database.

### SQL/NoSQL database

These types of databases are great for storing data long-term and are used for stateless server databases. However fetching data from these databases adds delay to processing requests or events.

## Different ways to transfer data

### REST API

This works with HTTP(s) protocol and your client makes a HTTP request to your server every time data is transferred. In general you have to poll to fetch data with this method. Because you need to poll data from the server, this is not well suited for real-time gameplay. If your game can tolerate a delay of second or two, then this approach may work for you.

### Websockets

These work almost just like TCP sockets. You create a connection to a server and that connection is kept alive until your client ends the session. In general WebSockets use event-based communications and either of the connected ends can send data at any point through the socket, no polling is required. This supports real-time applications really well, but because they use TCP under the hood they are not best suited for a very fast-paced gameplay (like a FPS game, Counter-Strike for example). If your game can tolerate a delay of hundreds of ms then this approach may work for you.

### TCP Sockets

Almost the same as Websockets, but you need to implement certain stuff yourself, like keepalive. Websocket uses TCP under the hood. I would recommend this over Websocket only if you really know you need it.

TCP makes sure your network packets arrive to the destination and in correct order. This means, if there is a hiccup in the network somewhere between you and the other end, there may be significant delays.

### UDP Sockets

UDP sockets are "connectionless" sockets and you need to handle a lot of things yourself, but this allows even faster message processing. UDP packets are not kept in order and they may arrive to the destination in different order than how they were sent if they arrive at all. This works really well for applications that require very small delays, like very fast-paced shooter games.

## Useful libraries

* Express is a great tool to serve REST API requests with Node.js
* Websocket package in npm works well for Node.js
* Protobuf is really good layer for managing and serializing your messages with sockets (Websocket, TCP, UDP) if you are not able to share code between the client and the server
* BSON is like "binary JSON" which you can use to serialize your data and send them over the network in efficient manner with sockets

## Your use-case

This really depends up on your own requirements which you did not really specify that much other than the game being a board game, but for what I can gather from your question I would use websockets along with a combination of two different servers, one to act as a lobby for matchmaking, and then another for the gameplay. Both servers could use stateless approach and websockets, and they can be combined in to one server if you prefer to do so.

Personally I have not used Socket.io and I have no clue what are the performance implications of that. But from a quick look at it I see it takes equal amount of effort to set up websockets, which allows you to design your own protocol (with BSON for example) or to use Protobuf for data transfers.

I hope this answers at least some of your not very specific questions.

---
Tags: architecture, matchmaking
---


# Question
Title: How to check if a line casted from one point to another point passes through a mesh?
Let's say we have two vectors A and B. Is there a way to use Three.js' Ray or Raycaster classes to cast a line between vector A and vector B and check is it passes through a mesh in the scene? I know from the documentation that both the Ray and Raycaster classes accept origin and direction vectors but I specifically need two points. Thanks in advance.

# Answer
As @DMGregory answered in the comment it can be done this way:

const a = new Vector3(xa, ya, za);
const b = new Vector3(xb, yb, zb);

const c = b.clone().sub(a);
const far = c.length();

const raycaster = new Raycaster(b, c.normalize(), 0, far);
const intersections = raycaster.intersectObjects(scene);
```

> 1 votes

---
Tags: 3d, javascript, linear-algebra, three.js
---


# Question
Title: How can I increase the spawn rate and speed after some time?
I'm working on a *Super Hexagon*-like game and the goal is to survive as long as possible. The game is working fine but I want to add a new feature that increases the spawn rate of the obstacles and also beside that, I want to increase the player speed. For example, let's say I want to change the spawn rate to 2 if the player survives 1 minute or change the player speed to 610 after lasting 50 seconds. But the point is that the player should play that 1 minute (or 50 seconds) without dying in order for values to be changed and if he dies in that time, then the values won't change and the timer will be reset. I don't know how I can implement this but I guess I should use coroutines. Any help would be appreciated.

Player script:

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

public class Player : MonoBehaviour
{
    public float moveSpeed = 600f;
    float movement = 0f;

    void Update()
    {
        movement = Input.GetAxisRaw("Horizontal");
    }

    void FixedUpdate()
    {
        transform.RotateAround(Vector3.zero, Vector3.forward, movement * Time.fixedDeltaTime * -moveSpeed);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        SoundManager.playSound();
    }

}

```

Spawner script:

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

public class Spawner : MonoBehaviour
{
    public float spawnRate = 1f;

    public GameObject hexagonPrefab;

    private float nextTimeToSpawn = 0f;

    // Update is called once per frame
    void Update()
    {
        if (Time.time >= nextTimeToSpawn)
        {
            Instantiate(hexagonPrefab, Vector3.zero, Quaternion.identity);
            nextTimeToSpawn = Time.time + 1f / spawnRate;
        }
    }
}

```

The game looks like this. When the spawn rate increases, the obstacles duplicate faster.

# Answer
> 1 votes
One convenient way to define changes in variables over time is using the AnimationCurve class. This creates a curve you can edit in the inspector, freely adjusting the value the variable should have at each moment in time, and how it should ramp up/down or jump between those keyframes.

Since you need to access the duration of the current life from multiple different places, let's make one separate script whose job it is to track that:

```
public class LifeTime : MonoBehaviour {

    public float TimeAlive { get; private set; }

    void FixedUpdate() {
        TimeAlive += Time.deltaTime;
    }

    // In case you ever want to start a new life without re-loading the scene from scratch.
    public void DieAndRespawn() {
        TimeAlive = 0f;
    }
}

```

Then your other scripts can hold a reference to this one, and ask it for the time value to use. We'll pass this time value into the animation curve to get the speed or spawn rate value we should be using in this moment.

```
public class Player : MonoBehaviour
{
    public float moveSpeed = 600f;
    public AnimationCurve moveSpeedOverTime;
    public LifeTime life;

    void FixedUpdate()
    {
        float speed = moveSpeed * moveSpeedOverTime.Evaluate(life.TimeAlive);
        float movement = Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;

        transform.RotateAround(Vector3.zero, Vector3.back, movement);
    }

    // etc...
}

```

You can make a similar adjustment to your spawner script.

If assigning a reference to the `LifeTime` instance in both classes is too fussy (maybe you destroy and respawn your `Player` instance), then you can instead use a Singleton pattern so they can access it via a static reference.

The advantage of doing it this way is that you don't need to complicate your code every time you want to change the difficulty progression of the game. The ramp-up rates can all live in the curve data. You can even have multiple scenes or prefabs with different curves to use for different game modes or difficulty settings, all sharing exactly the same code.

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