# Question
Title: Use Buttons based on Key Presses instead of Mouse Click
I have a UI button. I want a function to be called whenever I press a specific key on my keyboard while my mouse is hovering over the button. I want to make something similar to UI in Ark SE where you can press 'T' while hovering over an item in your inventory to transfer it.

The button component `OnClick()` has not received keypress input, only mouse clicks.

I am using the **New Unity Input System**

I have tried using a `Raycast` from `ScreenPointToRay` however this did not work as I do not have colliders on my UI and it is part of a `Canvas`.

# Answer
> 1 votes
I found a solution. I don't think it would be the best but it works for now. With the new input system I subscribe A function (OnTransferKey) to a Key Press

```
void OnEnable() {
    uI_Manager.uIInputManager.Inventory.OnTransfer.performed += OnTransferKey;
}

void OnDisable() {
    uI_Manager.uIInputManager.Inventory.OnTransfer.performed -= OnTransferKey;
}

```

In the OnTransferKey function I check if the mouse is hovering over the gameObject

```
    bool MouseOverSelf() {
    return EventSystem.current.IsPointerOverGameObject();
}

void OnTransferKey(InputAction.CallbackContext obj) {

    if (MouseOverSelf()) {
        print("Do Transfer");
    }
}

```

This works for me for now. Remember to add `using UnityEngine.EventSystems;`

# Answer
> 0 votes
I don't know much about the New Unity Input System, but you don't need colliders on your UI objects to raycast them, you just need a Graphic Raycaster component on the canvas, then make sure that the things you want to raycast have the "Raycast Target" box checked like so:

And then the scripting info you need is here in Unity's docs. That should be all you need let me know if I can help anymore.

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


# Question
Title: Get speed from vector using box2d and javascript
I need to find the speed of an object in a game. The game is made in HTML5 with jquery and jquery.box2d. For this I can use these methods:

```
 GetLinearVelocity().x;
 GetLinearVelocity().y;

```

I'm then trying to calculate the speed from this piece of code, but get some values that doesn't make sense when I console.log it. This is my code:

```
 var heroVelX = game.currentHero.GetLinearVelocity().x;
 var heroVelY = game.currentHero.GetLinearVelocity().y;

 var speed = Math.sqrt(heroVelX^2 + heroVelY^2);
 console.log(speed);

```

Some of the values in console.log are numbers, but most of them are NaN (Not-A-Number), which confuses me? Can someone help me solve this?

The goal I want to achieve, is to see when the speed(of object .currenHero) drop below a certain value, so I can excute a new state in the game.

# Answer
> 2 votes
Try this:

```
var speed = Math.sqrt(Math.pow(heroVelX, 2) + Math.pow(heroVelY, 2));

```

The case is that the **^** operator is the bitwise **XOR** operator. You should use *Math.pow(base, exponent)*.

Here is a an example: link.

# Answer
> 0 votes
You could use `Math.hypot()` for the magnitude of a right-angled triangle:

```
const speed = Math.hypot(heroVelX, heroVelY);

```

---
Tags: javascript, box2d, html5, jquery
---


title: When does a "frame" start and end?

text:
# Question
Title: When does a "frame" start and end?
Here is the main loop that I currently have (and it does work perfectly):

```
// in another header:

...
using i64u = unsigned long long;

...

// mainloop:
i64u lastTime = static_cast<const i64u>(SDL_GetPerformanceCounter());
double accumulator = 0.0;

double t = 0.0;
double dt = 1.0 / 30.0;

SDL_Event e;

while (IsRunning())
{
    bool bRet;

    bRet = SDL_PollEvent(&e) == SDL_TRUE;
    if (bRet)
    {
        if (SDL::ProcessMessages(e))
        {
        }
        else
        {
            IsRunning() = false;
            break;
        }
    }
    else
    {
    }

    bool render = false;

    const i64u now = static_cast<const i64u>(SDL_GetPerformanceCounter());
    const double frameTime = static_cast<const double>((now - lastTime) * 1000) / SDL_GetPerformanceFrequency();

    accumulator += (frameTime / 1000);

    while (accumulator >= dt)
    {
        if (bRet)
        {
            if (this->Game().Get()->InputDevice().Get()->ProcessMessages(e))
            {
            }
            else
            {
            }
        }
        else
        {
        }

        // side-note: should OnUpdate go here?
        // or remain outside of this loop and keep passing "frameTime"?

        t += dt;
        accumulator -= dt;

        render = true;
    }

    this->Game().Get()->OnUpdate(frameTime);

    lastTime = now;

    if (render == true)
    {
    }
    else
    {
    }

    this->Game().Get()->OnDraw();

    SDL::SwapWindow();
}

...
bool& <App>::IsRunning()
{
    return m_Running;
}

const bool <App>::IsRunning() const
{
    return m_Running;
}

```

My question is: How should (or rather, how does it normally tend to be implemented) a frame be determined?

For example, should `lastTime` be set after the `OnDraw()`, or should it be set before `OnDraw()` but AFTER the the logic and input has been determined (after `OnUpdate()`)?

What truly constitutes "a frame"? In my mind, a frame would constitute as "everything being prepared in order to be drawn", which I think of as "get the input, calculate physics and other game logic data, and then once that "frame" is finished, draw the "frame" - though I'm not really sure how this is (or might) done in the real world.

Is there even "a right or wrong way" when implementing this kind of loop? I would imagine so.

What would y'all recommend?

(Also, ignore the trailing `if` statements; that's some stuff to help me keep track of what's going on.)

# Answer
Assuming that you want to measure how long it takes to do one iteration of your game loop: It doesn't really matter at which point of your game loop you measure performance. All that matters is that you accurately measure the time it took since the last execution of that line of code:

```
 now = TheMostAccurateTimeFunctionYouCanFind();
 secondsPerFrame = now - last;
 last = now;

```

This gives you a measurement of how long the last iteration of your game loop took. Take the inverse, and you got the infamous Frames Per Second number the players like to obsess about so much: The number of different pictures being displayed on the screen during one second of wall-clock time.

This is also the number you need as a delta-time value if your game uses a variable time-step (as yours seem to do, implied by you passing the `frameTime` to `OnUpdate`). The real-world time marches on regardless of if your game is busy with rendering or busy with updating. So both account for the time it took since the last update.
> 1 votes

# Answer
> In my mind, a frame would constitute as "everything being prepared in order to be drawn", which I think of as "get the input, calculate physics and other game logic data, and then once that "frame" is finished, draw the "frame"

This sounds like a sensible definition. As long as you're consistent with this definition, and all parts of your game are written in agreement with this shared convention, you should be in good shape.
> 0 votes

---
Tags: opengl, c++, game-loop
---


# Question
Title: How do I create an event trigger system for a Discord bot?
I am making a card game and I am having issues implementing "effects" and effects that are continuous.

How can I get effects to activate at the right times, before and after an attack does damage as well as apply a continuous effect through out each phase? Is there a way I can implement some sort of checklist system before and after attack?

I've tried 5 times with this, and this is just my latest attempt, How can I coded this system without making `if`-code mess. Any tips or help, would be greatly appreciate it! (as this is my first time making a trading card game.)

For context I am making this into a Discord bot!

What I need help with:

* A System where I can check effects before, during and after attack
* A system where I continuous effects are applied before during or after an attack
* Applying the effect to the right target or to both targets

```
#while both players have health
# apply CONTINUOUS EFFECTS THROUGH OUT LOOP
while player1.hp > 0 and player2.hp > 0:
            print("test battle in progress")
            #class Card(object):
              #def __init__(self, name, hp, cardType, effect, attacks, description, ability):

            # Instantiate test subjects
            player1 = Card("Pinata Trent", 9, "Strong", None,
                       [Attack("Trample", 24, 2, None, None, None),
                        Attack("Body Bash", 62, 4, "selfDamage", 2, "self")],
                       "Trent card", None)

            player2 = Card("Barbarian", 10, "Strong", None,
                       [Attack("Head Bang", 68, 1, "selfDamage", 1, "self"),
                        Attack("Barbaric Swing ", 82, 2, None, None, None)],
                       None, None)

            #randomly choose a move for both NPC
            player1_move = random.choice(player1.attacks)
            player2_move = random.choice(player2.attacks)

            # Who ever player has the fastest attack value attacks first
            first_attack = firstAttack(player1_move, player2_move)

            if first_attack == 1:
                print("player 1 attacks first")
                await apply_damage(player2, player1_move)

                # Apply effect of attack after or before attack
                if player1_move.effect is not None:
                    print("player 1 attack effect activates")
                    player1 = player1.attack_effect(player1_move.effect, player1, player1_move.effectDamage)
                print(str(player1.hp) + " // " + str(player2.hp))

                # Player 2 attacks!
                if player2.hp > 0:

                    player1.hp -= player2_move.damage
                    if player2_move.effect is not None:
                        print("player 2 attack effect activates")
                    player2 = player2.attack_effect(player2_move.effect, player2, player2_move.effectDamage)
                print(str(player1.hp) + " // " + str(player2.hp))
                await asyncio.sleep(2)

            elif first_attack == 2 and player2.hp > 0:
                print("player 2 attacks first")
                player1.hp -= player2_move.damage
                if player2_move.effect is not None:
                    print("player 2 attack effect activates")
                    player2 = player2.attack_effect(player2_move.effect, player2, player2_move.effectDamage)
                print(str(player1.hp) + " // " + str(player2.hp))

                # Player 1 attacks!
                if player1.hp > 0:
                    player2.hp -= player1_move.damage
                    if player1_move.effect is not None:
                        print("player 1 attack effect activates")
                        player1 = player1.attack_effect(player1_move.effect, player1, player1_move.effectDamage)
                print(str(player1.hp) + " // " + str(player2.hp))
                await asyncio.sleep(2)

```

attack move class:

```
class Attack:
    def __init__(self, name, speed, damage, effect, effectDamage, target):
        self.name = name
        self.speed = speed
        self.damage = damage
        self.effect = effect
        self.effectDamage = effectDamage
        self.target = target

    def attack_effect(self, tag, target, x):
        """
        todo: card attack effects
        """

        if tag == "selfDamage":
            target.hp -= x
            return target

        if tag == "forEachDamageMoreDamage":
            totalDamageTaken = target.starting_health - target.hp
            for i in target.attacks():
                if i.effect == "forEachDamageMoreDamage":
                    i.damage += totalDamageTaken
            return target

```

card class itself

```
class Card(object):
    def __init__(self, name, hp, cardType, effect, attacks, description, ability):
        self.name = name
        self.hp = hp
        self.starting_health = hp
        self.type = cardType
        self.attacks = attacks
        self.original_attacks = attacks
        self.effect = effect
        self.description = description

```

attack speed calculation

```
        def first_attack(player_atk_speed, opponent_atk_speed):
            if player_atk_speed.speed > opponent_atk_speed.speed:
                return 1
            elif player_atk_speed.speed < opponent_atk_speed.speed:
                return 2
            else:
                # decides who attacks based on random generation if attack speeds are EQUAL
                return random.randint(1, 2)

```

# Answer
> 1 votes
solved it, i made a method that i call for both players, and give it a tag that says when to activate, the method "Attack\_effect\_checker" will only do something if the attack itself has that same exact tag, "preAttack" or "postAttack"

```
    print(" -- pre damage phase --")

    # pre damage
    # player1 predamage check
    player_array = attack_effect_checker(player_array, 0, player_array[0].attacks[0], player_array[0].attacks[0].tag,
                                         "preAttack")
    # player2 predamage check
    player_array = attack_effect_checker(player_array, 1, player_array[1].attacks[0], player_array[1].attacks[0].tag,
                                         "preAttack")
    # post damage, after a player attacks, post attack effects trigger AND/OR continuous effects trigger
    print(" -- attack phase --")
    # player 2 attacks
    player_array[0].hp -= player_array[1].attacks[0].damage
    player_array = attack_effect_checker(player_array, 1, player_array[1].attacks[0], player_array[1].attacks[0].tag,
                                         "postAttack")
    # player 1 attacks
    player_array[1].hp -= apply_damage(player_array[1], player_array[0].attacks[0].damage)
    player_array = attack_effect_checker(player_array, 0, player_array[0].attacks[0], player_array[0].attacks[0].tag,
                                         "postAttack")

```

and attacks that have a "continuous" effect will apply during BOTH phases/turns

```
if selected_attack.trigger == phase or selected_attack.trigger == "continuous":
        if both_players[player_int].attacks[0].target == "self":
            both_players[player_int] = tag_apply(both_players[player_int], tag, selected_attack.effect_var, phase)
        elif both_players[player_int].attacks[0].target == "opponent":
            # if player_int 1 then select 0, elif 0 select 1, basically the opponent
            both_players[int(not player_int)] = tag_apply(both_players[int(not player_int)], tag,
                                                          selected_attack.effect_var, phase)
        else:
            print(" You really tried to target both of us huh")

```

---
Tags: algorithm, game-mechanics, python, gameobject
---


# Question
Title: Optimal implementation for effects in a card game
I am working on a card game in Unity and want to implement a system where I can create card effects that happen when certain events are triggered.

The events could be anything from when a card is played or destroyed, to more complex events like buying and playing 3 cards in the same turn, for example. Similarly, the effects could be any number of things, from draw a card, to deal damage to all enemy units of a specified type.

The strategy I am currently considering is to have an event queue, and whenever anything happens, push an event object containing data about what just happened to the queue. Then, create a data structure to store a pointer to an Event class, which has a method that looks at the event queue and determines if the event has happened, and a pointer to an Effect class, which invokes a method to make something happen in the game. The cards will monitor the event queue and if it detects that the event was triggered, invoke the effect.

My concern is that this requires a lot of subclasses for each event and effect which will really muddy the codebase. Ideally I would be able to create new effects entirely within the inspector using enums for the event trigger and effect, but don't know how this would be implemented.

If anyone with experience of these kinds of systems has any advice regarding if this is the way to go, or on the implementation it would be greatly appreciated.

Thanks.

# Answer
> 0 votes
Consider C# events.

This allows you to have cards in the game which subscribe to events by registering a callback method with the event. The result is that as soon as you `.Invoke(arguments)` the event in your game loop, all those previously subscribed event handlers will get called.

I assume that you already have some class which manages the general progression between different game phases. I will call this class `GameState`. This `GameStateManager` would expose a bunch of events like this:

```
public event Action<Player> OnBeginTurn;
public event Action<Card> OnCardPlayed;
public event Action<Card> OnCardDestroyed;
public event Action<Unit, int> OnUnitDamaged;

```

and so on.

The `GameStateManager` would then invoke those events at appropriate times.

```
public void SwitchTurn(Player newPlayer) {
    currentPlayer = newPlayer;
    // all the other stuff which needs to happen on turn changes
    OnBeginTurn?.Invoke(currentPlayer);
}

```

A card could then subscribe to an event like this:

```
public void EnterGame() {
    gameStateManager.OnCardPlayed += OnCardPlayed
}
public void LeaveGame() {
    gameStateManager.OnCardPlayed -= OnCardPlayed
}

private void OnCardPlayed(Card playedCard) {
    // Deal 3 damage to every unit in the game when another player plays a resource card
   if (playedCard.type == Card.Type.RESOURCE && playedCard.owner != owner) {
       foreach(var otherCard in gameStateManager.allCardsInPlay) {
            if(otherCard.type == Card.Type.UNIT) {
                 otherCard.Damage(3);
            }
       }
   }
}

```

More complex events like "playing 3 cards in the same turn" might require to keep a journal of all events which happened in the current match and then search through that journal for what happened in the past.

---

Yes, this will require that you have a hardcoded `OnCardPlayed` method for every card (although similar cards might share the same method).

I don't think that it would be a good idea to try to get around hardcoding here. If you attempt to implement some "soft logic" which you can edit via a GUI in a custom editor window, you will likely end up investing a ton of work into a system which isn't much easier to use than just hardcoding and still won't be able to cover the more exotic use-cases you have in mind.

# Answer
> 0 votes
You can use an event bus. It is basically the observer pattern, but many-to-many instead of one-to-many; which means an arbitrary amount of listeners can listen to an event that can be raised by an arbitrary amount of emitters.

I have a library on GitHub that implements a simple event bus for Unity. You can use it, or write your own, it is a fairly simple piece of code: https://github.com/starikcetin/Eflatun.EventBus

---
Tags: unity, events
---


# Question
Title: What unity version should I install from the list?
The problem is that all my projects are in unity editor 2019 version and if I switch to a newer version I'm afraid it will start asking me for api changes and other changes that it will make to my projects. What version should I install so it will not change too much my projects and will not damage them ?

# Answer
It's not possible to answer this question as written, as we have no idea what APIs you're using, and what's changed in the different versions of Unity.

I recommend making a backup of your projects, then get the latest version of Unity listed for LTS (Long Term Support... these versions get 2 years of fixes and updates, meaning you can get updates to that version without breaking your project).

Let this version convert your projects, and see what doesn't work. Unity is generally pretty good at doing these upgrades without breaking things, though their auto-script fixes may not be the most efficient code possible.

If something is broken beyond your ability (or will) to fix, then revert to your backed up copy and stick with the version of Unity it was made with.
> 1 votes

---
Tags: unity
---


# Question
Title: Extra constructor call when using inheritance in Godot
I'm trying to design a character system for my game. Considering I'll need a player and non-player characters - and non-player characters will further come in many more forms, making use of inheritance sounds almost necessary.

Right now, I'm trying to make every instance hold a dictionary of context options and I need the dictionary to be modified with every level of inheritance. From the documentation I learned that the constructor implicitly calls the parent constructor, and so does the `_ready()` function as noted here.

... but first I wanted to test it, so I set up following scenes (slightly simplified):

# New scene: Character

* Character (`Type: Character` \- here I'm not sure why, should be just `KinematicBody`)

... with the attached script:

```
extends KinematicBody

class_name Character

func _init():
    print_debug(self.to_string(), " Character _init()")

func _ready():
    print_debug(self.to_string(), " Character _ready()")

```

# New inherited scene: Player

* Player (`Inherits: Character.tscn, Type: KinematicBody`)

... and detatched the `Character.gd` script and attached a new script:

```
extends Character

class_name Player

func _init():
    print_debug(self.to_string(), " Player _init()")

func _ready():
    print_debug(self.to_string(), " Player _ready()")

```

... and I instantiate one Player scene as a child scene in my main scene (through editor, not code).

---

For some reason, whenever I instantiate *Player*, Godot consistently prints this:

```
[KinematicBody:1422] Character _init()
   At: res://scenes/characters/Character.gd:22:_init()
[KinematicBody:1422] Character _init()
   At: res://scenes/characters/Character.gd:22:_init()
[KinematicBody:1422] Player _init()
   At: res://scenes/characters/player/Player.gd:26:_init()
[KinematicBody:1422] Character _ready()
   At: res://scenes/characters/Character.gd:30:_ready()
[KinematicBody:1422] Player _ready()
   At: res://scenes/characters/player/Player.gd:34:_ready()

```

However, when I instantiate only *Character* in its place, the output is as I'd expect:

```
[KinematicBody:1425] Character _init()
   At: res://scenes/characters/Character.gd:22:_init()
[KinematicBody:1425] Character _ready()
   At: res://scenes/characters/Character.gd:30:_ready()

```

Where is the extra `_init()` call coming from? Sounds like something that could make a lot of mess if I didn't notice this and blindly used it.

Also why does *Player* show as a `Type: KinematicBody` when hovering over it in the scene inspector and not like `Type: Player`, the same way *Character* shows as `Type: Character` \- or why don't they *both* show up as `Type: KinematicBody`?

# Edit

Following @Vaillancourt's suggestion, I placed breakpoints at each of the `print_debug()` calls. Stepping through the code, the last 4 prints behave as expected - first there's the *Character* constructor, implicitly called from the *Player* constructor, then the body of the *Player* constructor itself. This is clear from the backtrace. Same for the `_ready()` calls. But before this, there's always one extra *Character* constructor call not called from the *Player* constructor.

Same goes when I put multiple *Player* instances into the scene. Both had the correct constructor calls preceded by one extra, separate call.

Putting a *Character* instance along with a *Player* instance to the scene resulted in a - once again - malfunctioning *Player* (three `_init()` and two `_ready()` calls) and a correctly functioning *Character* (just one `_init()` and one `_ready()` call).

# Answer
Updated version of the initialization process (old version):

**Node instancing**

1. If the `Node` is an scene instance, do **Scene instancing** for the corresponding scene, and take the root node. Otherwise, create a new `Node` instance.
2. Script Change. If the `Node` script is different to the one we want (either it didn't have because we just created a new node, or it has a different one set by scene instancing):

1. Change the Script.
    2. If the script has *new* variables, allocate them. Initialize variables which are not `onready` to their default value if specified, zeroed otherwise.
    3. Send `script_changed` signal.
    4. Call `_init` on it. Base class `_init` runs first.
3. Set properties (initialize `export` variables, and any custom setters run if the value is not the default, even if the value is the same it has). *I think should consider "Script change" a property that is being set, but it is such an special case.*

**Scene instancing**

1. Do **Note instancing** for the notes, from the root to the leafs.
2. Connect IDE signals. Including connections from and to future children.
3. Parenting. From root to the leafs:

1. Add the node to its parent.
    2. `NOTIFICATION_PARENTED` (18).
4. `NOTIFICATION_INSTANCED` (20). *On the root node.*
5. Current scene handing. If instancing the current scene:

1. Add the root node as child to the `root` `Viewport`.
    2. `NOTIFICATION_PARENTED` (18). *On the root node.*
    3. Entering the scene tree. From root to leafs:

    1. `NOTIFICATION_ENTER_TREE` (10).
        2. Call `_enter_tree` on it. Base class `_enter_tree` runs first.
        3. Send `tree_entered` signal.
    4. Ready mechanism. From leafs to root:

    1. `NOTIFICATION_POST_ENTER_TREE` (27).
        2. Initialize any `onready` variables.
        3. Call `_ready` on it. Base class `_ready` runs first.
        4. `NOTIFICATION_READY` (13).
        5. Send `ready` signal.

---

You have a stored scene `Character.tscn` where you have a `KinematicBody` that has a script `Character.gd`.

And then, in another scene, you have an instance of that scene. And to that instance you set a script `Player.gd`.

So, when that scene instantiates, it loads and instances the other scene (`Character.tscn`), which has `Character.gd`. Then Godot runs `_init()` on it:

```
[KinematicBody:1422] Character _init()
   At: res://scenes/characters/Character.gd:22:_init()

```

Then Godot sets the new script (`Player.gd`). And Godot runs `_init()` on it, which has to run `_init()` on the parent class first:

```
[KinematicBody:1422] Character _init()
   At: res://scenes/characters/Character.gd:22:_init()
[KinematicBody:1422] Player _init()
   At: res://scenes/characters/player/Player.gd:26:_init()

```

And then Godot moves on to running `_ready`. Which runs on the parent class first:

```
[KinematicBody:1422] Character _ready()
   At: res://scenes/characters/Character.gd:30:_ready()
[KinematicBody:1422] Player _ready()
   At: res://scenes/characters/player/Player.gd:34:_ready()

```

---

You can confirm the change of script by printing `(self.get_script() as GDScript).resource_path`. With that added to your debug prints, this is how it looks like:

```
[KinematicBody:1201] Character _init() res://Main/Character.gd
   At: res://Main/Character.gd:6:_init()
[KinematicBody:1201] Character _init() res://Main/Player.gd
   At: res://Main/Character.gd:6:_init()
[KinematicBody:1201] Player _init() res://Main/Player.gd
   At: res://Main/Player.gd:6:_init()
[KinematicBody:1201] Character _ready() res://Main/Player.gd
   At: res://Main/Character.gd:9:_ready()
[KinematicBody:1201] Player _ready() res://Main/Player.gd
   At: res://Main/Player.gd:9:_ready()

```

---

You have the current scene, so Godot goes over **scene instancing** for it, which does **node instancing** on its nodes from root to leafs. Which encounters a node that is an instance of `Character.tscn`. So Godot goes over **scene instancing** for `Character.tscn`, which does **node instancing** on its nodes. There Godot sets the script `character.gd`. Since the script changed (from none to `character.gd`) Godot and calls `_init` on it. That is the first `_init` call.

After **scene instancing** for `Character.tscn` finished, **scene instancing** for the current scene continues. So it changes the script to `player.gd`. Since the script changed (from `character.gd` to `player.gd`) Godot calls `_init` on it, but first it calls `_init` on the base class. So you get two more `_init` calls.

Afterwards, since we are loading the current scene, it reaches the ready mechanism, where Godot calls `_ready`. Which are also two calls because Godot call `_ready` on the base class first.

---

A few extra notes:

* When the script changes, there is a `script_changed`. But if you connect to it from the current scene, you will not get it. This is because the IDE signals has not been connected yet at the time. However, the IDE signals for `Character.tscn` would have been connected for the second script change (from `character.gd` to `player.gd`).
* The values of the properties of the node are not lost when switching scripts.
* I don't think there is a way to know ahead of time if the script will be changed.
> 2 votes

---
Tags: godot, oop, initialization
---


# Question
Title: Difference between World matrix and Model matrix?
My current understanding of the Model matrix is that it is per object and stores the transformation, rotation, and scale of the object in local object space.

What I'm not sure about, is that whether or not the World matrix is a matrix that is product of all the Model matrices e.g. `WorldMatrix = ModelMatrix_object1 * ModelMatrix_object2 * ... * ModelMatrix_ObjectN`

Or that the World matrix is just another name for the Model matrix?

I should probably also note that I am trying to render multiple objects to the screen and not a single object.

# Answer
The names "world matrix" and "model matrix" are just terminology, and are not 100% standardised, so depending which source you read you may see them being used to refer to a number of different things.

Generally speaking, your 3D scene will consist of the following:

* Objects that move around in the scene.
* Static parts of the scene that don't move.
* A "camera" that positions the player's viewpoint in the scene.
* A projection that maps the 3D scene to 2D physical hardware (i.e. your monitor).

Each of these items can be defined by it's own matrix that specifies how the transform for that item is done. Everything else is terminology.

The **projection that maps the 3D scene to 2D physical hardware** is consistently referred to as the **projection matrix** and may be perspective or orthographic.

For **objects that move around in the scene** the matrix that positions them in the scene is commonly called a **model matrix**, an **object matrix**, or a **world matrix**.

For **static parts of the scene that don't move** there is often no matrix - these parts of the scene don't move. If a 3D engine does define a matrix for these, it may be identity.

For **a "camera" that positions the player's viewpoint in the scene**, this is a single matrix that may be called the **camera matrix**, the **world matrix** or the **view matrix**.

Some 3D engines may treat **objects that move around in the scene** and **static parts of the scene that don't move** as different cases of the same object type, in which case the matrices for the former defines their positions in the scene, whereas the matrix for the latter is just identity.

Classic fixed-function OpenGL concatenates all of the above matrices into a single **modelview matrix** containing transforms for an objects position in the scene, as well as for the player's viewpoint in this single matrix.

Classic fixed-function Direct3D uses two matrices with the terminology **world matrix** for positioning objects in the scene, and **view matrix** for positioning the player's viewpoint in the scene.

If you're writing a paper or presenting something to other people, **model matrix** (or **object matrix**) and **view matrix** are probably the most unambiguous terms to use; otherwise you should probably clearly define your terminology so that people can understand what you mean when you use each term.

And you don't even have to do any of it in these ways. You could, for example concatenate the projection and the player viewpoint to a single matrix, then each object in the scene would have it's own matrix. You could split things out even further if you wanted, maybe by splitting rotations out from other transforms if you needed to special-case them for whatever you're doing. In cases such as these the terminology you use is entirely up to you, so long as it makes sense to you and to anyone else who might be reading your code.

With programmable shaders there is not even a requirement to use the traditionally defined matrices and you can do whatever you want.
> 3 votes

---
Tags: matrix, transformation, linear-algebra, terminology
---


# Question
Title: Gamepad Input: How to assign the Dpad as individual buttons?
I've looked around and had no luck, so I want to ask here. I'm using an XBOX ONE controller for my game, I've set up the input, however my issue is with the Dpad itself.

Below is an example of how I want to implement the Dpad, but with actions instead of weapons:

but the problem is, I can't find any tutorials to explain how to actually go about setting something like this up. Initially, I tried going into the Project Settings, changing the Input but the Dpad is limited to axises and won't actually work as individual buttons.

What would be the best way to get the Dpad to work individually as buttons?

# Answer
> 1 votes
> but the Dpad is limited to axises and won't actually work as individual buttons.

This is by design. If you want to do something specific when a D-pad direction is pressed, you can do so the same way that you would detect if a player had pushed their thumbsticks up, or left, or right, or down.

You need to check what direction, if any, each dpad axis is pointing and then do something.

This unity answers thread is helpful

The parts we specifically care about are these

```
float x = Input.GetAxis("DPad X");
float y = Input.GetAxis("DPad Y");

IsLeft = false;
IsRight = false;
IsUp = false;
IsDown = false;

//Adjust these numbers to taste
if (x == -1)
    IsLeft = true;
else if (x == 1)
    IsRight = true;

if (y == -1)
    IsDown = true;
else if (y == 1)
    IsUp = true;

```

The one caveat is I'm not 100% sure if the names of the axes are correct here, you'll have to check your input settings. But there is no "Press dpad button left". You need to check the axes to see if the user pressed it far enough left, right, up or down.

# Answer
> 1 votes
The new input system offers the option to handle a directional pad as both a two-axis analog input or as four separate digital button inputs. And if necessary even both at the same time. The class `DPadControl` implements both `Vector2Control` itself and also has four `ButtonControl` members for the four directions. So you can access its state both like this:

```
if (Gamepad.current.dpad.x > 0f) {
    // player currently holds right
}

```

or like this:

```
if (Gamepad.current.dpad.right.wasPressedThisFrame) {
    // player just pressed right
}

```

You can also use both variants when you assign inputs to actions in the Input Actions asset (which I would actually recommend).

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


title: Unity Build Automation

text:
# Question
Title: Unity Build Automation
My current project has some editor scripts that I run just prior to run/build, which dynamically creates some game objects in my main scene based on configuration. I don't want these objects to clutter up version control however, so I delete them prior to saving the project and committing changes to the repo. Currently I'm doing both of these steps manually, but this seems like the kind of thing that should automated. Is there a way to automate running these scripts prior to a Build and then deleting the constructed objects (presumably can create another script to help with this) prior to saving the project?

# Answer
I don't know if it'll work for your specific use case, but note that there's the PostProcessBuild attribute for editor scripts that run automatically after a build. I use that to edit the XCode project generated by an iOS "build".

Another approach is to write a script that executes the build, and that script can probably do cleanup after a build too. Like, I routinely write editor scripts that add a "Custom Build" option to the File menu, and then that script does a bunch of stuff before calling BuildPlayer. Assuming the BuildPlayer method is synchronous (I don't know if it is, I've never tested this) then that script could also do more stuff *after* BuildPlayer.
> 1 votes

---
Tags: unity, build-process, automation
---


# Question
Title: How do you prevent inflation in a virtual economy?
With your typical MMORPG, players can usually farm the world for raw materials essentially forever. Monsters/mineral veins/etc are usually on some sort of respawn timer, so other than time there really isn't a good way to limit the amount of new currency entering the system.

That really only leaves money sinks to try to take money out of the system. What are some strategies to prevent inflation of the in-game currency?

# Answer
> 152 votes
Money sinks are I guess the only real answer. Which means items or currency getting lost forever.

Eve Online blatantly has this through the mass destruction of items and ships through pvp (only partially replaced by insurance). Eve also has many other money sinks such as office rent, station fuels, ammunition etc.

Other games have similar consumables, either necessities like ammo or items that provide buffs etc. (food, potions, pet food, poisons etc.)

Many games (such as World of Warcraft) feature Bind on Pickup and Bind on Equip items. They are actually money sinks. You can enchant and add gems to your items but at some point you will upgrade it. So upgrading actually destroys the old item along with any value added to it via enchanting etc. Or in some games you can 'recycle' it for less that the original value.

This is a nice sink because it doesn't negatively impact players. They only really notice it at the same time as they are cheering about their brand new shiny loot. Also, even if the item is never lost and just remains in a character's backpack it can be considered out of the economy because it will never pass to another player.

Which brings us to other utility money sinks like increased bank and inventory space.

Aesthetic upgrades are also a good way to introduce sinks without affecting the gameplay balance of your game. Things like clothing dye or vanity mounts and pets.

# Answer
> 63 votes
Notice that only one person here before me has given the correct answer - "currency can't inflate if there's a limited amount of it." Indeed, with infinite resource generation, currency will actually *deflate*, as the amount of resources goes up and the amount of currency stays fixed.

It's an economy. You're not the Fed. Stop minting currency, and stop listening to people that don't understand the economy when asking about it. The underlying cause of inflation is an increasing money supply, which we only think of as normal because we live in the very first semi-stable fiat currency in history (and that won't last - we'll get out of it, or the dollar will collapse.)

What you actually want to do is mint a fixed, large count of currency, and play a balancing game between resource production and resource consumption (that is, modulate resource availability such that the total production is approximately what consumption was yesterday.) Easiest long-term stable way to do that is to keep a running tally of production versus consumption differential, and to use yesterday's data as a target for a 95% repair towards zero (which will allow a damping effect on oscillation, which will occur naturally as the mining population periodically shifts.)

# Answer
> 54 votes
Several of the above answers mention some important ways to reduce inflation but there's a few important money sinks that deserve some more explanation:

* Economic exchange fees: These are fees from converting a player's wealth from one form to another. A prime example of this in nearly every game is the vendor sell price. NPC vendors will always pay less than a good is "worth", and in the process players lose a lot of economic value. Players also lose value by using the auction house (posting fees), or enchanting items. You could also charge a fee for mailing items (a twinking fee) without too much complaining I suspect. These fees are great because the player will normally 100% accept them as the price of doing business, as they mirror real world financial transactions.
* Death Penalty: Many many games (WoW included) take a tax whenever a player dies, often as item repair fees. These fees are great because they help provide players an incentive to not die while not being as prohibitively painful as XP loss or flat out item destruction.
* Developer-run auctions/lottos: I haven't seen too many games do this, but one way to automatically reduce inflation is to provide some sort of valuable auction that players can bid on, but which is actually run by the developer (so 100% of the value is removed instead of transferred to another player). For instance, you could auction off naming rights for a street in town to the highest-paying guild, or a statue placement, or anything you want. The best part of this is that the cost should automatically adjust to match available player wealth, with no effort on the developer's end. Kingdom of loathing has removed tons of money from the economy in a similar by using a lotto system (100 gold to buy a ticket, can buy as many as you want) for rare aesthetic items.

# Answer
> 29 votes
Creating resources endlessly is an issue but completely closed systems have their downfalls too. Take a look at Shattered World. Completely closed economy with player run shops, banks, etc. Monsters in the world were actually equipped by items purchased from player shops by the game. The hoarding instinct mentioned above killed the game though. There were taxes but there was also a player monarch who surprisingly also enjoyed hoarding of money.

To make a closed system work you need to give the rich players incentives to spend their money. This is similar to the classic open economy with the caveat that rich players giving money to poor players helps this system while it does little for the open one. One interesting way to do this is to put in place systems to allow rich players to "hire" poorer ones out. One could require large reserves of stone to maintain their opulent castle, much more then they could mine on their own, and allow them to have an NPC reward money from their vaults to players who help supply stone for the keep.

Depending on how other resources are handled in the game you may actually end up with large amounts of deflation with infinite veins etc mentioned before.

# Answer
> 23 votes
One crucial aspect that I don't see people mentioning here: make sure you have at least one money sink that scales up automatically as people get richer. Fees for walking around the world and armor repair won't scale up, since they're based on fixed values.

Special novelty items that you can buy for large amounts of gold *do* scale up, in an economic sense, because as more money floods into the world people will buy more of them. However, this has a firm upper limit, and if *way* too much money floods in, they'll stop scaling.

The standard scaling-money-sink is auction/market fees. Charge a percentage of the purchase on every successful auction. If people have ten times as much money, then auctioned items will go for ten times as much thanks to supply/demand, and your money sink will pull ten times as much cash out of the economy. Since money sources are almost always constant, this can easily serve to keep a lid on the economy.

You do have to ensure that people buy and sell things regularly, however - trade skills and consumable items (including gear enchants and gems, in the WoW model) are necessary for this.

# Answer
> 13 votes
Currency sinks alone won't save you, even if you're not creating free money from resources. If your number of players changes, then the distribution of money will change also. And if you scale the money supply linearly to match the number of players, that does nothing for the inequality of wealth distribution (which will tend to get worse as the numbers rise) and it tends to ignore that your new players don't have an 'average' amount of money but in fact start off in relative poverty. It's incredibly hard to get right which is why the real world doesn't do a great job of it either, despite having a more closed economy.

In my view the best thing to prevent inflation is to avoid currency altogether. If your game design allows for a barter-based system, that can help, because it's typically harder for players to manipulate the flow of goods. (Someone who can carry 10,000 gold pieces can rarely carry 10,000 pigs worth 1 gold piece each.) A compromise is multiple currencies with unfavourable exchange rates, which coerce players into preferring goods over stashes of cash.

# Answer
> 10 votes
Add a money-sink that trades money for services such as temporary buffs, items, etc. The money disappears and afterwards (say a few minutes or a week), the service disappears.

Possible services can be:

* extra experience
* special pet
* access to a dungeon
* speed buff (surprisingly useful in a MMO)
* temporary access to a spell

# Answer
> 9 votes
Money sinks are the obvious answer, as you say. You can do this through incentives ("pay 1M gold for this cool new sword") or through regular losses ("your weapons and armor degrade over time, pay gold at the blacksmith to restore them").

You can also try to find core mechanics that don't involve infinite-spawn -\> farm -\> net increase in global wealth. Maybe the monsters are limited and can be over-farmed, for example, although of course that creates its own problems.

You can accept inflation as part of the game, understand the inflation curve, and modify your new-player experience accordingly (e.g. maybe you give new players a gift of Gold, untradeable of course, that is a percent of the total global wealth... so the more you have inflation, the more new players get to start off).

But mostly, this is an unsolved problem (in MMOs and in the real world).

# Answer
> 8 votes
I think one issue here is that minerals and actual currency are separate things. Anyway, one way to combat inflation would be to limit currency generation - in a real economy currency is created at a fixed rate, not when people earn it. Essentially, when you kill an NPC and steal their wallet you would be taking from the "pool" of NPC money. As the NPC money pool decreases, you get less and less money from killing NPCs and vice versa. This could inherently push the game towards PVP as it evolves.

As for "drops" and various bits of incredible loot, the same system can be applied. If you make most rewards based on increasing your characters skills or something, you can limit the amount of +7 sword of bats without causing too much of a problem.

# Answer
> 8 votes
Not mentioned yet are services as money sinks. So the player uses some of the inflated money to buy a service (like health boosts and speed increases), which is essentially intangible and at the end of the service period, value disappears from the economy. This helps to counter the feeling that the player is buying something pointless (such as vanity items) or the feeling of loss they get (such as when the items that they spent lots on get destroyed during PvP).

Ideally the services provided are ones which don't make it notably easier for the player to then farm more value. Imagine a buff service that increased the speed at which players could dig for currency, resulting in them adding more currency to the economy than is taken away through the price of the service. Net result: hyperinflation as the player can use the extra currency they received to buy more / higher levels of the services, resulting in more currency, etc.

# Answer
> 8 votes
Multiple currencies works for a lot of Facebook games. Consider Mafia Wars - when dollars were too inflated, they added "Cuba" which required an entirely separate currency. Then later Bangkok, etc. Also it's fairly standard in Facebook games to have a separate currency that you can only acquire large amounts of by paying real money. This way, the basic currency can inflate a lot without affecting the for-pay currency that much.

# Answer
> 8 votes
You do need money sinks, but you can also encourage people to keep the items they receive in circulation, instead of NPCing them. If the benefit of selling an item to an NPC is minimal in comparison to trading with another player, then the economy will be self-sustaining.

Requiring players to pay a fee (whether monetary or farming related) before being allowed to go on a quest/raid with high rewards can also help, along with the other general ideas of charging for services (transport, auctioning, repairing), or consumable items.

# Answer
> 8 votes
Don't prevent inflation. You can fairly easily measure how fast currency is changing hands. Track it, and have the game automatically adjust NPC prices and drops accordingly, with a slow moving average so that prices don't spike. Just use a Big Integer for quantity and you'll be fine.

# Answer
> 7 votes
I was going to write an answer, but it ballooned into a huge article, so I made it one in a blog to link to so as to avoid having its' hugeness here. Warning, it's really long.

http://azaralgametalk.blogspot.com/

# Answer
> 6 votes
It is possible to limit the speed at which new resources are added to the game. For example limit the number of gold a player can dig per day. A less obvious limit is to apply luck to random events. If a player has lots of karma it is likely that he gets drops, but the karma is used up and has to be renewed by doing quests.

# Answer
> 6 votes
The general problem is, game authors tend to make the economy in which advances players will create tremendous amount of gold and goods. The more the level, the more the energy. The more the perk, the more goods or gold for one point of energy. Isn't it?

Well, good, balanced game should be more like a life. More advanced players can do more advanced things than beginners, not 100x more things ad day. Gold doesn't grow on trees. There's no computer tradesman that will buy everything you produce or any skin you will hunt in forest.

Have you considered to allow player guildes to emit their own currency? They would have to adapt it's number to the number of players. When they emit too much, it would inflate and nobody would buy it.

Doing good economy is very difficult, hovewer.

# Answer
> 5 votes
One solution that i don't see mentioned here is that money simply "wears out": when the money is interacted with (used to pay for something, taken out of/put in storage, examined, etc.) it loses "health", then it can be "redeemed" for new money somewhere if it's not too worn. This is a form of money sink, but a nonobvious one (and really the most accurate, at least for paper/coin money)

# Answer
> 5 votes
Another idea. Figure out your max expected population for the world, and how much money would be reasonable for that population. Put that much money in the world, but have most of it be mineral that must be mined up and converted into coins.

Allow humanoid NPCs to set up mining and don't give out money for non-humanoid npcs when it doesn't make sense for them to have money anyway. You can allow a skinning system to get material out of npcs that don't give money that they could trade for money(doesn't have to be just skins, claws, teeth, poison glands, whatever valuable body part the animal might have).

If player growth outpaces NPC mining's generation of money currency will deflate and encourage players to set up their own mines(gold rush?) until you eventually reach your theoretical max and things get balanced out. When players close their accounts you could convert the money they had back into mineral wealth in a new vein or extending an old vein.

# Answer
> 5 votes
**What I have not seen mentioned here is that inflation (and deflation) often result from changes in player spending habits.**

Fixing the amount of money in existence, particularly on a per capita basis, is a start. But if players spend money like crazy, they'll inflate it. If they hoard it (or take a few weeks off from the game) they'll deflate it. If you have 5 gold coins in your game and a player earns fast and spends fast, he can go through the same 5 coins in one session, earning and spending 500 in a few hours. If he does nothing, that's the same as having *zero* coins in the game.

Fixing the money supply is not good enough. In the "real" world, gold works better than paper because governments cannot inflate it. But if people stop spending and start hoarding, the price of gold skyrockets. There's the same amount in existence there ever was, but there's none on the market. Paper money does not need to have this problem.

**The only sure way to keep inflation and deflation under control is monitor your prices (however you measure them) and feed in more cash when they fall and and take it out when they rise, using the sources and sinks discussed elsewhere.** This is a lot more complicated than, say, just fixing the money supply. Worse, inflation in a game is more perception than actual rising prices. ("It took me 6 months to save up for my first Dragon Bane Sword. Now I buy them by the dozen.") Perhaps measuring average player expenditure per week would track it. Be sure to do this *by level*. Otherwise the spending of your level 40 players would inspire such deflation as to destroy your level 1's. The idea would be took keep the level 1 (and 2 and 3) financial experience the same over the years.

# Answer
> 4 votes
Diablo II has "the cube" which allows you to combine certain items to produce a single item. While most of the recipes include low and middle level items, there are a few that require the super rare items like an SoJ.

Diablo II has also had world events where only a very limited few can get in on the action at a time. Specifically the uber Diablo event which requires players to sell SoJs to vendors (money sink) to trigger the event.

The real problem facing a game that uses items as currency between players is that if the game becomes to popular, you will have to fight duplication.

One OOB idea I've had is to create a much richer merchant experience - allowing for things like loyal customer discounts, research & development, et cetera. This allows such "money sinks" to become useful pieces of the game. For example the more money you spend at a merchant, the better stock they will keep. This can, of course, be expanded very easily which makes me think it to be a decent concept. (Just wish I had a game to implement it on)

# Answer
> 4 votes
Some games sell game content. I think DDO does this, but I'm not positive. Players purchase access to new areas of the game, things like transportation fees, but very similar in practice to the expansion pack model, where you buy whole dungeons or quest packs. Many games use real cash for that, but in-game currency works too.

Any time you have a money sink of some kind, take the time to balance it. Measure the game, figure out how much it actually costs players to obtain a resource, and try to make it cost about the same amount. For a dungeon encounter, compare the average cost per player to the average value of loot obtainable.

# Answer
> 3 votes
Urban Dead doesn't allow trading, doesn't allow storage and the player can only carry a limited number of items. This means the player can't horde items but has to continually search for them.

# Answer
> 3 votes
The problem here is an "infinite" supply of resources. That is, if a player needs cash he can farm monsters.

You can have money sinks and all sorts of creative ways to take money out of the system; but that isn't the issue, the issue is that the scale is unbalanced on the side of money coming in.

So you need to limit it. A few things you could do is only allow players to farm X amount of items/gold in Y time. Or have a decay function. That is, hour 1 a player could earn say 100 gold; but on hour 20 he could only earn 1 gold.

You could put a reset or timers or whatever. The point is to make it dismissing returns.

Another option would be a "tax" either based on level or net worth. So, at level 1 a health potion costs 1 gold; but at level 100 it costs 1000 gold!

Or for ever 100 gold you earn, you need to be X in taxes to the "king".

A third option is to fix the amount of resources. For every player that joins, inject a 100 gold (or the equal worth) into the system, but no more.

The main point is, you don't want infinite input with a fixed output. You need to align then by either A) fixing the input to a fixed amount of B) have the output in align (by percentage, not fixed amount) with the input.

# Answer
> 3 votes
User7032 said it right. The problem with EVERY SINGLE MMORPG -- is the INFLUX or INPUT of items/currency. I will collectively refer to this as "value."

Value, in most MMORPG's (referred to hereafter as "games") is ALWAYS available. Take old Everquest, you kill a bat, you get some items. These items are the bat's harvestables + some common currency. This can be done endlessly as the bats will continually respawn. Value enters the game in this fashion so long as people are still online to gather it.

Therefore, the answer to dealing with inflation/deflation -- should NOT be Value sinks. While Value sinks are important for ensuring a level of realism to your game, they should not be viewed as the sole means of removing excess Value. Games such as Fallensword.com tried to do this. It fails.

Instead, build the game in such a manner that players WANT to spend their Value.

1. Instead of allowing for an infinite amount of Value to enter the game, randomize the amounts that enter; and the location to where it enters. Subsequently require certain skills and levels of that skill in order for each player to even access the given resource.
2. Completely remove influxes of "currency" from Farmable sources. For example -- do not allow players to gain currency Value from killing monsters, instead only allow them to gain currency from selling the harvest to either A) players or B) NPCs though at a much lower value.
3. Introduce enough types of skills that even more advanced players will have need of other, possibly less-experienced players, to harvest all the necessary Value for whatever it is they want to have. If it takes three harvesting skills to gather the necessary Value to produce a powerful item -- the more experienced player will likely pay a newer, poorer player for one of those harvests instead of trying to do all three himself/herself.

# Answer
> 3 votes
Many of the techniques @beetlefeet is talking about in his answer (the top and accepted answer, at the time of writing) don't actually remove any money from the economy.

> Eve Online blatantly has this through the mass destruction of items and ships through pvp (only partially replaced by insurance).

Money is not destroyed when you lose your ship, only your ship is destroyed. Your money got sent to the player who built the ship, who gave some money to the person who mined the minerals. When you lose a ship, money is injected into the economy through the insurance mechanic. EVE implements money sinks through station fees, market taxes, etc.

> Many games (such as World of Warcraft) feature Bind on Pickup and Bind on Equip items. They are actually money sinks.

In most cases they aren't. In the case of World of Warcraft people typically sell their items to a vendor when they get an upgrade, which means the money is created and injected into the economy. If you can't sell items to vendors, then they could be money sinks if there are repair costs, but there aren't many games that do this.

It's important to remember that destroying items doesn't destroy currency. If anything, it makes the currency even more inflated since there are fewer items, making them worth more.

# Answer
> 2 votes
The general solution I've seen used is to put anything cool on a separate, untradable currency. You can also go whole-hog like Eve and have a real, deep economy to take care of it. Most MMO economies are just too simple to have things like supply and demand curves, but it is possible.

# Answer
> 2 votes
Increasing costs of **training**.

The more **ability** the player have, the more it costs to train another point.

# Answer
> 2 votes
Volume is key here, and I think people are forgetting how manipulable this factor is.

What about setting up a futures market? Even, one which is not completely closed? According to various sources (I cannot speak to their academic merit here, but I will cite one popular example: http://www.cnbc.com/id/102456187), crypto-currency's volatility in the real world is largely due to lack of a futures/options market. You could easily set this up in such a way that it allows limited designer control of prices...simply have some sort of partially-NPC driven financial sector. For instance, you could keep a library of historic prices of commodities after various types of world events, similar to what might occur in game, and simulate random, quick volatility followed by a correction to equilibrium. You wouldn't have to get the complicated stochastic calculus exactly right, as long as the equilibrium price is somewhat sensible and there exists a reasonable system ingame by which people who are crazy about that sort of thing can gamble on the market and make a profit sometimes.

This could be particularly interesting if you decide to go all out...you could have users buying up houses near the exchanges and rushing to work every day so they can beat the market. You could very well also make a whole elaborate NYSE-style trading floor. And then what if someone tries to attack the physical exchange? What if there is a stock market crash? Now that would be some MMO.

# Answer
> 1 votes
Implement Social Security ;)

# Answer
> 1 votes
I'm not entirely sure if this would work, however, I think a viable solution would to simply stop respawns. Once a monster is dead, it's dead. Allow npc entities to 'breed' in certain conditions, which will replace the dead. This system could very well allow entire species to go extinct.

Take the analogy further with food production - poor agricultural practices should yield a plot of land infertile for a long time. Drought, diseases, and locusts should all be real problems for food production.

Also, character death should be permanent. Players may choose to have children, while alive, and this will serve as a "respawn" in the event of their death, but the character must care for and be able to financially support his children while he is alive.

Through these base principles a truly functioning economy should blossom if it is given enough freedom. However, this style isn't really an option for most games, so take it with a grain of salt.

Just my two cents.

# Answer
> 1 votes
Entropia Universe uses the real green stuff, as players deposit IRL money which they can later withdraw, so inflation needs to be kept in check -- otherwise the whole company may bankrupt in an instant. The solution for Entropia Universe is to forge new items with an average value \< the average value spent to create/obtain the items. This is the same type of system you find in gambling: ROI \< 1:1. (The surplus pays for development and owner dividends.)

If you run with this in a normal game (without IRL cash) you need to keep track of the total value in the system. Then you ("the Treasury") can choose when you need/want to create more value in the game, or do so automatically if the value drops below a certain threshold.

# Answer
> 1 votes
Many answers have hit on the essentials as far as limiting the INPUT i.e. do not allow infinite gold creation, infinite monster and material respawn based on simple timers, etc. Gold should circulate. Monsters should have loot because they got it from somewhere. Players who die in a dungeon could lose cash, that then ends up in the pockets of monsters that can then be killed by other players, etc. The point is to do everything possible to increase circulation, but limit spawning of currency out of nowhere.

One very interesting area that provided a lot of inspiration to me is to look at how historic economies actually worked. I like the fantasy genre, so I studied medieval economics. There were actually many highly efficient "gold sinks" built into most medieval economies. For example, guilds would have to buy royal charters from the king in order to operate. They would control the ability to allow (for example) blacksmiths to operate in a given area, but in turn, they would have to pay a bunch of money to the king for a "charter" that gave them that authority. This mechanic in an MMOG would allow for A: creation of local monopolies that would be a natural source of conflict between players seeking to control it (conflict is good if you channel it into game activity), B: Player arbitrage activity as they buy stuff in one location and move it to another (assuming you don't have instant, free, fast travel), and C: An efficient gold sink that allows the game developer to target a very specific industry. You can get some pretty fine grained control over exactly where you want to suck excess currency out of the economy by adjusting charter prices for blacksmiths versus bakers versus tanners.

There are a lot of simple solutions to economic problems (some of which create other problems of their own) to be found in historic economics. It does make a lot of sense for a fantasy game to implement some of them, because no only do they allow for band aid fixes, but the "flavor" element of having a mechanic like royal charters actually adds to the game, rather than feeling like an arbitrary, punitive mechanic.

# Answer
> 0 votes
We can go for one problem that creates the inflation:

The theoretical amount of money in trade in the entire MMO is infinite, because the input stream of monsters and quests can be infinitely done.

A shortcut fix would be to find places were money leaves the active economy without any return. That could be anything from paying money for re-spawn(probably the most unlikely) or something like a consumable item (so it can't go into endless trade) that costs a high amount of money.

# Answer
> 0 votes
You can instead opt to prevent the negative influences of inflation, while otherwise taking advantage of it. To do this you must make the market very accessible. Rather than relying on item clutter as a sink, drop only useful items that will be great hand-me-downs, upgrades or crafting components.

Where pragmatic, make drops slightly rare and prefer gold. Track inflation for equipment and items of all level/skill tiers, defining a ratio to the game's original value-balance.

Use this multiplier from the active market against gold drop rates. By doing this and restricting price changes to within + or - 40% within a given time, and increasingly discounted under market value for greater quantities of an item. Only allow price increases for small stacks (the size of an hour of drops/crafting) or HQ items. This way you provide players with a consistent financial-progress experience.

So, now that you've ensured a player can go grind and get obtain nice gear with a fair but not insane amount of effort, you can refine more market activity from there.

Detect trends within the market data gathered to track inflation. Give NPC guilds the ability to create items, given a combination of drops or money, as player crafters would. Then let them buy up underpriced items relative to how much cheap surplus is flooding an item's market. NPC activity can and should work at similar multiplier to player economy, making slightly less profit at a worse overhead than players (about 20-40% less efficient at profiteering is good). "Use" that profit to actually fund NPC salaries and activity. If NPC teams/armies can only move when they have enough gear, food, salary and recruits, the game can be quite dynamic from some simple self-balancing mechanics.

With a rough equilibrium formed, and as the game admin, you can play around with both inflation and deflation with temporary, gradient shifts in various ratios.

Another way to let both players and NPCs take advantage and self-adjust to inflation is through loans. Imagine a cursed ring of lending. Monetary activity is taxed until repayment, plus interest of course. If players can take out a substantial mortgage based on their average rate of earnings, and drops scale up with inflation as above, players can suddenly pay off their debts.

Ah, but you can measure the total inflation volatility, and pack that into the interest rates and transaction fees in various ways. Even go so far as to have various levels of tribes to governments take on massive debt and properly collapse, to suck tremendous amounts of gold out of the economy as needed.

Options are endless, but I'll provide one more. The most direct method of straight up deflating the economy is to really push the NPC involvement in player markets. Specifically, if:

* An item's cost inflates over x% of the original value
* The rate at which said item is bought is y pieces-per-(time unit of choice)
* Then, NPC group A undercuts the market; continuously lowering prices and posting more than y pieces-per-time until cost is z% below original value
* NPC group B-Z buys up all NPC group A's surplus once low enough in price
* The item's market value is now effectively reset and cannot inflate beyond x%
* If particular items continuously reset, trace its supply chain
* If taking this hardline approach by making the supply of goods higher than demand, directly deflating the market, you must be watchful to have mechanism that allow players to offload stagnant inventory that stopped selling after a market bust without going entirely broke

# Answer
> -2 votes
Actually failing game economies are as much about basic math as a direct result of social ineptitude.

The recycle-ability of things abroad, in-game or out-game is relatively the same. Massively people are used to doing whatever they are doing and leaving a humongous mess in their wake. These thought patterns directly go through designers making games. Where the world outside of games forces you to engage in a broken and heavily rigged economy just so you can obtain food, shelter and more. For a game and its economy you can simply walk away and spare your self the useless grind. You are at a grindy job with decreasing benefit any way, riding griffins in some game context isn't going to be awesome if you are subjected to the same economical torture you endure in your daily life.

Likewise overcompensating for this factor leads to absurd levels of inflation and abuse that quickly tears down any fun provided by the game environment. Not to mention technical issues resulting in exploits and such. And not even considering the hardest element of planning - efficiency variables - having an absolute best way to play the economy that usually renders most other gameplay activities useless, as players couldn't keep up with those "playing" efficiently.

The problems we are experiencing largely in the world today, play out numerously in games with economies. As they are built upon the same outdated and heavily faulty presumptions. except in games, the small scope and size of these projects reveals these flaws much faster than we get to comprehend them in the world we live in outside of games.

Overall most developers have economies for the same reasons a new car manufacturer puts tires on their cars. "Everybody else has them and the concept wouldn't work without them." However we all know the majority of manufacturers wouldn't go as far as to improve upon tires in any meaningful way or have any idea how to go about it even if they wanted to. That is IF their goals and budget have even considered tire improvements at all.

Why do economies fail? Because the people who make them lack the bare minimum of understanding. Its one thing to be in an economy as a participant. Its an entirely different thing to have the control over creating an economy and still fail in the end.

A lot of designers and devs I've spoken said to lack even basic projections for their economies. I know plenty who entirely "eyeball" their costs, times and so on. There are people who make large scale games and approach economy in a mystical fashion that, they can just set out and throw a bunch of whimsical random data that looks good on the eye and expect that it would "somehow" magically align to self-sustainability in the end. I also know people who do it on purpose. Here is a copy paste conversation from one of them I talked to just the other day:

"My boss wants me to design every feature, help with QA, babysit CMs more or less manage the coders, if he think I'm going to do the work of an expert mathematician and integrate it into the game in a way that makes sense, someone is gravely mistaken and its not me. I've insisted that either the scope is scaled back to fit what we can do, or more is invested to do it properly. Both were rejected, because the decision makers care more about appearing authoritative than actually understanding what is happening in their project. So congratulations, keep the payroll flowing and ask me create a new txt file type some random stuff in and then delete it, I'll repeat 24/7 if you insist - I don't care any more. When i go looking for a new job, it will be fine, I strictly followed my tasks, integrated with co-workers well, met my deadlines good enough, if anybody asks i sure as hell didn't make the economy, in fact i have an old email proving I have foreseen most of the problmes, not my problem that management ignored it. You know they never believe you when you say you didn't have enough to work with, considering we are in the crunch time industry, which is supreme at dehumanizing people with passion and potential about making games. Why do you think some of those cool profitable indies made it solo. Most of them begged companies to look at them and throw them a used bone, except corp scale devs could have bought them for pennies but instead threw em out flat on their ass because they are utterly incompetent at recognizing potential. They wouldn't even ship out their own games in a playable manner what do you expect?"

---
Tags: game-design, mmo, economy
---


# Question
Title: How an I find grid outer square positions by formula by script?
I mean automatic to find the outer grid square :

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

public class GenerateGrid : MonoBehaviour
{
    public GameObject gridPrefab;

    public int gridWidth = 10;
    public int gridHeight = 10;
    public int gap;
    public float spawnSpeed = 0;
    public bool gridGenerated = false;

    void Start()
    {
        StartCoroutine(CreateGrid());
    }

    IEnumerator CreateGrid()
    {
        for (int x = 0; x < gridWidth; x++)
        {
            yield return new WaitForSeconds(spawnSpeed);

            for (int z = 0; z < gridHeight; z++)
            {
                yield return new WaitForSeconds(spawnSpeed);

                GameObject block = Instantiate(gridPrefab, Vector3.zero, gridPrefab.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.localPosition = new Vector3(x + x * gap, 0, z + z * gap);
                block.tag = "Grid Block";
            }
        }

        gridGenerated = true;
    }
}

```

I marked them selected them in the screenshot to show what I mean by the outer square. I want to find automatic by some code logic only the outer square of the grid no matter what is the grid size if it's 10 on 10 or 3 on 7

This is working but with two problems that prevent from it to be automatic :

In another script I'm getting all the grid blocks positions :

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

public class GetGridPos : MonoBehaviour
{
    public GenerateGrid generateGrid;

    private List<Vector3> gridBlocksPositions = new List<Vector3>();

    private List<Vector3> gridOuterBlocks = new List<Vector3>();

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

    }

    // Update is called once per frame
    void Update()
    {
        if (generateGrid.gridGenerated)
        {
            var blocks = GameObject.FindGameObjectsWithTag("Grid Block");

            foreach (GameObject pos in blocks)
            {
                gridBlocksPositions.Add(pos.transform.position);

                if (pos.transform.position.x == 0 && pos.transform.position.y == 0
                    || pos.transform.position.z == 18 || pos.transform.position.x == 18
                    || pos.transform.position.y == 0 && pos.transform.position.z == 0)
                {
                    gridOuterBlocks.Add(pos.transform.position);
                }
            }

            generateGrid.gridGenerated = false;
        }
    }
}

```

The problems :

1. In this case I know the grid is 10 x 10 so there are 100 blocks and the gap between each blocks is 1 so the 4 sides length of the outer grid square will be 18 in this case but I want to find it automatic not to type the length on my own.
2. I need to add to the calculation also the gap factor.

So I'm still missing the right formula to get the grid outer blocks positions.

# Answer
> 2 votes
I would recommend you to use the same class for generation and for usage of the Grid, because, firstly, it is the same objects you are working with, secondly, because you can avoid usage of `Update()` for now:

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

public class Grid : MonoBehaviour
{
    public GameObject gridPrefab;

    private Transform[,] gridBlocks;

    private List<Vector3> gridBlocksPositions = new List<Vector3>();
    private List<Vector3> gridOuterBlocks = new List<Vector3>();

    public int gridWidth = 10;
    public int gridHeight = 10;
    public int gap;
    public float spawnSpeed = 0;
    public bool gridGenerated = false;

    void Start()
    {
        StartCoroutine(CreateGrid());
    }

    IEnumerator CreateGrid()
    {
        gridBlock=new Transform[gridWidth,gridHeight]();
        for (int x = 0; x < gridWidth; x++)
        {
            yield return new WaitForSeconds(spawnSpeed);

            for (int z = 0; z < gridHeight; z++)
            {
                yield return new WaitForSeconds(spawnSpeed);

                GameObject block = Instantiate(gridPrefab, Vector3.zero, gridPrefab.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.localPosition = new Vector3(x + x * gap, 0, z + z * gap);
                block.tag = "Grid Block";
                gridBlocks[x,z] = block.transform;
                gridBlocksPositions.Add(block.transform.position);
                if((x==0)||(x==gridWidth-1)||(z==0)||(z==gridHeight-1){
                    gridOuterBlocks.Add(block.transform.position);
                }
            }
        }

        gridGenerated = true;
    }
}

```

And even if you are going to use different classes, it would be useful to create `public Transform[,] gridBlocks` inside class `GenerateGrid` and add all blocks there, in order to avoid usage of the `FindGameObjectsWithTag()` because it is very resource-consuming, and finding elements at the corners would be a lot easier.

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


# Question
Title: How to blit a surface onto an already blitted surface in Pygame?
Consider the following code:

```
import pygame
pygame.init()

MAGENTA, CYAN = (255, 0, 255), (0, 255, 255)

screen = pygame.display.set_mode((800, 800))

box = pygame.Surface((600, 600))
box.fill(MAGENTA)
screen.blit(box, (0, 0))

subbox = pygame.Surface((400, 400))
subbox.fill(CYAN)
box.blit(subbox, (0, 0))

#box.blit(subbox, (0, 0))
#screen.blit(box,(0,0))

pygame.display.flip()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()

```

I would expected to get a cyan square in a magenta square in the window. However, the cyan square is not visible. When blitting the cyan square first, and the magenta square after, the intended result is achieved (see comment blocks). It seems to me more logical, and useful to be able to blit surfaces 'from bottom to top'.

Is this possible, and how? Why does my approach not work?

# Answer
You just have to blit the surfaces **inside** the main loop and also update the display at the end of it. Keep in mind that you should never blit to the screen outside of the main loop.

If you run this code below, everything will work as wanted :

```
import pygame
pygame.init()

MAGENTA, CYAN = (255, 0, 255), (0, 255, 255)

screen = pygame.display.set_mode((800, 800))

box = pygame.Surface((600, 600))
box.fill(MAGENTA)
subbox = pygame.Surface((400, 400))
subbox.fill(CYAN)
running = True

while running:
    screen.blit(box, (0, 0))
    box.blit(subbox, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
    pygame.display.flip()

```

And concerning the order of blitting surfaces, just think of the screen as layers that are blitted on each other, so the first surface you blit to the screen inside the main loop will be the background, the next one will be on top of it and so on.
> 0 votes

---
Tags: python, pygame
---


title: Unity Light Bugs in Android

text:
# Question
Title: Unity Light Bugs in Android
I was testing my game, so I made a build to test it on my phone. I noticed that when I play in an android build, it is so darker than when I play in the editor or in a PC build.

It looks like this in the editor and in PC builds:

And like this in Android builds:

It is a Unity Bug? Or is it an error in my project?

# Answer
> 1 votes
It seemed to be that I had `No Shadows` as the Shadow Type. I thought that it won't be that dark. But what I don't know is why only happened on Android builds and not in PC builds.
Changing Shadow Type to Hard or Soft Shadows should solve the problem.

Or

Leave Shadow Type in `No Shadows` and in the affected GameObjects disable both `Cast Shadows` and `Recieve Shadows` options under `Lightning` in `Mesh Renderer`

---
Tags: unity, android, lighting
---


# Question
Title: How to find names of variables on Unity components?
I’m trying to make a Distance Joint in Unity 2D. I have it set up and it works properly in the game. However, when I go to set the ‘Connected Rigid Body’ field through code, I can’t figure out what the actual variable name is to get a reference to it.

This is the variable I want to access through code:

I want to be able to set that property like this:

```
distanceJoint2D.[nameofproperty] = other.transform.GetComponent<Rigidbody2D>();

```

Is there a way to figure out what the variable names associated with its components are?

# Answer
> 0 votes
Thanks to @DMGregory for finding these docs: http://docs.unity3d.com/ScriptReference/ which have all of the components and the variables within them. The specific link to the Distance Joint 2D is here: https://docs.unity3d.com/ScriptReference/DistanceJoint2D.html So with that, the completed code looks like this:

```
distanceJoint2D.connectedBody = other.transform.GetComponent<Rigidbody2D>();

```

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


# Question
Title: How can I select random two positions from the grid outer square and also that the randoms will be from two walls facing each other?
```
IEnumerator CreateGrid()
    {
        gridBlocks = new Transform[gridWidth, gridHeight];
        for (int x = 0; x < gridWidth; x++)
        {
            yield return new WaitForSeconds(spawnSpeed);

            for (int z = 0; z < gridHeight; z++)
            {
                yield return new WaitForSeconds(spawnSpeed);

                GameObject block = Instantiate(gridPrefab, Vector3.zero, gridPrefab.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.localPosition = new Vector3(x + x * gap, 0, z + z * gap);
                block.tag = "Grid Block";
                gridBlocks[x, z] = block.transform;
                gridBlocksPositions.Add(block.transform.position);
                if ((x == 0) || (x == gridWidth - 1) || (z == 0) || (z == gridHeight - 1))
                {
                    gridOuterBlocks.Add(block.transform.position);

                    var cubeRenderer = block.GetComponent<Renderer>();
                    cubeRenderer.material.SetColor("_Color", Color.red);
                }
            }
        }

        gridGenerated = true;
    }

```

Here I color the outer grid blocks in red. But now I want to color in blue two positions each time and each one from the other outer side.

So each time I'm running the game it should pick two random positions each one from the parallel sides : For example :

Or like this :

So the two random positions will be picked from two parallel sides.

This is what I tried :

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

public class GenerateGrid : MonoBehaviour
{
    public GameObject gridPrefab;
    public GameObject pathPrefab;

    private Transform[,] gridBlocks;

    private List<Vector3> gridBlocksPositions = new List<Vector3>();

    private List<Transform> gridOuterBlocks = new List<Transform>();
    private List<Vector3> gridOuterBlocksX = new List<Vector3>();
    private List<Vector3> gridOuterBlocksXLength = new List<Vector3>();
    private List<Vector3> gridOuterBlocksZ = new List<Vector3>();
    private List<Vector3> gridOuterBlocksZLength = new List<Vector3>();

    private Vector3 startBlockPOs;
    private Vector3 endBlockPos;

    public int gridWidth = 10;
    public int gridHeight = 10;
    public int gap;
    public float spawnSpeed = 0;
    public bool gridGenerated = false;

    void Start()
    {
        StartCoroutine(CreateGrid());
    }

    IEnumerator CreateGrid()
    {
        gridBlocks = new Transform[gridWidth, gridHeight];
        for (int x = 0; x < gridWidth; x++)
        {
            yield return new WaitForSeconds(spawnSpeed);

            for (int z = 0; z < gridHeight; z++)
            {
                yield return new WaitForSeconds(spawnSpeed);

                GameObject block = Instantiate(gridPrefab, Vector3.zero, gridPrefab.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.localPosition = new Vector3(x + x * gap, 0, z + z * gap);
                block.tag = "Grid Block";
                gridBlocks[x, z] = block.transform;
                gridBlocksPositions.Add(block.transform.position);
                if ((x == 0) || (x == gridWidth - 1) || (z == 0) || (z == gridHeight - 1))
                {
                    if(x == 0)
                    {
                        gridOuterBlocksX.Add(block.transform.position);
                    }

                    if(x == gridWidth - 1)
                    {
                        gridOuterBlocksXLength.Add(block.transform.position);
                    }

                    if(z == 0)
                    {
                        gridOuterBlocksZ.Add(block.transform.position);
                    }

                    if(z == gridHeight - 1)
                    {
                        gridOuterBlocksZLength.Add(block.transform.position);
                    }

                    gridOuterBlocks.Add(block.transform);

                    var blockRenderer = block.GetComponent<Renderer>();
                    blockRenderer.material.SetColor("_Color", Color.red);
                }
            }
        }

        PickRandom();

        gridGenerated = true;
    }

    private void PickRandom()
    {
        Transform randBlock = gridOuterBlocks[Random.Range(0, gridOuterBlocks.Count)];

        if(randBlock.position.x == 0)
        {
            startBlockPOs = randBlock.position;
        }

        if (randBlock.position.x == gridWidth - 1)
        {
            endBlockPos = gridOuterBlocksXLength[Random.Range(0, gridOuterBlocksXLength.Count)];
        }

        if (randBlock.position.z == 0)
        {
            startBlockPOs = randBlock.position;
        }

        if (randBlock.position.z == gridHeight - 1)
        {
            endBlockPos = gridOuterBlocksZLength[Random.Range(0, gridOuterBlocksZLength.Count)];
        }

        for(int i = 0; i < gridOuterBlocks.Count; i++)
        {
            if(startBlockPOs == gridOuterBlocks[i].position ||
                endBlockPos == gridOuterBlocks[i].position)
            {
                var rend = gridOuterBlocks[i].GetComponent<Renderer>();
                rend.material.SetColor("_Color", Color.blue);
            }
        }
    }
}

```

But the result is all the time or 99% of the time that he pick the start position the 0,0 top left corner block and then the end position also at the top left corner the left example in the screenshot or he pick two positions start and end on same side the right example in the screenshot :

I can't make it to pick a random positions like I wanted in the two top screenshots examples with the light blue color.

The rules should be :

1. Never on the same side.
2. Never on the same position.
3. Always to pick the end position from the parallel wall side.

# Answer
> 1 votes
You could add inside the `CreateGrid()`:

```
    if (Random.Range(0,2)==0){
        var blockRenderer=GridBlocks[0,Random.Range(0,GridHeight)].GetComponent<Renderer>();
        blockRenderer.material.SetColor("_Color", Color.blue);
        blockRenderer = GridBlocks[GridWidth-1,Random.Range(0,GridHeight)].GetComponent<Renderer>();
        blockRenderer.material.SetColor("_Color", Color.blue);
    }else{
        var blockRenderer =GridBlocks[Random.Range(0,GridWidth),0].GetComponent<Renderer>();
        blockRenderer.material.SetColor("_Color", Color.blue);
        blockRenderer = GridBlocks[Random.Range(0,GridWidth),GridHeight-1].GetComponent<Renderer>();
        blockRenderer.material.SetColor("_Color", Color.blue);
    }

```

This method mostly utilizes the fact that you already have all elements of grid with their positions in `Transform[,] gridBlocks`. So using it with help of `Random.Range(0,2)` we decides will we recolor vertical or horizontal borders of the grid, afterwards just randomizing which to choose from both sides.

It would be like that in your code:

```
IEnumerator CreateGrid()
    {
        gridBlocks = new Transform[gridWidth, gridHeight];
        for (int x = 0; x < gridWidth; x++)
        {
            yield return new WaitForSeconds(spawnSpeed);

            for (int z = 0; z < gridHeight; z++)
            {
                yield return new WaitForSeconds(spawnSpeed);

                GameObject block = Instantiate(gridPrefab, Vector3.zero, gridPrefab.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.localPosition = new Vector3(x + x * gap, 0, z + z * gap);
                block.tag = "Grid Block";
                gridBlocks[x, z] = block.transform;
                gridBlocksPositions.Add(block.transform.position);
                if ((x == 0) || (x == gridWidth - 1) || (z == 0) || (z == gridHeight - 1))
                {
                    gridOuterBlocks.Add(block.transform.position);

                    var cubeRenderer = block.GetComponent<Renderer>();
                    cubeRenderer.material.SetColor("_Color", Color.red);
                }
            }
        }
        if (Random.Range(0,2)==0){
            var blockRenderer=GridBlocks[0,Random.Range(0,GridHeight)].GetComponent<Renderer>();
            blockRenderer.material.SetColor("_Color", Color.blue);
            blockRenderer = GridBlocks[GridWidth-1,Random.Range(0,GridHeight)].GetComponent<Renderer>();
            blockRenderer.material.SetColor("_Color", Color.blue);
        }else{
            var blockRenderer =GridBlocks[Random.Range(0,GridWidth),0].GetComponent<Renderer>();
            blockRenderer.material.SetColor("_Color", Color.blue);
            blockRenderer = GridBlocks[Random.Range(0,GridWidth),GridHeight-1].GetComponent<Renderer>();
            blockRenderer.material.SetColor("_Color", Color.blue);
        }
        gridGenerated = true;
    }

```

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


# Question
Title: Would using Minesweeper as a part of my game be illegal?
I want to use Minesweeper for a part of my game and I want to know if it's legal or not.

# Answer
> 9 votes
The answer depends on what you mean by "using minesweeper" and possibly what legal issue you're concerned about. If you're literally taking the code from Minesweeper and using it in your game, then that's probably a copyright violation (the original game probably isn't in the public domain, and it would be difficult to make a fair use claim). If you're merely using game mechanics that are equivalent, or close to it, to Minesweeper, that's not illegal.

> The principle laid down in Baker v. Selden was later codified in the Copyright Act of 1976, which says clearly: “In no case does copyright protection for an original work of authorship extend to any idea, procedure, process, system, method of operation, concept, principle, or discovery, regardless of the form in which it is described, explained, illustrated, or embodied in such work.”6 Thus, the idea-expression dichotomy that is fundamental to copyright law can be traced back to Baker v. Selden.
> Therefore, the systems or processes that make up the core of a game—generally referred to as the “game mechanics”—are not subject to copyright, even though the written rules, game board, card artwork, and other elements—often referred to as the “theme” of the game—may be.

https://www.americanbar.org/groups/intellectual\_property\_law/publications/landslide/2014-15/march-april/not-playing-around-board-games-intellectual-property-law

So the idea is not protected, but the expression is. That means that if you copy the artwork, etc., that can be a violation.

There may be patent issues, however, and the actual name "Minesweeper" is likely trademarked, so you should avoid referring to with that name.

# Answer
> 5 votes
The answer depends on whether you are talking about the game mechanic (a grid where selecting the wrong square means you die, selecting other squares shows you how man neighbouring squares are like this) or the artwork / look and feel of a specific implementation of a game.

* Game mechanics can’t be copyrighted, but may be patented (I’m not aware of anything covering minesweeper).
* Artwork, names etc can and are copyrightable.

See this question for some good information.

And as always, if you want proper legal advice, ask a lawyer not me

# Answer
> 4 votes
**I am not a lawyer. This is not legal advice. These are just my personal observations of the past. I accept no legal responsibility for any damages to you whatsoever.**

Many companies tried to sue other developers in the past for making a game with similar mechanics. Majority of those failed, and it will likely stay that way. Trying to claim game mechanics are intellectual property is like trying to claim chord progressions of a song are intellectual property. It just doesn't make sense.

Unless you make a literal clone of the original minesweeper (read: stealing game assets), then I would say you are fine.

I would suggest asking this question on law.se for actual legal advice. Most of us here are game developers, not lawyers. We can only talk about personal experiences and those usually vary from person to person.

---
Tags: copyright
---


# Question
Title: If a game automatically downloads addon content it doesn't already have when joining a server, how can I test this without a second computer?
What I want to do is host a local test server that has the file, and connect to it from a local client which doesn't have the file. The only issue is that both the server and the client will look for the file in the same place. So if the server has it, the client will as well. This means if I try to test the download process, it won't actually happen because the client already has the file.

I know I can test this by using two separate computers, but is there any good way to set this up locally without changing the code? Can I make a file visible to one process but not another?

# Answer
You can run a virtual machine for either the server or the client. That way you don't need to have two physical computers.
> 1 votes

# Answer
One thing you can do is make the addon path user-configurable. Besides allowing you to configure this differently on the server and the client, your end users may also find this feature useful, especially if they have multiple storage drives on their computer.

However, at least under Linux, it is possible to have a directory show up as having different contents for two different processes, by using what's called a **mount namespace**. By placing a process in a new mount namespace, it is possible to mount volumes which will only exist for that process and its subprocesses. If you create a new mount namespace, and mount a temporary file system on top of the addon content directory, you can then start the client in the new namespace and the server outside of it, and the client and server will see entirely different contents in that directory.

For the following instructions, replace `$ADDON_DIR` with the path to the addon content directory, and `$USER` with your local username:

1. Start the server normally, and tell it to use an addon you have installed.
2. Run `sudo unshare -m` in a terminal, and enter your password. This will bring you to a root shell in a new mount namespace.
3. At the root prompt, run `mount -t tmpfs tmpfs $ADDON_DIR`. This will mount a temporary, empty filesystem over the addon content directory, but will only take effect within the new mount namespace.
4. At the same prompt, type `runuser $USER`. This will switch back to your regular user in a subshell, which is still inside the new namespace.
5. From that subshell, launch the game client and connect to the local server. Since the client is running in the new mount namespace, it will see an empty addon content directory, and proceed to download the content.
> 1 votes

---
Tags: networking, client-server, modding, testing
---