# Question
Title: How to propertly send map to clients in MMO?
I'm designing a game where the map has 1 M tiles. The game is simple, is a 2D game with low graphic requirements and without player movements, only change states, so I don't need to update player positions for example. But I have a doubt about how to synchronize the map.

When a client connects, the server should send him data related with proximity tiles. Each tile is represented with a different picture, so I can represent them with an id (integer). Developing in c#, each tile requires 4 bytes to store the id. So when the client connects, I have to send him (4 bytes\*number of tiles). Sending data of 1000 tiles (a 30x30 grid), I'm sending 4 kb, and this is just in the first connection. When the client player moves, I have to send him more and more data, which has not a good performance.

On the other hand, if I store all the ids in the client, I will need to store 1M\*4 byte = 4 mb per client. This is just to store tile ids, but it seems to be ok.

How can I design or optimize the data messaging ?

# Answer
> 1 votes
If you want to ensure that your players have the most up-to-date map possible, I'd start by including a version-header within each of your map files. This doesn't necessarily need to be a header per-say, it just needs to be some marker or value stored within the file that affects nothing about it in terms of game-play, but can store a value with the version number of the game that the map is supposed to be used for. This is implementable through a variety of means: If using your own map file format, just include the header as the top line and ignore it when reading; when checking if the map needs updating, instruct the client to send the map version to the server and check the version server-side. If the map is not of the correct version: send them the new map. An equivalent approach for a generic map editor would be to include a "dummy" layer or tile that stores the version number and instead get the version number from the incorporated object in the map instead of the header.

Upon receiving the packet from the server indicating that the version number was incorrect, proceed to download the map and display a loading screen to the user to indicate that the map is currently loading. Send the map file in chunks of a size you determine, re-construct the file and voila! The latest map file has been downloaded in a relatively pain-free manner.

A pseudo-code representation might go as follows (very basically):

```
version = version of game...
send version to server
correctVersion = server response

if version != correctVersion then
    show loading screen
    request map from server
    re-construct map file
    load map from file
    exit loading screen
    show map on screen (if necessary at this point)
else
    load map from file

```

---
Tags: game-design, multiplayer, tilemap, mmo, server
---


# Question
Title: Apply transform.Translate to a specified object in the script
In Unity3D, if I place a C # script including transform.Translate on an object "A" in the hierarchy, it animates the translation of this object A.

How in C# can I apply that transform.Translate effect onto another object defined in the script itself?

I want to write a script similar to this:

```
using UnityEngine;
using System.Collections;

public class Create_Objects : MonoBehaviour {

    public float moveSpeed = 2f;
    public Transform otherObject;

    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Q))
        {
            GameObject Object1 = new GameObject ("Object1");
        }
        otherObject.Translate (Time.deltaTime * moveSpeed, 0, Time.deltaTime * moveSpeed);
    }
}

```

But somehow I want that `otherObject` that I'm translating to refer to the `Object1` I created when the user pressed "Q".

Thanks DMGregory for your last code!... and finally, same as before but the objects are created and translated from position of **each previous** object creates.

What is the new C # code?

# Answer
> 2 votes
This is a very basic C# syntax question. If you find this aspect of the language is unclear to you, I highly recommend spending some more time on beginner tutorials to learn these fundamentals inside and out.

We can modify your example script to do what you describe like so:

```
public class Create_Objects : MonoBehaviour {

    public float moveSpeed = 2f;
    // Create a private variable that can store a handle to the object we created.
    Transform latestCreation;

    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Q))
        {
            // When we create an object, cache a reference to its transform.
            var createdGameObject = new GameObject ("Object1");
            lastestCreation = createdGameObject.transform;
        }

        // If our latest creation is a valid game object
        // (already created and not yet destroyed)
        // then let's move it! Otherwise, skip this.
        if (latestCreation != null)
            latestCreation.Translate (new Vector3(1,0,1) * Time.deltaTime * moveSpeed);
    }

}

```

If you want to apply this translation to multiple created objects then:

1. That should have been in your question in the first place. When you ask about a singular object only, you'll get answers about a singular object only, so take the time to ensure your question covers what you really want.
2. We can replace our `latestCreation` with a collection of objects, and move all objects in that collection using standard iteration techniques like `for` or `foreach` loops.

Like so:

```
public class Create_Objects : MonoBehaviour {

    public float moveSpeed = 2f;
    // Create a private variable that can store a handle to the object we created.
    List<Transform> allCreations = new List<Transform>();

    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Q))
        {
            // When we create an object, add its transform to our list.
            var createdGameObject = new GameObject ("Object" + allCreations.Count);
            allCreations.Add (createdGameObject.transform);
        }

        // Iterate over all created transforms and move them.
        foreach ( var creation in allCreations ) {
            if (creation != null)
                creation.Translate (new Vector3(1,0,1) * Time.deltaTime * moveSpeed);
        }
    }

}

```

You can further improve on this in a couple of ways:

1. Use `List.RemoveAll()` to prune `null` entries from the collection after any of your created objects have been `Destroy()`ed.
2. Split this into two scripts: one that only moves an object, and one that only creates objects. The creation script can attach the movement script to the objects it creates using `AddComponent<NameOfYourMovementScript>()` so they'll continue moving themselves independently without needing to be tracked in a separate list.

# Answer
> 0 votes
I think you're asking how to have a script move a different object than the one it's attached to. The easiest way that I know how to do this is to declare a public variable at the top of the script, like `public Transform otherObject;`. You can then move that object by calling `otherObjects.Translate()` where you used to be calling `transform.Translate()`.

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


# Question
Title: What is the best way to import autocad models into unity?
I just got someone to create a 3d environment for my game in autocad 2015. I exported that environment and imported it into unity but that doesn't work well as I am unable to see my environment in the scene view correctly.

Any suggestions on how to do it better? I am not good with 3d modeling and I ever used autocad models in unity before. Any kind of help is highly appreciated. :)

# Answer
First of all you really need to see these official articles by Unity for dealing with your 3D assets.

The .fbx format for 3D assets is standard for most of the engines and 3D modelling software to communicated between each other. Also make sure to check scale setting for your 3D application before you export.
> 1 votes

---
Tags: unity
---


# Question
Title: How can I fix my velocity damping to work with any delta/frame time?
I am decreasing my velocity by 50% every second using a guide I found online. I am using the code here and it gives the right result but only for very small values for dt:

```
float dt, velocity, position;

dt = 0.002f;
velocity = 1.0f;
position = 0.0f;

for (float t = 0.0f; t <= 1.0f; t += dt) {
    position += velocity * dt;
    velocity = lerp(velocity, 0.0f, 1.0f - std::pow(0.5f, dt));
}

printf("dt = %f, p = %f, v = %f\n", dt, position, velocity);

dt = 0.09f;
velocity = 1.0f;
position = 0.0f;

for (float t = 0.0f; t <= 1.0f; t += dt) {
    position += velocity * dt;
    velocity = lerp(velocity, 0.0f, 1.0f - std::pow(0.5f, dt));
}

printf("dt = %f, p = %f, v = %f\n", dt, position, velocity);

return 0;

```

But I am getting roughly the right velocity BUT two different final positions back when I use two different delta times (not due to floating point issues):

```
dt = 0.002000, p = 0.722848, v = 0.499308
dt = 0.090000, p = 0.784219, v = 0.473029

```

How can I fix this difference inside of my update loop?

How do I account for the extra acceleration between timesteps?

# Answer
Although you're correcting your velocity, your position update:

```
position += velocity * dt;

```

...is still treating velocity as though it's a constant over the frame duration. So, the smaller your timestep, the more accurate this simplification is, but with longer timesteps, it gives too much weight to the high velocity early in the frame, without accounting for how it diminishes later in the frame.

To get this right, we'll need to integrate velocity over the frame duration with some calculus.

If your velocity is equal to...

$$\begin{align}\vec v\_{\Delta T} &= \vec v\_0 \cdot r^{\Delta T} \\\&=\vec v\_0 \cdot e^{\Delta T \ln r}\end{align}$$

Then your position is the integral of this value over your timestep:

$$\begin{align} \vec p\_{\Delta T} &= \vec p\_0 + \int\_0^{\Delta T} {\vec v\_0 \cdot e^{t\ln r}\ dt} \\\&= \vec p\_0 + \vec v\_0 \cdot \left(\frac {e^{t \ln r}} {\ln r} \right) \Bigg|\_0^{\Delta T} \\\&= \vec p\_0 + \vec v\_0 \cdot \left(\frac {r^{\Delta T} - 1} {\ln r} \right) \end{align}$$

In code:

```
position += velocity * (std::pow(r, dt) - 1.0f)/std::log(r);
velocity *= std::pow(r, dt);

```
> 2 votes

# Answer
The solution given by DMGregory is the right solution, however, in game loops concerning physics, it's usually advised to use fixed time steps.

Having fixed time steps helps having consistent results across devices with different speeds/capabilities, see this answer for details.

such game loop should look something like this:

```
while (!exited)
{
    deltaTime = time - lastTime;
    timeSinceLastFixedUpdate += deltaTime;

    int fixedFramesCount = (int)(timeSinceLastFixedUpdate / fixedDeltaTime);
    if (fixedFramesCount > maxFixedFrames)
    {
        timeToLose = (maxFixedFrames - timeSinceLastFixedUpdate) * fixedDeltaTime;
        timeSinceLastFixedUpdate -= timeToLose;
        deltaTime -= timeToLose;
    }

    while (timeSinceLastFixedUpdate >= fixedDeltaTime)
    {
        FixedUpdate(fixedDeltaTime);
        timeSinceLastFixedUpdate  -= fixedDeltaTime;
    }

    Update(deltaTime);
    Render(deltaTime);

    lastTime = time;
}

```

Please note that engines like Unity have the two kinds of update (fixed time step and variable time step), that's because it updates the physics engine at fixed time step, and then it can interpolate/extrapolate physics results inside the variable time step Update calls in order to keep everything smooth at high frame-rates, updating particles, animation, etc. also happens in varying time steps.
> 1 votes

---
Tags: physics, game-loop
---


title: Adding a dodge roll. Unity

text:
# Question
Title: Adding a dodge roll. Unity
I'm a newbie here. I need to add a second collider in CharacterController in the separate script with possibility to enabling/disabling them. I tried to find answer how to do it but I find nothing. Thanks for any help!

# Answer
You could change the collider of your character during the "doge roll" state.

The `CharacterController` has the properties `.center` and `.height` which affect the physical shape of the character's capsule collider. You could temporarily reduce them during the "dodge roll" state to make the character shorter and reset these back to the original values when leaving that state.

But remember to keep in mind what happens when the dodge roll ends while the character is under an object. If you increase the capsule collider at that time, you might run into some really weird physics interactions. In the best case, you might see some stuff fly around in funny trajectories. In the worst case, your player gets stuck. So make up your mind about what to do in that situation. One possible solution could be to add crouching to your game. Transfer the character to the "crouching" state so they can crouch out from under the object.
> 1 votes

# Answer
It is HIGHLY inadvisable to mutate a collider during runtime. This will lead to many many bugs and weird physics artifacts. Not to mention it puts strain on the physics system, as a lot of the broad phase and narrow phase cullings can rely on the shape of the collider being cached. Changing the shape will require the physics system to re evaluate these entries. My recommendation is to have two colliders that you toggle between. Simple disable your standing collider, and enable your rolling collider. However we can go further to increase the safety of what you're trying to do. Imagine the following setup:

```
PlayerGameObject
  {} PlayerController.cs
   - CollidersGameObject
     - StandingBodyColliderGameObject - Layer: "Default"
       {} Collider
     - RollingBodyColliderGameObject - Layer: "Default"
       {} Collider (Rolling) // Disabled
   - RollUnderColliderGameObject - Layer: "Roll Under"
     {} Collider (Same as standing but only collides with Roll Under)

```

The idea here is you have your standing and rolling hitboxes for physical interactions with other things in the game. However in your collision matrix, make it so the "Roll Under" layer only collides with itself. This means your normal collider will pass through and surfaces you could roll under. However if you have your RollUnderCollider enabled, it will collide with those surfaces and stop the player from being able to move through. When you roll, simply disable this collider. This will let your character phase through. If you want your player's standard hitbox to also shrink, disable the standing body collider and enable rolling body collider. However this rolling body collider will still phase through the roll under. This means that if your surface is slightly slanted, or not the exact right height, your roll will still work. When your roll is over, check if there's a roll under object above you (you can use physics queries for this). If not, restore your RollUnderCollider. Again, the reason for this multi collider setup is physics performance, edge case safety, and less constraint on level design. What you're trying to do isn't an easy problem, and an easy solution will likely turn complex very quickly as you go through edge cases. This is just my recommendation from time in the industry and dealing with changing colliders.
> 2 votes

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


title: What does UA mean?

text:
# Question
Title: What does UA mean?
When reading different articles about gamedev **here** and **here** I see the abbreaviation **UA**. What does **UA** mean?

# Answer
It means *user acquisition*.

It is generally used in the context of determining how you get people to pay for your service (or how do you get money from your users), and is often link to how much this costs.
> 4 votes

---
Tags: terminology, marketing, analytics
---


# Question
Title: How does a game like Minecraft generate new chunks in realtime?
I imagine looping through all 65,536 blocks with a noise function to set their type would be very slow. And Minecraft usually generates a ton of chunks at once. I read in one source online that Minecraft creates a column of 16x16x16 chunks, although I can't find any more information on that subject, and that doesn't really change how many blocks there are in one chunk "column". I assume there are optimizations made to make it work, although I can't find much about this subject online.

Edit: The way I am generating chunks in my own (2D) game is by looping through a 16x16 array using a Perlin Noise function for every chunk. With 16x16 chunks it runs fine in realtime. I want the chunks to be 3600 tiles high, and changing the size to be 16x3600 runs very slowly.

# Answer
> 1 votes
"Real time" is a subjective term that depends completely on the hardware you're running on. Speaking from experience, timely chunk generation is one of the primary reasons MineCraft Pocket Edition would be substantially different from MineCraft PC. You say that,

```
chunks to be 3600 tiles high, and changing the size to be 16x(16x)3600 runs very slowly.

```

It would, because you're no longer playing nicely with either cache line sizes or cache level sizes for run-of-the-mill consumer processors. Let's assume a simplistic architecture where there is only one level of cache, L1. If L1 has a total size of 32kb x 8 ways = 512kb, and your 16x16x3600 assumes *just one byte* per voxel, that is already 900kb per chunk, which means your cache is going to miss *at least* once (actually, more) and you will experience a lengthy pipeline stall as the data is fetched from the heap / main memory. If 10 bytes per voxel, then you will have many more cache misses in constructing the mesh for a single chunk - not to mention cache misses on game logic, physics etc.

Every cache miss means a call out to main memory (in this simplistic, one-level cache example) and instigates the loss of hundreds of CPU cycles where program thread is doing nothing but waiting for that data. This is known as a *pipeline stall*.

But that's not all. Treating surface terrain as a 3D grid is, as you suggest with your question about 65536 cubes, a fairly naive idea. Ideally you want to be doing 2D heightmap generation, not 3D grid generation, on the surface of your world, say e.g. 16x16x(32-bit float). This leads to exactly 1 kb per heightmap chunk. You could even use 64x64xfloat or what have you, as then each of these is still reasonably small and fits an L1 cache way. You could alternatively opt for octrees or KD-trees.

Once you get it working with heightmaps, then you can expand the solution to deal *selectively* with small sections of overhang where you use regular 3D grids, i.e. said grids override the underlying height map in terms of rendering and game logic. This allows for e.g. cave entrances at surface.

P.S. There is more to it than this. You need to be using a single array of struct for each of your chunks, and *never* an array of class / objects, at least in higher level languages like Java and C#, because with class instances you have no control over where they allocated, whereas with struct arrays, all array elements are allocated contiguously in memory, because structs are a *value type*.

---
Tags: procedural-generation
---


# Question
Title: Particle spawn on collision spawns too many particles
So i have the following code:

```
private void OnCollisionEnter(Collision collision)
    {
        foreach (ContactPoint contact in collision.contacts)
        {
            if (contact.otherCollider.CompareTag("Ground"))
            {
                //Instantiate your particle system here.
                Instantiate(Effect, contact.point, Quaternion.identity);
            }
        }
    }

```

Now this works great however it spawns way too many particles (as the animation I am doing with the item hits the ground a lot).

Is there a way to limit the particles in a sensible way?

# Answer
I'd recommend using object pooling to reduce the amount of runtime spawning & despawning you do. If you create one object to manage the pool, through which all spawning requests are routed, then you also have a central place where you can manage those spawns and enforce the limits of your choosing.

For instance, we could have something that looks like this:

```
public class EffectPool : MonoBehaviour {

    // Inspector parameters to control what effect(s) to spawn, and how many.
    public ParticleSystem effectPrefab;
    public int maxInstances = 20;
    public int maxSpawnsPerFrame = 3;

    // Users will hold a reference to the prefab of the pool,
    // but we'll spawn an instance in the scene & route requests to it so that
    // it can handle scene events, and get cleaned up when we leave the scene.
    EffectPool _sceneInstance;

    // Internally we won't spawn immediately/eagerly,
    // just queue-up requests to handle in a batch.
    struct SpawnRequest {
        public readonly Vector3 position;
        public readonly Quaternion orientation;
        public SpawnReques(Vector3 position, Quaternion orientation) {
            this.position = position;
            this.orientation = orientation;
        }
    }

    // Internal variables to keep track of the object pool state.
    List<SpawnRequest> _requests;
    ParticleSystem[] _effectInstances;
    int _nextSpawnIndex;

    // Scripts that want an effect to spawn call this.
    public void RequestSpawn(Vector3 position, Quaternion orientation) {
        // Ensure we have a pool in a loaded scene. If not, make one.
        if(_sceneInstance == null)
            _sceneInstance = Instantiate(this);

        // Ask the scene instance to queue-up this spawn request.
        sceneInstance.LogRequest(new SpawnRequest(position, orientation));
    }

    // Initialize a new object pool.
    void Awake() {
        _sceneInstance = this;
        _instances = new ParticleSystem[maxInstances];
        for(int i = 0; i < maxInstances; i++) {
            _instances[i] = Instantiate(effectPrefab);
            _instances[i].gameObject.SetActive(false);
        }
    }

    // Queue requests to process at the end of the frame.
    void LogRequest(SpawnRequest request) {
        _requests.Add(request)
    }

    // At the end of the frame, we have all the requests that have come in,
    // and we can control how to prune / combine them to limit spawns.
    void LateUpdate() {
        // Here, if we're over our spawning budget,
        // we'll just choose at random some requests to not service.
        while(_requests.Count > maxSpawnsPerFrame) {
            _requests.RemoveAt(Random.Range(0, _requests.Count));
        }

        // Now we're within spawning budget. Spawn requested items.
        foreach(var request in _requests) {
            Spawn(request);
        }

        // Clear the request queue for next frame.
        _requests.Clear();
    }

    // Recycle effect instances from our pool.
    void Spawn(SpawnRequest request) {
        var effect = _instances[_nextSpawnIndex];
        _nextSpawnIndex = (_nextSpawnIndex + 1) % _instances.Length;

        // You may want to log a warning here - this is a sign your pool is too small
        // for the length of your effects and the number that are active.
        if(effect.isPlaying)
           effect.Stop(true);

        effect.transform.SetPositionAndRotation(request.position, request.orientation);
        effect.gameObject.SetActive(true);
        effect.Play(true);
    }
}

```

Here for simplicity I'm using a fairly naive rule - enforcing a maximum number of new effects per frame, and randomly weeding-out requests until we reach that number. This already gives us benefits over handling the budgeting in each collision individually though:

* We know how many total particles we need to spawn before we start pruning them, so we don't exhibit a bias (say, if the contacts are processed left to right, we don't consistently spend all our budget on the effects on the left side and leave none for the right)
* We can coordinate spawns across multiple FixedUpdates / multiple collisions in a single frame.
* We can coordinate spawns across many instances of scripts that use this effect.

From here, you can iterate on the spawning rule to dial in on the right behaviour for your needs. For instance...

* You might want to limit the density of particles in any one place, by bucketing spawn requests by position, and pruning down to one effect instance per bucket.
* You might want to coordinate spawns over time - for instance, sharing budget from one frame to the next, so an object that's continually spawning gets its overall rate throttled.
* You might want to reserve a fraction of your pool as "ready to spawn" - as your pool utilization gets high, you can run through the oldest instances and tell them to stop emitting / fade them out, so they're ready to spawn to serve new requests without popping.
* You might want to randomize one of multiple effects to spawn for variety, or use your budget to select whether to spawn an expensive / high-fidelity effect (eg. with sounds attached), or a cheaper background "filler" effect to keep from overwhelming the scene.
> 1 votes

# Answer
I'd keep a count per collision. You could implement the following:

```
private void OnCollisionEnter(Collision collision)
{
int particleCount = 0;

    foreach (ContactPoint contact in collision.contacts)
    {
        if (contact.otherCollider.CompareTag("Ground"))
        {
            //Instantiate your particle system here.
            Instantiate(Effect, contact.point, Quaternion.identity);
            particleCount++;
        }
        if (particleCount > MAX_PARTICLES) break;
    }
}

```

A slightly nicer version of the code would be to use a regular for loop, instead of a foreach, and access the contact point using the index.

Alternatively if you're wanting to limit the particles generated in general, rather than per collision, you could have some sort of random number generated before starting the for loop, and use that as the chance that particles would appear.
> 0 votes

---
Tags: unity, collision-detection, particles
---


# Question
Title: How can I make that on escape press it will load back the main menu?
This script is attached to another scene that is not the main menu scene:

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

public class LoadMainMenuOnclick : MonoBehaviour
{
    private Scene scene;

    // Use this for initialization
    void Start ()
    {
        scene = SceneManager.GetActiveScene();
    }

    // Update is called once per frame
    void Update ()
    {
        if (scene.name != "Menu")
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                SceneManager.LoadSceneAsync(0);
            }
            //To check that if in gameplay mode
            //f in The Space Station scene or any other scene
            //that is not the main menu scene only then to be able
            //to click on escape key to load the main menu
            //and to check why the exit button and sound not working
            //when clicking pressing the escape key.

            // And here to also pause the game !!!!!
            // to check how to pause the game here when
            // clicking the escape key.
        }
    }
}

```

What I want is when I click the escape key to load the main menu scene that index 0 and then to pause the game. I don't want to unload or remove the current active scene when pressing escape I wan to keep both scene loaded when loading the main menu.

Not sure if to use LoadSceneAsync or just LoadScene.

When I start the game both scenes are loaded and the active scene is not the main menu but I see and use the main menu scene.

Then I click on a start game button and it's unloading the main menu scene:

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

public class LoadScenes : MonoBehaviour
{
    // Use this for initialization
    void Start ()
    {
        SceneManager.LoadScene(1, LoadSceneMode.Additive);
        StartCoroutine(WaitForSceneLoad(SceneManager.GetSceneByName("The Space Station")));
    }

    public IEnumerator WaitForSceneLoad(Scene scene)
    {
        while (!scene.isLoaded)
        {
            yield return null;
        }
        SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(1));
    }
}

```

When the game is running there are two loaded scenes: "Main Menu" and "The Space Station" The active scene is the "The Space Station" but the scene that load first is the main menu.

When I click the Start Game button it's unloading the Main Menu scene.

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

public class LoadSceneOnClick : MonoBehaviour
{
    public void ActivatePlayer()
    {
        GameControl.player.SetActive(true);
        SceneManager.UnloadSceneAsync(0);
    }
}

```

Now when I press escape I want to get back to the main menu scene to load it again and to pause the "The Space Station" scene.

I also want to save the game progress so far when pressing on escape. So it will pause the game but also will save the progress so far to a file on the hard disk.

# Answer
> 1 votes
Once Unity loads a new scene, the old one is unloaded automatically, all the GameObjects and scripts are destroyed (see it as a reset) and can't be accessed anymore (even if you have a reference).

You can use DontDestroyOnLoad on GameObjects, which makes Unity keep them and add them to the new scene. This means that you can share scripts between scenes, e.g.:

You're using a Slider to simulate a health bar. Switching to a new level (=scene) would destroy this health bar GameObject but if you use `DontDestroyOnLoad` in the script attached to it and reference it, the health bar will be in the next level too (with the same value it was before switching scenes).

Doing this for every GameObject in a scene isn't adviced, though.

What you can do:

1. Have a single, big scene with two "parent" objects, one for the main menu, one for your space station. It will take longer to load the overall game but if every GameObject in the scene is a child of one of the "parent" objects, you can change "scenes" by setting the parent of the main menu inactive and the parent of the space station active, which will then also deactivate/activate all of its children.
2. You can combine 1. with `LoadSceneMode.Additive`, which you're already using and which just adds the objects of the new scene to the old scene without destroying anything.
3. (recommended) Have two separate scenes and always only load one of them but save the progress from the second scene when you go back to the main menu. To do this just create a static class, which doesn't derive from MonoBehaviour and also isn't attached to a GameObject. This script then won't get destroyed when you switch between scenes and you can save information like the player position. This information you can later just write to a file to be able to restore everything after restarting the game.

Then switching scenes is easy: Just add a script to an invisible GameObject in your "space station" scene:

```
public class InputManager : MonoBehaviour {
    void Update() {
        if(Input.GetKeyDown(KeyCode.Escape)) {
            //Save stuff
            SceneManager.LoadScene("MainMenu");
        }
    }
}

```

Difference between `LoadScene` and `LoadSceneAsync`:

`LoadScene` loads the new scene and tries to instantly display it. If it's taking a while, your game will freeze.

`LoadSceneAsync` doesn't display the new scene but loads it in the background and only displays it once it's actually done (careful: it's still running on the main thread). This way you can create a loading screen that keeps the user updated with a loading bar.

# Answer
> 1 votes
A simple solution for your problem would be to go a bit "outside of the box". Instead of creating the menu as a separate scene, make it a part of UI.

Then, during the gameplay, on press escape - pause the game and show the UI element.

In my opinion this is the easiest way to achieve what you are looking for.

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


# Question
Title: Is it "wrong" to build Unity games entirely with UI elements VS sprites?
I find myself coming on board a Unity project with an outsourced programming team. Our mobile game has a number of minigames and they have built them entirely out of UI elemetents, or raw images on only one or two canvas elements. Now, I know the term "wrong" is open to interpretation since the games are quite simple and they run fine on the modern devices we've tested them on.

However my somewhat perfectionist attitude often has me concerned about the "correct/best practice" way of doing things and I have a hard time letting go of the idea that this is not the best way to be developing the games. I look at the Unity best practices of not having too many elements in a canvas due to redrawing it anytime something changes, sprite renderers optimized polygon trimming as opposed to max rects to keep overdraw down, etc. And the response I get from the programming team is, "the screen-ratio ability of canvas elements makes it easy to handle different aspect ratios, so that's how we build games".

I don't want this to be a down voted "personal" question, so is there a more compelling reason to not build simple mobile games in this fashion? Or is it a case of if it works on targeted devices and isn't causing issues why not? Thanks in advance for any replies, Jaysin

# Answer
A solution needs to be tailored to your needs. If the game needs (I.E. performance, responsiveness, ease of development, etc.) are met by using only UI elements, then there's no problem.

One thing that should be considered is that this system means that your development team probably doesn't know how to use Unity's full capabilities. If in the future the UI will be insufficient, it will probably be hard to steer them towards a more standard Unity flow.
> 4 votes

# Answer
I agree with nihohit on this. It's important to take the scope of the project into consideration. It might be easier/faster to get the project done this way. If it's only a small type of game or app, going the un-optimized way often saves a lot of time, which then saves money. If it's unlikely that a project needs to be maintained for years or needs to be expanded on, it might make sense to go with what the developers are used to, even if it's considered less of a good practice.

This doesn't mean that your mindset should be changed, because, if you start a project from scratch you should totally think about the way you implement things and how to make it the cleanest. But, if you're in production and especially if you work with outsourced code, it might be better to use a hack, which is unclean, but takes an hour to implement rather than refactoring a whole section of code to make it clean, which might take a week and costs thousands of dollars.
> 3 votes

# Answer
# There is nothing wrong with only using canvas elements

But there could be bad practices here none the less (but it isn't that).
> 1 votes

# Answer
I think the only question you should ask in this case is: "Is UI providing all the functionality that I need?"

I've head a very similar problem, except I was working with UE4. I wanted ot make a puzzle game where you move a lockpick and try to set up pins in proper position. At first I thought it would be easier and faster to use UI - but it quickly turned out that sprites already had a loot of features that I would have to implement myself. In my case, that answer was "No, UI is NOT providing all the features that I require".

It seems like for you it's not the case. But in future, maybe try sprites just to see if it is easier for you in the long run?
> 1 votes

---
Tags: unity
---


# Question
Title: How to interact spheres with random walls
I have a physics problem to deal with, I am asking here because a game developers often uses the efficient method. I have randomly distributed circles interacting to through Lennard-Jones potential or simply with a bounce back boundary condition to wall of random shape, as of know I am taking a V shaped wall. Please help me to understand an efficient algorithm the game developers uses for bounce back interaction.

# Answer
> 0 votes
First off, your wall definition should use a consistent counter-clockwise or clockwise vertex ordering.

This will properly define for each edge which side is 'inside' and which is 'outside.'

Let's assume counter-clockwise ordering: 'inside' is always left of the edge.

To find particle/wall collisions, you just test all edges of the walls, and reflect velocities if the particle is too close to the wall, or on the wrong side of the wall.

For low wall counts, say in the hundreds or less, it is perfectly fine to test each particle against all edges.

If the wall definition becomes too complex, you want to reduce the number of tests. This is done via spatial indexing.

The simplest form of spatially indexed world, is a uniform grid. Just list all walls present in each grid cell.

If the walls are very sparse, or range in sizes, you could consider a quad-tree instead.

To calculate whether a point is on the left or the right side of an edge, I use a 2d cross product, like so:

```
/* tells if vec c lies on the left side of directed edge a->b
 * 1 if left, -1 if right, 0 if colinear
 */
int left_of( cpVect a, cpVect b, cpVect c )
{
        const cpVect tmp1 = cpvsub( b, a );
        const cpVect tmp2 = cpvsub( c, b );
        const float x = cpvcross( tmp1, tmp2 );
        return x < 0 ? -1 : x > 0;
}

```

If you need to further accelerate the code, you should look into vectorized code via SIMD. You can test 8 particles against a single wall, or 8 walls against a single particle by using AVX vector instructions.

---
Tags: collision-detection, physics
---


# Question
Title: How can I use EditorGUI.indentLevel++; to construct the right structure in my inspector editor script?
```
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

[CustomEditor(typeof(DialogueTrigger))]
public class DialogueTriggerEditor : Editor
{
    private SerializedProperty _conversations;

    private void OnEnable()
    {
        _conversations = serializedObject.FindProperty("conversations");
    }

    public override void OnInspectorGUI()
    {
        //base.OnInspectorGUI();

        serializedObject.Update();

        _conversations.arraySize = EditorGUILayout.IntField("Conversations Size", _conversations.arraySize);

        for (int x = 0; x < _conversations.arraySize; x++)
        {
            var conversation = _conversations.GetArrayElementAtIndex(x);

            var conversationName = conversation.FindPropertyRelative("conversationName");

            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(conversationName);

            EditorGUI.indentLevel++;
            var _dialogues = conversation.FindPropertyRelative("Dialogues");

            _dialogues.arraySize = EditorGUILayout.IntField("Dialogues size", _dialogues.arraySize);

            for (int i = 0; i < _dialogues.arraySize; i++)
            {
                var dialogue = _dialogues.GetArrayElementAtIndex(i);
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(dialogue, new GUIContent("Dialogue " + i), true);

                EditorGUI.indentLevel--;
            }

            if (_dialogues.arraySize > 0)
            {
                if (GUILayout.Button("Save Conversation"))
                {

                }
            }

            EditorGUI.indentLevel--;
        }

        serializedObject.ApplyModifiedProperties();
    }
}

```

I'm using in some places the EditorGUI.indentLevel++; but the result is this:

But I want it to be like this:

```
Conversations Size
     Conversation Name
          Dialogue size
     Conversation Name
          Dialogue size
     Conversation Name
          Dialogue size
     Conversation Name
          Dialogue size

```

This is how it should look like in the Inspector.

The problem is in this part:

```
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(conversationName);
EditorGUI.indentLevel++;
var _dialogues = conversation.FindPropertyRelative("Dialogues");
_dialogues.arraySize = EditorGUILayout.IntField("Dialogues size", _dialogues.arraySize);

```

I can't make the "Conversation" Name the "Dialogues" and the "Dialogues size" the same as I wanted.

The "Dialogues" is fine but the others are not.

# Answer
Working solution is to add another decrement at the bottom of the outer loop:

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

[CustomEditor(typeof(DialogueTrigger))]
public class DialogueTriggerEditor : Editor
{
    private SerializedProperty _conversations;

    private void OnEnable()
    {
        _conversations = serializedObject.FindProperty("conversations");
    }

    public override void OnInspectorGUI()
    {
        //base.OnInspectorGUI();

        serializedObject.Update();

        _conversations.arraySize = EditorGUILayout.IntField("Conversations Size", _conversations.arraySize);

        for (int x = 0; x < _conversations.arraySize; x++)
        {
            var conversation = _conversations.GetArrayElementAtIndex(x);

            var conversationName = conversation.FindPropertyRelative("conversationName");

            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(conversationName);

            EditorGUI.indentLevel++;
            var _dialogues = conversation.FindPropertyRelative("Dialogues");

            _dialogues.arraySize = EditorGUILayout.IntField("Dialogues size", _dialogues.arraySize);

            for (int i = 0; i < _dialogues.arraySize; i++)
            {
                var dialogue = _dialogues.GetArrayElementAtIndex(i);
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(dialogue, new GUIContent("Dialogue " + i), true);

                EditorGUI.indentLevel--;
            }

            if (_dialogues.arraySize > 0)
            {
                if (GUILayout.Button("Save Conversation"))
                {

                }
            }

            EditorGUI.indentLevel--;
            EditorGUI.indentLevel--;
        }

        serializedObject.ApplyModifiedProperties();
    }
}

```
> 0 votes

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


# Question
Title: How can I use slerp to stop my orbit camera "shortcutting" across to its target position?
I'm working on a camera that moves around the player at a fixed distance. It's the standard right-stick-to-move-cam-around kind. The camera follows the player but stays at a fixed angle to (0,0,1) until moved by input, and the player is free to move in any direction without changing the camera rotation with respect to the world. Imagine the cam as being a point on an invisible sphere with the player at the centre.

However, there's a problem with it in that when I rotate the camera around the player too fast, the lerping I added to try and smooth the movement tries to "shortcut" across instead of moving around the sphere gracefully when the desired position gets too far away. The image below is a top-down view, the camera takes the red route, but I want it to take the green route while remaining smooth.

Currently I'm:

* Checking whether the look controls are inverted, and setting a modifier value.
* Updating the current angle to (0,0,1) using the normalized X component of a Vector2 set by keyboard input (cam left, cam right).
* Updating the current angle to the Y axis using the Y component, set by input (cam up, cam down).
* Finding the desired cam position from the two angles and position of the focus point (player).
* Lerping between the current cam position and the desired one and updating the lookAt vector.

Here is the update code (it's in Go which isn't especially common for game dev, but hopefully the syntax should be easy enough to understand what's going on):

```
// Update the gameplay camera with the focus at focusPos.
func StepGameplayCam(focusPos math32.Vector3, delta float64) {
    invertLookMod := float32(1)
    if settings.Control().InvertLook {
        invertLookMod = -1
    }

    //Get up/down and left/right components and set angles.
    currentAngleToZ = util.WrapAngleRad(currentAngleToZ + float32(movementVec.X*float32(delta)*settings.Control().CamSpeed*invertLookMod))

    if !((movementVec.Y < 0 && currentAngleToY <= math32.DegToRad(15)) || (movementVec.Y > 0 && currentAngleToY >= math32.DegToRad(165))) {
        currentAngleToY = util.WrapAngleRad(currentAngleToY + float32(movementVec.Y*float32(delta)*settings.Control().CamSpeed*invertLookMod))
    }

    distanceToFocus = maxDistanceToFocus //TODO cam collisions/not clipping through things

    //Set desired cam position.
    targetPos.X = focusPos.X + distanceToFocus*math32.Cos(currentAngleToZ)*math32.Sin(currentAngleToY)
    targetPos.Z = focusPos.Z + distanceToFocus*math32.Sin(currentAngleToZ)*math32.Sin(currentAngleToY)
    targetPos.Y = focusPos.Y + distanceToFocus*math32.Cos(currentAngleToY)
    camPos.Lerp(targetPos, float32(delta)) //TODO problem is here, we're LERPing between vectors but we need to do it spherically
    gameCam.SetPositionVec(camPos)

    gameCam.LookAt(&focusPos)

    if settings.Dev().DebugEnabled {
        updateCamDebug(focusPos.X, focusPos.Y, focusPos.Z)
    }
}

```

I have a strong feeling **slerp** is what I'm looking for here, but my understanding of 3D mathematics is starting to brickwall at this point, and I have no idea how to use it in this context.

**How can I stop my camera from "shortcutting" through the imaginary sphere around the player it is bound to?**

# Answer
> 1 votes
First, take the center and radius out of the equation, and just think of your two camera locations as directions - unit vectors pointing out from 0:

(For brevity, I'll pretend we're using a vector library so we don't have to repeat everything 3 times for x y & z)

```
// Unit vector in direction from focus position to the old camera position.
camDirection = Normalize(camPos - focusPos);

// Unit vector in direction from focus position to the new camera position.
targetDirection = (math32.Cos(currentAngleToZ)*math32.Sin(currentAngleToY),
                   math32.Sin(currentAngleToZ)*math32.Sin(currentAngleToY).
                   distanceToFocus*math32.Cos(currentAngleToY));

// Time-correct your Lerp if you want a framerate-independent exponential ease.
blend = 1.0f - math32.Pow(1.0f - 1.0f/30.0f, 30.0f * float32(delta));

// Take the shortcut.
intermediate = Lerp(camDirection, targetDirection, blend);

// Bend out the shortcut into a long-cut:
camPos = focusPosition + distanceToFocus * Normalize(intermediate);

```

---
Tags: camera, quaternion, go
---


title: Dealing with curved lines in GJK

text:
# Question
Title: Dealing with curved lines in GJK
I'm currently using a GJK implementation (supported by EPA for penetration) and I'm trying to optimise the calculation times of distance calculations. One of the biggest hits is trying to solve for distance between a simple 3D shape (ie a cylinder) and a curved line in the shape of a helix (https://en.wikipedia.org/wiki/Helix).

I'm just brute forcing them by chopping the helix into a lot of smaller straight lines and solving each one against the 3D shape.

Is there a better way to do this?

The image below shows the relative shape of the objects and how they can come into contact (the red disk is the moving object). In this screenshot its contacting an end point of the curve, but it will commonly contact anywhere between the end points of the helix.

# Answer
> 1 votes
GJK only works between 2 convex objects. So you can do a simplified collision where you converted the helix to a cylinder and then partition the helix based on the result of GJK.

---
Tags: collision-detection, 3d, algorithm
---


# Question
Title: SerialPort() data reading slowing down Unity
I am sending a few data from Arduino Uno to Unity using serial Port, baud rate is `115200`. Still Unity is response time is pretty poor.

At first it takes fraction of seconds to process, but as time goes response time increases a lot.

What can I do ?

Is there a better way to send data ? I have heard using byte\[\] will be very helpful. Can anyone please tell me how to send `Vector` from Arduino as byte & recieve in Unity, if actually possible.

As I said I will open-source the project. Take a look.

# Answer
> 0 votes
I have changed the `dalay` in Arduino. Then used `Quaternion.Lerp` in Unity, works pretty well & smooth for me.

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


# Question
Title: How to get rid of the white border/background on my png image?
I am making a game using pyGame; it is basically a space invader game, with a tank.

As we can see, this tank image I have has white borders / a white background, which I really want to get rid of.

I am thinking of editing it out, but it would be replaced by a different colour. Is there any way to somehow cut out this tank image from its original rectangular box?

# Answer
Use a file format that supports alpha (png), an editor that can save it with a transparent background (gimp2, photoshop, basically not paint) and make sure you load the sprite correctly
> 6 votes

---
Tags: pygame, image, transparency, alpha-blending, png
---


# Question
Title: 2.5D platformer how to darken building edges?
I was wondering how I could go about creating a vignette type effect / some sort of volumetric shadow for the 'cross section' parts of a 2.5D level. The effect I'm going for can be seen in 'This war of mine' where the edges of the rooms and walls / floors that are facing the camera have been darkened and blurred. (see below).

I thought about creating the edges in photoshop and then blurring them and putting them in, however the blur scales weirdly as I'm re scaling the sprites so it looks really fake and not like a visual effect. Is there perhaps a 2d shader I could use or make?

Any help on this would be appreciated!

Cheers

My photoshop attempt to recreate

# Answer
> 1 votes
You could implement a cross section shader but if you are not going to move the cross sectional plane then this would be a waste of time.

I believe the solution for TWOM was simply to overlay some black bars with rough edges a cutout/transparent shader.

# Answer
> -1 votes
The effect you are looking for is easily archieved with the help of the Post Processing Stack available on the asset store for free and owned by Unity Technologies. You can also create other effects using this as well with lots of tutorials around the web. An example with and without post procesing from the asset store:
An vignette type effect is also available the post processing script.

---
Tags: unity, lighting, post-processing, 2.5d
---


# Question
Title: What’s the best way to create a homebrew game project for a vintage system, so it can also be distributed on other hardware?
For years, i’ve considered writing an NES, Game Boy or maybe even a SNES homebrew title. I’m not expecting to make a knockout success but whatever I make, I’d like it to be easily distributable.

I’ve dabbled in the area of homebrew game dev before but I’ve never taken it to far because I’d also like to have the potential/option to release it as a stand alone app for PC/Mac/Linux and even to smart phones and possibly even distribute it through Steam.

I know that when you create multi-platform software, it’s generally a task of designing cross-compilable software that compiles down to bitcode for each target device. That might be the case for a project like this but since my #1 goal is to essentially make a ROM that can be played on legit early console hardware, I’d assume there might be special tools out there that help you take game ROMs and then wraps them into specific “emulation” applications which can be served to these other platforms types of devices and run on various operating systems.

I’m curious if anyone has had experience creating an old console homebrew project and has also distributed their game for multiple platforms like I’d like to do. What had worked and what hasn’t? I’m not trying to ask to broad of a question. I assumedly see two paths I could take— create a ROM title and wrap it in an emulator or setup a cross platform project that can also compile down to multiple platforms. What’s the best way to start a project like this, and set it up correctly from the beginning, so I can worry as little as possible about cross-platform development, and focus on writing the game logic?

# Answer
Trying to create a game which is able to cross-compile natively to both modern platforms and retro consoles will likely be futile. Some frameworks and game engines I know which can create PC games might be able to target current generation consoles, but I could not name a single one which implements support for old legacy consoles. Legacy consoles often have very specialized and unique hardware which requires specialized and unique programming methods to utilize.

The most promising approach would be to develop it as a classic game ROM, but then bundle it with an open source emulator for relase on modern platforms. That's actually not that uncommon. You can find most of SEGA's old Mega Drive game library on Steam which runs that way. Most of Nintendo's old catalog found on the Virtual Console service is also taking that route.

But keep in mind that the legal situation of emulators is a bit shaky. Some console manufacturers feel that 3rd party emulators violate their intellectual property rights, even if the whole implementation of their technology was made from scratch. So just because SEGA puts their old console games on Steam with an emulator doesn't mean they will allow you to do the same thing.

Another interesting route I have seen taken a few times is to create a cartridge which fits into a vintage console but actually contains a modern system-on-a-chip. The whole game runs on the cartridge. The vintage game system doesn't do anything but supply power and controller input signals and deliver the audio and video output to the TV set. But you can hardly claim that you actually created a homebrewed vintage console game when it requires modern hardware to run and degrades the vintage hardware to a glorified cable adapter.
> 3 votes

---
Tags: homebrew
---


# Question
Title: How can I reset/clean a serializedObject.Update();?
```
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

[CustomEditor(typeof(DialogueTrigger))]
public class DialogueTriggerEditor : Editor
{
    private SerializedProperty _conversations;

    private void OnEnable()
    {
        _conversations = serializedObject.FindProperty("conversations");
    }

    public override void OnInspectorGUI()
    {
        //base.OnInspectorGUI();

        serializedObject.Update();

        _conversations.arraySize = EditorGUILayout.IntField("Conversations Size", _conversations.arraySize);

        for (int x = 0; x < _conversations.arraySize; x++)
        {
            var conversation = _conversations.GetArrayElementAtIndex(x);

            var conversationName = conversation.FindPropertyRelative("conversationName");

            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(conversationName);

            EditorGUI.indentLevel++;
            var _dialogues = conversation.FindPropertyRelative("Dialogues");

            _dialogues.arraySize = EditorGUILayout.IntField("Dialogues size", _dialogues.arraySize);

            for (int i = 0; i < _dialogues.arraySize; i++)
            {
                var dialogue = _dialogues.GetArrayElementAtIndex(i);
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(dialogue, new GUIContent("Dialogue " + i), true);

                EditorGUI.indentLevel--;
            }

            if (_dialogues.arraySize > 0)
            {
                if (GUILayout.Button("Save Conversation"))
                {

                }
            }

            EditorGUI.indentLevel--;
            EditorGUI.indentLevel--;
        }

        serializedObject.ApplyModifiedProperties();
    }
}

```

It seems like the serializedObject contains old 3 dialogues with text names and sentences even if I set the conversations size to 0 and all dialogues also set in the inspector to 0 but still when using a break point on the line:

```
serializedObject.Update();

```

I see on the serializedObject that it contains the old dialogues. Either when running the game or in the editor I see the old dialogues. And then when running the game it's using this dialogues.

But I want that if I set the conversations size to 0 or the dialogues size to 0 to delete all dialogues sentences names all text.

Here is a screenshot showing when using a break point on it before the game is running: There are 3 dialogues names and sentences:

And this is a screenshot of the editor: Everything is empty the conversations size is set to 0. But still when running the game it's taking/getting the old dialogues from the serializedObject.

I'm not sure yet where this old 3 dialogues are kept. In the editor memory ?

Ok after a long search I found that the text of the dialogues names and sentences is stored for some reason inside the project scene file:

With my program that search inside files I could find it in the scene .unity file of my project.

Still I can't figure out what object or what script store it or call it or what and why make it show when running the game.

But at least I found where it stored. What next ? I have no clue.

After edited the file in notepad I found the area of the text:

```
GameObject:
  m_ObjectHideFlags: 0
  m_CorrespondingSourceObject: {fileID: 0}
  m_PrefabInstance: {fileID: 0}
  m_PrefabAsset: {fileID: 0}
  serializedVersion: 6
  m_Component:
  - component: {fileID: 1705786629}
  - component: {fileID: 1705786630}
  m_Layer: 0
  m_Name: DialogueTrigger
  m_TagString: Untagged
  m_Icon: {fileID: 0}
  m_NavMeshLayer: 0
  m_StaticEditorFlags: 0
  m_IsActive: 1
--- !u!4 &1705786629
Transform:
  m_ObjectHideFlags: 0
  m_CorrespondingSourceObject: {fileID: 0}
  m_PrefabInstance: {fileID: 0}
  m_PrefabAsset: {fileID: 0}
  m_GameObject: {fileID: 1705786628}
  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
  m_LocalPosition: {x: 0, y: 0, z: 0}
  m_LocalScale: {x: 1, y: 1, z: 1}
  m_Children: []
  m_Father: {fileID: 104156395}
  m_RootOrder: 2
  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &1705786630
MonoBehaviour:
  m_ObjectHideFlags: 0
  m_CorrespondingSourceObject: {fileID: 0}
  m_PrefabInstance: {fileID: 0}
  m_PrefabAsset: {fileID: 0}
  m_GameObject: {fileID: 1705786628}
  m_Enabled: 1
  m_EditorHideFlags: 0
  m_Script: {fileID: 11500000, guid: 8a658bdd09c49324ba103199b05e0b88, type: 3}
  m_Name:
  m_EditorClassIdentifier:
  conversations: []
  dialogue:
  - name: NAVI
    sentences:
    - Hey Hey, Someone is coming...
    - Quick let's hide.
  - name: PLAYER
    sentences:
    - I'm the player so....
    - And I can't play now
  - name: NEW MAN
    sentences:
    - Hello my friend
    - I need help
    - I lost my basket full of apples
    - Please help me find it
    - Your award will help you in your quest
  dialogueNum: 0

```

But it's a small part of the file not sure if it's telling anything more.

# Answer
> 1 votes
Your current code never removes items, so they stick around.

You can use ClearArray() to erase all of the items when setting the length to zero, or DeleteArrayElementAtIndex() to remove items past the new end of the array one by one:

```
int newSize = EditorGUILayout.IntField("Conversations Size", _conversations.arraySize);

// Delete items from the end when scaling-down the array
for (int i = _conversations.arraySize - 1; i >= newSize; i--)
   _conversations.DeleteArrayElementAtIndex(i);

```

You'll also want to call `Undo.RecordObject()` before applying your modified properties, so the engine is aware that the GameObject you're editing has changed and needs those changes serialized into the scene file for saving / play mode. This will also let you provide clearer messaging in the undo menu to track your changes.

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


title: How can I make a character crouch?

text:
# Question
Title: How can I make a character crouch?
I tried to make a crouch system. In my script I changed `.height` and `.center` properties of collider in `CharacterController` component. But there are some problems. First, once I press "crouch button" collider is changing its height and center position but when I release the key the collider isn't returning to its previous state. Secondly, if I change its height and position by hand when collider is under a block, it's just stuck. How can I fix this problem?

Here's my script:

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

[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour {

    public float moveSpeed;
    public float jumpForce;
    public CharacterController controller;
    public GameObject myCamera;

    private Vector3 moveDirection = Vector3.zero;
    public float gravityScale;

    public Animator anim;

    // Use this for initialization
    void Start () {
        transform.tag = "Player";
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update () {
        Vector3 forwardDirection = new Vector3 (myCamera.transform.forward.x, 0, myCamera.transform.forward.z);
        Vector3 sideDirection = new Vector3(myCamera.transform.right.x, 0, myCamera.transform.right.z);
        forwardDirection.Normalize ();
        sideDirection.Normalize ();
        forwardDirection = forwardDirection * Input.GetAxis("Vertical");
        sideDirection = sideDirection * Input.GetAxis("Horizontal");
        Vector3 directFinal = forwardDirection + sideDirection;

        if (directFinal.sqrMagnitude > 1)
        {
            directFinal.Normalize ();
        }

        if (controller.isGrounded)
        {
            moveDirection = new Vector3(directFinal.x, 0, directFinal.z);
            moveDirection *= moveSpeed;
            if (Input.GetButtonDown("Jump"))
            {
                moveDirection.y = jumpForce;
            }

            if(Input.GetButtonDown("Crouch"))
            {
                controller.height = 1f;
                controller.center = new Vector3(0f, -0.5f, 0f);
                moveSpeed = 3f;
            }
        }
        moveDirection.y = moveDirection.y + (Physics.gravity.y * gravityScale * Time.deltaTime);
        controller.Move(moveDirection * Time.deltaTime);

        anim.SetBool("isGrounded", controller.isGrounded);
        anim.SetFloat("Speed", (Mathf.Abs(Input.GetAxis("Vertical")) + Mathf.Abs(Input.GetAxis("Horizontal"))));
    }
}

```

Thanks for any help!

# Answer
> **Warning:** All code in this answer is untested. It only serves to illustrate the concepts. Do not assume it will just work out-of-the-box without problems when you copy it into your game.

In order to return the character to the original state, you need to save the information what that state actually was. You could of course hard-code the original values, but then you run into problems if you ever decide to change them for some reasons. So I would recommend you to read the original values in your `Start` method and back them up to a bunch of private variables.

<sub>(I would also recommend to turn the currently hardcoded crouched height and center into inspector properties, but that just by the way).</sub>

Add these variables to the behaviour:

```
private bool isCrouching;
private Vector3 originalCenter;
private float originalHeight;
private float originalMoveSpeed;

```

Assign their values in your `Start` method like this:

```
void Start () {
    transform.tag = "Player";
    controller = GetComponent<CharacterController>();
    originalCenter = controller.center;
    originalHeight = controller.height;
    originalMoveSpeed = moveSpeed;
}

```

Remember to set the `isCrouching` flag when entering the crouch state:

```
    if(Input.GetButtonDown("Crouch")) {
        controller.height = 1f;
        controller.center = new Vector3(0f, -0.5f, 0f);
        moveSpeed = 3f;
        isCrouching = true;
    }

```

Then in your Update-method, don't just set new values when the player crouches, also assign the old values when the player stops crouching:

```
    if(!Input.GetButton("Crouch") && isCrouching) {
        controller.height = originalHeight;
        controller.center = originalCenter;
        moveSpeed = originalMoveSpeed;
        isCrouching = false;
    }

```

To fix the problem with the character "growing" inside an obstacle and getting stuck, we need to further enhance this section of the update method to also check if the area above the character is actually free before restoring the original dimensions and leaving the crouched state. You can do that with the method `Physics.OverlapCapsule`:

```
if(!Input.GetButton("Crouch") && isCrouching) {
    Vector3 point0 = transform.position + originalCenter - new Vector3(0.0f, originalHeight, 0.0f);
    Vector3 point1 = transform.position + originalCenter + new Vector3(0.0f, originalHeight, 0.0f);
    if (Physics.OverlapCapsule(point0, point1, controller.radius).Length == 0) {
       controller.height = originalHeight;
       controller.center = originalCenter;
       moveSpeed = originalMoveSpeed;
       isCrouching = false;
    }
}

```
> 1 votes

# Answer
Looks like you forgot to put the collider back the way you found it on key release:

```
// Let's set up our capsule & speed parameters
// so we can easily tune them in the Unity Inspector.
[System.Serializable]
public struct StateSettings {
    public Vector3 capsuleCenter;
    public float capsuleHeight;
    public float movementSpeed;
}

public StateSettings standing;
public StateSettings crouching;

[Tooltip("Physics layers of obstacles that should stop the crouched player from standing")]
public LayerMask obstacleLayers;

// Keep track of our current state.
bool _isCrouching;

// ...

void Update() {

    // ...

    if(_isCrouching == false) {
        if(Input.GetButtonDown("Crouch"))
        {
            controller.height = crouching.capsuleHeight;
            controller.center = crouching.capsuleCenter;
            moveSpeed = crouching.movementSpeed;
            _isCrouching = true;
        }
    } else {
        // Every frame we're not trying to crouch, see if we can stand.
        // (This way it triggers even if we let go of the button, then crawled free)
        if(Input.GetButton("Crouch") == false) {

            // Watch your head!
            Vector3 newBottom = standing.capsuleCenter + Vector3.down * standing.capsuleHeight * 0.5f;
            newBottom = transform.TransformPoint(newBottom);

            RaycastHit hit;
            if(Physics.SphereCast(newBottom, controller.radius, transform.up, out hit, standing.capsuleHeight, obstacleLayers) == false) {
                // Stand up only if we found no hit, otherwise try again next frame.
                controller.height = standing.capsuleHeight;
                controller.center = standing.capsuleCenter;
                moveSpeed = standing.movementSpeed;
                _isCrouching = false;
            }
        }
    }
}

```
> 0 votes

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


# Question
Title: How could I format my C# code using Checkstyle?
Is there any possible way to check my C# code with Checkstyle in the context of Unity?

# Answer
You can't.

*checkstyle* is a tool for Java. Style checking tools are often made specifically for a language, and it's hard to adapt them to other languages. (And often the developers don't really care about other languages, for various reasons.)

I understand you're probably coming from the Java world, and you'd like to reduce the work involved with working with the new tool (Unity), but alas, I'm afraid you'll have to find a new style checker that works with c#.

I will not suggest alternatives, though, because it's not within the scope of this site, instead, I will suggest you search the web for them.

One thing worth noting is that Unity's API, and lots of common Unity scripts/asset packages based on it, deviate from standard C# coding conventions (like using PascalCase for public fields), so standard C# checkers might flag more than you want. ;) <sup>(Thanks to DMGregory for this tip; copied verbatim.)</sup>

---

You'll find out that you can use checkstyle with Visual Studio, but it still checks Java code, not c# code.
> 1 votes

---
Tags: unity, c#, visual-studio
---


# Question
Title: How to work with different artists sequentially?
Making games is a hobby for me and I don't always have consistent time to do it. Also, I'm terrible at art, so I plan to hire an artist. However I am concerned that after a job is done, if I want to return to the project and add more content, the same artist will not be available for any number of reasons. What can be done to help a new artist maintain the style of the previous?

Should I hire the original artist to create a graphic bible? Or is referencing the original art enough? Or is there an entirely different approach that would be better?

*Note that this is not a duplicate of this question, where multiple artists are coordinating simultaneously. In this case, one artist has done their work and is gone, unavailable for contact or future work, and a new artist is expanding the assets.*

# Answer
> 2 votes
While I am not personally *super* experienced with the art side of game design I can think of a couple of solutions too your problem.

**A). Make a style guide.** (Example here) Having the first/primary artist make a style guide on the character's proportions, colors, and references can allow future artists to duplicate the work more easily.

**B). Incorporate it into the game.** (Evoland followed this path) Splitting the game into several sections with each having their own art style and unique feel is not only fun but it also splits up the work nicely for yourself. Finnish a section of gameplay/narrative, then commission and artist to make that portion while working on the next.

**C). Stick with the same artist.** While I understand that this is directly contradictory to your question, this is a 1 man show hobby. As a result it should be very doable to find an artist to stick with. Make sure they know that this is a long term arrangement, and even better if you can develop a relationship where your both excited too work on the game.

I would also check out some of the other answers on this topic too shore up a full plan.

Maintaining Artistic Consistency

Finding Artists To Hire

Working With Artists

---
Tags: assets, art, project-management
---


title: OpenGL 2D Game Render Help

text:
# Question
Title: OpenGL 2D Game Render Help
I just recently started using C++ and OpenGL and I am running into an issue. I am not totally sure what I am doing so could you please tell me what I am doing wrong and what I could improve?

Here is the problem:
I can't see to get a textured quad to render at all. I've tried a bunch of different ways and even asked people who claimed to know C++ and they said they didn't see any obvious issues.

I am using the following libraries:

* GLFW (For input/window callbacks)
* GLUT (For OpenGL)

Here is my code:

```
///In class "Game"

    virtual void render() {

        int ww, hh;
        glfwGetWindowSize(gameWindow, &ww, &hh);

        glLoadIdentity();
        gluOrtho2D(0, ww, hh, 0);

        glClearColor(0, 0, 0, 1);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        gameRoom->render();

        glfwSwapBuffers(gameWindow);

        glPopMatrix();

    }

```

```
///In class "Sprite"

    void render(int index, int x, int y, float xscale, float yscale)
    {
        float tcx1, tcx2, tcy1, tcy2;

        tcx1 = (float)frames[index].x / base_width;
        tcx2 = (float)(frames[index].x + frame_width) / base_width;

        tcy1 = (float)frames[index].y / base_height;
        tcy2 = (float)(frames[index].y + frame_height) / base_height;

        float vx1, vx2, vy1, vy2;

        vx1 = (x - Game::gameView->x) / Game::gameView->width;
        vx2 = (x + frame_width * xscale - Game::gameView->x) / Game::gameView->width;

        vy1 = (y - Game::gameView->y) / Game::gameView->height;
        vy2 = (y + frame_height * yscale - Game::gameView->y) / Game::gameView->height;

        glPushMatrix();

        glBindTexture(GL_TEXTURE_2D, texture);
        glEnable(GL_TEXTURE_2D);
        glBegin(GL_TRIANGLES);

        glTexCoord2f(tcx1, tcy1); glVertex2f(vx1, vy1);
        glTexCoord2f(tcx2, tcy1); glVertex2f(vx2, vy1);
        glTexCoord2f(tcx1, tcy2); glVertex2f(vx1, vy2);

        glTexCoord2f(tcx2, tcy1); glVertex2f(vx2, vy1);
        glTexCoord2f(tcx1, tcy2); glVertex2f(vx1, vy2);
        glTexCoord2f(tcx2, tcy2); glVertex2f(vx2, vy2);

        glEnd();
        glDisable(GL_TEXTURE_2D);

        glPopMatrix();

    }

```

When I run the game all I get is a black screen... Please help!

# Answer
I fixed the issue.

The problem was this:

I programmed a converter in CSharp that took the image and outputted all of its pixels as raw RGBA data which my program read from, in the converter's for loop to read the pixels I forgot to offset the write position by 4 times the x and y value which caused only the red values to be written and not even in a format that's readable by my engine.
> 2 votes

---
Tags: opengl, c++, glfw, glut
---


title: Loop around a 2D Tile Map

text:
# Question
Title: Loop around a 2D Tile Map
I have made an algorithm for procedurally generating a 2D tile map in Unity.

The player can use the mouse to pan the view and look at the map.

My intention was that when the player reaches one of the sides of the map, he would simply see the other side as if he was going around the Earth so to speak.

The only way I have achieved this is by simply instantly setting the camera's position to the other side of the map when the player crosses one of the edges. The problem with this is that the player never actually sees the "border" connection continuously and that bothers me since I took the care to generate the map in such a way that connecting the east/west edges makes sense.

How can I achieve the desired effect?

# Answer
How about this:

You can count how many tiles the player can see when standing on the border (lets say they can see 5 more tiles).

In that case, each tile should know it's position in the array. If it is within the 5 tiles proximity of the border, it can make a copy of itself on the other side.

Lets say you are exactly on the right border. You want to see the 5 tiles most to the left... so each tile with x \< 5 should create a purely visual copy on the right?
> 1 votes

---
Tags: unity, 2d, graphics, tilemap
---


title: Counter won't add to score

text:
# Question
Title: Counter won't add to score
I'm trying to make a rolling ball game. But for some reason, I can't seem to get the counter to actually add to the score. Here's the code:

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

public class Movement : MonoBehaviour {
    public float speed;
    public Rigidbody rb;

    private int count;
    public Text countText;

    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody>();
        count = 0;
        SetCountText();
    }

    private void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rb.AddForce(movement * speed * Time.deltaTime);
    }

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "item")
        {
            other.gameObject.SetActive(false);
            count = count + 1;
            SetCountText();
        }
    }

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

    }
}

```

It's super simple. Like, new new newbie simple. The objects I want to display as collected are tagged "items", they have colliders, and they are kinematic. I've followed the tutorial (this tutorial, specifically: https://www.instructables.com/id/How-to-make-a-simple-game-in-Unity-3D/) to the letter (barring some changes due to Unity updates), but for some reason it's not working.

I'm feeling a lot of anxiety cause I've had panic attacks about failure before and I really don't want to repeat it. Please help!

# Answer
I can think of few reasons why this might not work: Are you sure the script is added to the proper object in the game world? Is the collider set properly to "trigger"? Is the collision array set properly? (it's an array where you set which items collide with which. So you can make bullets only react to hitting certain items etc)

And what I think might be the main culprit - didn't you switch around the collider deal? Of course you can do it in many ways, but I think it would be done like this: The sphere has "normal" collider, while the item has a trigger collider. When the sphere enters trigger collider, the **item** runs the "OnTriggerEnter" method. But it seems like in your script, the sphere has the trigger collider.

Since your sphere most probably only has a "normal" collider, the OnTriggerEnter will never even run!

Another idea: Is the GUIText set up in player settings?
> 0 votes

---
Tags: unity, c#, gui, scoring
---


# Question
Title: How do I draw 2D sprites from a sprite sheet in DirectX 11 without ghosting/artifacts
I'm new to DirectX and I am trying to get my feet wet by making a simple 2D game. I chose DirectX 11 and am using the DirectX ToolKit helper library which recommended I start with DX11 and not DX12.

The guide I am following to create an animating sprite is working great except for when attempting to draw a single sprite from the sprite sheet I am seeing "ghosting" of other sprites behind it. I created the sprite sheet and saved it as a PNG and also as a BMP and it seems to happen either way.

Here is the sprite sheet I am using:

It is 336px width, 48px height, in 48px x 48px square sprites. If I render the entire sprite sheet, or if I render the first sprite (0,0,48,48), it looks fine, but if I attempt to render the 2nd, 3rd, 4th, etc. this is how it renders:

Here is the code I am using to load the PNG file as a texture:

```
ComPtr<ID3D11Resource> ponyIdleResource;

DX::ThrowIfFailed(
    CreateWICTextureFromFile(_D3dDevice.Get(), L"assets/pony_idle.png",
        ponyIdleResource.GetAddressOf(),
        _Texture.ReleaseAndGetAddressOf())
);

ComPtr<ID3D11Texture2D> ponyIdleTexture;
DX::ThrowIfFailed(ponyIdleResource.As(&ponyIdleTexture));

CD3D11_TEXTURE2D_DESC ponyIdleDesc;
ponyIdleTexture->GetDesc(&ponyIdleDesc);

```

and here is the code I am using to draw:

```
_SpriteBatch->Begin();

RECT sourceRect;
sourceRect.left = 48;
sourceRect.top = 0;
sourceRect.right = 96;
sourceRect.bottom = 48;

_SpriteBatch->Draw(_Texture.Get(), _ScreenPos, &sourceRect, Colors::White, 0, _Origin);

_SpriteBatch->End();

```

If I pass the RECT in as 0,0,48,48, it looks fine. Is there some special way I need to format my image? I've tried it as both PNG and BMP.

# Answer
`SpriteBatch` uses premultiplied blending by default. The spritesheet in question is using straight-alpha, hence the 'ghosting'.

Fix is to either:

(a) Use straight-alpha blending

```
_SpriteBatch->Begin(SpriteSortMode_Deferred, _States->NonPremultiplied())

```

(b) Convert the spritesheet to pmalpha (this creates a `ponyidle.dds` with pmalpha instead of straight alpha)

```
texconv ponyidle.png -pmalpha -m 1

```

See Shawn Hargreaves' Blog, DirectX Tool Kit, and DirectXTex.
> 1 votes

---
Tags: directx, sprites, directx11
---


# Question
Title: Random FPS drop with OpenGLES 2.0 on android, sudden white screen with Vulkan
I'm having a problem with my 2D game on Android.

When I use OpenGLES 2.0 as the graphics API, I experience sudden FPS drops in the game. The game starts to slow down sometimes randomly, And it can drop down to 25 FPS sometimes (from 60). I tried debugging it, and nothing special was consuming CPU time or anything.

it was only GFX.Waitforpresent.

To fix this, I tried using Vulkan as the first Graphics API, and the other two OpenGLES APIs next. The problem of FPS drop is gone! never slows down again on my device.

But I had two other problems.

The first is the screen suddenly turn all white. This is again random! can't reproducde it easily. But it does happen. And when this happens sound can be heard and it's obvious the game is running, and it's just not rendering properly.

The other problem is game won't start on an old device a friend tested it on.

I've been testing this on my Huawei P10 Lite device with Android 8.

# Answer
> 0 votes
I upgraded my Unity to latest version (2018.3) and the problem with Vulkan is gone.

---
Tags: unity, opengl-es2, vulkan, opengl-es3
---


# Question
Title: Turn-based battle mechanics with balance of HP and damage
(Major rewrite to be more specific)

## Scenario

I'm prototyping a turn-based battle system. The theme is survival in a despaired setting with conflicting interests:

* 2 players, attacker and defender
* each player starts with an army of 20+ characters to choose each battle's party from
* 6--8 characters per battle party on a 3x3 grid (distance can be used for tactics and variation)
* character death is permanent
* combatants will likely die, and the scenario is short, so there's not much point in complex leveling systems; characters do not improve that much over the course of 1 game
* I want to ignore equipment for now; imagine everyone's fighting naked

With ~6 characters, it's not that much of a problem if one dies during a battle. Two deaths should feel impactful. 4 deaths are serious.

If your party is wiped out, the battle ends and both start selecting combatants for the next fight until one army is wiped out.

## How do you figure out numerical representations for stats and effects?

It puzzles me how I should start setting base HP, damage output, evasion rates, and the like.

Established pen & paper make no "sense" but work. Looking at AD&D3 rule books, for example, gives me a sense of security: the rules work well enough, and the success of playing justifies how things are computed. This is a pragmatic argument: if it works, it's good, no matter how odd the formula looks. (I picked the example on purpose because there are newer revisions.)

It's all about numerical representations, but which?

I find it hard to imagine how to work with the full spectrum of random values on a computer. What do I need a random number of 65000 for? What could it mean? Even limiting myself to something that's easy to imagine, 1--100% (e.g. from 0.0 to 1.0, or 1 to 100), I cannot imagine how you come up with a rule like: **I want a 70% chance to hit.** Why 70%? Isn't that too high or too low? How do you find out good starting values?

1. Sticking to this example: What's a good-enough hit chance, and how do you decide that? Maybe 80%+ so players don't feel like missing their foes all the time? Do you only find that out via experimentation? If you settle on 80%, do you then *infer* a character attribute like `Accuracy` to produce a 80% chance? (`rand(1,100) > 20` is an 80% chance, so let's try `Accuracy = 20`? Probably rather the inverse, `Accuracy = 1` and `didHit = rand(1,100) > (20 - Accuracy)` so the values increase when one gets better.)
2. How do you come up with the amount of HP a character should have? And how do you calculate damage?

* If an example character has 100 HP, a single attack dealing 1000 damage points is clearly overkill for regular battles. In some games, it could signal "you need to level up", of course, but that's not relevant my prototype. So the damage needs to be lower.
    * Absorbing, say, 20 damage points per hit at 100 HP seems manageable in a 1:1 fight. Then you don't have to heal every other turn and can deal damage yourself for a couple of turns. This could work.
    * But absorbing 20 damage points from 6 opponents each at 100 HP means a char gets killed immediately in the first turn if all attacks hit. That's not good.
    * What about special low-HP mechanics? I can imagine at \<20% HP, characters have reduced damage output but better evasion rates "to save their lives". That sounds kinda cool at first, but it makes fighting more complex and looks like band-aid to a problem of insta-killing. The complexity to figure out possible outcomes becomes greater; it's harder to get a feeling for the mechanics.
    * So what do you do? Reduce base damage to 15 so `6 chars * 15 dmg < max HP` to prevent insta-kills, or would you rather go with a more complex low-HP-mechanic and then *try it out* to see if it's fun?

## Which calculations turn out to be fun?

From that I can derive a few pragmatic heuristics already:

* Absorbing damage of around 1/5 of the max HP will result in tanking damage from 3+ hits, then you need to heal. 1/7 will keep characters alive longer, but 1/3 is probably too much to be playable. Longer lives might be desirable.
* Insta-kill (100% damage) or even healing every odd round is an indicator of too difficult an opponent. It's probably more fun to tank a couple of hits so you can be effective yourself and change the outcome by inflicting damage, and not just manage not to die.
* It could be fun and interesting to vary character behavior, e.g. characters react differently at low HP. Go berserk and do more damage and reduce evasion, or focus on survival via evading and reduce damage output.

Start with something like that and then adjust?

Is that *all* there is? Pragmatism?

I guess it boils down to: how do you estimate if your calculations turn out to be fun? How do you pick the first numbers to play-test with?

# Answer
> 1 votes
If you want to emulate what pen and paper does, you can basically do the same things. If you want the player to "roll at least a 7" to hit something, that means that there is a 14/20 chance to hit - or 70/100, also known as 70%. That means you can generate a random number between 1 and 100, and if it's above 30, you register that as a hit, otherwise a miss. Same for your damage: instead of rolling 3 different dice as in your example, you just generate a number between 3 and 18, or whatever min and max values are good for your game and the current level. It's really all the same things, it's just that games hide these "dice throws" usually.

Now, as you mentioned, pure random numbers can feel unfair to the player, because human brains are bad at randomness and statistics. There are several approaches you can take here to combat that, and there's really no single approach that is better all the time. It depends on your game, what the numbers are for, how "fair" or "good" you want it to feel, how important the results of that check are, and so on.

* You could hard code something like "if the player has missed 2 times in a row, the next strike is a guaranteed hit". This way, you avoid having any frustratingly long streaks of failure. Same could be done for damage numbers, saying that if they did damage below the expected value for the last three times, the next hit will do above average damage, or will be a crit, or whatever is appropriate.
* You could generate a list of numbers ahead of time and process it to remove any extreme outliers, or modify long streaks of especially good or bad values. Then during the game, you pull numbers from that list instead of generating them on the fly.
* If you show your % chances to hit like for example in the XCOM games, you could trick the player by showing a slightly lower chance than it actually is. This way, they should probably be pretty "lucky" a lot of the time.

These are only a few basic ideas, and others have gone into a lot more detail about that, for example here: How do I avoid "too" lucky / unlucky streaks in random number generation?

With regard to balancing, it's really a matter of playtesting, I suppose. You can try and come up with a calculated power value for each party (combined from HP, average damage, and other relevant values) to have a ballpark estimate of how strong they are and how big the difference is, but that will probably only get you so far - you'll have to do the finetuning by yourself.

---
Tags: rpg, turn-based
---


# Question
Title: weird behaviour doing simple XMMATRIX multiplications
I have the following function:

```
void AnimatedModelShaderClass::PrepareToDraw(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
XMMATRIX projectionMatrix, ID3D11ShaderResourceView* mesh) {

WVP = worldMatrix * viewMatrix * projectionMatrix;
cbPerObj.WVP = XMMatrixTranspose(WVP);
cbPerObj.World = XMMatrixTranspose(worldMatrix);
[...]

}

```

WVP is defined in the AnimatedModelShaderClass class as

```
XMMATRIX WVP;

```

The world, view and projection matrices are correctly received by the function, but as soon as the first line is executed, i can see that WVP contains some very weird values.

If i substitute the first line with the (supposedly) equivalent:

```
WVP = XMMatrixMultiply( XMMatrixMultiply(worldMatrix,viewMatrix), projectionMatrix);

```

then WVP is evaluated correctly and the numbers inside make sense.

Aren't the two ways equivalent? What am i missing?

Thanks in advance.

UPDATE:

It doesn't seem to have anything to do with the multiplications order, it works correctly if i replace the faulty line with:

```
XMMATRIX temp1 = projectionMatrix;
XMMATRIX temp2 = viewMatrix;
XMMATRIX temp3 = worldMatrix;

WVP = temp3 * temp2 * temp1;

```

What's the difference? I don't get it...

# Answer
> 0 votes
Ok, i have a solution to my problem, even if i still need time to understand what it does exactly. The fix is to use the XM\_CALLCONV annotation to make sure the function uses the appropriate calling convention, like so:

```
void XM_CALLCONV AnimatedModelShaderClass::PrepareToDraw(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* mesh)

```

This solves my problem, WVP is instantiated correctly. I won't go into details explaining why it works because i don't know it myself. For reference, this is where i got the answer, hope it helps!

thanks

# Answer
> 1 votes
This has to do with the order of multiplication. While in regular Maths the multiplication goes from left to right, C++ and to my knowledge other programming languages do it the other way around. With scalar math, this is no problem but with matrix multiplication being *noncommutative* you should switch up the order to make it work with the standard `*` operator while XMMultiply uses an order that from left to right and thus is not suffering from this issue. This means that calculating the MVP/WVP correctly using the `*` operator the calculation should be

```
WVP = projectionMatrix * viewMatrix * worldMatrix ;

```

Yet this does not mean that `XMMatrixMultiply()` is the preferred method as this depends on the style used in your project so feel free to use either the function or the `*` operator as both are equally right.

# Answer
> 0 votes
Matrix transformations are non-communicative i.e. A * B != B * A.

Consider what you are doing with the matrices:

You are taking something in what is called *model space*, and applying the model, or "world" transform to it:

```
VertexWorld = WorldTransform * Vertex;

```

The result of this is to change the vertex to a new coordinate basis, or change it's frame of reference.

Next you would, for the purposes of graphics, put it into a frame of reference dependant on the camera, or eye (we call this "view space"):

```
VertexEye = ViewTransform * VertexWorld;

```

Now, you want the vertex in screen, or "clip space":

```
VertexScreen = ProjectionTransform * VertexEye;

```

Note the order of multiplication: in computers, statements are evaluated right to left, so the vertex is multiplied by the matrix, then assigned to the new variable.

So if you want to condense this down into a single line of code, you can concatenate the transformations into a single matrix:

```
WVPTransform = ProjectionTransform * ViewTransform * WorldTransform;
VertexScreen = WVPTransform * Vertex;

```

Or:

```
VertexScreen = ProjectionTransform * ViewTransform * WorldTransform * Vertex;

```

Hope that helps you understand.

---
Tags: c++, shaders, directx, graphics, graphics-programming
---


title: How to use Game Assets from Behance

text:
# Question
Title: How to use Game Assets from Behance
I need to use dinosaur/dragon eggs in my game. I have found out this resouce from Behance.net. I am not sure how to download these resources. Can anyone help me with it.

# Answer
This looks to me like an artist's portfolio, a page where they demonstrate their skills to potential employers.

As Pikalek points out in the comments, the license specified on these images is CC BY-NC-ND 4.0. That means you can download and distribute the images only unmodified, with attribution, and for non-commercial purposes. You can't build upon them/use them in derivative works like your own game without contacting the rights-holder to negotiate a different licence.

Judging by the caption, rights to use these assets in-game are likely exclusively owned by the studio that made Tiny Miners.

So, if you want assets like the ones shown there, hire the artist and pay them to create assets for you.
> 1 votes

---
Tags: assets
---


# Question
Title: Separating scene generation and scene starting in Unity?
I'm working on a game, where the **map is generated**, and:

* The **map is generated** in an **Awake()**, so when an **object's Start() is called**, the map should be **fully initialized**.
* But the scene's **physics world won't be updated till the next FixedUpdate**.
* So when **Start() is called**, there is a high chance, that physics operations are **done in an incorrect world** (*like raycasting*)

I tried using **Physics.SyncTransforms**, but it **didn't solve** the issue for some reason. (**Why?**)

My next approach was to **start the objects with a delay**. Precisely: after a **FixedUpdate**.

* So I started a **Coroutine in the Start()** method, which **waits for a FixedUpdate**, then **starts the object**.
* But this caused that for example: **ObjectA's Update() is called before ObjectB's Start coroutine finishes**.

**How could I achieve that scenes won't be started until the scene is fully initialized?**

Is there a way to tell Unity to call every Start() i.e. 1 frame later? Or how else could I fix this? What is the best solution?

# Answer
> 4 votes
The neatest way to do this is probably with an event. Content that needs to initialize after the map's physics are ready can subscribe to the event.

Using a generator method like the one below, this subscription can be as simple as:

```
void Start() {
    MapGenerator.DeferUntilPhysicsReady(InitializeAfterPhysics);
}

void InitializeAfterPhysics() {
   // Do the thing.
}

```

Here's a sketch of a generator script that can handle this deferred initialization:

```
public class MapGenerator : MonoBehaviour
{
    static MapGenerator _instance;
    public static MapGenerator instance { get {
            if (_instance == null)
                _instance = FindObjectOfType<MapGenerator>();
            return _instance;
        } }

    public static void DeferUntilPhysicsReady(System.Action callback) {
        var generator = instance;
        if (generator == null) {
            Debug.LogError("Trying to defer in scene with no Map Generator.");
            return;
        }

        if(generator._isPhysicsReady) {
            // Handle late-spawning scripts that can safely initialize now.
            callback();
        } else {
            // Otherwise, wait until physics is ready, then call it.
            generator.OnPhysicsReady += callback;
        }
    }

    public event System.Action OnPhysicsReady;
    bool _isPhysicsReady;

    IEnumerator Start()
    {
        GenerateMap();

        // Wait until just before the next physics step.
        yield return new WaitForFixedUpdate();
        // Let physics step at least once, then resume after Update().
        yield return null;

        _isPhysicsReady = true;

        // Physics are all up to date:
        // ready to call our deferred initialization methods.
        if (OnPhysicsReady != null)
            OnPhysicsReady();
    }

    void GenerateMap() {
        // Do the thing.
    }
}

```

---

You can even offload this subscription logic to a separate standalone component that wakes the rest. Just spawn you object with the sensitive scripts initially disabled, and use a script like this to wake them and start ticking their Start / Updates on demand:

```
public class WakeAfterMapReady : MonoBehaviour {

    public Behaviour[] disabledBehaviours;

    void Start() {
        MapGenerator.DeferUntilPhysicsReady(InitializeAfterPhysics);
    }

    void InitializeAfterPhysics() {
         foreach (var behaviour in disabledBehaviours)
             behaviour.enabled = true;
    }
}

```

# Answer
> 2 votes
Ordering dependencies in Unity is a pretty complex thing, once you have too many different game objects in the scene. In my experience it's better not do things like raycasting in Start, simply because you don't know the initialization state of each object. You cannot ensure when or in which order will Start() be called. GameObjects are designed to be independent, not reliant on the state of other objects.

I find that the best solution is to sort out your dependencies in the design stage, in order to have your code properly reflect them. For example, if I understand your description correctly, you have the following order of stages:

1. generate map
2. ensure that the Physics state of each object has been set (I.E. each object has ran FixedUpdate at least once).
3. Setup each object.

Assuming this is correct, it seems pretty obvious that what you need is to implement a barrier for stage 2, and only after the barrier has been entered by all the objects can stage 3 start. It can be as simple as having a global counter that each object increments in Start(), and then have check in Update():

```
void Start() {
    counter++;

    // Other non-dependant logic
}

void Update() {
    if (counter < targetNumber) {
        return;
    }

    // Implement dependant logic
}

```

---
Tags: unity, procedural-generation, initialization
---