# Question
Title: World War Game units and resources mechanics
I'm currently building a world war game with a timeline between the first world war up to current days. In the game there will be many fighting units with a diversified range of classes and sub-classes. Also there will be around 5 to 6 resources where the player will have to manage because every equipment will have a different trend on cost. Some examples that I have in mind for resources:

* Money (Main resource. Used to build buildings and fund researches);
* Manpower (Used mainly to make disposable infantry units);
* Steel (Used everywhere in fighting units. Used a lot in armored units);
* Oil (The heavier, the costlier);
* Rare Materials (Used in... I'm not really sure where);
* Electronics (Used in modern units);

**Here are some examples of fighting units:**

* Early Anti-Tank Gun
    + Class: Anti-Tank
    + Sub-class: Stationary
* Self-propelled artillery
    + Class: Artillery
    + Sub-class: Self-propelled
* Motorized Rocket artillery
    + Class: Rocket Artillery
    + Sub-class: Motorized
* Machine Gun
    + Class: Infantry
    + Sub-class: Machine Gun

**And I'm currently facing two problems:**

* There will be many fighting units and as time passes the player will have to retire some of its older equipment. And the problem is that warfare and the purpose for each war equipment changes through time, so: **how do I classify all these fighting units from a very broad timeline?**
* Also I'm trying to make the player have a very balanced army. If he decides to go full on planes he will soon lack some resource that is crucial to building planes. Or if he spams cheap infantry he will run out of manpower, so: **How do I balance the player resources? Which ones should I use?** (This can also be manipulated so that in the future I can have a world map where the player plays as a certain country that has a higher production of a given resource in a way that he can play/is forced to play with a certain army configuration)

I'm currently making this system of units and resources to later have many playing modes like world conquest, survive waves of incoming enemy units, missions with rewards, and many others.

Two sources I'm currently using: Wikipedia (for information on technologies used during a given time and trying to make a classification system) and Hearts of Iron 4 (the resources system). My game will be played on the browser (until I change my mind), so It can't be very calculation-intensive such as HoI4. Current prototype is in pure JavaScript that simulates a very simple the battle.

This is my very first game that is more than a couple of source files long and that will probably require a lot more thinking than coding at first. I'm currently very lost. I feel like if I go head-on making the game and the user interface I will eventually hit a wall because "I haven't thought enough" about how the game mechanics.

**Edit:**

The battle mechanics is almost done. If needed, I can describe it how it is, but think of it as a very simple one, like machine guns and artillery are good against infantry, anti-tank... well..., planes are good against bombers, CAS against land units and so on. Also there will be ships and submarines...

# Answer
In both cases, unit and resource properties will dictate mechanics, and mechanics will direct player actions.

**Q1: How do I classify all these fighting units from a very broad timeline?**

Really if you look at the military unit concept, not much has changed to some extent. Range attackers have been range attackers for thousands of years. Early on it was someone throwing a spear, then a bow that shot farther, then an artillery, then a rocket. But the concept is the same - stand away from the enemy and cause damage from a distance, but don't let the enemy get close.

To implement this, you should look at defining units by attributes. E.g,, short versus long range attack (artillery vs machine gun), mobile vs stationary, high damage vs low damage, slow travel speed (soldier on foot) vs high travel speed (airplane).

Then over time, you increase the abilities of units by upgrading their attributes. An early infantry unit can't travel as fast, nor shoot as far, nor do as much damage as a modern infantry unit for example. An early tank can't go as fast, can't take as much damage, and can't shoot as far as a modern tank.

From the perspective of unit evolution over the time period of the game, the thing you should do is figure out how to modify over time the attributes of unit types as they upgrade. A player will not want to keep using outdated units because newer versions of the same unit type will outmatch them in combat.

**Q2: How do I balance the player resources?**

Each type of unit has strengths and weaknesses, and you need to create unit types that both contrast and compliment each other.

The range attacker for example can cause damage at range, but if engaged in direct combat is weak. So artillery is powerful against infantry if the infantry is not close by. But if infantry can directly attack artillery, the artillery is weak.

Where actual resources CAN work is with the idea of upgrades, and your first question. Let resources be the thing you need in order to upgrade your units. So modern infantry needs more oil in order to transport units farther and faster. But unlike infantry, airplanes need factories and oil.

**Summary**

In a nutshell, units are defined by their attributes (good and bad). Units get better over time by having those attributes go up as part of upgrades. Upgrades require resources.

Balance is created by creating complimentary and contrasting unit attributes, and structuring resources such that resource availability dictates the types of upgrades that can be done.
> 1 votes

---
Tags: game-mechanics
---


# Question
Title: How to detect when the mouse is over a particular enemy collider, without falsely selecting bullet colliders?
I have an enemy shooting around. My game mechanic involves hovering over the enemy with the mouse to drain its health. While the enemy is moving, you need to follow it with your mouse. If you don't succeed to follow it and the mouse leaves the enemy's collider, the enemy's health should be refilled.

The trouble is that the enemies' bullets have also a collider, and OnMouseOver acts weird when more colliders appear on top of each other.

How can I only select a particular Layer for the enemy to detect only that layer without acknowledging the bullets layer?

My Code so far:

```
public class FightDarkalls : MonoBehaviour
{

    [Header("Guidance Light On?")]
    public bool _guidanceLight = false;
    [Header("Target Settings")]
    public GameObject _monster;
    public GameObject _targetEffect;
    public Animator _TargetEffectAnim;
    public LayerMask _monsterLayer;
    int _layer;
    [Space]
    [Header("Damage Darkall")]
    public float damage = 0.1f;
    public float damageSpeed = 2.5f;
    [Header("OBJs to deactivate when Darkall dead")]
    public GameObject[] _deactivateOBJsOnDeath;
    [Header("Health Settings")]
    public GameObject _healthBar;
    public float startingHealth;
    public float health;
    public GameObject _deathDarkallParticle;
    //Animator
    private Animator _anim;

    Vector2 mousePosition;
    public LayerMask _interactLayer;

    private void Start()
    {
        _targetEffect.SetActive(false);
        _anim = GetComponent<Animator>();
        _TargetEffectAnim = _targetEffect.GetComponent<Animator>();
    }

    private void Update()
    {
        CheckIfGuidanceIsActive();

        _healthBar.transform.localScale = new Vector2(health, 1f);

        _deathDarkallParticle.transform.position = Vector2.Lerp(_deathDarkallParticle.transform.position, _monster.transform.position, 100f * Time.deltaTime);

        SetMousePosition();
    }

    void CheckIfGuidanceIsActive()
    {
        if (GameObject.Find("_GuidanceLight").GetComponent<FollowCursor>   ()._guidanceActivated == true)
        {
            _guidanceLight = true;
        }
        else
            _guidanceLight = false;
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawSphere(mousePosition, 1f);
    }

    private void OnMouseOver()
    {
        if (_guidanceLight)
        {
            //[DAMAGE]\\
            health -= damage * Time.deltaTime * damageSpeed;
            _anim.SetBool("TakeDamage", true);
            //Activate Target Effect
            _targetEffect.SetActive(true);
            _TargetEffectAnim.SetBool("OnDarkallOver", true);
            //Damage the target
            //Kills the target
            if (health <= 0f)
            {
                foreach (GameObject _dOBJs in _deactivateOBJsOnDeath)
                {
                    _dOBJs.GetComponent<SpriteRenderer>().enabled = false;
                }
                //Change Cam Shake to another OBJ
                GameObject.Find("Main Camera").GetComponent<CameraShake>().CamShakeEffect(0.1f, 0.5f);
                health = 0f;
                _deathDarkallParticle.SetActive(true);
                _deathDarkallParticle.GetComponent<ParticleSystem>().Play();
                _monster.gameObject.SetActive(false);
                Destroy(_monster.gameObject, 3f);
            }
        }
    }
    private void OnMouseExit()
    {
        _anim.SetBool("TakeDamage", false);
        //If failed to kill, reset health
        health = startingHealth;
        //Deactivate Target
        _targetEffect.SetActive(false);
        _TargetEffectAnim.SetBool("OnDarkallOver", false);
    }

    void SetMousePosition()
    {
        mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
}

```

# Answer
First, configure your Layers so that you have a layer for bullets and a layer for enemies. Ensure you've set the bullet prefabs to use the bullet layer, and the enemies/enemy prefabs to use the enemies layer.

Next, you can apply your hovering damage using a script like this one. Main things to note about this strategy:

* We check for objects overlapping the mouse position with Physics2D.OverlapPoint \- this says "Give me a collider in one of the selected layers that's touching this point, or `null` if there's no such collider touching this point"
* We use a `public LayerMask` parameter configured in the inspector to include only the enemies layer in this check, and ignore bullets
* We do this search for *any* overlapping collider only when we don't currently have a target we're damaging
* When we already have a target, we do a cheaper check to see if we're still within that collider

In addition to being cheaper (checking just one collider instead of multiple), this also makes this damage mechanic "sticky" - if two enemies overlap, this will pick one and stick with it instead of flickering between them.

---

```
public class HoverDamage : MonoBehaviour {

     // Set this to exclude your bullets and include your damageable enemies.
     public LayerMask layersToDamage;

     public float damageRate;

     // Keep track of our current target.
     // I recommend making a DamageTaker component to keep track of health transactions.
     DamageTaker _currentTarget;
     Collider2D _targetCollider;

     void Update() {
         if(_currentTarget == null) {
             // If we don't have a valid target, try to find a new one.
             FindTarget();
         } else {
             // Otherwise, follow and damage the target we have.
             TrackAndDamageTarget();
         }
     }

     Vector2 MousePositionInWorld() {
         // You could cache a reference to the camera,
         // or get this position from a cursor/reticle object instead.
         return Camera.main.ScreenToWorldPoint(Input.mousePosition);
     }

     void FindTarget() {
         // Find any collider in the right layer overlapping our mouse.
         _targetCollider = Physics2D.OverlapPoint(MousePositionInWorld(), layersToDamage);
         if(_targetCollider == null)
             return;  // No such collider! We'll go without a target for now.

         // Try to get something we can damage on this object.
         _currentTarget = _targetCollider.GetComponent<DamageTaker>();
         if(_currentTarget == null)
             return;  // Nuts - the thing we found isn't damageable. Still no target.

         // We have a valid target now! Remember it for next frame,
         // and deal it some damage right away!
         DamageTarget();
     }

     void TrackAndDamageTarget() {
         // Check if our mouse is still over the target's collider from a previous frame.
         // You could use a distance query here instead to give a little tolerance.
         if(_targetCollider.OverlapPoint(MousePosition)) {
             // We're still on-target - deal damage!
             DamageTarget();
         } else {
             // We slipped off the collider. Stop tracking & damaging it.
             _targetCollider = null;
             _currentTarget = null;
             // Next frame we'll search for a new target.
         }
     }

     void DamageTarget() {
         _currentTarget.TakeDamage(damageRate * Time.deltaTime);
     }
}

```
> 4 votes

---
Tags: unity, c#, collision-detection, input, raycasting
---


# Question
Title: Platform Games vs. First Person Shooters
When going through the source code of some platform games I have noticed they use .png and .jpeg images in their source code for the sprites and various animations. I was curious if modern first person shooter games use the same strategy or do they just rely on a game engine such as Unreal or Rockstar Game Engine to render their graphics.

# Answer
> 0 votes
You may have looked at the install directory of a major 3D game and wondered where all of the texture files are.

Almost all 3D games do come with image files that are loaded from the game data, just like a 2D game engine could load a PNG image; But there are some major differences between how 2D and 3D game engines work that lead to PNG files being less useful than other formats to store the image data in.

Some of the reasons that 3D games do not use PNG or JPEG files in particular:

* Number of textures used:
In a 3D perspective, you have the potential to display hundreds of textures in one frame. Loading all of these textures from a PNG file and then copying them to the GPU can take a long time. It is quicker to load a compressed image that the GPU can directly use.
* Textures can have additional "layers":
Bump maps, Normal maps, Specular Maps, etc. All of these are additional images that have to be lined up and combined properly to render a surface. Since these textures need to be bundled together, the file type they are stored in takes care of this too.
* To prevent user tampering/modding:
This is especially true for multiplayer games; Imagine if you could simply replace a wall texture with a transparent PNG image!
* To save space:
Even if there were PNG files included in the game data, games often ship with a compressed resource library that contains all of the game assets in a single or handful of files.

Despite these reasons to not use regular image files, game engines usually support loading these types of files and engines with resource managers such as Unity and Unreal will convert them automatically to the format that is optimal for that engine when you build the game.

---
Tags: game-design
---


# Question
Title: Does transparency work with SSS in Unity's HDRP Lit shader?
I am using Unity's HDRP Lit shader in Shader Graph (all are version 4.8.0-preview) on Unity 2018.3.0b12.

I am trying to use both transparency and subsurface scattering on the material. However, it appears that the visual appearance loses SSS when transparency is introduced.

Example: The cube on the left has transparency enabled, and has no visible SSS. The cube on the right has the same SSS settings as the left cube, however the right cube has no transparency enabled.

I need transparency to fade in the cube depending on its position, like this:

And here is my master node:

If anyone has an alternative solution that sidesteps this potential limitation, I am all ears. Cheers!

# Answer
> 0 votes
The answer is no, transparency doesn't work with SSS in Unity's HDRP Lit shader.

HOWEVER, you can set the surface type to "opaque" **and still keep alpha clipping enabled**. Enjoy.

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


# Question
Title: Partial object culling without alpha + transparency?
I am trying to partially cull an object which has subsurface scattering. It's simple to do it with an alpha channel, however, using an alpha channel with transparency will disable subsurface scattering.

Potentially relevant information: I am using Unity 2018.3.0b12 with v4.8.0-preview HDRP

Example: here I am achieving the effect with alpha + transparency. The object is either fully opaque or invisible

# Answer
While this doesn't **technically** answer the question as this solution involves alpha clipping, I found out that you are able to do culling with "alpha clipping" while keeping surface type set to "opaque" instead of "transparent".

This solved the motivation behind me posting this StackExchange post. I don't have an answer for those looking for other ways to do partial culling without alpha and transparency.

Anyways, I did this by opening up the shader graph and editing the master node, as shown:
> 0 votes

---
Tags: unity
---


# Question
Title: Detect when a bullet rigidbody is on ground
I have a rigidbody that is on top of a plane or another rigidbody. How do I check if said rigidbody is on top of it?

I tried to check the Y-part of the velocity but it is never 0, it is always a small value.

What would be the best way to detect this?

# Answer
> 0 votes
You could do a ray test straight down from the rigid body and test the distance of the ray hit.

One way is to simply use the rigid body position and subtract 10,000 or some arbitrary number to get a destination for the ray test.

```
btVector3 btFrom(pos.x, pos.y, pos.z);
btVector3 btTo(pos.x, -10000.0, pos.z);
btCollisionWorld::ClosestRayResultCallback res(btFrom, btTo);

btWorld->rayTest(btFrom, btTo, res); // m_btWorld is btDiscreteDynamicsWorld

if(res.hasHit()){
    /* Use Ogre::Vector3::squaredDistance() to find the difference from the rigid body to the ray hit */
}

```

# Answer
> 0 votes
Another way to do this, it to check the normal of the collision. If the y value of the normal is very high then it is more flat (facing upwards). You can also change the threshold you allow for larger or smaller slopes.

```
//Go through collisions
int numManifolds = btDispatcher->getNumManifolds();
    for (int i = 0; i < numManifolds; i++)
    {
        btPersistentManifold* contactManifold = btWorld->getDispatcher()->getManifoldByIndexInternal(i);
        btCollisionObject* obA = const_cast<btCollisionObject*>(contactManifold->getBody0());
        btCollisionObject* obB = const_cast<btCollisionObject*>(contactManifold->getBody1());

        GameObject* gameObjA = static_cast<GameObject*>(obA->getUserPointer());
        GameObject* gameObjB = static_cast<GameObject*>(obB->getUserPointer());
        if (gameObjA->name == "Camera" || gameObjB->name == "Camera" /*have some way to check if one of the objects is the rigidbody you want */) {
            int numContacts = contactManifold->getNumContacts();
            for (int j = 0; j < numContacts; j++)
            {
                btManifoldPoint& pt = contactManifold->getContactPoint(j);
                if (pt.getDistance() < 0.f)
                {

                    glm::vec3 normal;

                    if (gameObjB->name == "Camera") //Check each object to see if it's the rigid body and determine the correct normal.
                        normal = -pt.m_normalWorldOnB;
                    else
                        normal = pt.m_normalWorldOnB;

                    if (normal.y > 0.4f /*put the threshold here */) {
                        //The character controller is on the ground
                    }
                }
            }
        }
    }

```

---
Tags: physics, ogre, bullet-physics
---


# Question
Title: Testing Live Ads Before Publishing Admob
I am testing ads with the test device method and test ads are showing perfectly but when I try to load live ads they won't load.

I have implemented the OnAdFailedToLoad which tells me that ads are not loading, this only happens when I try to load live ad but in the test ad everything works fine.

Does this happens all the time? we can't see live ads without publishing the game first? or there are no ads available at the moment if so when do the get available or they even get available for new users. How can I make sure that I will get live ads after publishing the on Google Play Store.

I don't know I am just confuse about this thing, I am using Unity 3D and building for Android.

I have searched on internet but everybody says that ads might not available at the moment I am just curious why are ads not available its been two days and I haven't seen any ad when are the ads going to be available. Thanks for reading this.

# Answer
> 1 votes
When you register a new app with admob, it usually takes a couple days to run ads on consistent basis. Once you publish your app and your app starts making more ad request, live ads will be running without a problem. If test ads are working properly then there's no problem with your app networking with admob. so don't worry. Just publish the app with live ads ID. :)

Remember! if you get live ads showing on your own device, google might see that as invalid activity and that might get your admob account suspended. and trust me THEY WILL SEE THAT.

---
Tags: unity
---


title: Store temporary state in DB or not

text:
# Question
Title: Store temporary state in DB or not
### Background

I'm trying to implement a little MMORPG. I'm planning to use Cassandra DB for the database.

---

### Question

I don't really understand which data should be store in DB and which one should be just kept in memory.

For example : the friend list. Friend list will be stored in DB, but what about connected / disconnected friends ? Should I keep in memory all connected account and access it directly ? Or should I store this information in the DB (therefore writing / reading quite often for something that could be kept in the memory) ?

# Answer
> 3 votes
Deciding where to keep your data is a tradeoff between speed and RAM usage. Keeping information in the database saves you money, because your game servers need far less RAM. But keeping it in the database means the data will take longer to access, so you can't do it in real-time. When you need to do something which depends on data from the database, you need to wait until the database returned that information, which can take a few ms.

So when you have data you need really fast access to and which you access very frequently, you should keep it in memory.

The positions of currently playing players, for example. You will need those at least once every update tick, so it would be crazy to read those from the database on demand.

But what about the friend list? Well, that depends on what the "friend list" actually does in your particular game.

* Inform players about connect/disconnect events of their friends? That happens every few minutes to every few hours for each player, depending on how sociable they are. It's also no problem at all when these messages appear with a latency of a few seconds. So you could retrieve the friend connections from the database whenever someone connects or disconnects and discard the database result immediately after you posted the events.
* Tell the player where in the world their online friends are currently playing? This means you need to send regular updates to all friends who are also online. Depending on how often you want to send these updates, you might either keep the currently online friends in memory or do it from the database. Keeping the offline friends in memory makes no sense in this particular scenario. But remember to update the online friends list in memory on connect and disconnect events.
* Do you have social game mechanics which actually use the friends list for mechanical reasons? Like, say, people give 10% of their collected experience to all their friends even if the friends are offline? If you had a mechanic like that then it would make sense to keep the complete friends list in memory. But it would not make sense to update their exp count in the database after every exp event. You could just keep track of the exp share of each offline friend in memory and write them to the database at regular intervals.

---
Tags: mmo, databases
---


title: A* Algorithm for Tactical RPGs?

text:
# Question
Title: A* Algorithm for Tactical RPGs?
I'm messing around with writing a really poor tactical RPG in C++. So far I have a 2D tile map and just got the A\* algorithm working based on the pseudocode in the wikipedia.

But real tactical RPGs don't just find the best path on a flat plane and move there. They typically have limited move ranges and must climb up or down. If you've ever played Final Fantasy Tactics these would be affected by the Move and Jump stats. This is where I get lost. How do I alter the A\* algorithm so that it finds the best path toward a target, but the path is only so many tiles long? How should I take height differences and jump stats into account? How do I implement jumping over a gap?

If it helps, right now my map is represented by a Vector of Tile objects. Each tile has pointers to the North, South, East, and West tile, which are set to a nullptr if no tile exists there, such as along the edge of the map or if a tile is set to non-passable.

# Answer
> 33 votes
Climbing, and gaps, are just different cost functions. For a unit that can jump the gap has a normal(?) cost, while for a non-jumping unit it has arbitrarily high cost. Climbing costs extra, as does difficult terrain, etc. The A\* algorithm is well able to handle cost functions, so if your implementation is not doing it already, just google for how to implement A\* with a cost function.

Having said that, however, I don't think A\* is a particularly good approach for a tactical RPG. Or more accurately, it's not a complete story. You don't want your units to blindly blunder towards their goal, you want them to position themselves to exploit cover, high ground, whatever, whilst progressing towards the ultimate goal and seeking to flank opponents and so forth. So the tactical value of the end point of each move is of huge importance, not just how close it is the goal. This requires more in-depth problem solving than mere pathfinding.

# Answer
> 13 votes
When you want all possible movement options of a unit, use Dijkstra's Algorithm.

The difference between A\* and Dijkstra is that Dijkstra gives you all the possible shortest routes achievable with a given cost, and if none of them reaches your destination yet, it increases the cost by one and continues. A\*, on the other hand, prefers to calculate those routes first which have a good chance to reach the destination.

So when you just want the shortest path from point A to point B, then A\* is a good choice. But if you want all possible movement options and the shortest path to each of them, then Dijkstra is exactly what you want.

All you need to do is run Dijksta's Algorithm with no specific destination node, but with a maximum cost which must not be exceeded (the unit's movement range). When traveling to a node would exceed the maximum cost, do not visit it. When the algorithm terminates due to lack of unvisited edges, each node in the visited set is a possible destination, and the previous node markers of the nodes form a linked list representing the path back to the initial node.

Regarding jumps: Those can be represented as yet another edge in both A\* and Dijkstra. They can have the same cost as traversing a regular edge or a different one. You can also pass a "jump\_height" parameter to the algorithm which tells the algorithm to ignore jump-edges which exceed a given height.

# Answer
> 2 votes
The other answers have some good information, so be sure to read them.

However, to answer your question: based on the pseudocode that you linked to, you have some kind of function `heuristic_cost_estimate` where you're calculating the cost from tileA to tileB (assuming they are adjacent). Instead of using a flat (1) for that cost, you would have to adjust it to include the tile stats and unit stats, and possibly edge stats.

For example:

```
if (edge == JUMP && !unit.canJump())
    return INF;
if (tile.Type == Forest && unit.moveType == HORSE)
    return 2;
//Other cases here
//-----
else
    return 1;

```

This will give you your path. Then, you would simply move the unit along their path while consuming movement points and stop them when remainingPoints \< edgeCost. Note that this may not be completely optimal if you end up with remainingPoints = 1, but it should be good enough for a practice RPG. In reality, you'd want more tactical, as Jack Aidley pointed out!

Challenge:
If you want to get more advanced, you probably want to use Djikstras as suggested to find all spaces within X distance, then you want to evaluate each space in that list for a "best" place, based on closeness to target, defense power, whether or not you can be attacked from that position, etc. Based on that info, you would choose a tile, then move there following the path you just calculated using Djikstras.

# Answer
> 1 votes
Climbing and gaps are pretty trivial since they only modify cost. Pathfinding (and most of tactical AI) is all about summing up the cost on all to-be-visited nodes and minimizing that. An impassable cliff will have an infinite (very, very high) cost, slopes will have a higher cost than normal, etc.

This, however, finds the globally optimal path which not the best solution because real adversaries usually **do not** find the optimal path. It's highly unrealistic, sometimes to a point which is obvious to the player, and annoying (especially when the AI as such is basically invincible because it, too, chooses the optimum).

Good simulations *deliberately* do not find the best path. A much better algorithm might be to do hierarchical pathfinding -- if nothing else, by drawing a straight line on the map, and taking 4-5 waypoints, then pathfinding from one waypoint to the next, considering only the node weights that are so far known, and setting all other node weigths to "indifferent". Alternatively, you can run A\* on a coarser grid first, and then pathfind from one large node to the next (but I'm guessing that drawing a line on the map is just fine, too).

This is much more realistic (and also consumes a fraction of the processing power because the graph is *much* smaller). Yes, it can mean that a unit moves towards a cliff only to find out that it can't get across. That's fine, it happens to real adversaries, too. Next time, it won't happen again (because now the infinite cost is known).

---
Tags: path-finding
---


title: Accelerometer input for flying game

text:
# Question
Title: Accelerometer input for flying game
I'm trying to create an infinite flying game where the gameobject (a plane) keeps moving forward and at a particular height throughout the game. I want to be able to
roll and pitch the plane but not move it up/down. I added a rigid body to the plane and selected "y" position constrain. However the plane doesn't stay in the 'y' position but starts move up or down. I just have a script that translates the plane in the z direction. Not sure how to implement the mobile input and keep at the same "y" position throughout.

**Update**

Here is the code for the plane. Its very basic as I'm not sure how to use the accelerometer:

```
public class Player : MonoBehaviour {

public float speed = 1.0f;

void Update () {
    float tempx = Input.acceleration.x;
    float tempy = Input.acceleration.y;
    float tempz = Input.acceleration.z;
    transform.Translate(0, 0, 10); // move forward in z
    transform.Rotate( 0,  tempy * speed, tempz * speed);
}

```

As for the freezing of the 'y' position, I'm just selecting the y constraint available in the inspector that comes along with the rigidbody.

# Answer
> 1 votes
When in doubt, be sure to read the documentation for the methods you're using.

Here you'll find out that if you give `transform.Translate` three float parameters and no `Space`, it defaults to translating in local coordinates. ie. in this case, it moves along the object's Z axis, not the world's Z axis.

Once you rotate the plane, that direction might point up or down, changing the global y coordinate of the object.

Because this change is going through the `Transform`, it completely bypasses the constraints you imposed on the Rigidbody.

So, possible fixes:

* Specify `Space.World` if you want to move forward in world space, not local space

`transform.Translate(0, 0, translationSpeed * Time.deltaTime, Space.World);`
* If you want to steer left/right, just not up/down, compute a desired translation in world space, then clamp-out the y:

`var desiredTravel = transform.forward * translationSpeed * Time.deltaTime;` `desiredTravel.y = 0f;` `transform.Translate(desiredTravel, Space.World);`
* Or, route all movement via the Rigidbody by setting its velocity instead of teleporting with `Transform` changes. This lets the physics engine maintain the constraints you've configured:

`rigidbody.velocity = transform.forward * translationSpeed;`

---
Tags: unity, accelerometer
---


# Question
Title: Why do RPGs let you know how much XP you need to level up?
I was reading this article called Behavioral Game Design, and it says:

> ...how do we make players maintain a high, consistent rate of activity? ... the answer is a variable ratio schedule, one where each response has a chance of producing a reward.

RPGs (I'm thinking of traditional JRPGs like Final Fantasy 1-6) don't do this when it comes to leveling up characters. You can always pause the game and look at how much XP you need to level up again. I haven't played WoW before, but I suspect it lets you know how much XP you need to level up, too. In WoW, there's plenty of examples of "variable ratio schedule" elsewhere in the game, so why not when it comes to XP you need to level up?

I suspect most professional game designers know the lessons in this article. So why is it typical for the XP you need for the next level to be known? They could design the game so that it's random, where you never know how many enemies you need to kill for that next level. So why don't they use this as an opportunity to have a "variable ratio schedule"?

# Answer
It's common for games to have multiple overlapping loops of gameplay and reward, hitting different frequencies and motivation types, so that we don't have all our eggs in one basket, motivationally speaking. This helps the game appeal to more players, and more consistently appeal to any one player, since every player is a multifaceted human being with a variety of interests & needs.

RPGs typically scratch the "variable ratio" itch with combat and loot drops. You have a random chance of encountering this mob or that mob, a random degree of success on attacks and dodges, and a random reward on completion. Unknown rewards in chests and breakables found as you progress through the world function similarly.

This forms a very high-frequency loop every few minutes of gameplay, making it well suited to produce a feeling of "just one more fight!" - a good loot roll could be just around the corner, and it only takes a few minutes more to try another time.

XP and leveling progression serve a different niche, on a longer term - ensuring the player can see they're making measurable progress and growth over hours of gameplay, or from one game session to the next. Even if I get a terrible sequence of loot rolls and am nowhere closer to crafting that shiny new item, hey, at least I'm 1000 XP closer to my next level, so I'm still being productive and haven't wasted my time!

Because of the longer timescale of leveling, a random chance isn't quite so motivating here. I don't want to sink another hour of play just for a *chance* I *might* level up. For an investment that large, a player will typically want some predictability. Even if I don't manage to hit level n+1 today, knowing I'm just 500 XP away makes me eager to come back and finish the level tomorrow, opening up a new long-term goal of hitting n+2...

So, it's not that these games forego variable ratio rewards, they're just choosy about where they deploy them.

Player expectations are a factor here too - players have a lot of experience with random loot drops and predictable XP progression at this point, so sticking to this convention helps the players feel comfortable, and learn the systems efficiently. Suddenly making level progression randomized risks alienating players, so it's often safer to place those variable ratios elsewhere in the game design.

This expectation might be a factor in why RPGs that have decided to use variable ratio rewards as their long term progression — eg. Destiny and other games with high-end leveling based on gear score — have chosen to do so via the loot system, to better match where players are used to seeing this type of randomness. They could as easily have given out a "level token" randomly, but by attaching leveling to the quality of gear that drops, they piggyback on a familiar gameplay pattern of loot grinding, and also give more interest to the "failed" rolls. (ie. Gear that doesn't increase your net level might still be useful to sell, use in crafting, or have some other value like a special ability useful in some circumstances, or a desirable visual appearance)
> 134 votes

# Answer
It's a matter of motivating the player.

* The player has an achievable goal to work towards
* The player sees how far away from the goal they are
* The player sees how playing the game visibly progresses them towards the goal

Variable ratio rewards can also be a great motivator, but so is an "honest pay for honest work" game mechanic where the reward after each action is guaranteed. The player never feels like doing something was pointless, because there is always at least a minimum reward in form of experience points.

Many MMORPGs recognized this and made the levelup progress bars much more accessible than classical single player RPGs. They are often very prominent, always visible UI elements. I have seen MMORPGs which made the EXP progress bar span across the whole width of the screen. Some even make it a two-tiered bar with one bar showing the progression between 0% and 100% and a smaller bar below showing the progress to the next full percent. That way players can still see visible progress when they get into the lategame phase where it takes several days to level up.

Using experience and gold as a reliable reward and item drops as a variable reward has proven to be a practicable and effective combination. So it basically became a standard convention of the RPG genre. There is of course no reason why you shouldn't try to do it the other way around in your game. I could see it work quite well. But keep in mind that you are in experimental territory here.

In more "skinnerboxy" games you see a lot of such numerical progression systems. Progress to next level, progress to levelup individual skills, progress to completion of quest, etc.. The player should always find something to work towards.

One secret of addicting game design is to layer many different reward systems which stimulate the player's reward neurons in as many different ways as possible:

* Short-term, mid-term and long-term rewards
* Constant, slightly variable and you-just-won-the-lottery variable rewards.
> 23 votes

# Answer
Think about what would happen if level up happened randomly. You have a party of three players. At the beginning, all are the same level (for simplicity, 1). After playing around one levels and two don't. Not a huge deal normally. Since the one leveled, the others will level next and catch up. But under your system, the one who just leveled may level again before the others do. Over time, you end up with one person who was really unlucky and is level 5. Another is level 7. And the lucky one is level 11.

How does the system balance a party with a level 5 and a level 11? The level 5 player will die if the encounter is set up for a level 11, and the level 11 will be totally bored if the encounter is set up for level 5. And if they compromise and set up for level 8, they have both problems at the same time. The level 5 is constantly dying while the level 11 is constantly bored.

Now, perhaps you play solo. So this doesn't matter to you. But if the game is designed to include team play, it has to handle this issue. And they can't really have different behavior for this in solo versus team, as the same characters can participate in both. Even if your game is solo only, players will expect it to work like this.

Another problem is when the luck is going against you. You're stuck at level 5. You can't advance because you're waiting to level. You get tired of the game and quit, because it's a constant grindfest as you wait to level.

A third problem is when you level early. There's a certain amount of level 5 content. But you leveled and can do level 6 content. Do you stay and do the now easy level 5 content? Or do you switch to level 6 content? If you switch, you're essentially skipping part of the game. Your enjoyment is reduced because you didn't get the full content. And if you do the level 5 content anyway, you get bored as the encounters are not challenging to a level 6.

It can get worse. While you're doing the extra level 5 content, you may level again. Now you're a level 7 doing level 5 content.

This problem is reduced with loot, as it doesn't progress the same. You find a good sword. How lucky. Then you find a great sword. But having the good sword doesn't make the great sword any more powerful. Having a level up event on top of another level up event is more powerful than a single event. So the second amplifies the first. But with the swords, each drop is isolated.

All this isn't to say that you can't have random variation in the experience rewards. But with team play, you want all the members of the team to get the same experience result. And in solo, you have to find ways to match the difficulty to the player's capability. If you have both, then you need to be consistent between them.
> 12 votes

# Answer
The short answer: psychology.

The long answer:

We humans are driven by the expectation of a reward, just like a dog. Knowing how much experience you have reached and how much is still needed for reaching the next level gives you a nice feedback that what you do is good or bad for evolving your character.

Edit: also, not knowing how long it will take for levelling up is like downloading a big file without a progress bar. It may take the same 10 minutes, but without a progress bar it will feel like 10 hours
> 11 votes

# Answer
There is actually a quite interesting GDC talk that has been given on this topic by someone who worked on the reward structures for large sections of World of Warcraft and Diablo 3:

https://www.youtube.com/watch?v=urijgWXLYck

He talked at length about how players experience randomized versus deterministic rewards and how both reward types work together to provide a player with a sense of progression while also encouraging them to continue playing. I also recommend a related video from someone who played World of Warcraft for a long time, a video that gives his own comments on the video and clarifies a number of things from the perspective of the player:

https://www.youtube.com/watch?v=OjQAnJYyXf4&t=0s

I recommend watching both videos if you have time, because they provide a good overview of the challenges with reward structures and how he solved deterministic versus random rewards.

He found that in order to keep players playing, they need to feel like they improved meaningfully every time they played, even if they only played a short while and only got a small reward. That's the role that EXP delivers: you can play a short period and still feel like you did something worthwhile with your time. He also found that if everything was deterministic, the player dynamic would change and they would view the game more and more as a really grindy system that was very predictable in pacing and felt like a deliberate slowdown of the game. This was especially noticeable during Icecrown Citadel and Firelands, when Emblems of Frost and Dragonwrath respectively changed a large and impactful part of progression to a mostly deterministic path, where you could predict when you'd get the next step in your gearing process months in advance and guilds planned around them.

He had exactly the reverse problem in Diablo 3: the loot players got was too random and often not usable for their class, so players would go days or weeks without any upgrades because the few legendaries they'd get were meant for one of the other 4 classes. The result is that players would stop playing the game for their OWN loot and instead played to get as much loot as possible to sell on the ingame Auction House so they could then buy their own gear with the proceedings. It turned the game entirely deterministic and players were quitting the game in droves because the core part of the game felt unrewarding. They additionally also had the problem where their intended max level deterministic reward, Paragon levels, would eventually cap out and players would no longer see reason to continue playing for them.

That problem was solved through removing the AH, redesigning Paragon so there was no level cap, and rebalancing player loot drop rates so they would get far more legendary rewards and far more rewards that were suited for their class. They then found that their loot had pretty much become deterministic, which they fixed by adding Ancient items, which essentially were Legendary items with more stats on them. They also added a way to more or less target specific items, but without losing the random chances.
> 7 votes

# Answer
# TL;DR

* People are impatient.
* More randomness tends to make games more difficult.

---

As you have pointed out, it's been scientifically proven that many species find variable ratio setups 'irresistible'. This is because they appeal to a very primitive part of the brain, and assuming that the individual judges risk/reward ratios correctly, it's actually a really important survival trait. Because it's such a low-level response, it's really hard for most people to not follow up on it, and therefore it does indeed make a good draw for a lot of players.

The problem is, this impacts behavior in ways people might not expect. People don't like to wait for results to be visible, they want them *now*, which in turn means that for many people, no visible progress towards a reward equates to zero progress towards said reward, which then means that most (sane) people will stop trying to get that reward after a while. This is actually the same reason that a 'clicker' or whistle is used when training animals, it helps fill-in the space between the desired action and the tangible reward, making it easier for the animal to equate the action and the reward mentally.

As a result of this, people tend to get irritated when they make no visible progress after spending multiple hours working on something (not just in games, but also in real life). The exact point at which this starts to become an issue varies from person to person, so most games err on the conservative side here and give you easy access to exact information about how far you've progressed.

Some people go even further than this though, and want to know exactly what they need to do to to achieve something, and as a result you can find information on exact amounts of XP you get from any given action in a number of the more populate RPG's out there with a simple search of the internet.

---

All that psychology is useful info for explaining this, but there's an even more important, and much simpler, line of reasoning that explains it, leveling is one area where more randomness makes a game *really* hard, and if you're not going to make it random, you might as well just show players the numbers because they're going to figure them out themselves through experimentation anyway.

Imagine trying to level on a bell curve. You have to get some minimum amount of experience to *possibly* get the next level, are guaranteed to get it after getting some higher amount of experience, and most people level about halfway between those two numbers. This has all kinds of issues:

* In a single-player RPG, it makes the game much less consistent. This can technically increase replay value for veteran players, but it can make the game hellishly difficult on a person's first play-through (or insanely easy, in which case they may not end up liking the game as much either).
* In a drop-in co-op RPG (like Borderlands), it makes it very difficult for people to actually work together as a team. Part of the reason such games work at all is that they provide reasonable guarantees that a group of people who start the game at the same time and only play together will have roughly equal power levels. Without that guarantee, the whole format falls apart (because anybody who gets lucky a couple of times will constantly steal the spotlight).
* In an MMORPG, it just makes things miserable in general. Imagine playing WoW or Warframe but not knowing when you'll be high enough level to join your clan/guild on their next big raid. It's just as bad for sensible clan/guild leaders, because they can't realistically organize long-term coherent groups of people who are about the same level to progress together.
* In any type of RPG, it makes coherent story progression nearly impossible (oh, I finished this series of story quests, but I'm not quite high enough level yet to be able to even attempt the next set of story quests, guess I have to go grind enemies from the last quest for a couple of days instead of getting further in the story).

It also, somewhat ironically, would make the developers life much more difficult. This approach would require a lot of complexity in the code that ahndles leveling, and complex code is more difficult to maintain, more difficult to debug, and more likely to have bugs. Even systems which have you send XP directly on power ups instead of leveling are simper than this.
> 2 votes

---
Tags: game-design, rpg, progression
---


# Question
Title: Does Unity3D custom shader use its default GPU or CPU skinning automatically?
I'm writing my own shader in mobile, but was wondering if it uses default GPU or CPU skinning feature in Unity3D?

I'd like to use GPU skinning and already enabled GPU skinning. Is there any way to determine which (GPU or CPU) was actually used?

My shader is as below:

```
 Shader "Mobile Custom/Specular Map" {
 Properties {
     _ShininessColor("Shininess Color", Color) = (1,1,1,1)
     _Shininess ("Shininess", Range (0.03, 1)) = 0.078125
     _MainTex ("Base (RGB)", 2D) = "white" {}
     _SpecMap ("Specular Map", 2D) = "white" {}
 }
 SubShader {
     Tags { "RenderType"="Opaque" }
     LOD 250
     Cull Back

     CGPROGRAM
     #pragma surface surf MobileBlinnPhong exclude_path:prepass nolightmap halfasview interpolateview noshadow nofog nometa nolppv noshadowmask

     inline fixed4 LightingMobileBlinnPhong (SurfaceOutput s, fixed3 lightDir, fixed3 halfDir, fixed atten) {
         fixed diff = max (0, dot (s.Normal, lightDir));
         fixed nh = max (0, dot (s.Normal, halfDir));
         fixed spec = pow (nh, s.Specular * 128) * s.Gloss;

         fixed4 c;
         c.rgb = (s.Albedo * _LightColor0.rgb * diff + _LightColor0.rgb * spec) * atten;
         UNITY_OPAQUE_ALPHA(c.a);
         return c;
     }

     sampler2D _MainTex;
     sampler2D _SpecMap;
     uniform float4 _ShininessColor;
     half _Shininess;

     struct Input {
         float2 uv_MainTex;
     };

     void surf (Input IN, inout SurfaceOutput o) {
         fixed4 tex = tex2D(_MainTex, IN.uv_MainTex);
         o.Albedo = tex.rgb;
         o.Gloss = tex2D(_SpecMap, IN.uv_MainTex) * _ShininessColor;
         o.Alpha = tex.a;
         o.Specular = _Shininess;
     }
     ENDCG
 }

 FallBack "Mobile/VertexLit"
 }

```

# Answer
The closest I was able to come to tracking this down was a comment I noticed in an official Unity tutorial called Mobile Considerations (for version: 2017.4):

> **GPU Skinning**
>
> Although GPU Skinning is a selectable option in Build Settings for all platforms, it is not supported by any mobile platform. This option will be removed in upcoming Unity releases.

Taken from your own finding about Android settings on version 2018.3, it appears that Unity now limits GPU skinning to VR:

> **GPU Skinning**
>
> Enable this option to use OpenGL ES 3 GPU skinning. To learn more about GPU skinning, see the Wikipedia page on skeletal animation.
>
> **Note:** This property only supports VR apps, and only works if the Virtual Reality Supported checkbox is ticked.

Regarding their motivation for this, the best I could find is this piece (from version 2018.3) on mobile optimization:

> **Focus on CPUs**
>
> It is often the case that games are limited by the GPU on pixel processing. So they end up having unused CPU power, especially on multicore mobile CPUs. So it is often sensible to pull some work off the GPU and put it onto the CPU instead (Unity does all of these): mesh skinning , batching of small objects, particle geometry updates.

My best guess is that Unity eventually decided that either in general the performance trade offs were such that CPU skinning gave better results than GPU skinning or that the there were some other complications with support this feature. Based on some much older forum discussions, it seems that GPU skinning is only available on certain version of DirectX & OpenGL. It's also possible that rather than deal with a lot of user confusion about when & where a minor feature was & was not taking effect, that they simply removed it from the options.

Regarding the comment about CPU skinning hurting performance (in mobile apps), the only way to know that for certain would be to profile. It's fine to have hunches, but if you are serious about improving performance, should always start & end with profiling. Use profiling at the beginning to find the problem spots (instead of guessing & wasting time on things that aren't relevant) & use it after changes in development strategy to make sure you're moving the right things in the right direction.
> 1 votes

---
Tags: unity, shaders, gpu, skinning
---


# Question
Title: Godot: does parse_json accept multiple JSON objects?
If I had a JSON file that had multiple objects, can the method read through without some form of exception?

# Answer
> 3 votes
It looks like the implementation of `parse_json` calls `JSON::parse`. `JSON::parse` looks like a fairly generic JSON parsing routine, but it does expect the top-level of the JSON fed to it to be a single value (since defers, once, to `_parse_value`).

Thus, it looks like you can provide it JSON containing multiple objects within a top-level array or structure. But if you provide it a string that happens to contain two independent sets of JSON, it will only parse the first one.

---
Tags: godot, json
---


title: Unity - X axis back to front

text:
# Question
Title: Unity - X axis back to front
I'm using Unity 2018 and its really confusing me. I generate a plane mesh in code and when it comes to positioning (transform.position.x) it on the X axis I can't understand why moving it **further to the right the X value decreases** (into the negatives) and the X value **increases** to the left??

The Y axis works as expected, up increases the value (positive), down decreases (negative). The Z axis, away from camera = negative and towards = positive.

(Just creating a basic 3D cube game object using the Unity Create tool, the same issue applies.)

I need to figure if this is how Unity is set up now? Or I'm doing something wrong.. But I'm stuck on this!!

//create mesh code:

```
Mesh CreateMesh(float width, float height)
    {
        Mesh m = new Mesh();
        m.name = "ScriptedMesh";
        m.vertices = new Vector3[] {
         new Vector3(0, 0, 0.01f),
         new Vector3(width, 0, 0.01f),
         new Vector3(width, height, 0.01f),
         new Vector3(0, height, 0.01f)
     };
        m.uv = new Vector2[] {
         new Vector2 (0, 0),
         new Vector2 (0, 1),
         new Vector2(1, 1),
         new Vector2 (1, 0)
     };
        m.triangles = new int[] { 0, 1, 2, 0, 2, 3 };
        m.RecalculateNormals();

        return m;
    }

```

//build our first wall mesh obj

```
                    var wallObj = new GameObject("Wall-" + wallc.WallLengthCM + " (" + wallIndex + ")");
                    var _wallMesh = (MeshFilter)wallObj.AddComponent(typeof(MeshFilter));
                    _wallMesh.mesh = CreateMesh((float)wallc.WallLengthCM, (float)wallc.WallHeightCM);
                    MeshRenderer wallRenderer = wallObj.AddComponent(typeof(MeshRenderer)) as MeshRenderer;
                    wallRenderer.material = ShedWallMat;
var wallMesh = Instantiate(_wallMesh,
                new Vector3 { x = 0, y = ((float)wallc.WallHeightCM * 2 * wallIndex) + vertSpace, z = 0 },
                new Quaternion { w = 0, x = 0, y = 0, z = 0 });

```

# Answer
Unity's coordinate system is a little different than you described. From the perspective of the default camera in a new scene (looking along the z+ axis):

* X+ = right
* Y+ = up
* Z+ = forward / away from the default camera (not negative as described in the question)

In this example you've turned your viewpoint around to look "backward" along the world's negative Z axis, so naturally the positive X axis is turned to point leftward from this perspective.

If you turn your view around the other side, you'll find that your mesh disappears. That's because you've wound your triangles in counter-clockwise order, but Unity's materials treat clockwise triangles as front-facing by default. Simply interchange two indices of each triangle to match this convention.

One last minor issue: an all-zero quaternion does not correspond to a 3D rotation. We typically want our quaternions to be unit length. So you may want `{w = 1, x = 0, y = 0, z = 0}` instead, also available as the constant `Quaternion.identity` (I suspect Unity is falling back to this when given all zeroes anyway)
> 1 votes

---
Tags: unity, orientation, axis
---


# Question
Title: Tell Unity to use a certain LayerMask to raise or not OnDrop (for a class that implements IDropHandler)
I am trying to make a draggable GameObject that can be dropped within a container but when i'm releasing the mouse button even though the mouse is over the container (and the dragged object too) `OnDrop` isn't raised on my container. To make it work i must pick the dragged GameObject right at its edge so that the mouse is over the container but not the draggable when i release the mouse button

According to what I've seen drag and drop handled by unity is based on Raycasts and Raycasts could be configured to ignore objects that are in certain Layers thanks to a `LayerMask` the problem is that i wasn't able to find anything to apply a `LayerMask`

Is there a way to do this or any workaround that could let the drop target know that a dragged was dropped on him?

# Answer
There is a checkbox called `Raycast Target` on certain components or `Blocks Raycasts` on `CanvasGroup`. So when you release the drag, your mouse is over the object that you are dragging. You can just uncheck that box on objects that you are dragging, so that raycast would go through. If you want to use LayerMask, or you want to raycast multiple targets, you can create a custom raycasting solution and your own interfaces for it.

GraphicRaycaster.Raycast \- this example explains pretty much how to create custom behaviour for raycasting. You could combine it with OnDrop but I would suggest just writing your own if it's required. But it's probably achievable with current system. I bet what EventSystem does is basically checks for button press, when button was pressed/released it raycasts, if object hit implements IDropHandler, then call OnDrop. With custom system you can have LayerMask which will tell what layer to hit while raycasting.
> 0 votes

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


title: Sprite Management

text:
# Question
Title: Sprite Management
I'm working on a game right now using my own engine. In the engine, I have a State Machine which handles input for, updates, and draws the current State - the one at the back of the vector. The game engine itself stores Sprites in two maps and a vector, and the States also store pointers to those Sprites. With this many references, it is becoming difficult for me to manage all my Sprites and their scope. Furthermore, I have a Button class which derives from Sprite and adds some mouse input behavior.

I'm trying to figure out a storage solution for my Sprites that would allow me to update all Sprite animations, handle Button input, identify specific Sprites (likely by a string name) primarily for cutscenes, access Sprites directly to begin animations or instantly modify their position, color, or texture coordinates, and batch Sprites of the same batch type (Menu, Background, Player, etc.) together for drawing.

My current solution stores a map of BatchType (an enumerator) to a vector of shared\_ptr's pointing to Sprites, solving the batching problem; then a map of strings to Sprites for naming; next, a vector of smart pointers to Buttons for their specific handleInput function; and lastly, the engine's createSprite method returns a shared\_ptr to the new Sprite so it can be stored in the State that created it for direct access. In order for any Sprite to be deleted, I have four potential references to delete, and it feels convoluted.

Are there any better storage methods which will still achieve all this? I think the main problem here is that I need to separate Sprites from Buttons in order to call the Button handleInput function.

# Answer
Update to my solution: I have been doing more research into game development and I feel a lot more prepared after looking into best practices and design patterns. Probably my biggest mistake was treating my game states as *scene managers* rather than the scenes themselves. Realistically, the title screen is in itself a scene with a sub-scene for the specific menu the game is in, which also solves my problem from a while back wherein I was unsure how to handle Sprite batching in combination with state. Ultimately I have a background and logo Sprite displayed by the base Title Screen and it draws the sub-scene on top. Plus, each of these menus, now treated as scenes as they should be, will store their Sprites independently and only need one additional draw call for the Menu batch. This allows me to define Sprite scope easily and reduces the risk of lingering Sprites between scenes by having to manually delete them.

Overall, I will store Sprites per-scene and use the State Machine for the core Opening Credits, Title Screen, Game and Cinematic states, then basically treat Title Screen and Game as scene managers which have sub-scenes that share Sprites with their super-state. This will come in handy later for pause menus and player menus (quests, inventory, etc.) which get displayed on top while still drawing the super-state normally.
> 0 votes

---
Tags: c++, sprites
---


# Question
Title: Wraparound world with wraparound horizontally physics implementation in Unity
What is the best way to implement a wraparound world with wraparound horizontally physics in Unity?

That means that if I have an object and move it so that a part of it sticks off to right (so that the camera does not see it) I would like the part of the object to be shown on left. The same goes for the left side.

The best (even though I do not like it at all) implementation I was able to find is to have three objects. One of them is visible for the camera and two others become visible when the middle object goes off the camera.

Any other ideas on this?

Here is my explanation with images of what I want to happen:

Thank you.

# Answer
> 0 votes
Can you set up multiple camera views that are side by side and seamless?

Imagine one view that represents the right most 95% of your game window, and the left view is the other 5% of what's off the right side. Then with two views (and a single camera) you can render the same item twice, and create the wraparound effect. Basically when the object is half off the right, it's also being rendered on the left, because the left view represents what's off the right side of the screen.

Here's a pic that might help...

In the above, the green lines are the views, and the black line is the game screen.

Note that it wouldn't be 95/5 really, but based on the size of your object - specifically half the maximum width. If it is 100 pixels wide, your left side narrow view needs to be at least 50 pixels wide.

**Edit and Refinement**

As pointed out in comments, this does not solve the problem of physics and wrap around worlds. To solve **that** problem, what you need to do is not think of your world (and its physics) using 2D Cartesian coordinates. Instead, you need to model your world with the coordinate system of a cylinder. A cylinder has no "edge" and as such, there is no concept of "wrapping around the edge" at all. Yes, there is one if you try to go off the top, but if all you are concerned about is horizontal (X) wrap, a cylinder solves your problem.

Here's a picture to show the idea of an object on a cylinder, and how you render it (via something like my 2 view idea above) in a 2D space.

Your only challenge (which I think is valid as a separate question) is, "How do I render a cylindrical world space onto a flat, 2D view port?"

Note 1: If if you want to make things wrap around the top, it's going to get more complex.

Note 2: I am curious how the old asteroids game (which has wrap around on all sides) handles collisions in this (literal) edge case.

---
Tags: unity, 2d, physics, camera
---


title: FoV value scaling

text:
# Question
Title: FoV value scaling
I'm creating an FPS project in Unity 2018. My reference FoV is 90. Let's say I'd like to create an sniper rifle which let player change FoV to 60 when he's aiming with optics.

But what should be the FoV of this gun when using optics for player who plays in 105 or 80 FoV by default? How should I scale it?

# Answer
> 2 votes
It depends on your goal.

If your goal is to express the particular feel of *this specific* weapon and its optics, then arguably its FoV should not scale at all. If you've determined that this sniper rifle has 60 degrees of visibility when aimed down sights, then 60 degrees is the value everyone uses.

Or you could set a different goal - like trying to ensure the portion of the scene image visible through the scope is a fixed ratio of the unzoomed scene. For this approach, you can do something like this:

```
// These parameters represent your default normal FoV and its corresponding zoomed FoV,
// in radians, measured from the bottom of the view to the top.
float referenceFullFoV = 90.0f * Mathf.Deg2Rad;
float referenceZoomedFoV = 60.0f * Mathf.Deg2Rad;

// This derived value describes what fraction of the default scene should fit in the zoomed image.
float zoomedHeightRatio =  Mathf.Tan(0.5f * referenceZoomedFoV)
                         / Mathf.Tan(0.5f * referenceFullFoV);

// This describes the half-height of the projection of the full scene
// at the current FoV (in radians) onto an image plane 1 unit away from the camera.
float unzoomedHalfHeight = Mathf.Tan(0.5f * currentFullFoV);

// Now we scale this by our ratio and undo the tangent operation
// to calculate the FoV to use for the scoped version (in radians).
float zoomedFoV = 2.0f * Mathf.Atan(zoomedHeightRatio * unzoomedHalfHeight);

```

# Answer
> 1 votes
As a designer, I would allow the player to choose FoV for normal play. Movement can make people ill if the FoV is too high. I personally have to play at 90 when I'm in Quake 3 or I get sick.

But for zooming, since it's not usually for movement and the FoV is lower, not higher, I would set it to what you want for playbalance. So if the zoomed FoV is normally 60, then it would be 60 for anyone regardless of their normal FoV.

---
Tags: unity, camera, first-person-shooter
---


# Question
Title: realtime multiplayer game database design
I'm creating a real time client/server game, where each match is a 1v1. I'm a little lost as how to implement this. I want it to be viable for 1,000 simultaneous matches, but as I'm expecting around 100 db entries per match (I need to log players' past states), that would be a 100k row table.

I don't know if I should use an RDBMS that indexes the table by match ID, and if that would be fast enough.

I'm also contemplating using plain files with my own extension for each match, but that would be 1,000 of them on my machine, and I don't know if that would be too slow.

If anyone has any suggestions on how I can implement this, I'd really appreciate it.

# Answer
> 5 votes
Databases usually only make sense for data "at rest". As in data which someone might or might not look at at a much later point in time and which you want to be searchable by different keys. If you aren't going to do that, using a database usually doesn't make any sense.

When you have a real-time game, you should store all data you need for your ongoing games in the server's memory. The reason is that fetching a row from a database in the same datacenter under absolutely ideal conditions (database is an ultra-fast magic NoSQL store and has the value cached in memory) takes at least 5000 times as long as reading a value from memory. In the worst case, the database won't have the data in memory and will have to do a hard-drive seek, which takes 10,000 times as long as reading from memory. With hundreds of ongoing games, you might have thousands of hard drive accesses per second. This **will** become a bottleneck.

So you should better keep the data of all ongoing matches in your game-server process and only persist match results to a database.

A scenario where it can make sense to persist complete matches with all their ticks to the database is if you want the ability to watch replays of past matches or maybe even run some data-mining to analyze games to find out how to improve your game (or catch cheaters). How your database schema would look, depends on what exactly you want to do:

1. Replays, complete playback only: You need two columns, `match` and `data`, where data is a `BLOB` of your internal match representation. Unpack that whole blob when you want to replay the match. You might want to add some more columns with meta-data which helps you to find interesting matches (when was the match, who vs. who, who won, etc.)
2. Replays, frame-by-frame playback: Three mandatory columns, `match`, `tick` and `data`. The data is again a `BLOB` of your internal representation of the match-state.
3. Everything you want to data-mine: Now you will have to normalize the BLOB and split it into multiple database columns with readable values. That means whenever you have something you have multiple of, you will need to create another database table with `match`, `tick`, `thingID` and all the properties of that "thing".

# Answer
> 0 votes
Although @Philipp makes a good point, I don't fully agree with his assertions.

Now this rally depends on what you intend to do, but databases are good at efficiently persisting data and work through huge volume of data efficiently.

There are three levels of data access you need to consider. First you have your objects fully formed in memory. This generally quick access, but if you need to look through large swaths of objects to find something you need to implement the appropriate access algorithms (e.g. indexing).

In memory databases can make life a bit easier when the amount of data you handle surpasses your ability to organize efficiently. You can to it yourself, but if you are juggling a few GB of data, you are effectively re-implementing a database, just use an existing one.

Disk backed databases should be used when your data surpasses the RAM capacity or need long term storage. Databases generally are good at keeping the relevant bits in memory and hot; but yes if you get a cache miss, it will hurt bigtime. But if you use your database mostly for write only storage, they can be quite efficient. The key feature is that the write will be quick to memory and the database backend will later persist it when time allows.

Although you are not entirely clear on the details, you can have the best of both worlds. Why not keep your current game state in objects and each move / tick you write the game state changes to the database before updating to the next.

---
Tags: multiplayer, databases
---


# Question
Title: Are dice-rolls for damage calculation bad design for a tactic focused game?
I'm trying to come up with a combat system for a turn-based RPG that is inspired by pen & paper RPGs, but with more importance on positioning and strategy.

I feel like in games where a good strategy is important, a dice roll for damage calculation like in Dungeons & Dragons, etc is really bad, because your best strategy can and (eventually) will be ruined by a bad roll or a very good roll of the enemy.

The two most obvious solutions to prevent the player from this frustration are to do a fixed damage calculation without dice or to reduce the impact of the dice rolls, but they both just don't feel right.

So is it considered bad design to do a dice-based calculation model or is there a better approach to combine those two key features?

# Answer
Adding some randomness to a game can make a game less predictable. This can lead to a more varied game experience and a higher replayability due to unlikely events leading to unexpected situations. It also makes the game more exciting, because the player can never be 100% sure how a situation will turn out.

But on the other hand, if you overdo randomness in your game, it might become so unpredictable that it turns into a pure game of chance where most decisions end up being meaningless because the player is just guessing what will happen. You can also have game sessions which end up being frustrating experiences, because even though the player plays well she loses due to a streak of bad luck. Or you can have game sessions which end up boring because due to some lucky events the game becomes far too easy.

Extra Credits made some interesting videos about randomness in games. The Delta of Randomness - Can You Balance for RNG? and More Ways to Use Randomness - What is the Goal of RNG?

So what does that mean for damage calculations in your game?

Having a slight chance of randomness can spice things up, but you should not have so much randomness that the players can't properly plan their moves. Damage calculation formulas in games usually have uncertainty ranges of about +/- 10%.

Another video I can recommend about randomness in games is the GDC 2018 talk White, Brown, and Pink: The Flavors of Tabletop Game Randomness. While it claims to be a board game talk, most of it can be applied just as well to video games. It makes an interesting point: You want your game to be both planable, but also have interesting random events from time to time to make the game more exciting. That means that when you have some game mechanic which is affected by randomness, there should be a very high chance that things play out the regular way, but also a very low chance for something unexpectedly impactful happens.

A common implementation of this paradigm in RPGs is a "critical hit" mechanic. Such systems can be something like "95% of attacks do between 10 and 12 damage, but there is a 5% chance that an attack does between 30 and 36 damage". The players will still be able to plan and execute strategies successfully by assuming the usual damage output, but a sudden critical hit can turn their plan around and force them to improvise.
> 1 votes

# Answer
A little randomness can add an element of unpredictability to what would otherwise be totally deterministic gameplay, which can become boring. If I know I deal 10 damage on every hit, I can always kill a 100HP monster in 10 hits. Something that deals 9 damage on every hit can never kill me when I'm at 100HP - because I know the outcome, there is no risk, I just have to press attack 10 times without even looking at the screen. If there's even a small amount of randomness, say +1, +0, or -1 to every hit, I am now invested throughout the fight, since I may need to update my strategy as the fight progresses. I'll still win most of the time, but there is a chance for failure, which is exciting.

I agree too much randomness can be a bad thing, but a little bit encourages more adaptive and branching strategies. Without it, every fight against enemy X will be identical. You could allow the player to select their preferred amount of randomness through weapon or ability selection - you might have a regular sword that always deals 10 damage, and a berserker axe that deals between 5 and 15 damage. Both deal the same damage on average, but it allows the player to choose whether they want swingy randomness or constant predictability.
> 1 votes

# Answer
### You can have the good without the bad, but it's more work

While introducing randomness is often the easiest and most effective way to reduce predictability, it is not your only option. You can also

* give players more tactical choices, add complexity in how those choices interact
* model characters in greater detail, allow for emergent properties
* restrict the flow of information, create uncertainty

One big advantage of videogames over pen&paper RPGs is that you're not limited by how many rules and variables players can keep track of or in how much detail you can describe a scene before people get bored or confused. The computer can handle all the calculations, you only need to worry about the presentation. A seemingly straightforward result like "hit or miss", "glancing blow or critical" can depend on a whole host of variables and circumstances, each individually simple to track and understand, but difficult to predict all at once.

I've had this specific problem in a recent project and decided against RNG as it was inappropriate for the (sub)genre I was aiming for. The trick is to look at each interaction (e.g. each action in a fight) individually and ask yourself "how can I make the outcome of this less predictable in a way that adds tactical depth?" Think outside the box. Try to identify popular/effective strategies and think of tweaks to make them "branch off" into multiple different scenarios.

You'll likely come up with *a lot* of new mechanics, new stats to track etc. That's okay. Don't implement or discount anything yet, make a list. Once that list is nice and long, pick the options that fit your theme and provide the best cost/benefit ratio. Implement a handful, test, reiterate.

Basic suggestions for a "character attacks and does x damage" scenario:

* Instead of dice rolls, make damage scale with stamina (melee fighters), distance to target (marksmen), distance moved this turn (cavalry) ...
* Give units an ability to take reduced damage from one direction/target/damage type/... and allow them to switch between these options
* Add a spell or ability that gets stronger or weaker over time, to mess with target priorities
* Allow units to damage stamina/morale/initiative/... in addition to hp. Make them choose one.

Note that all but one of these suggestions interact in some way with positioning, which you stated should be important in your game. You'll usually get the most mileage out of new mechanis if they tie into existing ones, preferably ones that are central to your game concept.

### Use resources to mitigate bad luck

If you *do* want random damage rolls, one way to keep it "swingy" but reduce frustration is to give players a limited resource that can be used to "defend" against particularly bad results by, say, allowing a re-roll or shrugging off half the damage from a critical hit. You can also tie this resource into a risk/reward mechanism, where running low or not replenishing it means faster progression. Offer risk-averse players a "path of minimal frustration" and let the firebrands have their unmitigated chaos.
> 0 votes

---
Tags: game-design, random, turn-based, game-theory
---


# Question
Title: How to efficiently (no pointers) store hex grid with shared edges and vertices?
I have a hex grid stored in a 2d array; now I want to add some properties to the edges of the grid (e.g. rivers between hexes) and also potentially to the vertices. How can I store edges and vertices

1. Without duplication, i.e. I don't want to store a river between two hexes in both, or check neighboring hexes - I want to store it once in the edge.
2. With a fast way to find mapping between things, i.e. from a given edge to two hexes it's dividing, or from a given vertex to its 3 edges, etc.
3. Efficiently i.e. without tons of pointers in every object to every neighboring object?

I was thinking there should be 3 2d arrays (hexes, vertices, edges) with arithmetic formulas to map things to things. However for the only schemes I can come up with to store vertices and edges (since they don't map naturally onto a 2d array), the mapping formulas between array coordinates are very convoluted. I wonder if there's some simple scheme that I'm missing?

# Answer
Assuming you have Hex objects stored in a 2d array, just make each Hex own some of its edges and vertices. For example, have each hex own the edges with arrows pointing to them as well as the two vertices between those edges:

```
 __
/  \ <3
\__/ <2
  ^
  1

```

We only store three edges and two vertices, so where do the others come from? Well, continuing counter-clockwise, edge 4 would be edge 1 from the hex above this one, edge 5 would be edge 2 from the hex to the upper left, etc. Vertices would be accessed similarly. You could add some accessor methods to make this ownership more transparent by automatically going to the appropriate neighbor to find the needed edge/vertex.

The downside of this approach is that along some of the sides of your grid, there won't be edges and vertices. You can add a set of dummy hexes around these sides and give them a flag like `isDummy` to indicate that they only exist to provide edges and vertices to other hexes.
> 5 votes

---
Tags: mathematics, hexagonal-grid
---


# Question
Title: How can I detect a long press then activate an animation?
How can I detect a long press on a touch screen then activate an animation? And when the finger is released, play another animation smoothly? Let's take for example the main character in Crossy Road: when the user presses down, the chicken "squats" and when the user releases their finger, the chicken jumps. Same concept. C#.

# Answer
> 1 votes
You can use Input functions to detect these actions. Following code shows how you can achieve it and I have commented the events when they are true.

```
void Update()
{
    if (Input.GetMouseButtonDown (0))
    {
        //Touch Begin - True when the finger touches the screen
        //Play animation for chicken squat
    }
    else if(Input.GetMouseButton (0))
    {
        //Touch Continued - True when the finger is still touching the screen
    }
    else if(Input.GetMouseButtonUp (0))
    {
        //Touch End - True when the finger is lifted from the screen
        //Play animation for chicken jump
    }
}

```

Note: You need to handle a situation where the user touches the menu buttons . Which should not be considered for playing the animation. So for that you need to check your mouse position, whether it is inside a particular area and then only consider the touch for animation.

# Answer
> 1 votes
You can Detect a long press by simply using Touch.deltaTime.

Unity Document Reference : https://docs.unity3d.com/ScriptReference/Touch-deltaTime.html

```
    Touch touch = Input.touches;
    for (int i = 0; i < Input.touchCount; i++)
    {
        Touch t = touch[i];
        if (t.deltaTime > 0.2f) // if long touch
        {
            // do stuff.

            // If you want to detect long press on an object, do the following.
            Vector3 pos = Camera.main.ScreenToWorldPoint(t.position);

            if (Physics.Raycast(pos, Camera.main.transform.forward, out hit))
            {
               Debug.Log("Long Pressed on "+hit.transform.name);
            }

        }
     }

```

# Answer
> 0 votes
You can define an integer value to use as counter, meaning how long the user has kept his finger on the screen to track a long press:

`int timer = 0;`

Then, you're going to detect just an event - the mouse pressed event - and increment the timer at your will:

```
void Update()
{
    // Increment the timer
    if (Input.GetMouseButton (0))
    {
        timer += 1;
        // Additional code for chicken squat
    }
    else if (timer > 0)
    {
        timer = 0;
        // Additional code for chicken jump
    }
}

```

The lower the variables to check for, the more performant your code will be.

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


# Question
Title: How do RPGs balance linear damage formulas?
I'm developing a damage formula for an RPG. I've checked many popular titles formulas for reference (Final Fantasy, Chrono Trigger, Golden Sun and Castlevania) and most seem to use linear functions.

My issue is that for linear functions, the % in which damage increases when leveling up goes down in every level. For example, when you go from Lvl 2 to Lvl 3 and damage increments 50%, however when you go from Lvl 50 to Lvl 51, an attack only does 0.5% more damage to the same enemy.

This coupled with the fact that XP to level up goes up exponentially in these titles doesn't make sense to me. So while I'm tempted to forgo this type of function for my game, I feel there's something I must be missing since many of my favorite games use them. Moreover I have played these titles and I never noticed this.

Eg: Golden Sun damage calculation is a simple: Damage = Attack - Defense. Pokemon's damage formula below is a bit more complex but absolute damage growth also decreases on each level.

Am I right to think in these games damage increases at a lower percentage on each level?

How do they balance the game so that levels are still important later on the game?

# Answer
> 10 votes
This is intentional, because making levels important is not the goal.

Usually for RPGs there are two conflicting design goals: to give players freedom in how they play (and therefore how much grinding/side-quests to do, and hence their XP), and to make sure the difficulty of the game scales predictably for the length of the game. You don't want to make the game too easy for those that complete all the side-quests and earn as much XP as possible, but you also don't want the end of the game to be impossibly hard for those that are rushing through.

A common method is to make the XP between levels to grow, so for example 100 XP missed may matter a lot at lower levels, but at higher levels it makes no difference. What you're describing is simply another method of achieving the same aim; by making stat growth diminish in percentage terms, the difference between levels also diminishes.

Compared to the former, the latter has the advantage of still giving the player regular level ups (which players tend to enjoy) whilst maintaining the difficulties of later stages of the game. Usually RPGs use a bit of both techniques.

This is in contrast to, say, MMOs, which have a number of reasons to use more of the former than the latter, such as:

* Using exponential XP curves to stretch out the game time and make more money from subscribers
* Making sure that level differences are meaningful to create envy between different players, and hence encourage players to stay in the game

# Answer
> 1 votes
In most RPGs the damage formula itself only tells part of the story. Things outside level also affect the formula and aren't linear - good equipment is normally gated carefully, and better spells and abilities unlock higher damage options in later levels (Pokemon and Chrono Trigger are both good examples of this). Tactical options also increase at higher levels, with various non-damaging effects becoming available, and this reflects the shift in later levels from beginner play (hit it until it stops moving) to expert play (more tactical options, more prep before battles to optimise your party, less dependence on sheer grinding).

Essentially, what the damage formula tells you is that if your tactic is to out-level your opponents, then this strategy is viable at low levels but time-consuming at high levels. The exact balance is one factor that determines how beginner-friendly your game is.

# Answer
> 0 votes
In our game we use the level like in the Pokémon formula, but use other stats like strength and so on that increases the damage more. But the Main point is that the stats & level aren't so important for damage. They are just percentage values and the real damage comes from items. 0,5% of 100 damage are the same like 5% of 10 damage - so the percentage goes down, but the damage itself increases anyway.

And to prevent one hits against low level mobs we use the capped level difference - so the level doesn't go directly in the calculation.

---
Tags: mathematics, game-design
---


# Question
Title: What is the value range from a dot-product between two normalized vectors?
I've recently learned about the existence of dot product and I was wanted to know how to determine the value range between two normalized vectors.

# Answer
The dot product of two normalized (unit) vectors will be a scalar value between -1 and 1.

Common useful interpretations of this value are

* when it is 0, the two vectors are perpendicular (that is, forming a 90 degree angle with each other)
* when it is 1, the vectors are parallel ("facing the same direction") and
* when it is -1, the vectors are anti-parallel ("facing opposite directions")

Because the dot product is, geometrically, the product of the magnitudes of the vectors and the cosine of the angle between them (\\$\vert{a}\vert\vert{b}\vert \cos{\theta} \\$) it also useful for finding \\$\theta\\$: it's just \\$\arccos{(a \cdot b)}\\$ since the magnitudes of the vectors are both one.

You may also be interested in interpretations of the dot product between *non*-normalized vectors, which is discussed in this related question.
> 7 votes

---
Tags: vector
---


# Question
Title: How do I compile a namespace to a .DLL in Unity?
I'm developing a core library that I will use in my other games. I've only heard of using Unity .DLLs recently, and have spent some time putting my core scripts into a namespace. If I understand .DLLs correctly, I should be able to take that .DLL, plop it into one of my other projects, and then immediately start using it.

The question is, how do I compile that namespace into a .DLL that I can use in other projects? I'm using Visual Studio and Unity 2018.2.17f1.

# Answer
> 2 votes
Yes, that's basically how it works. But DLLs aren't exclusive to unity. DLLs are a widespread concept for reusable code components in many different programming languages. Just to make clear that there are many many differences on how .dlls are treated.

**1. TL;DR:**

.NET was originally implemented for windows only. .NET by itself is not a specific programming lanugage but a whole infrastructure that can be compared to how Java works. The whole idea is to execute code on a virtual CPU. This might not appear like a big deal at first but it is.
By concept, .NET separates a program and its execution environment. While the .NET platform (the CLR which runs written programs to be more precise) must be installed on a system, programs remain platform independent. This allows you to write code on say Windows and reuse it on mac OS or Linux for example. While this is old news for .NET developers, this might be news for people who know .NET only from Unity.

Let's talk about Mono. Originally, there were no other platforms to support .NET other than differnet versions of Windows (Windows RT, Windows mobile, etc.). After a while, some people started to write a runtime which was capable of executing .NET code without relying on Windows. This lead to an abstraction of the underlying operating system. You can think of Mono as a cross-platform version of .NET.

Meanwhile, Microsoft is really invested in open source and dropped the 'Windows-only' part of .NET some years ago. That's the story behind .NET **Core**. Core has basically the same goal as the Mono project but is developed by Microsoft.

Why the history lesson? Because in the context of Unity this really is news. Until the version release in 2018, Unity was based on a super old implementation of the Mono runtime. .NET compatibility was there but only up to version 3.5. That version was released late 2007 and since then never updated for Unity until 2018. This means that no new C# language features were available for Unity developers for 12 years. That's huge.

If you're still rading this, I might as well go ahead and bother you with .NET Standard. Late 2018, .NET Standard 2.1 was released. This is nothing but a definition of language features which must be supported by a .NET runtime (Mono or Microsoft or others) in order to be compatible with a specific version. So instead of .NET 3.5, .NET 4.0 and so on, all versions - it doesn't matter if CORE, not Core, Microsoft or Mono - are identified by .NET Standard, .NET Standard 2.0 and .NET Standard 2.1.

You don't have to know all of this information but why not understand the technology you're working with. You'll see some .NET specific stuff in Unity so you might as well know the story behind. In Unity, check the 'Other Settings' panel under Edit / Project Settings / Player to see your .NET configuration:

We finally have support for modern .NET and can use the latest C# language features. Awesome. This is important because you have to consider these things not just when consuming a .dll but especially when writing one. By selecting the right .NET version for your Class Library project in Visual Studio, you define whether your DLL is compatible with Unity and other .NET components. So take that into consideration when creating a new Class Library project. Without this knowledge you'll have a hard time understanding the differences between the many different project templates:

* Portable Library
* Multiplatform Library
* .NET Standard Library
* Class Library
* Library

Make sure to understand which project template is compatible to which .NET version. If you select the wrong library type, Unity won't be able to understand the DLL and that will cost you some research time to figure out why.

**Finally the answer**

Just make sure to select a compatible Class Library project template and write down your code. The whole namespace thing: A DLL always exports the namespaces just as you use them:

```
namespace I.Like.Big.Namespaces.And.I.Can.Not {

    public class Lie {

    }
}

class Whatever {

}

```

There's nothing more to it. After building your DLL, navigate to your output folder (should be *bin/* in your project's root directory) and copy the .dll file into your Unity project (Assets/Scripts/\_dlls/ for example). Open Unity and wait until the newly added DLL is detected and there you go. Now you can import and use code from your lib.

While DLLs are a good way of organizing your project, there are some things to consider before using them. Be sure you really need DLLs in your project. You won't be able to access Unity classes out of the box for example. There are ways of adding certain dependencies and build complex Libraries even specifically for Unity, but that complicates your overall project setup.

---
Tags: unity, visual-studio, .net, dll
---