title: How does entity communication work?

text:
# Question
Title: How does entity communication work?
I have two user cases:

1. How would `entity_A` send a `take-damage` message to `entity_B`?
2. How would `entity_A` query `entity_B`'s HP?

Here's what I've encountered so far:

* Message queue
    1. `entity_A` creates a `take-damage` message and posts it to `entity_B`'s message queue.
    2. `entity_A` creates a `query-hp` message and posts it to `entity_B`. `entity_B` in return creates an `response-hp` message and posts it to `entity_A`.
* Publish/Subscribe
    1. `entity_B` subscribes to `take-damage` messages (possibly with some preemptive filtering so only relevant message are delivered). `entity_A` produces `take-damage` message that references `entity_B`.
    2. `entity_A` subscribes to `update-hp` messages (possibly filtered). Every frame `entity_B` broadcasts `update-hp` messages.
* Signal/Slots
    1. ???
    2. `entity_A` connects an `update-hp` slot to `entity_B`'s `update-hp` signal.

Is there something better? Do I have a correct understanding of how these communication schemes would tie into a game engine's entity system?

# Answer
Good question! Before I get to the specific questions you asked, I'll say: don't underestimate the power of simplicity. Tenpn is right. Keep in mind that all you're trying to do with these approaches is find an elegant way to defer a function call or decouple the caller from the callee. I can recommend coroutines as a surprisingly intuitive way to alleviate some of those problems, but that's a little off-topic. Sometimes, you're better off just calling the function and living with the fact that entity A is coupled directly to entity B. See YAGNI.

That said, I've used and been happy with the signal/slot model combined with simple message passing. I used it in C++ and Lua for a fairly successful iPhone title that had a very tight schedule.

For the signal/slot case, if I want entity A to do something in response to something entity B did (e.g. unlock a door when something dies) I might have entity A subscribe directly to entity B's death event. Or possibly entity A would subscribe to each of a group of entities, increment a counter on each event fired, and unlock the door after N of them have died. Also, "group of entities" and "N of them" would typically be designer defined in the level data. (As an aside, this is one area where coroutines can really shine, e.g., WaitForMultiple( "Dying", entA, entB, entC ); door.Unlock();)

But that can get cumbersome when it comes to reactions that are tightly coupled to C++ code, or inherently ephemeral game events: dealing damage, reloading weapons, debugging, player-driven location-based AI feedback. This is where message passing can fill in the gaps. It essentially boils down to something like, "tell all the entities in this area to take damage in 3 seconds," or "whenever you complete the physics to figure out who I shot, tell them to run this script function." It's difficult to figure out how to do that nicely using publish/subscribe or signal/slot.

This can easily be overkill (versus tenpn's example). It can also be inefficient bloat if you have a lot of action. But despite its drawbacks, this "messages and events" approach meshes very well with scripted game code (e.g. in Lua). The script code can define and react to its own messages and events without the C++ code caring at all. And the script code can easily send messages that trigger C++ code, like changing levels, playing sounds, or even just letting a weapon set how much damage that TakeDamage message delivers. It saved me a ton of time because I wasn't having to constantly fool around with luabind. And it let me keep all of my luabind code in one place, because there wasn't much of it. When properly coupled, you can use embedded languages like Lua to easily add new features/monsters/weapons/levels/etc to the game without ever recompiling the C++ code.

Also, my experience with use case #2 is that you're better off handling it as an event in the other direction. Instead of asking what the entity's health is, fire an event/send a message whenever the health makes a significant change.

In terms of interfaces, btw, I ended up with three classes to implement all of this: EventHost, EventClient, and MessageClient. EventHosts create slots, EventClients subscribe/connect to them, and MessageClients associate a delegate with a message. Note that a MessageClient's delegate target doesn't necessarily need to be the same object that owns the association. In other words, MessageClients can exist solely to forward messages to other objects. FWIW, the host/client metaphor is kind of inappropriate. Source/Sink might be better concepts.

Sorry, I kinda rambled there. It's my first answer :) I hope it made sense.
> 70 votes

# Answer
```
// in entity_a's code:
entity_b->takeDamage();

```

You asked how comercial games do it. ;)
> 80 votes

# Answer
A more serious answer:

I've seen blackboards used a lot. Simple versions are nothing more than struts that are updated with things like an entity's HP, which entities can then query.

Your blackboards can either be the world's view of this entity (ask B's blackboard what its HP is), or an entity's view of the world (A queries its blackboard to see what the HP of A's target is).

If you only update the blackboards at a sync point in the frame, you can then read from them at a later point from any thread, making multithreading pretty simple to implement.

More advanced blackboards may be more like hashtables, mapping strings to values. This is more maintainable but obviously has a run-time cost.

A blackboard is traditionally only one-way communication - it wouldn't handle the dishing out of damage.
> 17 votes

# Answer
I have studied this issue a bit and I have seen a nice solution.

Basically it's all about subsystems. It is similar to the blackboard idea mentioned by tenpn.

Entities are made of components, but they are only property bags. No behavior is implemented in entities themselves.

Let's say, entities have a Health component and a Damage component.

Then you have some MessageManager and three subsystems: ActionSystem, DamageSystem, HealthSystem. At one point ActionSystem does its calculations upon the game world and generates an event:

```
HIT, source=entity_A target=entity_B power=5

```

This event is published to the MessageManager. Now at one point in time the MessageManager goes through the pending messages and finds that the DamageSystem has subscribed to HIT messages. Now the MessageManager delivers the HIT message to the DamageSystem. The DamageSystem goes through its list of entities which have Damage component, calculates the damage points depending on the hit power or some other state of both entities etc. and publishes event

```
DAMAGE, source=entity_A target=entity_B amount=7

```

The HealthSystem has subscribed to the DAMAGE messages and now when the MessageManager publishes the DAMAGE message to the HealthSystem, the HealthSystem has access to both entities entity\_A and entity\_B with their Health components, so again the HealthSystem can do its calculations (and maybe publish corresponding event to the MessageManager).

In such a game engine, the format of messages is the only coupling between all the components and subsystems. The subsystems and entities are completely independent and unaware of each other.

I don't know whether some real game engine has implemented this idea or not, but it seems pretty solid and clean and I hope someday to implement it myself for my hobbyist level game engine.
> 9 votes

# Answer
Why not have a global message queue, something like:

```
messageQueue.push_back(shared_ptr<Event>(new DamageEvent(entityB, 10, entityA)));

```

With:

```
DamageEvent(Entity* toDamage, uint amount, Entity* damageDealer);

```

And at the end of the game loop/event handling:

```
while(!messageQueue.empty())
{
    Event e = messageQueue.front();
    messageQueue.pop_front();
    e.Execute();
}

```

I think this is the Command pattern. And `Execute()` is a pure virtual in `Event`, which derivatives define and do stuff. So here:

```
DamageEvent::Execute()
{
    toDamage->takeDamage(amount); // Or of course, you could now have entityA get points, or a recognition of damage, or anything.
}

```
> 5 votes

# Answer
If your game is single player, just use the target objects method (as tenpn suggested).

If you are (or want to support) multiplayer (multiclient to be exact), use a command queue.

* When A does damage to B on client 1 just queue the damage event.
* Synchronize the command queues via the network
* Handle the queued commands on both sides.
> 4 votes

# Answer
I would say: Use neither, as long as you don't explicitly need instant-time feedback from the damage.

The damage-taking entity/component/whatever should push the events to either a local event-queue or a system on an equal level that holds damage-events.

There should then be an overlaying system with access to both entities that requests the events from entity a and passes it to entity b. By not creating a general event-system that anything can use from anywhere to pass an event to anything at any time, you create explicit data-flow which always makes code easier to debug, easier to measure performance, easier to understand and read and often leads to a more well-designed system in general.
> 2 votes

# Answer
So what happens if we have player A and B trying to hit eachother in the same update() cycle? Suppose the Update() for player A happens to occur before the Update() for player B in Cycle 1 (or tick, or whatever you call it). There's two scenario's I can think of:

1. Immediate processing through a message:

* player A.Update() sees the player wants to hit B, player B gets a message notifying the damage.
    * player B.HandleMessage() updates the hitpoints for player B (he dies)
    * player B.Update() sees player B is dead.. he can't attack player A

This is unfair, player A and B should hit eachother, player B died before hitting A just because that entity/gameobject got update() later.

1. Queueing the message

* Player A.Update() sees the player wants to hit B, player B gets a message notifying the damage and stores it in a queue
    * Player A.Update() checks its queue, it's empty
    * player B.Update() first checks for moves so player B send a message to player A with damage aswell
    * player B.Update() also handles messages in the queue, processes the damage from player A
    * New cycle (2): Player A wants to drink a health potion so Player A.Update() is called and the move is processed
    * Player A.Update() checks the message queue and processes damage from player B

Again this is unfair.. player A is supposed to take the hitpoints in the same turn/cycle/tick!
> 2 votes

# Answer
Just make the call. Do not do request-hp folllowed by query-hp -- if you follow that model you will be in for a world of hurt.

You might want to have a look at Mono Continuations as well. I think it'd be ideal for NPCs.
> 1 votes

# Answer
You have tagged the question as : "A programming paradigm in which gameobjects (entities) are composed out of components, and are operated upon by systems. Each entity is an ID that points to specific components." (note: the tags are a mess and this tag should really be called , ECS for short. Perhaps the prevailing terminology was different, back in 2010 when the question was asked.)

Yet, the question is about *entities* sending messages to each other. This is not something that exists in ECS. In an ECS architecture, components are where the data is, systems are the code that operates on the data, and entities just tie components together into coherent game objects. Entities don't *do* things except as defined by their components. Components don't really *do* things either, just tell systems what to do. When you are playing the game and you see a monster attack a player, the attack is done by (for example) the MonsterAttackSystem, not the MonsterEntity - in fact there is no MonsterEntity, just an Entity with a HealthBarComponent and a ChasePlayersComponent.

Of course, don't take this as specific advice - it might be that in your game you have something called AttackSystem or CombatSystem or ScriptingSystem, and CombatantComponent or ScriptableObjectComponent. The point is that the attack is done by a *system* and not by an entity, even if it makes the entity move on your computer screen and the strength of the attack is based on the entity's stats.

So with that in mind, both your questions need re-framing. Because the questions are vague, I will fill in specific examples:

> How would \[a spike trap\] send a take-damage message to \[a player\]?

The TrapSystem may send a take-damage message to the HealthSystem.

One way to implement this is to directly call upon the HealthSystem: `healthSystem.takeDamage(player, 20);`.

Another way is to queue this message until it's the HealthSystem's turn to run: `healthSystemQueue.append(TakeDamage(player, 20));`

One advantage of the latter is that if the player gets hit multiple times in the same game tick, the order isn't perceptible to players - even if one trap is enough to kill the player, they can still be hit by multiple traps and a monster "simultaneously" without revealing which trap is processed first. Sometimes this is desirable. It also means the player can't become dead at any time outside of HealthSystem processing, which can prevent bugs.

The rendering system could read the same event and use it to display an icon showing the amount of damage, like in Runescape.

> How would \[a monster\] query \[a player\]'s HP \[in order to target the weakest player in range\]?

The MonsterAttackSystem may query the HealthSystem to find out the player's health. This should be a direct function call, because there is no reason to defer it. If take-damage is deferred, then deferring query-hp as well makes no difference, but adds needless complexity.

At least, that works in the framework I am using, where health is private data of the HealthSystem. Depending on how your particular ECS framework does things, you might instead look up and query the HealthComponent for that entity. Details, details.
> 0 votes

---
Tags: architecture, entity-system
---


# Question
Title: How can I remove dither effect on player's shadow?
I am trying to make a dithering effect on the player so that when the camera comes below or very close to the player he will be dotted or transparent like in Genshin Impact. So, I followed a tutorial and created this shader graph:

It works when I get close to the player, the problem is that if I set `ditherOffset` to a value different than `0` and `ditherRange` to a value different than `1` the shadow will have holes in it like this:

The more I alter them, the more it fades. So, how can I fix this? Is it possible not to apply the dithering effect on the shadow?

# Answer
There are several options.

Probably the best one is to use the technique shown in this thread, where the dithering effect is disabled for the shadow pass with an `#ifdef` check. Here's how to write that in a graph using a Custom Function node:

If you are using HDRP, there is also a parameter called Shadow Threshold which sets a separate clipping threshold specifically for the shadow pass. I'm not sure if something similar exists for the other RPs.

And lastly, the nuclear option is to duplicate the mesh, have the "normal" mesh not cast shadows at all, and set the duplicate (with a separate material that does not have dithering) to only cast shadows and not be rendered otherwise. But this is the worst option, in my opinion.
> 1 votes

---
Tags: unity, shadows, unity-shader-graph
---


# Question
Title: How to make root motion animation roll in world coordinates instead of local?
I am currently prototyping a top down 3D game in Unity 2021.3.4f1.

My character moves with standard "WASD" and always faces towards my cursor's location on the screen. The camera is fixed and wont rotate with the character at all. Simply described in the picture below:

My current solution to roll at the correct angle is with a 2D freeform Cartesian animator blend tree, please see below attached SS on set up and script to control the Parameters: `MoveX` and `MoveZ`:

(Please disregard the * -1 in the `GetAxis`, its simply corrected for my character that's 180 degrees rotated in game)

Basically moving character "up" with "W" and pressing roll bind with roll the character "up". No problem so far.

My issue with the presented solution is when the character starts to rotate towards the cursor. `GetAxis` works in local coordinates described in below picture:

As soon as I rotate my character the coordination system rotates with it locally:

This causes major issues with my roll animation that uses root motion and basically dash the character in its local coordinate system, but I want it to dash in my world coordinates. Trying to describe in the some what confusing picture below:

This video is showcasing the issue in game.

You can clearly see in first rolls that the character rolls in the direction that the character is moving. When rotating 180 degrees its exactly mirrored.

My first thought since I'm not a to good coder is to do a massive If/else statement controlling my `MoveX` and `MoveZ` parameters when moving with WASD. Or I replace the `Input.GetAxis` to get it in world coordinates (haven't found any way to do this)...

What is the simplest and most elegant way of achieving above results?

# Answer
If I understand the problem correctly, you just need to transform the desired world-space movement into a local-space vector to feed it into the blend tree, yes?

In that case, something like this could work

```
Vector3 worldMovement = new Vector3(moveX, 0, moveZ);
Vector3 localMovement = transform.worldToLocalMatrix.MultiplyVector(worldMovement);
animator.SetFloat("MoveX", localMovement.x);
animator.SetFloat("MoveZ", localMovement.z);

```
> 0 votes

---
Tags: unity, c#, animation, root-motion
---


# Question
Title: How do I make the dialogue visibility a toggle based on user input?
So the code is working but when I press `F` key again it starts from the beginning but I want it to disappear and if the player wants to see it again to press the `F` key once more to see the dialogue again. I know that my mistake is in the void `EndDialogue()` but I don't know how to fix it.

This is the dialogue script

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Dialogue : MonoBehaviour
{
    public GameObject window;
    public GameObject indicator;
    public TMP_Text dialogueText;
    public List<string> dialogues;
    public float writingSpeed;
    public int index;
    private int charIndex;
    public bool started;
    private bool waitForNext;
    private void Awake()
    {
        ToggleIndicator(false);
        ToggleWindow(false);
        started = false;
    }
    public void ToggleWindow(bool show)
    {
        window.SetActive(show);
    }
    public void ToggleIndicator(bool show)
    {
        indicator.SetActive(show);
    }
    public void StartDialogue()
    {
        if (started)
            return;
        if (waitForNext)
            return;
        started = true;
        ToggleWindow(true);
        ToggleIndicator(true);
        GetDialogue(0);
    }
    private void GetDialogue(int i)
    {
        index = i;
        charIndex = 0;
        dialogueText.text = string.Empty;
        StartCoroutine(Writing());
    }
    public void EndDialogue()
    {
        started = false;
        waitForNext = false;
        StopAllCoroutines();
        ToggleWindow(false);
    }
    IEnumerator Writing()
    {
        yield return new WaitForSeconds(writingSpeed);
        string currentDialogue = dialogues[index];
        dialogueText.text += currentDialogue[charIndex];
        charIndex++;
        if (charIndex < currentDialogue.Length)
        {
            yield return new WaitForSeconds(writingSpeed);
            StartCoroutine(Writing());
        }
        else
        {
            waitForNext = true;
        }
    }
    void Update()
    {
            if (!started)
                return;
        if (waitForNext && Input.GetKeyDown(KeyCode.F))
            {
                waitForNext = false;
                index++;
            if (index < dialogues.Count)
            {
                GetDialogue(index);
            }
            else
            {
                ToggleIndicator(true);
                EndDialogue();
            }
        }

    }
}

```

and this is the dialogue trigger script

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DialogueTrigger : MonoBehaviour
{
    public Dialogue dialogueScript;
    private bool playerDetected;
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.tag == "Player")
        {
            playerDetected = true;
            dialogueScript.ToggleIndicator(playerDetected);
        }
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            playerDetected = false;
            dialogueScript.ToggleIndicator(playerDetected);
            dialogueScript.EndDialogue();
        }
    }
    private void Update()
    {
        if (playerDetected && Input.GetKeyDown(KeyCode.F ))
        {
            dialogueScript.StartDialogue();
        }
    }
}

```

# Answer
I fixed it: I just had to move the void `Update()` from the dialogue script to the dialogue trigger script and it worked perfectly.
> 0 votes

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


# Question
Title: does having code spread in multiple files decrease performance?
Let's say there's a game that I could code in 1 file main.py but I decide to split it in more files like:

main.py graphics.py settings.py interface.py menu.py

and so on, would the game in turn perform slower because it has to import data from multiple instances instead of just loading all the code at once in a single file?

From my understanding it should make a difference, even if minuscule, is it true?

# Answer
> 2 votes
Partitioning code into different files is the right thing to do, If the project is small (only a few hundred lines) and you want to focus on finishing it at the moment, you can put all the code in one file, But as your program gets longer, you may want to split it into several files for easier maintenance.

Your guess is basically correct, putting all the code in the same file will improve performance, Python uses modules to manage different files. You can use the `import` keyword to introduce the contents of other files into the namespace of the current module, so multi-file projects have this extra performance overhead. but this is negligible, and using single file will bring a series of other harm.

Python is an interpreted language, but it will "compile" the source code into bytecode and store it in a disk file (`.pyc`) for faster loading. The granularity of this compilation is a `.py` file. They are stored in a common cache directory (`__pycache__`). The python interpreter checks the modification date of the `.py` source code to determine whether it needs to be recompiled. That is, if you are working on a project with 10,000 files, when you modify a source file and hit the run button, only one file will be recompiled. This greatly reduces recompilation time. When all the source code is in the same file, the compilation time will be longer. This mainly affects development efficiency. (To clarify here, the compiled `.pyc` will only affect the file loading speed rather than the execution efficiency.)

In addition, a single file that is too long will affect the rendering efficiency of a text editor, especially a text editor that uses the error checking function. But its main harm is to reduce code readability and portability.

In conclusion:

1. Single file is better if you focus on completing the current small project.
2. If you are trying to use design patterns, cultivate a good code style, etc., it is good to use multiple files in a small project.
3. In large projects, using a single file to store source code greatly reduces code quality and development efficiency. It brings negligible performance gain. Reducing the number of files has never been one of the options for improving performance.

# Answer
> 1 votes
It depends. This question on Stack Overflow asked why performance dropped after refactoring related classes into separate files.

In that particular case, the answer was that the slow down came tight loops that accessed the functions/classes from another module. The additional interpreter lookup added a slight slowdown that accumulated. The is also backed up by an optimization tip in the Python wiki to consider alternatives to function references in loops.

I think that it's important to note a couple of things. The first is that this was discovered through benchmarking. If your code is underperforming, use tools like benchmarks & profiling to determine where the problems actually are rather than guessing & changing code that is unrelated to the problem. The second is that the wiki itself says that the suggested solution should be used with caution. Optimizations can make code more difficult to maintain which in turn makes it more difficult to make sure the code is correct.

---
Tags: pygame
---


# Question
Title: GridMap centers meshes of different heights in cell
I am trying to use the superb GridMap in Godot 4 beta 5.

I have, so far, only 2 different types of meshes in my `MeshLibrary`.

1. 1x1x1 cube
2. 1x1 plane

My intention is to use the plane as a floor

All meshes were designed in blender, exported with GLTF 2.0, and their scales are all set to 1 and applied. They all seem to import perfectly.

This image illustrates my issue. On the left, you can see the cube and the plane as child nodes of the root node. The bottom of the cube and the plane are aligned with y = 0. On the right, the sames meshes, only in a `GridMap`. You can see that the cube is correctly positioned, but the plane is centered in it's cell in the x, y and z directions. Obviously, only the Y causes an issue.

If I untick "Center Y", the plane aligns properly but then the cube is 0.5m too low...

I'm not sure I'm phrasing the question correctly but:

How can I make sure the origins of all the meshes are aligned with the y=0 plane of the `GridMap`?

# Answer
Select (or open) the `MeshLibrary`, and on the top bar you should see a "MeshLibrary" menu, there select "Update from scene" and select "Apply with Transforms", that should fix the issue.

---

**Addendum**:

> I see the option, but it's greyed out. Any ideas?

The result of using "Apply with Transforms" should be equivalent to changing the origin of the Mesh Transform.

You can do that manually: Open the `MeshLibrary` in the inspector, go to the "Item" you want to displace (They are numbered in the same order they are displayed in the `GridMap`). Once you found the one you want (e.g. the "Rock"), go to the "Mesh Transform" property, there the last column is the origin (it is a 3x3 basis augmented with the origin vector). You can tweak the values to what you want (e.g. set the "yo" component to `1` or `0.5`).
> 3 votes

---
Tags: transformation, 3d-meshes, godot-4
---


# Question
Title: How do I use elementals to deepen jRPG combat strategy?
I want my game to feature deep strategy--for players to want to sit there considering their next move as in a game of chess.

Things like elemental resistances reward players who research their opponent, but the ultimate strategy of using fire attacks against ice monsters is still relatively shallow. Increasing the size of the elemental table, as in Pokemon, doesn't seem to make combat much deeper.

Things I've considered to create depth include using a multi-axis elemental system (say, there are hot-wet, and hot-dry elementals), and for elemental techniques to buff and nerf stats and elemental resistances so that players have to consider a more complex state as a fight evolves. What other mechanics might I consider to make my elemental system feel deeper? Or are there more fundamental avenues I should first consider in creating depth?

# Answer
> 17 votes
Elemental resistances usually create strategic depth but not tactical depth. Strategic depth means that they affect which characters are good in combat and which are bad.

Let's take Pokemon, for example. The elemental resistances / vulnerabilities and the different moves available to each mon mean that not every mon is a good matchup against every other mon. That means the player who only trains a single mon will fail as soon as they face an opponent that hard-counters it. So the player needs to train multiple mons with different elemental types and moves to make sure they have the right mon for every occasion. This forces the player to strategize while deciding which mons to invest time into.

But this only works when the player can actually decide what kind of characters they bring into battle. Many JRPGs don't allow that. The player has to fight with whatever characters are in their party at that point of the story and the options to customize the abilities of these characters are limited. So the player can't strategize based on elemental resistances and vulnerabilities. They can only make tactical decisions regarding which abilities to use. However, this gives you as the designer the option to make characters appear weaker or stronger during parts of the story where that feels appropriate for the narrative without actually changing their stats. You can make an individual character shine simply by confronting the player with lots of enemies that are vulnerable to that character's attacks.

Another way to make elemental resistances more interesting is by not making them static but dynamic. That means that enemies might change their resistances during combat. Either automatically, or triggered by the player's actions. That forces the player to decide what to do when. For example, an enemy that changes their resistances based on the element of the last attack that hit them. Or one that transforms through different forms, with each form having different resistances. Or you could have opponents that change their strategy when hit by elemental attacks (a common gimmick in 16bit Squaresoft JRPGs were opponents who would retaliate against each attack with an attack using the same element).

# Answer
> 3 votes
Have you considered a drenching system?

Have elemental attacks buff the damage of other later elemental attacks from a different type

An example that makes sense is water attacks (and root of the name), make affected creatures vulnerable to lightning damage but grants resistance to fire damage (because they are wet). Fire attacks dry creatures out making them soak up more water when hit by a water attack, and do more damage to.

I don't know what other effects that you could do that would make sense out of game. But you don't necessarily need real world logic to work... This works best of the elements can be used in a spider wave of chains rather then a boring cycle of fire makes water better makes lightning better...

# Answer
> 1 votes
Typically, the assumption is that it effective attacks deal more damage. But as you've discovered, allowing the player to optimize for damage isn't necessarily an interesting system. Instead of relying only on damage, I would strongly consider pairing additional, non-symmetric mechanics or traits with your elemental system.

Here's a simplified example:

* Paper
    + Bonus damage against rock
    + Smothering: hits an additional random target
* Rock
    + Bonus damage against scissors
    + Smashing: bonus damage against full health enemies
* Scissors
    + Bonus damage against paper
    + Bleeding cut: deals an additional damage over time

With the additional riders, in some situations it becomes worth considering attacks other the the basic rock-paper-scissors triangle. Rock has an incentive to be used as as an opener. Scissors has an incentive for battles that are likely to drag out & also makes a good opener. Paper adds some randomness as it may steer the player toward eliminating an injured target rather than focusing just on biggest threat. And if there's just one enemy left, paper effectively gets bonus damage.

Since the riders are asymmetric, each element has its own characteristic feel. Ideally, they provide mechanics that support your game's theme &/or story. It's okay to bend that rule in places. For example, if paper has lots of area of effect attacks & scissors has only one, then that one area of effect scissors attack will stand out. But I would advise against balancing to the point where every rider is equally available to every element as that effectively reduces the meaningful differences between the options.

# Answer
> 1 votes
This is what I've been able to come up with:

* Consumable items (or equipment) that buff elements. Of course.
* You can have elemental chains/combos. In this case an element would get a bonus if used after another element. So it might be advantageous to use a weak element for the situation in order to set up a bigger follow up.
* If you have the means to allow mixing skills (e.g. combined techniques by two party members, or by a single character by picking from its own techniques) then you could also elemental combination generate a different elements. You can take this further and say that there are only elements, and it is the combination of elements (performed during battle) which creates different powers/spells/magic.
* Your enemies - in particular bosses - could change their own elemental resistances during battle. For example, a common trope is a boss that is weak to the last element is used. Another is a boss that has different weaknesses on different phases.
* You could add another component into the mix. Such as the terrain, the time of day, or the weather. Which would also make some elements more or less effective. And you might even have magic that changes said component during battle.
* Speaking of another component: give a random element have a buff each turn. To take it one step further, pull it from a deck built by the player, so the game is also a deck building game (and the deck could have other kinds of cards too).

# Answer
> 1 votes
Depth comes from the optimal choice not being straightforward to determine. As you note, simply increasing the number of element types makes it "harder" to determine the correct choice, but only in a trivial sense; it is still straightforward, it just takes longer.

You can make it harder to determine the optimal choice by making the outcome depend on more variables - so it's not just a matter of what the enemy's resistance or weakness is, but also e.g. their location in the battle arena, their distance from the player, what protective spells they have used, what attack you used last turn, or so on. This is sort of what puzzle games do - there is still one definitely optimal choice that does the most damage, but it's harder to figure out what that choice is, and if the puzzle is designed well then the player enjoys figuring it out.

You can also make it harder to determine the optimal choice by adding more variables to the outcome. Suppose the spell you cast doesn't just damage the enemy you target, it might apply status effects, it could damage enemies nearby, or allies nearby, or perhaps also damage yourself; it might affect the battle arena in some way, e.g. melting ice, moving an obstacle, blocking visibility. Or so on. The point here is that the outcome is not a one-dimensional space where doing more damage is better. This is more what strategy games are like - there isn't an obvious metric by which you can judge short-term actions, rather it's up to you as the player to make a judgement about the relative values of each possible outcome.

# Answer
> 1 votes
The thing that gives Chess its strategic depth is that the moves each side can make (and especially the moves that each side can **safely** make) depend strongly on every move that has been made so far.

Each side doesn't just have a simple current state (e.g. hitpoints and mana remaining) where it doesn't matter how they got there, the "fight state" state is a complex arrangement of all the pieces, essentially very little less information is relevant than the entire move history of the match. (At least until the end game where there aren't many pieces left; at that point lots of different move histories could have reached this state)

Combined with this, it's very difficult to gain a lot in a single move that cannot be countered (although novices such as myself may not reliably see the threats to counter them).

The net result is that every time you make a move you need to consider what state you're working towards several moves ahead, trying to gradually manoeuvrer your opponent into a weaker position over many moves. (And also considering what state your opponent is simultaneously trying to manoeuvrer you towards!)

Typical jRPG combat has you deciding what attack to use against what enemy (or what non-attack ability to use instead, e.g. heals, buffs, debuffs etc), trying to maximise the damage you're able to do to the other side and minimise the damage they'll be able to do back. A more complex system of resistances and vulnerabilities makes these choices more interesting. For example, if to win I need to both heal my party and kill some monsters in the combat so that I'm taking less damage, and if all attacks are equally good against all target, then I'll just use my strongest healer to heal and my strongest attacker to attack (targetting either the enemy with the lowest HP or the strongest attack). But if each of my party attacks with a different element, then which one **is** the "strongest attacker" depends on which enemy I decide I need to take down first; there can be complex trade offs where I'm sometimes better off attacking with my strongest healer, and therefore someone else needs to heal instead, etc.

But this kind of complexity still doesn't ultimately create that "chess like" flow of both sides angling for position over multiple rounds. The clashes still essentially "add up" in the HP damage exchanged (and resources depleted) over time, rather than forming a combinatorial explosion of possibilities. You can make the best move take more knowledge of the game systems and the enemies and more complex calculation to determine.

So if you're after a "chess-like" experience where players carefully consider their moves based on thinking through a long term strategy, rather than just repeatedly calculating the best move for the next round or two, maybe you need to think rather differently than a typical elemental resistance & vulnerability system. Maybe you can build up very powerful effects via *sequences* of elemental effects applied over multiple rounds, with the enemies also choosing between building up sequences of effects on your characters vs disrupting the ones you're trying to do to them. Or something along those lines.

# Answer
> 0 votes
Top of the list would be making the system dynamic in some way. IOW, instead of having a system where a given character only has one elemental attribute to their attacks, something allows the players to change the attributes, either outside of combat (for example, by modifying their weapons, or learning specific attacks), or in combat (perhaps you can swap characters in-combat like in Pokémon, or maybe they are able to spend an action in combat to just reconfigure their weapon).

This gives players more direct agency in choosing how they fight, in addition to allowing them to more efficiently utilize elemental effects. For example, if the game lets the player swap out elemental attributes outside of combat, but does not limit where they can do this, then players who have trouble with a boss can use this to make the fight easier.

---

The second thing I would recommend is to make the choice of element more than just a simple matter of looking up numbers in a table. Each element should have things it’s good at and things it’s bad at independent of damage, and ideally should also have specific buffs and debuffs. For example, maybe fire excels at applying a damage-over-time debuff, and specific fire attacks add additional effects to burning enemies. Maybe ice is good at reducing enemy movement or swinging the action economy in favor of the players.

There’s literally a million things you can do here, but the important thing is that this aspect helps incentivize playing differently for reasons other than just raw numbers, which in turn lends depth to the system because you have to consider more than just numbers.

---

My third recommendation is to have interactions between the elements that are *not* pure numbers. For example, it makes logical sense that using a fire attack on an enemy that’s frozen solid would thaw them out (this is actually a thing in Pokémon games for example). Similarly, maybe a water attack will put out an enemy that’s on fire. And the interactions don’t all need to be negations like this. Maybe ice attacks do bonus damage to enemies that just got hit by water attacks (the water freezes) or fire attacks (emulating thermal shock).

This further builds upon the second point above, making it even less of a case of simply looking up an element in a table to decide what to use, and incentivizes experimentation if combined with the first suggestion above.

# Answer
> 0 votes
## Elemental Attributes are Bad for Strategic Depth

We've see it done so many times, that we just assume it is good for making a game more strategic... but it actually does the exact opposite. It makes the relationship between any two given adversaries more predictable which makes any other rules in your game less meaningful.

Let's take a common elemental chart like this:

Now lets say you have to choose between attacking with a Fire Hero who drops a single enemy's defense by 30% for 5 turns, and an Earth Hero who can AoE silence spells and poisons enemies for 90 damage over 3 turns, and you are going up against a Water hero who can reduce accuracy by 40% for 4 turns... who do you bring?

Knowing which power is best is really hard to guess and may change a lot based on the battlefield and what other heroes there are; so, without elemental factors to worry about it takes a lot of critical thinking skills to decide which one is better... but once you put in elemental bonuses, it becomes clear that you should attack with the Earth hero, because all other powers aside, you know he will do better than your Fire hero.

What normally happens in JRPGs is that your heroes have an element, a level, and unique powers. If your level is high/low enough, there is no strategy. The battle is a lost cause for one side or the other. Then you match up colors to offset some of that level to punch a bit above your weight class... while this is a satisfying experience for many players, it is just as deterministic as not having elemental bonuses. Now lets imaging you have 15 well leveled heroes to pick from and can only bring 3. Each of those heroes has some unique power that may or may not help based on the unique powers of your enemies. There are many matchups to consider, but if the enemy has 3 fire heroes, you will always want to bring your 3 water heroes no matter what. 12 possible strategies are immediately removed from consideration based on a counting and color matching strategy that a 4 year old can solve. If you remove the elemental bonuses and simply drop the matchup level of enemies a bit, then the game becomes more strategic because now all 15 heroes are valid picks. You can still hit above your weight class a bit, but only with well though out combinations of powers that takes a much more mature though process (and a fair amount of trial and error) to figure out.

## Why Are Elements so Popular?

They are popular because they reduce the difficulty of a seemingly complex game. Game designers often have to choose between complexity and playability. If your game is too complex, then it will only appeal to niche audiences, but simple games appeal to people of all intelligences. Games like Pokemon are appealing to children because before you learn all the complex rules, you can still do well understanding only the very basic rules of levels and elements.

They can also be seen as helpful for making games where the point is to collect a lot of different heroes. If you have 100+ heroes in your game, seeing a lot of thier powers and roles overlap in inevitable. Elemental bonuses can basically be used to copy many very similar powers/roles across many heroes without making any one of them completely useless because having an Earth Healer might not be very helpful when fighting a Fire Army, so also owning a nearly identical Water Healer becomes important. This does not really make the game more strategic though, just makes it easier to stuff in lots of extra content and grinding to increase play-through time.

If you want a game to be enjoyed by millions of players of all ages and demographics and keep people entertained for a long time, then elements is a smart way to go, but if you want to make a very tactical game that focuses on thinking things through... it's actually better not to have them.

## The deepest strategy comes from the vaguest METAs

Part of what makes Chess so strategic is that both players have characters with a wide range of powers, but no one piece can be uniformly described as superior. Pawns are numerous making them good sacrificial pieces for baiting traps and blocking movement. Rooks, Bishops, and Knights can all cover a lot of ground but have significant blind spots that can be exploited. The queen is a bit OP, but you only get 1 so you have to plan heavily around what the queens are doing... but at the end of the day, a well played pawn is every bit as lethal as the queen. Bishops don't beat Rooks because anyone playing a Bishop can always beet a Rook with one, but they beat them WHEN one player does a better job of maneuvering the bishop, than the Rook player does of maneuvering the Rook.

If you add elemental abilities, make them represent abilities and not paper-rock-scissors relationships. Maybe all Fire heroes have a chance to cause burn damage, all dark heroes have a chance to drop enemy accuracy, etc. That way, it becomes more about bringing the right hero for the job, and not any one of the right 30 heroes for the color matchup. Another way elements works is to tie them to skill trees: so, you could make it such that all Fire heroes get a common set of skills and bonuses they can get, (probably in addition to individual hero or class skills and abilities.)

---
Tags: game-design, rpg, balance
---


# Question
Title: SharpDX 3d Camera Rotation clamping Camera y rotation
Im trying to make some 3D graphics in C#.

Everything been working out great so far except for one thing.

I want a fps-like camera, that stops when looking down / up.

## I Tried:

* Clamping the "rotationY" variable. (Using MathF.Clamp)
* Clamping the "rotationY" variable. (Using if statements)

None of which worked.

Any help is appreciated!

Code:

```
float rotationX = 0;
float rotationY = 0;
float dist = 1;

Window.MouseMove += (s, e) = >
{
    if (e.Button == MouseButtons.Left)
    {
        var yRotate = lastX - e.X;
        var xRotate = lastY - e.Y;
        rotationX += xRotate * moveFactor;
        rotationY += yRotate * moveFactor;
        lastY = e.Y;
        lastX = e.X;

        float h = cos(rotationX) * dist;
        Vector3 cameraTarget = Vector3(cos(rotationY) * h, sin(rotationX) * dist, sin(rotationY) * h);

        viewMatrix = Matrix.LookAtRH(cameraPosition, cameraPosition + cameraTarget, cameraUp);

        updateText();
    }
};

```

# Answer
Fixed it by Clamping the "rotationX" variable.
> 0 votes

---
Tags: c#, 3d, sharpdx
---


# Question
Title: How do you resolve continuous collision in a multi body system?
I've been trying to figure this out for weeks but every resource only provides answers for a single body. As far as I can tell for a single body you

1. Find the time of impact
2. Step up to that time
3. Resolve collision
4. Restart from 1 until there's no impact until present frame

I've also seen some engines limit these "sub steps". The closest I could find is that an engine steps each body to their first collision. But what if A and B collide at 0.1 and A and C collide at 0.4. If we resolve the AB collision, the AC collision may not exist, thus stepping C up to 0.4 would be incorrect.

My question is, for multi body systems, how do you go about resolving and stepping continuous collision?

# Answer
I wrote this free article last month that you may find useful: Perfect, Infinite-Precision, Game Physics in Python. It covers multiple collisions. Although I used Python, the math and methods work for any language. It also has links to other discussions and references. The biggest surprise for me was that Newtonian physics is (at best) incomplete and (at worst) non-deterministic.

* Carl
> 0 votes

---
Tags: collision-detection, physics, algorithm, collision-resolution, physics-engine
---


# Question
Title: How to Start with a Flashlight in the Off Position on Start
I'm fairly new to Unity, and I have a script I'm working with that plays two different flashlight sounds (one for the off and one for the on position).

Here's the script I'm currently working with:

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

public class FlashlightClick : MonoBehaviour
{
public Light flashLight;
public AudioSource AudioSource;

public AudioClip soundFlashlightOn;
public AudioClip soundFlashlightOff;

private bool isActive;

void Start ()
{
    isActive = true;
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.F))
    {
        if (isActive == false)
        {
            flashLight.enabled = true;
            isActive = true;

            AudioSource.PlayOneShot(soundFlashlightOn);

        }
        else if (isActive == true)
        {
            flashLight.enabled = false;
            isActive = false;

            AudioSource.PlayOneShot(soundFlashlightOff);
          }
       }
    }
}

```

The script creates four variables: Flash Light, Audio Source, Sound FlashLight On, and Sound FlashLight Off.

On the Flash Light variable, I have the flashlight (just the spotlight game object), on Audio Source, I have the FPSController object, and on Sound FlashLight On and Sound FlashLight Off I have the two sounds for the flashlight toggles.

When I start the game, the flashlight is on by default. Any ideas how to modify the script so that my character starts with the flashlight set to off?

Components added to FPSController, NOT FirstPersonCharacter

Thanks in advance for any guidance!

# Answer
You could disable the Light component in the gameobject / prefab, or just make sure the flashlight is disabled in `Start`:

```
void Start ()
{
    isActive = false;
    flashLight.enabled = false;
}

```

By the way: I find it a bit weird that you have the line `isActive=true` in your Start-method, and then wonder why it starts in the enabled state. I mean, it wouldn't work to just set this one to `false`, because it only affects the state of this controller, not that of the light. But it makes me think that you perhaps copied that code from somewhere. It's generally not a good idea to just copy code into your project when you don't understand how it works and what it does. That might cause lots of problems down the line.
> 0 votes

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


# Question
Title: Assign clickable function to UI Button Unity
So I'm trying to change the function of a button by a clickable method in Unity. I'm using a `GetComponent` to access the button component of the game object and then assign the clickable function.

But I get this error:

> GetComponent requires that the requested component 'Button' derives from MonoBehaviour or Component or is an interface

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
using Button = UnityEngine.UIElements.Button;

public class Button_System : MonoBehaviour
{
    public GameObject Button01;
    public GameObject Image01;

    public void Start()
    {
        Button01.GetComponent<Button>().clickable = new Clickable(Example);
    }

    public void Example()
    {
        Image01.SetActive(false);
    }

```

# Answer
See the documentation for the UI Toolkit:

> In UI Toolkit, the visual tree is virtual and doesn’t use GameObjects. You can no longer build or view the UI hierarchy in the hierarchy view, but it removes the overhead of using a GameObject for each UI element.
>
> ...
>
> Since there are no GameObject or components in UI Toolkit, you can’t directly assign references to a control in the Editor. They must be resolved at runtime using a query function. Instead, access the Visual Tree via the UIDocument component.

So you cannot use `GameObject.GetComponent()` to get access to a `UIElements.Button` component, because this kind of button is not a component that gets attached to a `GameObject`.

Instead, as shown in the docs, you need to take a reference to the UIDocument component at the root of the visual tree, and use a query:

```
public UIDocument uiDoc; // Assign this in the Inspector.

public void Start()
{
    // Finds a Button-type element with a specific name under the root.
    var button = uiDoc.rootVisualElement.Query<Button>("element name");
    // Now do what you want with the button.
}

```
> 0 votes

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


# Question
Title: How to detect if a mobile device is a foldable phone?
There are new "foldable" mobile devices such as Samsung foldable phones.

Is there any way we can write a C# script in Unity to detect if the device is a foldable phone ?

I try, but can't find any online tutorial on how to do this yet.

# Answer
Searching for "samsung foldable phone api" brings up the Android developer documentation on foldables which links to the information on making your app fold aware:

> To make your app fold aware, use the Jetpack WindowManager library, which provides an API surface for foldable device window features

All of the code examples in the above mentioned Android developer documentation are in Java or Kotlin. However, searching for "Jetpack WindowManager library c#" brings up Microsoft's documentation for the Jetpack Window Manager for Unity. The Microsoft docs include Unity game samples for Surface Duo and an accompanying explainer blog post:

> To access the new APIs from Unity, copy the C# code from the file SurfaceDuoScreenHelper.cs from GitHub into your game. This will provide the following functionality:
>
> **DeviceHelper.IsDualScreenDevice** – Call this method before accessing other dual-screen APIs.

`IsDualScreenDevice()` returns a `bool` indicating whether your app is running on a dual-screen device.
> 4 votes

---
Tags: unity, c#, mobile, resolution, aspect-ratio
---


# Question
Title: Function to calculate exponentially cumulative debuffs
Let's say I have a character with a number of stats. I want a function to calculate the current effective value of my character's attack after some number of debuffs are applied, with each debuff being more punishing than the last. The number of debuffs can be from 0 to 4.

The opposite case is easy: I use a logarithmic function to calculate the diminishing returns of applying more than one buff to a stat. Logic says that I should use an exponential function to handle the debuffs, but I can't quite figure out a function that works as intended.

Let's call the function `calculateStat(baseValue, numberOfDebuffs)`. We'll say that one of my character's stats has a base value of 100. Here are the expected outputs of the function:

```
calculateStat(100, 0) = 100 // pretty obvious
calculateStat(100, 1) = 90  // a flat 10% decrease; let's call this 'a'
calculateStat(100, 2) = b ; b < 80 // b should be less than 80% of the base value
calculateStat(100, 3) = c ; a-b < b-c // the difference between b and c should be larger than the difference between a and b
calculateStat(100, 4) = d ; d ~= 0, b-c < c-d

```

Since there are only five possible values for `numberOfDebuffs` I've considered simply making this a piecewise function with some rough approximations for each value, but I'd rather have something more elegant that "just works" for each of the values if possible.

My problem with exponential functions like `calculateStat(baseValue, numberOfDebuffs) = baseValue - baseValue * (0.1) ^ (1/numberOfDebuffs)` is that it doesn't work for `numberOfDebuffs = 0`, and it trends too quickly towards 0 to start with. The difference between 1 and 2 is greater than the difference between 2 and 3, which is the opposite behavior of what I want to achieve.

I'm not great at math, so there may be a very obvious solution that I'm missing.

# Answer
What I needed for this specific case was an "upside-down" quadratic. `-5x^2-5x+100` gives 0=100, 1=90, 2=70, 3=40, and 4=0. I asked WolframAlpha to interpolate the three known values (0, 100), (1, 90), and (4, 0) to get this result.

If I change my design to accept values \>=5 I'll need to recalculate the equation but this works perfectly fine for now.
> 1 votes

---
Tags: mathematics
---


title: Raster Graphics vs Vector graphics

text:
# Question
Title: Raster Graphics vs Vector graphics
There was this game that I used to play when I was a kid. It's named Another World. It was ahead of its time in graphics, it even has real-time cutscenes on the SNES version. That game does not use any image files, it draws everything using vectors.

Wikipedia says the game devs used vectorization to reduce memory use. If raster graphics have fixed resolution and use higher memory, then why vector graphics isn't being used in games? Are there any downsides?

---

I mean, today we have 8K graphics and this can generate a heavy raster file. Wouldn't we have more performance using vector graphics?

# Answer
## Memory isn't that much of an issue as it was in the 90s.

The SEGA Mega Drive had only 64 kB of RAM and another 64 kB of VRAM. Yes, KILObyte. And it rendered at 256x224 pixels at the lowest resolution mode with 6 bit per pixel. That meant that there was barely about enough VRAM for one screen full of pixels. And then you have nothing left for sprites. So if you want a full-screen bitmap image that doesn't consist of repeating tiles, you can barely have any motion in it.

But PCs today? The best screens today (UltraHD aka "8k") have 7689 x 4320 pixels at 4 byte per pixel = 126 MB. As you know, RAM sizes of both system RAM and video RAM are measured in GB today. Which means that you can comfortably fit not just one but several full-screen bitmaps into memory at once. You don't *need* to use clever vectorization tricks to fit graphics into memory.

## We got better tricks today

Although RAM is now far more plentiful, you can never have enough. More VRAM means more and larger textures which allows game scenes with a higher visual fidelity. But there are other tricks today we use to conserve (V)RAM through more use of processing power:

* Texture compression means that we have textures in packed formats which get unpacked on-the-fly during rendering. We use algorithms which are either lossless or have losses you are not going to perceive, so it doesn't really impact the aesthetics of the game. That means the aesthetics of games today are less driven by technical constraints and more by the creativity of the artists.
* Pixel shaders can be used to generate the texture of a polygon procedurally on the GPU while it is being rendered. Although pixels shaders often use one or more textures as input, there are also shaders which have no input textures at all and generate the color value solely as a function of the texture coordinates. That is another processing power for RAM trade, but one which *does* affect aesthetics, because it allows us to do things that would be hard to accomplish using static textures. Sometimes this is used for things you can call "vector art". Signed Distance Fields, for example.
* Vertex Shaders and Geometry Shaders do the same thing, but for the shape of 3d models instead of their textures.
> 2 votes

# Answer
1. One can think of 3D graphics as being vector. After all, despite the internal "3D World", they are still vertices and vectors, just with some fancy textures and lighting/shaders thrown on top to make them look "nicer". In that sense vector graphics is kept being used since.
2. Pure vector graphics imply minimalistic look. Some games choose it (e.g. Superhot is quite vector-y). But in modern day and processing power available, it's very easy to throw in some after-effects like SSAO and DoF and such, that make the graphics overall "smoother", yet steal a bit from the pure vector style.
3. In the end, everything gets rasterized into pixels on your display. Vector or not, it becomes raster. Difference is "when" it does so and what aesthetics it tries to be.
> 2 votes

---
Tags: rendering, rasterization, vector-art
---


# Question
Title: Unity UNET Project suddenly does not work anymore
I have an older Unity Unet Game which I build 2 or 3 years ago and forgot about it. Now I wanted to show it to a friend but it does not work anymore. When I start the server as player1 in the editor I can see that player2 can join and no errors (using runtime build) occur in the console but player2 can't play, he seems stuck but I can see him in the hierarchy of the editor.

When I start the server as player1 in the runtime and try to join with player2 in the editor I can see that player2 has a playercontroller-id of -1 a network-id of 0 and also a scene-id of 0.

Is that because Unet is EoL or should it work and I just missed something?

I am using the old version 2018.3.0f2.

I can still see the other player and can kill him but the other player simply seems to not take over the main camera. I have to investigate a bit further.

In the editor I got this error message:

```
IndexOutOfRangeException: NetworkReader:ReadBytes out of range: (21440) NetBuf sz:41 pos:5
UnityEngine.Networking.NetBuffer.ReadBytes (System.Byte[] buffer, System.UInt32 count) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkBuffer.cs:45)
UnityEngine.Networking.NetworkReader.ReadString () (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkReader.cs:305)
Player_Controller.OnDeserialize (UnityEngine.Networking.NetworkReader reader, System.Boolean initialState) (at <811655ab22fa4c9c9e92117581e47a9e>:0)
UnityEngine.Networking.NetworkIdentity.OnUpdateVars (UnityEngine.Networking.NetworkReader reader, System.Boolean initialState, UnityEngine.Networking.NetworkMessage netMsg) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkIdentity.cs:745)
UnityEngine.Networking.ClientScene.ApplySpawnPayload (UnityEngine.Networking.NetworkIdentity uv, UnityEngine.Vector3 position, System.Byte[] payload, UnityEngine.Networking.NetworkInstanceId netId, UnityEngine.GameObject newGameObject, UnityEngine.Networking.NetworkMessage netMsg) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/ClientScene.cs:499)
UnityEngine.Networking.ClientScene.OnObjectSpawn (UnityEngine.Networking.NetworkMessage netMsg) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/ClientScene.cs:560)
UnityEngine.Networking.NetworkConnection.HandleReader (UnityEngine.Networking.NetworkReader reader, System.Int32 receivedSize, System.Int32 channelId) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkConnection.cs:469)
UnityEngine.Networking.NetworkConnection.HandleBytes (System.Byte[] buffer, System.Int32 receivedSize, System.Int32 channelId) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkConnection.cs:425)
UnityEngine.Networking.NetworkConnection.TransportReceive (System.Byte[] bytes, System.Int32 numBytes, System.Int32 channelId) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkConnection.cs:576)
UnityEngine.Networking.NetworkClient.Update () (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkClient.cs:754)
UnityEngine.Networking.NetworkClient.UpdateClients () (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkClient.cs:966)
UnityEngine.Networking.NetworkIdentity.UNetStaticUpdate () (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkIdentity.cs:1086)

```

Maybe you can explain what that error message says?

I kind of fixed it by adding the following method to my networkbehavior

```
 public override void OnDeserialize(NetworkReader reader, bool initialState)
 {
     base.OnDeserialize(reader, initialState);
 }

```

But now lots of other bugs occur, when I kill my opponent points are not assigned and so on. Does this happen because of deprecated Unet or am I just too dumb?

I built the game using version 2018.3.11f1 which seems to have some differences to 2018.3.0f2. Using the correct minor version did the trick. I wonder that much has changed between these 2 minor change releases.

# Answer
`IndexOutOfRangeException: NetworkReader:ReadBytes out of range: (21440) NetBuf sz:41 pos:5`

Look like you're sending/receiving a byte array of which you do not know the size of nor you check things. Also I don't believe you're using exception handling.

Treat all data as if it is wrong or invalid and use exception handling. These exception are barely mentioned anywhere but self-respecting developers (professionals and amatures) as wel self-respecting-code will be using exception handling *very often*.

Exception handling:

```
try
{

    // Receive data.
    // Process data.
    // Whatever.

} catch(Exception e )
{

    // Give feedback or simply ignore any catched errors.

} finally
{

    // Code what has to be executed to tie up things.
    // Not per se needed.

}

```

*Deprecated* code is code one should not use anymore, still it is valid for backwards compatability.

Another thing comming to mind is did you change one (or more) systems in the meanwhile. There is this thingy of `little` and `big endian`, messing up your data big time.

With the information you have given, nothing else can be said without guessing. It can be just one little thing to resolve every thing. Make a back up of the original one with the initial error so you can revert when messing up big time in your bug diving adventure.
> 0 votes

---
Tags: unity, unity-networking
---


title: Sprite Pixels, and ScreenToWorldPoint

text:
# Question
Title: Sprite Pixels, and ScreenToWorldPoint
Just asking a really basic question, but I'm really confused about pixels and positioning.

This is in my update function:

```
//Global variables, GameObject go, SpriteRenderer renderer.
Vector2 worldBoundary = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height/ 2));
Vector3 position = new Vector3(worldBoundary.x, worldBoundary.y, 0);
var rect = new Rect(0, 0, 4, 4);
var sprite = Sprite.Create(Texture2D.whiteTexture, rect, Vector2.one *0.5f);
renderer.sprite = sprite;
go.transform.position = position;
go.transform.localScale = new Vector3(10f, 10f, 1f);

```

What I am just trying to understand, based on the code, is that position and camera-relative position are different things. So, assuming my screen is 840px, but my X position is 10.7523.

It's safe to assume that the function just converts the pixel to some position value, isn't it? If I have a square that is 40x40px in the example where scale a 4x4 square by `10.0f`, if I set the `Screen.width / 2 - 20`. What I expect to see is that the square moves 20px, which is equivalent to a square's width, but it's not what I was expecting. Assuming I change to the code below

```
Vector2 worldBoundary = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width - 20.0f, Screen.height/ 2));

```

Update: The Camera settings is in Orthographic, and the sprite.pixelsPerUnit is 100. The Orthographic height is 10.0, and the Orthographic size is 5.

# Answer
> 0 votes
The Pixels per Unit (PPU) value creates a mapping between the texel size of your sprite and the size its corresponding object will be in the game world (at 1x scale).

$$\begin{align} \text{default world size} &= \frac {\text{texel size}} {\text{PPU}}\\ &= \frac 4 {100}\\ &= 0.04 \end{align}$$

This is then affected by your scaling factor:

$$\begin{align} \text{scaled world size} &= \text{scale} \times \text{default world size}\\ &= 10 \times 0.04\\ &= 0.4 \end{align}$$

Your camera's orthographic size determines how much of the world it can see vertically. As you noted, the size parameter is half it total height. That height in your world gets mapped to the pixel height of your screen/window/viewport.

$$\begin{align} \text{pixel size} &= \text{scaled world size} \times \frac {\text{window pixel height}} {2 \times \text{camera size}}\\ &= 0.4 \times \frac {392} {10}\\ &= 15.68 \end{align}$$

That gives us about the 16 pixel width & height we can measure in your 392-pixel-tall example image.

So half your square's width is 8 pixels at this resolution, not 20. That's why the square moves on screen by more than you expect.

If you want to calculate the position that just touches the right edge of the screen, assuming the camera is unrotated and looking straight along the z+ axis, you can do so with...

```
static void SnapToRightEdge(Renderer renderer, Camera camera) {
    float rightEdgeOfShape = renderer.bounds.max.x;

    float rightEdgeOfScreen = camera.position.x +
                              camera.orthographicSize * camera.aspect;
                              // half height * width:height ratio = half width

    renderer.transform.Translate(
           rightEdgeOfScreen - rightEdgeOfShape,
           0,
           0,
           Space.World // Translate in world space, not local space.
    );
}

```

Note that we don't need any pixel calculations here at all, so this will work at any screen resolution. Things get a little more complicated if you need to deal with rotations though, since the bounds structure is a world axis-aligned bounding box.

---
Tags: unity
---


title: when to unbind vao in drawing loops

text:
# Question
Title: when to unbind vao in drawing loops
I am very new to open gl and am struggling to understand relation between vaos vbos and ibos like how is currently bound vao related to currently bound ibo?

now i am trying to render 4 triangles with vertex data and index data for ibo as

```
float vertices[] = {
        -0.5f, -0.5f,  2.0f,     1.0f, 0.0f, 0.0f ,1.0,
         0.5f, -0.5f,  2.0f,     0.0f, 1.0f, 0.0f ,1.0,
         0.0f,  0.5f,  2.0f,     0.0f, 0.0f, 1.0f ,1.0,

         0.0f,  0.0f,  1.0f,     1.0f, 1.0f, 0.0f ,1.0,
         0.0f,  0.0f,  3.0f,     0.0f, 1.0f, 1.0f ,1.0,
         0.0f, -1.0f,  2.0f,     1.0f, 0.0f, 1.0f ,1.0,
    };

    float vertices1[] = {
        -0.5f, -0.5f,  0.0f,     1.0f, 0.0f, 0.0f ,1.0,
         0.5f, -0.5f,  0.0f,     0.0f, 1.0f, 0.0f ,1.0,
         0.0f,  0.5f,  0.0f,     0.0f, 0.0f, 1.0f ,1.0,

         0.0f,  0.0f, -1.0f,     1.0f, 1.0f, 0.0f ,1.0,
         0.0f,  0.0f,  1.0f,     0.0f, 1.0f, 1.0f ,1.0,
         0.0f, -1.0f,  0.0f,     1.0f, 0.0f, 1.0f ,1.0
    };

    unsigned indices[] = {
        0,1,2,3,4,5
    };

    unsigned indices1[] = {
         0,1,
         1,2,
         2,0,
         3,4,
         4,5,
         5,3
    };

```

and i am creating vaos and ibos as:

```
unsigned int VBO[2], VAO[2], IBO[2];
    glGenVertexArrays(2, VAO);
    glGenBuffers(2, VBO);
    glGenBuffers(2, IBO);
    glBindVertexArray(VAO[0]);

    glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO[0]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);
    //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glBindVertexArray(VAO[1]);

    glBindBuffer(GL_ARRAY_BUFFER, VBO[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices1), vertices1, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO[1]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices1), indices1, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);
    //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

And I am drawing it as:

```
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO[0]);
        glBindVertexArray(VAO[0]);

        glDrawElements(GL_TRIANGLES, sizeof(indices1) / sizeof(unsigned), GL_UNSIGNED_INT, 0);

        glBindVertexArray(0));
        //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO[1]);
        glBindVertexArray(VAO[1]);

        glDrawElements(GL_LINES, sizeof(indices1)/sizeof(unsigned), GL_UNSIGNED_INT, 0);

        glBindVertexArray(0));
        //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

If i dont unbind vao in the draw call then it will not be drawn as expected i.e. partially drawn lines or missing triangles. Are'nt vaos supposed to override any previous bindings and bind a new one specified? Even if i dont unbind vao after setting glVertexAttribPointer I get a blank screen! Then I got Totally confused on when to bind before doing what. What does vao hold other than vertex attribute?like can i unbind ibo before vao?

# Answer
> 1 votes
**Unbinding** is an OpenGL anti-pattern; it doesn't exist in OpenGL as designed, it's not necessary except in very limited cases, it often doesn't do what you think it does, but yet you see it used in tutorials and people have assimilated the thinking that you need to do it.

This is an unfortunate side-effect of old (non-DSA) OpenGL using the same state for drawing as it used for creating and modifying objects. As a result of that, code to accomplish the one will dirty the state used for accomplishing the other, and unbinding was used as a crutch to help prevent that (or at worst, assist detecting errors arising from it).

However, for many object types, object 0 is actually a valid object name and has special meaning.

* For vertex buffer objects, binding object 0 will switch the pipeline back to using client-side (i.e. system memory) arrays.
* For vertex array objects, binding object 0 will switch the pipeline back to using global array state.
* For texture objects, binding object 0 will switch the pipeline back to OpenGL 1.0 behaviour before texture objects existed.
* For sampler objects, binding object 0 will switch the pipeline back to using per-texture parameters.
* Etc.

The answer to the question of "when to unbind" is therefore: **never**. The exception is when the GL specification might require an object to not be bound, e.g. before deleting it; otherwise **you should never unbind**.

Instead the correct pattern to use is to just bind everything you need immediately before using it. Don't rely on global state, and definitely don't assume that state might carry over from previous operations. Better again, just use the modern API with DSA.

# Answer
> 0 votes
I don't do it that way any more. In cases when the shader-pipeline doesn't change and the interface (vertex attributes) from the application stays the same one can create a vao and just switch the buffers before the draw calls. Example with plain c-code, to sketch the way, OpenGL 4.5, a vertex array with a static and a dynamic buffer and one vertex attribute, for brevity:

```
// Configure vertex array and buffers
glCreateVertexArrays( 1, &(i->vertex_array) );
// Only one vec4f attrib: .xy = coords, .zw = texture coords from font atlas
glVertexArrayAttribFormat( i->vertex_array, 0, 4, GL_FLOAT, GL_FALSE, 0 );
glEnableVertexArrayAttrib( i->vertex_array, 0 );
glCreateBuffers( 1, &(i->static_vertex_buffer) );
glCreateBuffers( 1, &(i->dynamic_vertex_buffer) );

```

Copy in static data to the static buffer (1 time only):

```
glNamedBufferData( in->static_vertex_buffer, (GLsizeiptr)buffer_size, buf, GL_STATIC_DRAW );

```

Prepare dynamic buffer storage. Size cannot be changed later, contents can:

```
glNamedBufferStorage( in->dynamic_vertex_buffer, size, NULL, GL_MAP_WRITE_BIT );

```

Every frame, update dynamic buffer:

```
// obtain a pointer
vec4f* buf = glMapNamedBuffer( in->dynamic_vertex_buffer, GL_WRITE_ONLY );
// ... use the pointer to write to the buffer, e.g. via memcpy() ...
if( GL_TRUE != glUnmapNamedBuffer( in->dynamic_vertex_buffer ) )
    // do something about it

```

And in the draw you just bind the array. You can switch the buffers as needed:

```
// draw static and dynamic buffer
glBindVertexArray( i->vertex_array );
glVertexArrayVertexBuffer( i->vertex_array, 0, i->static_vertex_buffer, 0, sizeof( vec4f ) );
glDrawArrays( GL_TRIANGLES, 0, i->num_static_vertices );
glVertexArrayVertexBuffer( i->vertex_array, 0, i->dynamic_vertex_buffer, 0, sizeof( vec4f ) );
glDrawArrays( GL_TRIANGLES, 0, i->num_dynamic_vertices );

```

If you draw elements you glCreateBuffer it once and connect it to the vao via glVertexArrayElementBuffer. If its contents change map/write/unmap as above. During drawing, just use the shader and the vao and switch buffers as needed, or keep them when they don't change.

Don't forget error checking the return value of glUnmapBuffer.

Hope that clarifies.

---
Tags: opengl
---


# Question
Title: Is it still possible to set default script template for Unity Mac?
I want to setup/update the default template(s) for C# scripts in my games.

According to the docs https://support.unity.com/hc/en-us/articles/210223733-How-to-customize-Unity-script-templates on Mac I should be able to go to:

`Applications/Unity/Editor/Data/Resources/ScriptTemplates`

And modify the templates within... however I don't have any "Editor" folder inside my `/Applications/Unity` folder (2020.3.8f1)

Has this moved to a new location? or has my install become corrupt and I need to re-install?

# Answer
> 3 votes
I suppose you installed your Unity Editor via Unity Hub, and if yes, then the path has changed to this

`/Applications/Unity/Hub/Editor/2021.3.11f1/Unity.app/Contents/Resources/ScriptTemplates/`

It may be in `/Applications/Unity/Unity.app/Contents/Resources/ScriptTemplates/` if so, you will need to use the context menu (2-finger press on touchpad) to expand further into the `Unity.app` package.

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


# Question
Title: Android Specifications : What are the integer values for "small" screen size, "normal" screen size, ldpi, mdpi, hdpi?
Android has this document where they define thee terms for screen size, and pixel density such as ***screenSize="small", "ldpi"***. Here is the link to that document:

https://developer.android.com/guide/practices/screens-distribution

Here is the section of definitions:

```
<manifest ... >
    <compatible-screens>
        <!-- all small size screens -->
        <screen android:screenSize="small" android:screenDensity="ldpi" />
        <screen android:screenSize="small" android:screenDensity="mdpi" />
        <screen android:screenSize="small" android:screenDensity="hdpi" />
        <screen android:screenSize="small" android:screenDensity="xhdpi" />
        <!-- all normal size screens -->
        <screen android:screenSize="normal" android:screenDensity="ldpi" />
        <screen android:screenSize="normal" android:screenDensity="mdpi" />
        <screen android:screenSize="normal" android:screenDensity="hdpi" />
        <screen android:screenSize="normal" android:screenDensity="xhdpi" />
    </compatible-screens>
    ...
    <application ... >
        ...
    <application>
</manifest>

```

But, I don't know the **specific integer values** for "small" screen size, "normal" screen size, ldpi, mdpi, hdpi, xhdpi from that document. Can anyone please tell me the integer values of these terms ?

# Answer
> 2 votes
Dropping `android:screenDensity="ldpi"` into the site search at the official Android development site gives the screen densities reference as the second hit which in turn provides the table for the pixel densities qualifiers

Table 1. Configuration qualifiers for different pixel densities.

| Density qualifier | Description |
| --- | --- |
| ldpi | Resources for low-density (ldpi) screens (~120dpi). |
| mdpi | Resources for medium-density (mdpi) screens (~160dpi). (This is the baseline density.) |
| hdpi | Resources for high-density (hdpi) screens (~240dpi). |
| xhdpi | Resources for extra-high-density (xhdpi) screens (~320dpi). |
| xxhdpi | Resources for extra-extra-high-density (xxhdpi) screens (~480dpi). |
| xxxhdpi | Resources for extra-extra-extra-high-density (xxxhdpi) uses (~640dpi). |
| nodpi | Resources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen's density. |
| tvdpi | Resources for screens somewhere between mdpi and hdpi; approximately 213dpi. This is not considered a "primary" density group. It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate. If you find it necessary to provide tvdpi resources, you should size them at a factor of 1.33\*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi. |

Dropping `screen android:screenSize="small"` into a general web search brought me to Alvin Alexander's blog post on Android screen sizes, with the following info:

* xlarge screens are at least 960dp x 720dp
* large screens are at least 640dp x 480dp
* normal screens are at least 470dp x 320dp
* small screens are at least 426dp x 320dp

Or with more digging at the Android dev site, you can find the same info here about a third of the way down (or search that same page for `SCREENSIZE_SMALL`).

Most of this information is also available in the Stack Overflow post Android splash screen image sizes to fit all devices.

---
Tags: unity, android, resolution, aspect-ratio
---


title: Box2D not updating b2Body* positions

text:
# Question
Title: Box2D not updating b2Body* positions
For context, this is inside my custom 2D game engine. Inside the editor code, when the 'play scene' button is clicked, the scene creates it's `b2World` and then creates all of the bodies necessary. Then in the update method the editor checks if it should update the scene and calls `Scene::updateRuntime(const float& dt)` if the scene is currently playing which should update the correct entities

What is Wrong:

I initialize b2World and create it with a gravity of -9.8, but when I call the `Step()` method and then update the corresponding entities, none of the positions change even though my log shows that the correct updates are running and my data is correct.

Please note: I tried to pull a minimally reproduceable example out of the project, but I'm building this engine to learn and so my code is unfortunately a little too coupled at the moment (hopefully this changes in the future) and attempting to separate this tiny area of scene updates from the rest of my code base proved to be more than I could handle. Because of this I am trying to include as much information as I can so please forgive me.

What I have tried:

1. I have printed out and logged the timestep (averaging about 0.016-0.017), position data, and random other data which appears correct
2. I have ran my debugger and stepped through the code repeatedly, but nothing is wrong except for the lack of physics
3. I made a new project outside of my game engine just to track the numbers from box2d. This example is copied and pasted from the docs and that, of course, worked just fine, so I copied the relevant lines back into my engine (almost verbatim) and it didn't work anymore.

extra things -

1. `b2World->GetGravity()` gives the correct value
2. I can successfully manipulate my Entity's positions in the manner I show in the code (updating the physics body's position and then setting the entity position equal to the physics body position) and the only time it doesn't successfully update is if I try and do it with `b2World::Step()`

Here is the scene class **Scene.hpp**

```
class Scene {
        core::AssetLibrary<graphics::VertexArray> Meshes;
        b2World* world;

        std::map<int , Entity> entities;
        entt::registry entRegistry;
        int numEnts , totalEntsCreated;
        bool playing;
        std::string name , path;

        friend class Entity;
        friend class ScriptedEntity;
        friend class SceneSettingGUI;
        friend class SceneSerializer;

        public:
            Scene();
            ~Scene();

            void updateFromEditor();
            void updateRuntime(const float& dt);
            void render();

            inline bool isPlaying() const { return playing; }
            void playScene();
            void pauseScene();
            void stopScene();

            Entity createEnt(const std::string& name = "{BLANK ENTITY}");
            void destroyEntity(Entity& ent);
            Entity& getEntity(entt::entity handle);
            Entity& getMainCameraEntity();
            Entity getNullEnt();
            inline entt::registry& Entts() { return entRegistry; }
            inline int getNumEnts() const { return numEnts; }
            inline int getTotalEntsMade() const { return totalEntsCreated; }

            inline core::AssetLibrary<graphics::VertexArray>& getVertLib() { return Meshes; }
            inline std::string getName() const { return name; }
            inline std::string getPath() const { return path; }

            inline void setSceneName(const std::string& name) { this->name = name; }
            inline void setScenePath(const std::string& path) { this->path = path; }

            void createSprite();
    };

```

**Scene.cpp**

```
static b2BodyType MachyPhysicsTypeToBox2DType(PhysicsBody2DComponent::PhysicsType type) {
        switch (type) {
            case PhysicsBody2DComponent::PhysicsType::Static: return b2_staticBody; break;
            case PhysicsBody2DComponent::PhysicsType::Kinematic: return b2_kinematicBody; break;
            case PhysicsBody2DComponent::PhysicsType::Dynamic: return b2_dynamicBody; break;

            default:
                MACHY_ASSERT(false , "Unknown Physics Type");
                return b2_staticBody;
            break;
        }
    }

    Scene::Scene() : numEnts(0) , totalEntsCreated(0) , playing(false) , name("{Blank Scene}") {
        Entity nullEnt;
        nullEnt.handle = entt::null;

        entities[0] = nullEnt;

        std::shared_ptr<graphics::VertexArray> VA = core::FileSystem::loadVertexFile(sceneBaseMeshPath);
        std::shared_ptr<graphics::VertexArray> tVA = core::FileSystem::loadVertexFile(sceneTexMeshPath);

        Meshes.load(VA->getName() , VA);
        Meshes.load(tVA->getName() , tVA);

        world = nullptr;
    }

    Scene::~Scene() {
        entRegistry.each([&] (auto entity) { entRegistry.destroy(entity); });
    }

    void Scene::updateFromEditor() {
        return;
    }

    void Scene::updateRuntime(const float& dt) {

        entRegistry.view<NativeScript>().each([=](auto entity , auto& script) {
                if (script.instance == nullptr) {
                    script.instance = script.BindScript();
                    script.instance->entity = { entity };
                    script.instance->entity.setContext(this);
                    script.instance->onCreation();
                }
                script.instance->onUpdate();
            });

        entRegistry.view<CameraComponent , PositionComponent>().each([=](auto entity , auto& cam , auto& pos) {
                pos.pos.x = cam.cameraPos.x;
                pos.pos.y = cam.cameraPos.y;
                pos.pos.z = cam.cameraPos.z;
                pos.rotation.x = cam.cameraRotation;
                cam.camera->setHeight(pos.pos.z);
            });

        const int32 velIterations = 8;
        const int32 posIterations = 3;

        float timestep = 1.0f / 60.0f;
        world->SetAllowSleeping(false);
        world->Step(timestep , velIterations , posIterations);

        auto view = entRegistry.view<PhysicsBody2DComponent>();
        for (auto& ent : view) {
            Entity entity{ ent };
            entity.setContext(this);

            auto& pos = entity.GetComponent<PositionComponent>();
            auto& physBody = entity.GetComponent<PhysicsBody2DComponent>();

            b2Body* physics = (b2Body*)physBody.runTimePhysics;
            const auto position = physics->GetPosition();
            pos.pos.x = position.x;
            pos.pos.y = position.y;
            pos.rotation.z = physics->GetAngle();
        }

        return;
    }

    void Scene::render()  {

        auto sprites = entRegistry.view<RenderComponent , PositionComponent>();
        auto cameras = entRegistry.view<CameraComponent>();

        if (playing) {
            if (cameras.size() > 0)
                for (auto& ent : cameras)
                    if (entRegistry.valid(ent)) {
                        Entity entity{ ent };
                        entity.setContext(this);
                        auto& cam = entity.GetComponent<CameraComponent>();
                        MachY::Instance().getRM().submit(MACHY_SUBMIT_RENDER_CMND(PushCamera , cam.camera));
                    }
        }

        for (const auto ent : sprites) {
            if (entRegistry.valid(ent)) {
                Entity entity{ ent };
                entity.setContext(this);
                if (entity.HasComponent<RenderComponent>() && entity.HasComponent<RenderComponent>()){
                    auto& renderable = entity.GetComponent<RenderComponent>();
                    auto& position = entity.GetComponent<PositionComponent>();

                    glm::mat4 model = position.getModel();
                    if (renderable.skeleton.get() != nullptr && renderable.material.get() != nullptr)
                        MachY::Instance().getRM().submit(MACHY_SUBMIT_RENDER_CMND(RenderVertexArrayMaterial , renderable.skeleton , renderable.material , model));
                }
            }
        }

        if (playing) {
            if (cameras.size() > 0)
                for (auto& ent : cameras)
                    if (entRegistry.valid(ent)) {
                        MachY::Instance().getRM().submit(MACHY_SUBMIT_RENDER_CMND(PopCamera));
                    }
        }

        return;
    }

    void Scene::playScene() {
        playing = true;

        b2Vec2 grav{ 0.f , -9.8f };
        world = new b2World(grav);

        auto view = entRegistry.view<PhysicsBody2DComponent>();
        for (auto& ent : view) {

            MACHY_INFO("Creating Physics Simulation");

            Entity entity{ ent };
            entity.setContext(this);

            auto& pos = entity.GetComponent<PositionComponent>();
            auto& physics = entity.GetComponent<PhysicsBody2DComponent>();

            b2BodyDef newBodyDef;
            newBodyDef.type = MachyPhysicsTypeToBox2DType(physics.type);
            newBodyDef.position.Set(pos.pos.x , pos.pos.y);
            newBodyDef.angle = pos.rotation.z;

            b2Body* newBody = world->CreateBody(&newBodyDef);
            newBody->SetFixedRotation(physics.fixedRotation);
            physics.runTimePhysics = newBody;
        }

        return;
    }

    void Scene::pauseScene() {
        playing = false;

        delete world;
        world = nullptr;

        return;
    }

    void Scene::stopScene() {
        playing = false;

        return;
    }

    Entity Scene::createEnt(const std::string& name) {
        Entity newEnt(entRegistry.create());
        newEnt.setContext(this);

        auto& id = entRegistry.emplace<EntityID>(newEnt.get());
        auto& pos = entRegistry.emplace<PositionComponent>(newEnt.get());

        numEnts++;
        totalEntsCreated++;

        id.ID = totalEntsCreated;
        id.name = name;

        entities[id.ID] = newEnt;

        return newEnt;
    }

    void Scene::destroyEntity(Entity& ent) {
        if (entRegistry.valid(ent.get())) {
            entRegistry.destroy(ent.get());
            ent.nullify();
            numEnts--;
        }
        return;
    }

    Entity& Scene::getEntity(entt::entity handle) {
        auto& id1 = entRegistry.get<EntityID>(handle);
        for (auto& entItr : entities)
            if (entRegistry.valid(entItr.second.get())) {
                auto& id2 = entRegistry.get<EntityID>(entItr.second.get());
                if (id2.ID == id1.ID) {
                    return entities[id1.ID];
                }
            }

        return entities[0];
    }

    Entity& Scene::getMainCameraEntity() {
        auto view = entRegistry.view<game::EntityID , game::CameraComponent>();
        for (auto ent : view) {
            const auto& id = view.get<game::EntityID>(ent);
            const auto& camera = view.get<game::CameraComponent>(ent);
            if (camera.camera != nullptr)
                return entities[id.ID];
        }

        return entities[0];
    }

    Entity Scene::getNullEnt() {
        return entities[0];
    }

```

Here are the relevant Entity Component ***entityComponents.hpp***

```
/// position
    struct PositionComponent {
        glm::vec3 pos , size , rotation;

        PositionComponent() : pos(glm::vec3(0.f)) , size(glm::vec3(1.f)) , rotation(glm::vec3(0.f)) {}

        glm::mat4 getModel() {
            glm::mat4 rot = glm::toMat4(glm::quat(rotation));
            glm::mat4 model = glm::mat4(1.f);
            model = glm::translate(model , pos) * rot * glm::scale(model , size);
            return model;
        }
    };

    /// sprites
    struct RenderComponent {
        std::shared_ptr<graphics::VertexArray> skeleton;
        std::shared_ptr<graphics::Material> material;
        glm::vec3 color;
        std::string meshName , matName;

        RenderComponent() = default;
        RenderComponent(const RenderComponent&) = default;
        RenderComponent(std::shared_ptr<graphics::VertexArray> skeleton , std::shared_ptr<graphics::Material> material)
            : skeleton(skeleton) , material(material) , color(glm::vec3(0.f)) {}
    };

    /// cameras
    struct CameraComponent {
        std::shared_ptr<graphics::Camera> camera;
        glm::vec3 cameraPos;
        float cameraRotation;

        CameraComponent() : cameraPos(glm::vec3(0.f)) , cameraRotation(0.f) {
            camera = std::make_shared<graphics::Camera>();
            camera->setHeight(3.f);
        }
    };

    // physics
    struct PhysicsBody2DComponent {
        enum class PhysicsType{ Static = 0 , Kinematic , Dynamic };
        PhysicsType type;
        bool fixedRotation;

        void* runTimePhysics;

        PhysicsBody2DComponent() : type(PhysicsType::Static) , runTimePhysics(nullptr) , fixedRotation(false) {}
        PhysicsBody2DComponent(const PhysicsBody2DComponent&) = default;
    };

    // scripting
    struct NativeScript {
        ScriptedEntity* instance = nullptr;
        bool bound;

        ScriptedEntity*(*BindScript)();
        void (*DestroyScript)(NativeScript*);

        NativeScript() : instance(nullptr) , bound(false) {}
        ~NativeScript() { DestroyScript(this); }

        template <typename T>
        void Bind() {
            BindScript = []() { return static_cast<ScriptedEntity*>( new T() ); };
            DestroyScript = [](NativeScript* script) { delete script->instance; script->instance = nullptr; };

            bound = true;
        }
    };

```

# Answer
> 0 votes
There was an issue with my enum, probably smart to sure your enums are in the right order lmao

---
Tags: c++, box2d
---