# Question
Title: How does a "static" IEnumerator work in this context? (The code works, but what is it actually doing?)
I am generating many objects procedurally in my Unity C# app/game such as user interfaces, user profiles, etc. I have made classes which feature static variables/functions to allow this. Everything seems to be working as intended. But there's something I don't understand about how or why they work pertaining to static functions/variables.

For example, here is a sample code I made to illustrate having a button in a "profile" object that if you click it will hide a generated "profile" object.

```
public class GenerateProfile {

    private static IEnumerator showOrHideIENumerator;

    public static VisualElement generateObject() {

        VisualElement objectVE = new VisualElement();
        CustomObject customObject = new CustomObject(); //'hide' button to click
        objectVE.Add(customObject);

        customObject.runButtonFunction += delegate { //ie. adding to an event 'runButtonFunction' inside this custom object
            hideFunction(objectVE, ref showOrHideIENumerator);
        };

        return objectVE;
    }

    private void hideFunction(VisualElement objectToHide, ref IENumeratorToUse) {
        if (IENumeratorToUse != null) {
            MonoBehaviorApp.Instance.StopCoroutine(IENumeratorToUse); //using a monobehavior singleton to run coroutine and stop it first in case already running.
        }
        IENumeratorToUse = hideObject(objectToHide);
        MonoBehaviorApp.Instance.StartCoroutine(IENumeratorToUse); //using a monobehavior singleton to run coroutine once should now be stopped
    }

    IEnumerator hideObject(objectToHide) {
        //function to hide object like for simplicity:
        objectToHide.style.visibility = Visibility.Hidden;
    }
}

```

Now somewhere else you create multiple instances of this using:

```
VisualElement generated = GenerateProfile.generateObject();

```

# Question

If you then click on the button, what actually happens for each generated object when the fade out function runs?

Is every single copy of this generated object actually using the same `showOrHideIENumerator` or do they each get their own?

The reason I am arranging things like this is so I can then allocate a show or hide function to the same IEnumerator `showOrHideIENumerator` as needed, and stop it if it is already running in either direction. (ie. if you click "hide" while it is half way finished showing, it stops showing, and starts hiding).

I ideally wanted to put `showOrHideIENumerator` inside the `generateObject()` function so that it would make a new one for every generated object to have to itself. However, this wouldn't work.

I suspect what's happening is there is just one `showOrHideIENumerator` for the whole app and all these objects made from `generateObject()` are then sharing it (which is actually fine since I don't need multiple ones running at once).

I'm just curious to better understand how this works. Thanks for any clarity. Or if there's a better way to do what I'm trying to do I'm open to suggestion.

# Answer
> 3 votes
You can build a quick synthetic test to find out:

```
public class CoroutineTest : MonoBehaviour
{
    IEnumerator Tester() {
        // Create a reasonably-unique ID,
        // so we can distinguish multiple instances of this function running.
        var id = Random.Range(0, 10000);

        // Each frame, print our ID, how many cycles we've done, and the frame.
        for (int i = 0; i < 10; i++) {
            Debug.Log($"IEnumerator {id}: iteration {i} @ frame {Time.frameCount}");
            yield return null;
        }
    }

    // Store a single shared instance of this IEnumerator.
    static IEnumerator iEnumerator = Tester();

    void Start() {
        // On startup, make a coroutine using this IEnumerator.
        StartCoroutine(iEnumerator);
    }
}

```

Make a few copies of a GameObject with this script attached, and hit play. You'll generate a log like this:

> IEnumerator 130: iteration 0 @ frame 1 UnityEngine.Debug:Log (object)
> IEnumerator 130: iteration 1 @ frame 1 UnityEngine.Debug:Log (object)
> IEnumerator 130: iteration 2 @ frame 1 UnityEngine.Debug:Log (object)
> IEnumerator 130: iteration 3 @ frame 2 UnityEngine.Debug:Log (object)
> IEnumerator 130: iteration 4 @ frame 2 UnityEngine.Debug:Log (object)
> IEnumerator 130: iteration 5 @ frame 2 UnityEngine.Debug:Log (object)
> IEnumerator 130: iteration 6 @ frame 3 UnityEngine.Debug:Log (object)
> IEnumerator 130: iteration 7 @ frame 3 UnityEngine.Debug:Log (object)
> IEnumerator 130: iteration 8 @ frame 3 UnityEngine.Debug:Log (object)
> IEnumerator 130: iteration 9 @ frame 4 UnityEngine.Debug:Log (object)

What we learn from this:

* We can see the ID is always the same, so every coroutine spawned from this `IEnumerator` instance is sharing that same instance.
* Anytime *any* coroutine spawned from this `IEnumerator` gets ticked, it advances the state of that shared `IEnumerator` instance.

From reading the code, we might think this coroutine will take 10 frames to finish. But if we spawn three coroutines sharing an `IEnumerator` instance, then it actually it takes 4. Each time one coroutine ticks it steps the instance forward from wherever it last yielded.

This behaviour is not immediately obvious or intuitive (hence the question), so I'd recommend avoiding it in your code. It's likely to lead to confusion and bugs down the line.

Instead of storing a `static IEnumerator`, try storing a `static Coroutine`. This will represent one instance of the iteration that is also bound to only a single coroutine - even if you make a coding mistake, it won't be possible to spawn multiple coroutines all sharing an underlying instance like in the example above. You can still call `StopCoroutine` on it (and it may be more efficient since Unity won't have to look up the coroutine instance from the `IEnumerator`, since you already provided it directly). You can get a `Coroutine` instance by capturing the value returned from `StartCoroutine`.

# Answer
> 0 votes
The easiest solution is to create a local Coroutine like:

```
public class GenerateProfile {

    public static VisualElement generateObject() {

        //define animation functions locally
        IEnumerator hideObject(objectToHide) {
                //function to hide object like for simplicity:
                objectToHide.style.visibility = Visibility.Hidden;
                yield return null;
            }

        void hideFunction(VisualElement objectToHide, ref CoroutineToUse) {
            if (CoroutineToUse != null) {
                MonoBehaviorApp.Instance.StopCoroutine(CoroutineToUse); //using a monobehavior singleton to run coroutine and stop it first in case already running.
            }
            CoroutineToUse = hideObject(objectToHide);
            MonoBehaviorApp.Instance.StartCoroutine(CoroutineToUse); //using a monobehavior singleton to run coroutine once should now be stopped
        }

        //assign animation functions
        Coroutine showOrHideCoroutine = null;

        VisualElement objectVE = new VisualElement();
        CustomObject customObject = new CustomObject(); //'hide' button to click
        objectVE.Add(customObject);

        customObject.runButtonFunction += delegate { //ie. adding to an event 'runButtonFunction' inside this custom object
            hideFunction(objectVE, ref showOrHideCoroutine);
        };

        return objectVE;
    }

```

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


# Question
Title: Simulating sprite shadows for a 2D top-down game
I have read some other posts with almost identical titles on here, but they are not exactly what I am looking for. (What I have seen come up a lot in 2D shadows is some sort of "ray-cast effect").

I am trying to figure out something similar to how it's done in "Songs of Syx" (picture above is from this article) or this video

I am pretty sure, the shadows in that game or similar are done in another way. The shadows could perhaps be sprites.

You have some dynamic directional light (effectively the sun) that revolves around the the terrain. Every sprite cast a shadow on the terrain (only).

I'm not sure, but I THINK that each sprite has a "depth texture" in addition to its color (and normals). Similar to to the illustration below:

So \[2.\] (the depth texture) has a value \[0-1\] for every pixel. Where 0 (or black) cast no shadow, and 1 (or white) indicates a "maximum height". Let's say a height (Y-value) of 1 correspond to 1 in world units. And you could imagine that the blue rectangle in the picture has dimensions of (1,1,1).

I am somewhat familiar with 3D-lighting and shadow-mapping, where I rendered the geometry first from the light's perspective to a a depth texture bound to a framebuffer object. Then I render all geometry again to do depth testing with the depth texture.

I would think something similar can be done in this case? Only with the depth texture instead of vertex geometry.

And since no sprites need to cast shadow on other sprites (only the terrain), maybe it's possible to render the sprites and a "depth map" in a single shader pass?

But I am not sure how I could do this. I would like the light position to be a 3D coordinate. So when the light is above the sprite it cast no visible shadow (it does, but the sprite hides it). And when the light is all the way down the horizon (below the virtual height of the sprite), the shadow cast has to be limited in distance (let's say the shadow cast cannot have a length greater than the virtual height of the sprite).

The terrain that receives the shadow lies entirely flat on the XZ-plane. The camera is not orthographic perspective. And you can pan around and "pitch" it to some degree.

How can I achieve this?

# Answer
I have found a solution where I am using a depth texture for each sprite to simulate 3D shadows similar to the illustration in my question.

I don't know if "Songs of Syx" in particular does it the same way, but i suspect it's in the same ball park.

I am rendering the scene to multiple textures bound to a framebuffer object.

Diffuse (rgb8), Normals(rgb8), Height(red8) (Off screen buffers)

After the entire scene is rendered I do another shader pass where I calculate shadows. (Height texture only). In the fragment shader, every fragment cast a ray FROM it's position TOWARDS the light. I sample pixels from the height texture along that ray (with a delta value), if any sampled pixel values are greater than the value of the fragment you are processing, then you know it is in shadow.

Here you could "accumulate shadow" if you want, based on how many pixels you "hit" while tracing the light.

Then you could store the accumulation in another "shadow texture" used in the final lighting calculations.

At this point, you have a "shadow texture", "normal texture" and "color texture" of the entire scene. To use with any lighting algorithms you want.

I am still testing things out, but I am very happy with how it looks, feels and performs. :)
> 1 votes

---
Tags: opengl, 2d, sprites, shadow-mapping, top-down
---


# Question
Title: Is there a practical reason for saving game data in %UserProfile%\Documents instead of %AppData%?
My documents folder is flooded with subfolders of various games, including those of some very recent AAA titles. As a professional application developer with no experience in the gaming industry this is just plain wrong, these files belong into %APPDATA% or %LOCALAPDATA%.

My question is, is there a conscious decision to put these files in %UserProfile%\Documents to gain some specific benefits, or is this just legacy behavior that carried over from the days of Windows XP? Or is there an even better reason like, e.g. Steam requiring or recommending this, or a popular engine doing this by default?

Related: In which directory to write game save files/data? (to avoid pointless discussions)

# Answer
Looking at my disk, I have

* 1 game that saves savegames in `%APPDATA%`
* 1 game that saves savegames in `%LOCALAPPDATA%`
* 2 games that save "other stuff" in `%APPDATA%`
* 3 games that save "other stuff" in `%LOCALAPPDATA%`
* 2 games that save savegames in `%UserProfile%\Saved Games`
* 21 Games that save savegames and loads of other stuff in `%UserProfile%\Documents`, not counting...
* 15 Games that save savegames and loads of other stuff in `%UserProfile%\Documents\My Games`

That's a ratio of 1:9 for savegames being stored in `%APPDATA%`, `%LOCALAPPDATA%`, `%UserProfile%\Saved Games` versus `%UserProfile%\Documents\*`. In my sample, all 4 games that don't put savegames in `%UserProfile%\Documents\` or `%UserProfile%\Documents\My Games\` are from tiny studios. So I have to assume the big studios with multi-million development costs have a reason for putting all their files - including temp files - in `%UserProfile%\Documents\*`.

While legacy behavior can explain some of this, I don't think it is a strong enough reason to account for *every major studio* putting their files in the wrong place. So there has to be better reason.

The best reason I can think of is **to reduce cost of customer support**. The problem is that `%APPDATA%` and `%LOCALAPPDATA%` are hidden directories, and nobody seems to know about `%UserProfile%\Saved Games`. Placing the files in `Documents`, studios can save money on support calls that ask how to backup savegames, or how to migrate the savegames from one machine to another. Examples of users who couldn't find savegames because they were located in `%APPDATA%` here, here, here, and here.

Another reason might be **because users ask for it**, as happens in this example.
> 19 votes

# Answer
No, not really.

Game developers have not traditionally been great at respecting the conventions established by an operating system. Although to be fair, lots of regular application developers don't either.

The `%AppData%` and documents folders are for saving per-user data. The difference between them, for the purposes of this question, is primarily that `%AppData%` is where stuff the user should not need to see or interact with goes, and the documents folder is for the *user's documents*: stuff they'd want to see and interact with.

Games will sometimes store their settings and save files in the documents folder because it makes them visible, so less technical users will see them and be reassured that they do exist, or will be more likely to correctly back them up if their backup method is a crude, "copy the stuff in my user folder to another drive."

Games will also sometimes store files there because they haven't changed the behavior of the relevant code from older OS versions, as you suspect, or simply because they don't care to think about the problem that much.

It's silly and usually wrong, but it is what it is.
> 36 votes

# Answer
I don't care to recall the number of games I've had to start over after a backup/restore or similar thing because I moved all my important files from my documents, but totally forgot about user application data such as save files because it's often in with the program files or other weird places (like in a hidden folder such as appdata).

Personally for this reason I like having it in my documents, although I'm sure someone will tell me to just get a proper backup system instead of doing it manually.

A little consistency would be nice, and even nicer would be for services like Steam to keep copies of save files on a network somewhere.
> 5 votes

# Answer
From my own personal experience, I chose to save into %UserProfile% because the user always had read/write/modify access to it without having to change any of the permissions.

This was not true with %APPDATA%. Particularly when using Restricted user accounts, you often don't have write access to files created by other accounts inside %APPDATA%. I imagine the AAA titles made the choice for the same reason as us; we didn't want the headache.
> 0 votes

# Answer
From my personal perspective as a user, I primarily distinguish between data I want backups of and data where I don't care about it.

Creating incremental backups of `%LOCALAPPDATA%` is a mess, because it will clutter the backup with tens of thousands of temporary files, many of which are locked by background services. This makes backups slow (high overhead from many small files), and unnecessarily big (frequently changing temporary files sabotage the "incremental" part). Preventing this requires manually maintaining an exclusion list.

`%APPDATA%` is slightly better, as it isn't supposed to contain *temporary* files such as caches - sadly it does anyway, and a lot of the program settings really don't warrant a backup.

Ultimately, save games are a type of data I *want* to interact with as a user, and the `%UserProfile%\AppData` doesn't lend itself to that.
> 0 votes

# Answer
You're joking right? Most people don't even know of the existence of appdata folder, as it's hidden and not meant to be accessed by the user. So how do you expect people to move their save files as they do a clean reinstall of Windoes or move to a new computer? With documents, it's easy - "hey, since I won't use this computer anymore I'd better move my documents files to the new PC" But with appdata... heck even me, knowing about it I don't wanna bother with that folder or I plain forget to move files from it and lose my saves in the process. appdata is THE WORST place to store game save files.
> -1 votes

# Answer
Why not use /"game installation folder"/savegame/ as did older games ? I never understood why put savegames in hidden folder or even in my documents on system drive ?

In the old days you always knew where savegames were.
> -3 votes

# Answer
It is a disreputable practice to not allow one to choose the directory that the saved games get stored in upon installation, just as it is to not allow the user to choose the installation directory (like some games don't). -Notice the period there? PERIOD!
> -4 votes

---
Tags: windows, savegame
---


# Question
Title: LibGDX - My sprite glitches when it moves
My player sprite glitches when it moves across the screen. I've tried multiplying movements by delta time. I've tried rounding. It seems to do this completely at random. Sometimes I can move it all the way across the screen and its fine, other times it glitches and twitches the entire way.

```
@Override
public void render(float delta) {
    //update the camera
    camera.update();

    //clear the screen with black
    Gdx.gl.glClearColor(0,0,0,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    //update the renderer and render
    renderer.setView(camera);
    renderer.render();

    //update players movement on x-axis and apply gravity and increase x-axis speed if the player is jumping
    if(player.movingLeft)
        player.movement[0] -= Math.round(player.playerSpeed * delta);
    if(player.movingRight)
        player.movement[0] += Math.round(player.playerSpeed * delta);
    if(player.movingUp)
        player.movement[1] += player.playerSpeed * delta;

    //handle jumping
    if(player.isJumping) {
        if(player.jumpCurrentY < player.MAX_JUMP_DURATION) {
            player.momentum = 0;
            player.jumpSpeed++;
            player.movement[1] = player.jumpSpeed;
            if (player.jumpSpeed > 5)
                player.jumpSpeed = 5;
            player.jumpCurrentY++;
        } else if(player.hangTime < player.MAX_HANG_TIME) {
            player.momentum = 0;
            player.hangTime++;
            player.movement[1] = 2.8f;
        } else {
            player.isJumping = false;
            player.jumpCurrentY = 0;
            player.hangTime = 0;
            player.jumpSpeed = 0;
            player.momentum = gravity;
        }
    } else {
        player.jumpCurrentY = 0;
    }

    updateSprite(delta, player, player.movement, collidableTiles);

    //set sprite batch projection matrix and draw to the screen
    game.batch.setProjectionMatrix(camera.combined);
    game.batch.begin();
    player.draw(game.batch);
    game.batch.end();

    //reset player movement
    Arrays.fill(player.movement, 0);

    //increment player momentum by gravity and assign it to the players y-axis movement
    player.momentum += gravity;
    player.movement[1] = player.momentum;
    player.momentum += -1;
    if(player.momentum < -5)
        player.momentum = -5;

    //TEMPORARY
    camera.position.set(Math.round(player.getX()), Math.round(player.getY()), 0);

}

```

# Answer
> 7 votes
It happens because you update the camera's position out of sync with the `player`'s position.

In `public void render(float delta)` in `LevelOne` you start by updating the `camera`'s transform by calling `camera.update`, but you really want to do this **after** you've calculated the new position of the player.

If you change around your code to first calculate the new positions of the player, then call the `updateSprite` method and then call `camera.update` the glitching will go away.

Or in code, change your `LevelOne` `render` method to:

```
@Override
public void render(float delta) {

    //clear the screen with black
    Gdx.gl.glClearColor(0,0,0,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    //update players movement on x-axis and apply gravity and increase x-axis speed if the player is jumping
    if(player.movingLeft)
        player.movement[0] -= Math.round(player.playerSpeed * delta);
    if(player.movingRight)
        player.movement[0] += Math.round(player.playerSpeed * delta);
    if(player.movingUp)
        player.movement[1] += player.playerSpeed * delta;

    //handle jumping
    if(player.isJumping) {
        if(player.jumpCurrentY < player.MAX_JUMP_DURATION) {
            player.momentum = 0;
            player.jumpSpeed++;
            player.movement[1] = player.jumpSpeed;
            if (player.jumpSpeed > 5)
                player.jumpSpeed = 5;
            player.jumpCurrentY++;
        } else if(player.hangTime < player.MAX_HANG_TIME) {
            player.momentum = 0;
            player.hangTime++;
            player.movement[1] = 2.8f;
        } else {
            player.isJumping = false;
            player.jumpCurrentY = 0;
            player.hangTime = 0;
            player.jumpSpeed = 0;
            player.momentum = gravity;
        }
    } else {
        player.jumpCurrentY = 0;
    }

    updateSprite(delta, player, player.movement, collidableTiles);
    //TEMPORARY
    camera.position.set(Math.round(player.getX()), Math.round(player.getY()), 0);
    //update the camera
    camera.update();

    //update the renderer and render
    renderer.setView(camera);
    renderer.render();

    //set sprite batch projection matrix and draw to the screen
    game.batch.setProjectionMatrix(camera.combined);
    game.batch.begin();
    player.draw(game.batch);
    game.batch.end();

    //reset player movement
    Arrays.fill(player.movement, 0);

    //increment player momentum by gravity and assign it to the players y-axis movement
    player.momentum += gravity;
    player.movement[1] = player.momentum;
    player.momentum += -1;
    if(player.momentum < -5)
        player.momentum = -5;
}

```

---
Tags: java, libgdx
---


# Question
Title: How to create a box collider that surrounds an object and its children?
I have a car that needs a box collider.

If the car were 1 single mesh, I would only need to call:

```
        boxCol = gameObject.AddComponent<BoxCollider>();

```

and it would create a `BoxCollider` that perfectly fits my car, based on my car's mesh.

Now I have a car which consists of many different parts in the transformation hierarchy. (For example: the body of the car is the parent of the 4 doors. Every door is a separate game object, and has a doorknob child, etc.)

Now I need a script that changes the `BoxCollider` so that its box surrounds the whole car, including all of these parts.

I found this pose on Unity Answers, but it just doesn't get me the right collider.

Here is the code I'm using:

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

public class ColliderToFit : MonoBehaviour
{

    [MenuItem("My Tools/Collider/Fit to Children")]
    static void FitToChildren()
    {
        foreach (GameObject rootGameObject in Selection.gameObjects)
        {
            if (!(rootGameObject.GetComponent<Collider>()  is BoxCollider))
                continue;

            bool hasBounds = false;
            Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);

            for (int i = 0; i < rootGameObject.transform.childCount; ++i)
            {
                Renderer childRenderer = rootGameObject.transform.GetChild(i).GetComponent<Renderer>();
                if (childRenderer != null)
                {
                    if (hasBounds)
                    {
                        bounds.Encapsulate(childRenderer.bounds);
                    }
                    else
                    {
                        bounds = childRenderer.bounds;
                        hasBounds = true;
                    }
                }
            }

            BoxCollider collider = (BoxCollider)rootGameObject.GetComponent<Collider>();
            collider.center = bounds.center - rootGameObject.transform.position;
            collider.size = bounds.size;
        }
    }

}

```

# Answer
> 4 votes
I found out that the Boxcollider I get from the solution above was only expanding the bounds of all the children while leaving out the gameObject itself aswell as all other descendants, and it only delivered the right solution for position and rotation 0, and scale 1, which confused me at first.

here is the code that will surround the gameobject and every descendant: (keep in mind that you need to set the position and the rotation to 0 and the localScale to 1 and to get the right Collider. Just store the old transform variables somewhere and then set them to 0 (and scale to 1) , then change the collider (call this script), then set the transform variables back again) . Have fun!

```
public void addBoundsToAllChildren()
{
    if (boxCol == null)
    {
        boxCol = gameObject.GetComponent(typeof(BoxCollider)) as BoxCollider;
        if (boxCol == null)
        {
            boxCol = gameObject.AddComponent<BoxCollider>();
        }
    }
    Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
    Renderer thisRenderer = transform.GetComponent<Renderer>();
    bounds.Encapsulate(thisRenderer.bounds);
    boxCol.offset = bounds.center - transform.position;
    boxCol.size = bounds.size;

    allDescendants = gameObject.GetComponentsInChildren<Transform>();
    foreach (Transform desc in allDescendants)
    {
        Renderer childRenderer = desc.GetComponent<Renderer>();
        if (childRenderer != null)
        {
           bounds.Encapsulate(childRenderer.bounds);
        }
        boxCol.offset = bounds.center - transform.position;
        boxCol.size = bounds.size;
    }
}

```

# Answer
> 3 votes
A modified version of @OC\_RaizW answer for BoxCollider2D (only children taken into account, not self):

```
public void addBoundsToAllChildren()
{

    var boxCol = gameObject.GetComponent<BoxCollider2D>();
    if (boxCol == null)
    {
        boxCol = gameObject.AddComponent<BoxCollider2D>();
    }

    Bounds bounds = new Bounds(transform.position, Vector3.zero);

    var allDescendants = gameObject.GetComponentsInChildren<Transform>();
    foreach (Transform desc in allDescendants)
    {
        Renderer childRenderer = desc.GetComponent<Renderer>();
        if (childRenderer != null)
        {
            bounds.Encapsulate(childRenderer.bounds);
        }
        boxCol.offset = bounds.center - transform.position;
        boxCol.size = bounds.size;
    }
}

```

# Answer
> 1 votes
I had the same issue, hopefully, this will help somebody someday.

##### First, get all possible mesh renderers:

```
var renderers = gameObject.GetComponentsInParent<Renderer>().ToList();
renderers.AddRange(gameObject.GetComponentsInChildren<Renderer>());

```

##### Set the center of initial bounds to the position of the parent object and size to zero, and then encapsulate every mesh:

```
var bounds = new Bounds(transform.position, Vector3.zero);
foreach (var r in renderers)
{
    bounds.Encapsulate(r.bounds);
}

```

##### Add the collider to the parent object and set the size and center for the collider, keep in mind the assumption here is that the position of the object is 0:

```
var spaceCollider = gameObject.AddComponent<BoxCollider>();
var c = spaceCollider.center;
spaceCollider.center = new Vector3(c.x, c.y + bounds.size.y / 2, c.z);
spaceCollider.size = bounds.size;
spaceCollider.isTrigger = true;

```

# Answer
> -1 votes
Maybe I'm misunderstanding the question, but why don't you just go into Unity and create the Box Collider and make it the right size you want? As opposed to trying to create it in code. As long as all the other components are a part of the car, it will surround them too.

---
Tags: unity, c#, bounding-boxes, meshcollider
---


# Question
Title: Unity Animation (2D) - Cannot drag sprite into animation
I am trying to create animations for my sprite which are configured to the "Multiple" option. When I try to drag the sprite into the timeline for the animation it won't do anything. It will just go back into the folder like nothing happened. I don't know if this is normal or there is a problem.

Thank You.

*EDIT* \- First I created a 2D animation, I gave it a name, docked and locked the animation then tried to drag the sprite into the timeline and didn't let add components nor drag the sprite i spliced.

# Answer
> 2 votes
TLDR; Create animations by creating a game object with an animator use the animation window to create a new clip.

I believe this to be a bug\* in Unity. I have had this issue multiple times before, and have quit working early in frustration with it on multiple occasions.

If you create an animation (Animation Clip) through the project browser context menu you cannot drag and drop sprites into it. However; if you create the animation through an animation on a game object you are able to drag sprites into it.

\*Animation clips created through the context menu have different inspector properties than ones created through the animation ui as well. Though from what I can they have identical content/metadata except that the ones created through the animation UI have loop time defaulted to 1.

---
Tags: unity, 2d, animation
---


# Question
Title: Why do some 2D games like Hollow Knight and Ori use 3D Unity instead of 2D?
What are the advantages of using 3D in Unity that you don't get with 2D?

I am creating a 2D game like Hollow Knight and Ori. When would I use 3D Unity and when do I use 2D?

Would the graphics be clearer or more realistic if 3D was used instead of 2D in making a 2D game?

# Answer
Someone literally asked the same question a few years ago on Reddit.

Basically, there's no real 2D environment in Unity. It's the same 3D engine but with a different perspective (to this day, it seems that Unity still doesn't have a true 2D environment). Also, the Parallax effect (the '*moving backgrounds*') it's easier to achieve on a 3D scene due to the depth (Z axis).

Edit: Oh, forgot about your other question, oops!

> when do I use 3d unity and when do I use 2d?

Again, there's no difference in the way Unity renders your game, however, there IS a difference in the components you use in your game. By components, I mean: colliders, physics, camera settings, etc.

Basically, if you're going to make a 2D game, choose 2D mode (even though the game will be rendered as 3D). 2D components are optimized for, well, 2D. If you're going to a 3D game, then choose 3D.

In fact, these modes (3D and 2D) are just pre-configured settings for different environments. This means that you could create a 3D project, and turn it to 2D if you wanted to, or vice versa.
> 2 votes

---
Tags: unity, 2d
---


# Question
Title: How to rotate a sphere on its axis with a tilt?
How can I simulate a planet's rotation on the Z axis but tilted x° ( similar to how the Earth's rotation axis is tilted 23° relative to its orbit).

I know with Euler angles I'll meet some gimbal lock issues, so I'm looking for a quaternion solution.

This video illustrates what I'm trying to do.

EDIT :

Ended up doing something like that in my update :

```
SpinAngle += deltaTime * Speed;
Quaternion rotationAboutAxis = Quaternion.Euler(0, SpinAngle, 0);
Quaternion tiltOfAxis = Quaternion.Euler(0, 0, TiltAngle);
transform.rotation = tiltOfAxis * rotationAboutAxis ;

```

Where TiltAngle is in degree :) Thanks !

# Answer
You can just compose the quaternions.

```
// Rotate by spinAngle degrees about our local z+ axis.
var rotationAboutAxis = Quaternion.Euler(0, 0, spinAngle);

// Tilt the object's z+ spin axis by tiltAngle on the parent/world x+ axis.
var tiltOfAxis = Quaternion.Euler(tiltAngle, 0, 0);

transform.rotation = tiltOfAxis * rotationAboutAxis;

```

Put whatever rotation you want to be "more local" to the right side of the multiplication, and whatever rotation you want to be "more global" to the left side.
> 1 votes

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


# Question
Title: Where can I find sources on how many people play with sound disabled/enabled?
This is probably more a problem with me being unable to find statistics which i am absolutely certain must exist in some form: How many people play with the sound off/on when playing browser games or very casual mobile games. Because in my experience: nobody, but that is too subjective.

The question i want to answer for myself: Is it worth adding sounds to my game. But I dont want to base that decision off of my personal experience (sound is always off), but rather some cold hard fact.

They must exist somewhere, someone must have compiled that data, but I cant find it anywhere...

# Answer
> 2 votes
I just happened to run across 73% of mobile play **with** sound (a bit old but probably a decent starting point). https://toucharcade.com/2013/11/05/73-of-mobile-gamers-play-with-the-sound-on/

My own game, Six Ages, has over 80% of music on (I only track the iOS build, so it might be different on PC).

# Answer
> 1 votes
I think you're underestimating the importance of sound in a game, especially sound effects.

To some, sound can add immersion, or tension, that usually applies to the music and enviromental sounds, if immersion is not what you want, then it's understandable why that would be turned off.

But sound can also give feedback to what's happening.
Imagine adding a sound just to hitting/destroying a target. You no longer have to focus on the unit if is hit/destroyed, but you can now also hear that it hits.
And that kind of feedback applies to a lot of things: shooting, charged shots, running out of ammo, Critical Hits, Combo's, getting hit, well-timed moments, ect.

Even if it's not something that would apply to you, it's certainely going to be worth adding for those who do play with sound. Implementing sound effects like these makes it prehaps the feature that makes your game feel 'alive'.

It's perhaps not an answer towards "Where can I find stats on how many users play with sound?",
but more towards your other question: "Is it worth adding sounds to my game?"

---
Tags: game-design, audio, browser-based-games
---


# Question
Title: I made a quest in Creation Kit. Testing it, Quest Log and Quest Marker do not appear. Why is that, and how do I fix this?
**I made a quest in Creation Kit. Testing it, Quest Log and Quest Marker do not appear. Why is that, and how do I fix this?**

I have made a **quest object** in Creation Kit, including stages, quest log ("diary") and actors (filled in as aliases). When I started the game, I see via "**sqv questname**" in console (*show quest variables myquest*) that my quest successfully started. I see a stage, perhaps not the latest I wanted to set. However, NPCs (initially disabled) do not spawn, and / or my quest markers and my quest log do not update /appear at all. What is the problem? My Quest fragments seem logic (in the stages), and I cannot find any issues with my dialogue, scenes, objectives and conditions? *(So, no errors in second tab "quest fragments", third tab "objectives", "dialogue tab" and "scene tab").*

# Answer
# Description:

*This issue occurs often when you are new to making quests and you want to get it running. However, when you test your quest in-game, it does not start, so it seems. I have seen a few posts online where people asked why their quests would not run in-game, but no specific response to it outside the lengthy tutorials. So here is the fix straightforward.*

# Fix:

1. First, make sure that your stages are being set. Type in console (^) "**SetStage (YourQuestName) (x)**" ;x being the stage number, example: SetStage SAtm\_MQ01 0.This should start your quest even if you have issues and for some reason, it does not start.If you did everything perfectly and you check-marked "Start game enabled" it should run automatically, though.
2. Now, you can check if the log, the quest marker, and the quest objective did update.
3. If your quest objective did not update, the way you set stages (stage fragment or trigger box or dialogue fragment or custom script or alias script) does not work. So this is the first thing to fix. You want to be able to run from stage to stage and see it, add a Debug.Notification("Stage x+1 was set!") for yourself to confirm this in-game.
4. Now, since your quest stages are being set correctly, you can tackle the aliases. In fact, if your quest log and quest markers did not update, but your stages run already, you know that the alias had not been filled correctly. Type in console (^) "**sqv (YourQuestName)"**, (show quest variables) and see if your quest is running, which stage it is, and more importantly what aliases are being filled. If you see **(youraliasname) -\> None** then it was not filled. And here, this will help you:
    1. Set **ALL** your Aliases to optional in your CreationKit / Quest Object / Quest Aliases tab.
    2. Check **ALL** your actors to have "persistent locations". Click on their reference objects placed in the game in the render window, and under "persist location" choose a nearby location like "WhiterunLocation".

This made all the actors fill the aliases and thereby my quest was now automatically running when starting the game without console commands as it should, and I saw my quest log and got the quest markers. Sometimes, you come back to Creation Kit implementation after months or even years and you oversee an actor and you think "it should still work without this one actor being set up correctly" but I have experienced that it does not, so this minor detail is very important. Best of Luck! :)

**Attention01: Do not overdo persistent actors. I would avoid setting NPCs to persistent when it's not necessary. This makes them loaded at all times. Persistence location should be fine for NPCs that are only stationary or only move outside their hometown as part of a quest. I here only used the NPCs during a quest. Thanks, Elscrux, for pointing that out!**

**Attention02: Story Manager Quests cannot be debugged this way. Thanks, Elscrux, for pointing that out!**

# Disclaimer:

1. *I do not take any responsibility for missing files or broken games, I just share the approach in best faith, with the goal of helping you to find the solution yourself, at your own risk.*
2. *Thank you to everyone working with me on Creation Kit contents, especially Elscrux, Woni, and Tascani. This is mostly a fix for starters, anyone who knows their way around CK is probably aware of this method by logic.*
3. *This post was made by me before on reddit here:https://www.reddit.com/r/skyrimmods/comments/rpoh0z/quest\_log\_and\_quest\_marker\_not\_appearing\_fix/ I replicated it for documentation and allowing people to find these contents, like my other posts*.
> 1 votes

---
Tags: modding, editors, skyrim-modding
---


# Question
Title: How to calculate camera view matrix from world transform, specifically the orientation?
In my engine, camera is just any other object in the scene. It has a transform -- position, rotation (quaternion), and scale (ignored for camera view matrix). I want to convert this to the camera's view matrix. I tried the following formula (currently, there is no rotation) but for some reason, the position in the X axis is incorrect:

```
mat4 cameraTransform = translate(identity, transform.position) * to_mat4(transform.rotation); // rotation is quaternion

auto viewMatrix = inverse(cameraTransform);

```

Camera's transform (from perspective of a generic lookUp camera for testing purposes):

Camera's view:

The issue here is that, the camera's position is somehow flipped. The camera is positioned to look in the X direction (the red axis line); however, from camera's view matrix, it is looking in the Z direction (blue axis line). The thing is, from the looks of it, the camera's position is actually correct (I counted the grid boxes on the ground). The problem is that, it is rotated. I can't seem to figure out why. There is currently no rotation (`(0,0,0)` in euler angles).

How should I calculate this? Also, what does the view matrix represent in terms of what valeus are in the matrix? Does it represent where the camera is looking at or where the camera actually is?

# Answer
> 1 votes
The view matrix represents the transformation you need to apply to a point in the world to get it into camera space — a space where the camera is the origin, the x+ axis points to the right of the camera's view, the y+ axis points to the top, and the z+ axis points forward in the direction the camera is looking (or the z- axis, depending on your coordinate system).

Your strategy of inverting the camera's world matrix looks correct to me. That's how it's usually done.

I think the problem is that you've drawn your camera gizmo as though it looks along its x axis. That is, when unrotated, it looks along the world x+ or x-.That departs from the more common convention your rendering code is using, which assumes the camera's z axis should be it's look direction.

So, rotate the marker graphic you draw for your camera to match the perspective you observe when looking through that camera, and you should have it behaving correctly from there.

---
Tags: camera, matrix, transformation, view
---


# Question
Title: JS 2D top down movement doesn't act as expected
I realise this is very similar to other 2D movement questions already posted but cant find a solution that fits the behaviour I'm looking for, so I'm posting in the hope that someone more knowledgeable than myself can give me a nudge in the right direction.

Here goes:

I have an object that I am moving round a canvas. This object always faces the cursor position and accelerates to a maximum speed when the mouse is held. now the issue I have is when implementing the movement of the object. I want the object to slowly loose velocity when no longer accelerating and to slowly change direction based on the acceleration and direction (imagine a boat going at top speed then hitting reverse instantly, I want it to slow to a stop before going in the other direction) so far I have logic along these lines in my code (simplified for ease of debugging, swapped in constant values instead of references):

```
velocityCalculation() {
    //thrust
    if (_thrust> 0) {
        _velocity.x += mouseMagnitude.x * (_thrust * 0.1);
        _velocity.y += -mouseMagnitude.y * (_thrust * 0.1);
    }

    if (_velocity.x != 0)
    {
        //drag
        _velocity.x += -Math.sign(_velocity.x) * 2;

        //cap velocity
        if (_velocity.x > 100) _velocity.x = 100;
        else if (_velocity.x < -100) _velocity.x = -100;
        if (_velocity.x < 2 && _velocity.x > -2) _velocity.x = 0;
    }
    if (_velocity.y != 0) {
        //drag
        _velocity.y += -Math.sign(_velocity.y) * 2;

        //cap velocity
        if (_velocity.y > 100) _velocity.y = 100;
        else if (_velocity.y < -100) _velocity.y = -100;
        if (_velocity.y < 2 && _velocity.y > -2) _velocity.y = 0;
    }
}

```

where mouseMagnitude is a normalised vector pointing towards the cursor, thrust is the current acceleration (probably named badly, I have no clue the correct terminology). Now if I place the cursor just off axis the object begins accelerating and moving normally however after reaching the correct direction of the mouse(shown as white arrow) it continues accelerating until its travelling diagonally (shown as red, objects velocity = 100x,100y) instead of in the direction of the mouse. I'm sure I'm missing something simple but how do I make the object continue travelling in the direction of the mouse instead of diagonally?

# Answer
> 1 votes
Your issue is that you're clamping the x and y components of the velocity independently. So once the x value hits 100, it saturates. Meanwhile, if the mouse is still above the object, the y value keeps accelerating, until it also hits 100 and saturates.

What you've done is clamp the velocity vector to a square shape. That means there are only 8 stable states for the velocity when it's accelerating:

* the 4 corners of the square, which are stable equilibria: once the velocity gets into one of theses 45-degree corners of (±100, ±100), as long as the acceleration vector is anywhere in a 90-degree span, the velocity will stay pinned in that corner.
* the centers of the 4 edges of the square, which are unstable equilibria: if the acceleration has even a tiny magnitude in the perpendicular direction, the velocity will slide along the edge of the square to the corresponding corner.

What you really want to do is clamp the velocity to a circle:

```
let speed = Math.sqrt(_velocity.x * _velocity.x + _velocity.y * _velocity.y);

let reducedSpeed = Math.max(0, Math.min(100, speed - 2));

_velocity.x *= reducedSpeed / speed;
_velocity.y *= reducedSpeed / speed;

```

By applying our limits and deceleration to the magnitude of the vector, instead of to each component separately, we ensure the effect is radially-symmetric, and affects vectors in all directions equally. No more corners in our clamping function.

Also, bonus: less code, with more sensible behaviour near zero.

---
Tags: 2d, javascript, movement
---


# Question
Title: Copyright/trademark protections of character classes
I want to create a game that uses character classes from World of Warcraft. Are the classes protected by copyright/trademark law? For instance WoW has a Warlock class that is essentially a spell-caster focused in dark magic and summoning demons.

# Answer
> 2 votes
During the planing and design of your game, I suggest you do a bit of research.

For instance, a simple search for "Warlock" in my favourite search engine leads to Wikipedia which shows that the concept of warlocks dates back to long before WoW was created. Even Heroes of Might and Magic had Warlocks in 1995, long before WoW.

Often, game designers will not try to *invent* new terms, they'll use something that exists before that players recognize easily.

IANAL, but it's safe to say that these *terms* are not copyrighted, nor trademarked. Just keep in mind that you should come up with original skills and features; you may get on a more slippery slope if you also intend to "borrow" the skills and features offered in another game.

---
Tags: legal
---


title: Measuring RTT for my network game?

text:
# Question
Title: Measuring RTT for my network game?
I'm building networked racing game right now. I'm using winsock with TCP/UDP socket and IOCP.

I'm having trouble with latency masking and I don't even know if my implementation is wrong.

So, I'm measuring latency between client and server with tcp packet. Server gives tcp packet with current time to client first and then client send back another tcp packet containing time value that received from server, and server would calculate the latency by `(current_time - time_sent) / 2`.

But as far as I know, tcp packet transfer time can be different every time based on network traffic and packet lose.

So, I'm wondering if I should use UDP packet for latency measure.

Can anyone give me advice for this one?

# Answer
> 1 votes
It's irrelevant. You don't need to know how long "a packet" takes, you need to know how long **that** packet took. As you mentioned, you can have random latency spikes. Maybe your measurement packet didn't get delayed but then your actual game packet did. You need to be prepared for any packet to arrive late.

If your game has tight timing requirements then switching to UDP could be a better choice. You will still have to deal with latency spikes, because UDP packets are not immune to delay. They are just immune to delay caused by packet loss and retransmission. (The tradeoff is that you have to deal with the packet loss yourself)

If you want the *average* latency, then you should calculate the average of several measurements.

# Answer
> 0 votes
You really only want to use TCP if you're making a multiplayer browser game. In this case, you need to figure out the median of the RTT because, as you said, some packets can get stuck in network traffic. The median can help you get rid of the anomalous values of the curve and get a more realistic view of the player's latency.

But if you're using UDP, you can do this easily as DMGregory mentioned.

---
Tags: networking
---


title: Rotate Sprite towards mouse cursor SDL

text:
# Question
Title: Rotate Sprite towards mouse cursor SDL
I have trouble to make my sprite(Arrow) to point at the position of my mouse cursor but i don't get the Right results. I've tried this:

```
SDL_Point Center{ 40,40 };
int Delta_x; int Delta_y;
int mouse_x, mouse_y;
double Result;
SDL_GetMouseState(&mouse_x, &mouse_y);
Delta_x = xPos - mouse_x;
Delta_y = yPos - mouse_y;

Result = (atan2(Delta_x, Delta_y) * 180.0000)/ 3.14159265;
m_Sprite->Render(Result, Center);

```

RendercopyEx:

```
SDL_RenderCopyEx(m_Renderer, m_Texture, NULL, &m_Rect, Angle , &Center, SDL_FLIP_NONE);

```

This is the result I get (in the original picture, the arrow is pointing up):

# Answer
> 2 votes
`atan2` expects the Y parameter first. See this SO question for answers as to why the Y parameter is passed in first.

# Answer
> 2 votes
```
void LookAt(Vector2 p2)
{
    int DeltaX;
    int DeltaY;
    double result;
    DeltaX = position.x - p2.x;
    DeltaY = position.y - p2.y;
    result = (atan2(-DeltaX, DeltaY) * 180.00000) / 3.141592;
    angle = result;
}

```

This is how I did it, position being the position of the object that needs to be rotated angle being the angle of the object, The negative x in the y's place actually worked perfectly,its pretty much the exact same as yours just make the DeltaX negative, I dont know if it will work for you but it was perfect for me BUT I have no idea why it works haha.

---
Tags: c++, rotation, sdl
---


# Question
Title: Setting a border around a unity 2d tile map
I've a procedurally generated hex tilemap, which is larger than the bounds of the screen (when not zoomed out). What I want to do is create a border around the tilemap.

The tilemap is a child of a Canvas object, because I want to be able to write text to the map. What I've done is place a UI panel as a parent of the hex grid, then added a nine-slice image as a background to the panel. Once the tilemap has been generated, I resize the UI panel using the local bounds of the tilemap. Have tried resizing the panel - borderImage in the code below - various ways (including ContentSizeFitters and HorizontalLayouts on the UI panel) with no success. The image just shows up as a small rectangle in the bottom left-hand corner of the screen.

```
Bounds bounds = map.localBounds;
RectTransform uiTransform = borderImage.GetComponentInParent<RectTransform>();
//uiTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, bounds.max.x);
//uiTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, bounds.max.y);
//uiTransform.localScale = new Vector3(bounds.max.x, bounds.max.y, 0);
uiTransform.sizeDelta = new Vector2(bounds.max.x, bounds.max.y);

```

Placing the border image on the canvas gives me a border around the screen, but what I want is to have the border around the edges of the tilemap.

Thanks in advance for suggestions about how to solve this problem.

# Answer
OK, so the answer to this problem is actually pretty simple (perhaps the reason nobody bothered to reply).

First create a new sorting layer - background - and move it above the default sorting layer. Then create a new empty game object called Background, setting the transform position to match the position of the canvas which contains the Tilemap, minus whatever offset you want to use to display the border. Then add a Sprite Renderer component with your border sprite as sprite.

Finally, add your Background game object to whatever object is handling the Tilemap generation. As soon as the Tilemap has been generated, just modify the size of the background image to the size of the Tilemap plus the offset for the border to display.

```
Bounds bounds = map.localBounds;
Vector3 worldMax = bounds.max;
SpriteRenderer backgroundSprite =
    borderImage.GetComponent<SpriteRenderer>();
backgroundSprite.size =
    new Vector2(worldMax.x + BorderOffset, worldMax.y + BorderOffset);

```
> 0 votes

---
Tags: unity, tilemap
---


title: How to Implement ECS Archetypes in C#?

text:
# Question
Title: How to Implement ECS Archetypes in C#?
I'm trying to figure out how to implement a simple ECS with an Archetype approach, similar to what Unity's ECS uses.

An archetype is just a category for entities that have a specific set of components.

Let's say I had three components, `A`, `B`, and `C`, and I had the following systems:

* System 1 (Archetype requires component `A`)
* System 2 (Archetype requires components `A` and `B`)
* System 3 (Archetype requires components `A` and `C`)
* System 4 (Archetype requires components `A`, `B`, and `C`)

Because components could be added and removed from entities on the fly, an entity switches archetypes whenever a component is added or removed.

I'm not quite sure what these archetype collections are supposed to look like. They must be arrays of some kind, but I'm not sure how to store and organize components in them that belong to a specific entity.

My question is, what would this look like in pure, vanilla C# code?

And could generics also help with this?

# Answer
> 2 votes
Those Archetypes are `IEnumerable<TComponentKind>`, where `TComponentKind` is what you use to identify components. You can, of course, do better than that. For example, they could be `TComponentKind[]`, or `HashSet<TComponentKind>`. `TComponentKind` could be `string`, `Type` or even `int` (and you use bit flags to identify components, in which case the Archetype is also `int`). Or you might come with something else. That depends on how you implement your ECS.

---

I have a toy ECS that should give you some idea of how to go about this: https://github.com/theraot/Theraot.ECS \- You may download the code an play with it. Please read design decisions on the readme. After all, you are going to have to make your own take on those decisions for your custom ECS.

My toy ECS has the particular quirk that it lets you provide an implementation for custom `TComponentKind`. Which is likely not something you want in a ECS you use in production. But it means that the code is rather agnostic to that decision, which - I hope - makes for a good case study.

# Answer
> 3 votes
Here is a sketch of how you can implement an archetype in C#:

```
class Archetype {
    System.Type[] _componentTypes;
    System.Array[] _components;

    int _capacity;
    public int Count { get; private set; }

    public Archetype(int capacity, params System.Type[] componentTypes) {

        _capacity = capacity;
        _componentTypes = componentTypes;

        _components = new System.Array[componentTypes.Length];
        for( int i = 0; i < componentTypes.Length; i++) {
            _components[i] = System.Array.CreateInstance(componentTypes[i], _capacity);
        }
    }

    public T[] GetComponentsArray<T>() {
        int index = System.Array.IndexOf(_componentTypes, typeof(T));
        if (index < 0) return null;
        return (T[])_components[index];
    }
}

```

Note that adding and deleting entities or disabling them is elided from the sketch above - the chat thread I wrote it for has more discussion of the pros and cons of different strategies to use there.

So if I want to create an archetype for entities that have a `Transform`, `SpriteRenderer`, and `AudioSource` component, with room for 200 such entities at a time, I'd write:

```
var noisySprites = new Archetype(
                          200,
                          typeof(Transform),
                          typeof(SpriteRenderer),
                          typeof(AudioSource)
                   );

```

And it will create the necessary internal arrays. Here we're representing your elements in SoA or Structure of Arrays layout, so there's no one patch of memory that corresponds to the entity as a whole. Instead, each entity is an index. Entity #0 has its `Transform` component at `noisySprites.GetComponentsArray<Transform>()[0]`, and its `SpriteRenderer` component at `noisySprites.GetComponentsArray<SpriteRenderer>()[0]`, etc.

This might look strange if you're used to AoS or Array of Structures layout, but this approach can actually give you significant performance wins. If your components are all `struct` types, then the instances of each component type will be laid out contiguously in memory. So if you have a system that cares about only 2 of the 3 components in a given archetype, it can iterate over a densely-packed array of each of those types, without having to skip over every third item. Every bit of data that's pulled into cache gets used, so you make optimal use of the caching and prefetching mechanisms to hide memory latency.

A system in this form might look something like this:

```
public class SpriteRenderingSystem : System {

    // On start-up, query for the kinds of archetypes we need to work on.
    // This way any search/indexing can be done up-front and cached.
    public void Initialize(ArchetypeCollection collection) {
        _signature = collection.GetComponentSignature(
                        typeof(Transform),
                        typeof(SpriteRenderer)
                     );
    }

    public void Update(ArchetypeCollection collection) {
        // Iterate over each archetype matching the
        // Transform + SpriteRenderer component signature.
        foreach (var archetype in collection.GetArchetypesWithSignature(_signature)) {
            // Get the packed arrays of components we care about.
            Transform[] transforms = archetype.GetComponentsArray<Transform>();
            SpriteRenderer[] sprites = archetype.GetComponentsArray<Sprite>();

            // Iterate over all active entity indices and do our work.
            for (int entity = 0; entity < archetype.Count; entity++) {
                RenderSprite(transforms[entity], sprites[entity]);
            }
        }
    }
}

```

Note that we pay any search costs and cache misses for getting the right arrays just once per archetype that we want to iterate over, and then all memory access for each entity is linear and contiguous from there (again, assuming your components are `struct` types), so you get efficient iteration for the things you're doing hundreds or thousands of times, and the overhead in the archetype handling is more manageable since you likely have just dozens of those, or a small handful that any one system needs to act on.

---
Tags: c#, entity-system, component-based, entity-component, entity-component-system
---


# Question
Title: Oculus Quest: How to disable casting, video recording, screenshots
How can I disable casting, video recording (video capture), and taking photos (screenshots) when developing an Oculus/Meta Quest game.

Answering my own question after spending hours googling.

# Answer
> 1 votes
According to this:

> It is important to note that the sharing features such as casting, video recording (video capture), and taking photo (screenshots) are enabled for your apps, by default. To disable any sharing features, go to Sharing, select an app, and from the Enabled Features list, clear the checkbox for the features you do not prefer to share, and click Save.

This will work for all platforms, Unity, Unreal, native apps.

---
Tags: unity, oculus
---


# Question
Title: How to format bespoke struct, so that it appears like Vector3 in Unity Editor inspector?
I have a bespoke struct, which has XYZ variables just like Vector3, but unlike Vector3, the inspector does not display them neatly and horizontally. I have tried to read documentation and copy Vector3 to no avail. Please tell me how to make my custom struct display XYZ in the inspector exactly like Vector3. Below is a screenshot from the Unity editor to show the difference ("Test" is a Vector3, Position is my own class).

# Answer
As Zibelas noted, you can use a custom property drawer. However, let's analyze *why* you are making a custom struct with the same fields as a `Vector3` (or **why you probably shouldn't**).

If your struct functions exactly the same as a `Vector3` (or `Vector3Int`), there's no point in using it over `Vector3`, since Unity's APIs make extensive use of `Vector3`.

If your struct behaves like a `Vector3` but adds *new functionality*, you should strongly consider using extension methods or helper functions instead. For example, let's imagine you want a way to swap the X and Y values for some reason. One way to do this is with extension methods:

```
public static class ExtensionMethods {
    public static void SwapXY(ref this Vector3 v3) {
        float temp = v3.x;
        v3.x = v3.y;
        v3.y = temp;
    }
}

```

This adds a new function to `Vector3` which we can use like any other function! Note that I used the `ref` keyword because `Vector3` is a value type and in this example we're modifying the original value.

```
Vector3 test = new Vector3(1, 2, 3);
test.SwapXY();
Debug.Log(test); //(2.0, 1.0, 3.0)

```

Alternatively, we can use static helper functions:

```
public static class Vector3Helpers {
    public Vector3 SwapXY(Vector3 value) {
        return new Vector3(value.y, value.x, value.z);
    }
}

```

So when *should you* consider creating your own struct?

* **To make the struct immutable**. `Vector3` is mutable (its fields can be changed after it is created). Mutable structs are generally discouraged in C#, but Unity makes extensive use of mutable structs for debatable reasons I won't get into here.
* **For type safety**. For example, if a function argument expects a position and you want to be sure you don't accidentally pass in a `Vector3` representing euler angles, you could make a `Position` struct that's otherwise identical to `Vector3`.
* If you want to **change how `Vector3`'s existing functions work** (I can't think of any reason you'd want to do this)
* If you want to **add new fields**, or implement other new functionality that can't be accomplished with extension methods.
* **To make the struct serializable**. That doesn't directly apply here because `Vector3` is *already* serializable, but standard structs built into C# like `TimeSpan` are not compatible with Unity's serialization system.
* **To change the precision** (e.g. use doubles instead of floats)
> 1 votes

---
Tags: unity
---


# Question
Title: D3D11 CreateInputLayout error: CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE
I created a simple shader, and it compiled, but when using the vs as input layout, it failed with `CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE`. I don't know why.

Here is the shader:

```

struct appdata
{
    float3 vertex : POSITION;
};

struct v2f
{
    float4 vertex : SV_POSITION;
    float2 uv : TEXCOORD0;
};

 v2f VSMain (appdata v)
 {
    v2f o;
    o.vertex = float4( v.vertex, 1);
    o.uv = float2(0.0,0.0);
    // o.uv = v.uv;
    return o;
 }

Texture2D _MainTex : register(t0);

SamplerState MeshTextureSampler : register(s0);

float4 PSMain (v2f i) : SV_Target
{
    // fixed4 col = tex2D(_MainTex, i.uv);
    // fixed4 col = _MainTex.Sample(_LinearClamp, i.uv);
    //fixed4 col = _MainTex.Sample(MeshTextureSampler, i.uv);
    float4 col ;
    col = float4(1.0, 1.0, 0.0, 1.0);
    return col;
}

```

Here is the InputLayout code:

```
HRESULT PreviewWindow::CreateBlitPSO(int shaderSourceLength, const char* shaderSource) {
    HRESULT hr;
    ComPtr<ID3DBlob> vs = nullptr;
    hr = CompileShader(shaderSourceLength, shaderSource, "VSMain", "vs_5_0", vs);
    if (FAILED(hr)) {
        return hr;
    }
    auto vsLength = vs->GetBufferSize();
    hr = m_pDevice->CreateVertexShader(vs->GetBufferPointer(), vsLength, nullptr, m_vs.ReleaseAndGetAddressOf());
    if (FAILED(hr)) {
        LogFormat("Create vertex shader from blob failed! hr = %08x\n", hr);
        return hr;
    }
    ComPtr<ID3DBlob> ps = nullptr;
    hr = CompileShader(shaderSourceLength, shaderSource, "PSMain", "ps_5_0", ps);
    if (FAILED(hr)) {
        return hr;
    }
    hr = m_pDevice->CreatePixelShader(ps->GetBufferPointer(), ps->GetBufferSize(), nullptr, m_ps.ReleaseAndGetAddressOf());
    if (FAILED(hr)) {
        LogFormat("Create pixel shader from blob failed! hr = %08x\n", hr);
        return hr;
    }
    D3D11_INPUT_ELEMENT_DESC ied[] = {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    };
    int length = _countof(ied);
    hr = m_pDevice->CreateInputLayout(ied, length, m_vs.Get(), vsLength, m_input.ReleaseAndGetAddressOf());
    if (FAILED(hr)) {
        //d3d11 debug layer reports "CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE" here
        LogFormat("create input layout failed! hr = %08x", hr);
        return hr;
    }
    return hr;
}

```

The shader file is saved using the western Windows-1252 code page, I also tried UTF8, but the result is the same.

# Answer
> 1 votes
```
hr = m_pDevice->CreateInputLayout(ied, length, m_vs.Get(), vsLength, m_input.ReleaseAndGetAddressOf());

```

The `m_vs.Get()` should be `vs->GetBufferPointer()`.

So I misinterpreted the `CreateInputLayout` signature.

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


title: Do a quiz from web api data

text:
# Question
Title: Do a quiz from web api data
i'm new to unity and i want to do a quiz using data coming from a web api

I was able to retreive data from the api but i couldn't make the game logic with them

This is where i arrived

```
    private IEnumerator GetRequest()
{

    UnityWebRequest response = UnityWebRequest.Get(apiUrl);

    yield return response.SendWebRequest();

    if (response.result == UnityWebRequest.Result.ProtocolError)
    {
        response = null;
    }

    else if (response.result == UnityWebRequest.Result.ConnectionError)
    {
        response = null;
    }
    else
    {
        var quest = JsonConvert.DeserializeObject<QuestionResponse>(response.downloadHandler.text);
        if (quest.documents.Count >= 0)
        {
            currentQuestion = Random.Range(0, quest.documents.Count);
            QuestionTxt.text = quest.documents[currentQuestion].fields.q.stringValue;
            Ch1Txt.text = quest.documents[currentQuestion].fields.ch1.stringValue;
            Ch2Txt.text = quest.documents[currentQuestion].fields.ch2.stringValue;
            Ch3Txt.text = quest.documents[currentQuestion].fields.ch3.stringValue;
            Ch4Txt.text = quest.documents[currentQuestion].fields.ch4.stringValue;
        }
        else
        {
            GameOver();
        }
        }
    }

```

# Answer
> 0 votes
Here is a rough breakdown how I would make a quiz game.

First divide the responsibility. Currently your request that gets the data is as well handling the display. To adapt it easier, I would first create a `GameManager`, `GameLogic` or however you want to name it. This should handle

`GameManager`

* Holding the questions
* Knows which answer is right
* How many question were right/ wrong

`UIManager`, `DisplayManager`, etc

* User can choose an answer
* User gets displayed right/ wrong answer
* Pointdisplay

`DataManager`

* Loads questions

The UIManager does not know which answer is right or wrong. It just tells your GameManager: The Player picked Answer 1. Now it is the responsibility of the GameManager to check if that is right or wrong and just tells the UIManager back: That was correct. Or wrong. Your GameManager does not care how you want to display this to the player. Your DataManager is just loading the questions. As you have done this already with a WebService, nothing to add. But they could be as well just stored in a json file on your device. Or a database. Later you can swap the DataManager for something else and just pass the questions to the GameManager. This means, the GameManager does not care at all from where your questions are coming. It just wants the questions.

If you plan your game ahead, it will make it easier to make changes later as well. Change how the questions should be displayed? Your UIManager is the correct place. Nothing needs to be done on the actual logic. You have new features? Like a 50/ 50 joker etc. Adding to the GameManager and handle the logic there, telling the UIManager what should be removed.

This can be later made than as well easily in a network game where your GameManager is on your server and the player can't just cheat with seeing the answer in your UIManager. Or how you get the questions. Or from where.

# Answer
> 0 votes
This is my answer script, the thing that i want to do is to relate both together

```
  public void Answer()
{
    if (isCorrect)
    {
        GetComponent<Image>().color = Color.green;
        Debug.Log("Correct Answer");
        theQuiz.correct();
    }
    else
    {
        GetComponent<Image>().color = Color.red;
        Debug.Log("Wrong Answer");
        theQuiz.wrong();
    }
}

```

---
Tags: unity, databases, json
---


# Question
Title: How to call an invoke repeating when a bool is true and canceling when it isn't?
I'm trying to make my player launch an object every 3 seconds when a bool is true but I can't `InvokeRepeating` in `Update`, `Awake`, or `Start` without losing control of the function. How can I do this?

# Answer
> 0 votes
Here's one way to do it:

```
bool _shouldDoThing;
Coroutine _periodicAction;

IEnumerator DoThingPeriodically() {
    var delay = new WaitForSeconds(3f);

    while(true) {
        if (_shouldDoThing) {
            DoTheThing();
            yield return delay();
        } else {
            yield return null;
        }
    }
}

void Start() {
    _periodicAction = StartCoroutine(DoThingPeriodically());
}

```

This will call `DoTheThing()` once every three seconds (approximately) while the boolean is true. When the boolean is false, it will fall back to waiting until it is true again, then calling `DoTheThing()` immediately when it goes back to true if it's been at least three seconds.

If you ever want to stop the action, you can call `StopCoroutine(_periodicAction)` to abort it.

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


# Question
Title: How to set the camera projection matrix so that its 4 rays always exactly hit the corners of a defined rectangle?
I have a camera, and I have a rectangle drawn in an arbitrary plane.

I need to change the projection matrix of the camera so that the rays along the edges of the camera's frustum always hit the corners of the rectangle.

The camera and the rectangle are supposed to be movable, rotatable, and the rectangle can be scaled.

Usage:

I am making a stereo-3D game with eye tracking, where my 2 eye vectors hit the exact same parallax plane.

That parallax plane is defined, and we have the corners of the display rectangle in that plane.

# Answer
What I understand is that you are trying to create a non-stereoscopic background to represent a very far view in the background in a stereoscopic view.

I would try creating a multi-camera setup instead of adjusting the main camera.

* Set the Display in Game view to match your 3D viewer target resolution. Create a new one if no option for stereoscopic views (e.g. 1080x1080).
* Create two additional cameras and two new layers for the background of each eye. (Background-LeftEye and RightEye).
* Set the `Culling Mask` of each camera to render only one of those layers.
* Set the `Depth` of each camera less than the Depth of your main camera.
* Target each camera only to one eye, left and right.
* Create two new `Canvas` for background for each eye.
* Set the `Layer` of each Canvas to your new layers respectively.
* Set `Canvas Render Mode` to `Screen Space - Camera`.
* Set `Render Camera` to your background cameras.
* Set `Plane Distance` to something that makes it work comfortably in your Scene view.
* Create an `Image` inside each Canvas and set its width and height to match your resolution (e.g. 1080x1080).
* Suggested use prefabs so that you don't need to setup everything twice.

I didn't build and test this on a VR viewer but you can use this as a starting point.

* It may be possible to achieve the same with a single background camera.
* I think you may instead use `Render Texture` instead of creating canvases.

As for the technique you ask, you can try raycasting and field of view instead of setting a projection matrix:

## Monoscopic view:

Assuming the rectangle is static from your last comment, you should be able to do it with raycasting on app start. I'll first propose a solution for monoscopic view, then extend to stereoscopic view.

* Set the display resolution canvas aspect ratio to the same as your rectangle.
* Make the rectangle child of the camera.
* Position the rectangle so that the camera is perpendicular to the rectangle and looking at its center (not applicable to stereoscopic view as both cameras will be non-perpendicular).
* Set a sufficiently large `fieldOfView` so that the whole rectangle is visible but not touching the edges.
* Start casting rays from screenspace to worldspace from the corners of your plane.
* Reduce `fieldOfView` until you get a raycast hit, preferably from all four corners.

## Stereoscopic view:

For that you need two additional background cameras similar to the Screen Space Camera solution, each with a rectangle as a child (preferably from the same prefab, otherwise cameras in the build will not be perpendicular to the rectangles.

Use a render texture if you want to modify the image rendered in each plane.
> 1 votes

---
Tags: unity, camera, projection, projection-matrix
---


# Question
Title: Using C# summary documentation as tooltip in Unity
In unity, I often end up with duplicating the tags for code documentation, and the \[tooltip\] tags for the Unity Inspector.

Is there a way to automatically extract tags into Unity \[tooltip\]s, or vice versa?

```
    /// <summary>
    /// This field sets the whirlygigs speed.
    /// </summary>
    [Tooltip("This field sets the whirlygigs speed.")]
    public float value;

```

# Answer
There is a plugin in the asset store doing the exact same: https://assetstore.unity.com/packages/tools/utilities/comment-to-tooltip-120659#description
> 1 votes

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


# Question
Title: Detect Collisions While Dragging 3D Game Object
Hello i am making a game in which i have to drag a sphere on x axis and z axis on a plane with my mouse and i have created walls from cubes so that my sphere not go anywhere else in the game but while dragging my sphere is not detecting collisions with the wall i also added rigidbody but nothing is working ths is my code thanks

```
using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour
{
    Rigidbody r;
    private void Start()
    {

        r = GetComponent<Rigidbody>();

    }

    void OnMouseDrag()
    {

        float distance_to_screen =
Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
        Vector3 pos_move = Camera.main.ScreenToWorldPoint(new
Vector3(Input.mousePosition.x, Input.mousePosition.y,  distance_to_screen));
        transform.position = new Vector3(pos_move.x, transform.position.y,
pos_move.z);

    }

  }

```

# Answer
This is an old thread, but maybe someone wants to do the same..

I found a nice way on the internet to do this:

This thread

https://forum.unity.com/threads/collision-detection-while-dragging-object.182493/

links to this video

https://www.youtube.com/watch?v=ZfjVR-0ZFHU

which explains a solution.

If you don't want to watch or read too much:

Basically you should stop setting the transform, because this cancels physics!

This is all you need:

```
private void Update()
{
    rb.velocity = (getWorldPosition() - transform.position) * followSpeed;
}

private Vector3 getWorldPosition()
{
    lastMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    lastMousePos.z = 0;
    return lastMousePos - offset;
}

private void OnMouseDown()
{
    lastMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    lastMousePos.z = 0;
    offset = lastMousePos - transform.localPosition;
}

```
> 2 votes

# Answer
Because you're using transform.position you're basically teleporting your object around, so it's possible it will be able to teleport into or through a wall without any problem.

You can still detect collisions using the OnCollision event, as this will be triggered when your object rematerialises, but the physics engine won't stop the objects intersecting.

If you want your movement to be limited by physics, you need to use something like either Rigidbody.MovePosition or Rigidbody.AddForce
> 1 votes

# Answer
As @JeffUK points out my mistake a have changed the code a bit

```
public class Ball : MonoBehaviour
{
    public float speed = 10f;
    Rigidbody r;
    private void Start()
    {
        r = GetComponent<Rigidbody>();
    }

    void OnMouseDrag()
    {
        float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
        Vector3 pos_move = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
        // here we are adding force on X and Z axis and i put normalized so the magnitude will be 1
        // It will prevent the super fast moving of the ball
        r.AddForce(new Vector3(pos_move.x, 0f, pos_move.z).normalized * speed * Time.deltaTime, ForceMode.VelocityChange);
    }

    private void OnMouseUp()
    {
        // it will stop moving the ball as soon as you lift the left mouse button up
        r.velocity = Vector3.zero;
        r.angularVelocity = Vector3.zero;
    }
}

```

I also add the float called speed, you can tweak its value to get your desired speed.

Now the only problem we have is the ball will not move to the mouse pointer, but it will gradually follow it.

And yes this time i have tested it myself. :)
> -1 votes

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


# Question
Title: Matrix math: How to specify camera distance so that an object with a given size is completely visible?
This is my code that draws a top down view tile based map. But Iam do not know how high the camera needs to be placed in the sky so that the map is fully visible so that nothing is cut away and I do not see any borders at the screen border.

I tried to use the formula "tan(angle) = a/b" where "angle" I guess is my FOV (45 degrees) and "a" my screenwidth and "b" the wanted height but it did not return the correct result. Is this the correct formula or can the problem lie somewhere else?

```
        float aspectRatio = graphicsDevice.Viewport.AspectRatio;
        float fieldOfView = MathHelper.ToRadians(45);

        //var height = camera.WindowSize.X / MathF.Tan(FieldOfView); // this does not give the right result
        float height = 2410; // found out experimentally, todo how to calculate this?
        var camPos = new Vector3(camera.ScaledWindowSize.X * 0.5f, camera.ScaledWindowSize.Y * 0.5f, height);
        var camTarget = camPos;
        camTarget.Z = 0;

        float nearClip = 0.1f;
        float farClip = 10000.0f;

        var mProjection = Matrix.CreatePerspectiveFieldOfView(
            fieldOfView,
            aspectRatio,
            nearClip,
            farClip);

        var mView = Matrix.CreateLookAt(camPos, camTarget, Vector3.Up)
            * camera.GetViewMatrix()
            * Matrix.CreateScale(1, -1, 1);

```

# Answer
> 1 votes
If your field of view is measured from the bottom of the frustum to the top, then at a distance d your frustum is h units tall, where:

```
h = 2 * d * tan(fieldOfView/2)

```

So you can solve this to get d:

```
d = h / (2 * tan(fieldOfView/2))

```

If your field of view is measured from the camera's forward axis to the top of the frustum (half the angle) then use `tan(fieldOfView)` instead of `tan(fieldOfView/2)`. Unfortunately both conventions are in use in different engines/libraries, and the documentation is often less explicit than it could be about which one to expect.

---
Tags: 3d, mathematics, matrix, projection
---


# Question
Title: How can I achieve a similar look to this "2.5D"-ish art style?
Recently I came across a game concept (New Game Plus @ Superflatgames) that used a very interesting "2.5D" art style where the world is in 3D and the characters & objects are in 2D (see image below).

I've experimented on and off for about a week now but I can't for the life of me replicate this camera angle/perspective and look. At first, I thought that this was as simple as doing a 3D world and having the characters in 2D but the 3d part looks really off. I then tried "tweaking" the 3D world in different ways such as tilting the 3D tiles away from the camera, because if you look at the top-left structure in the image it looks *slightly* tilted in the direction the camera is looking. But none of my experimentation thus far has yielded any results.

Does anyone have any ideas on how to replicate this? I know this art style exists in other games so maybe someone has implemented this before.

(Note that I am **not** asking about the pixel art look; that is simply 2D pixel art textures on 3D objects).

Here is a picture of my latest attempt with the tilted tiles compared side-by-side with this image. As you can see, my tiles almost seem to tilt at a different angle. Unfortunately, I can't show all of my attempts as I haven't saved any screenshots of those.

If I put the camera higher and tilt it down a bit more, it's closer to the "PoV" of the original image, but as you can see on the very bottom grass tiles they are *super thin*, compared to the original image where the sides of the tiles are almost completely visible (almost as if they are tilted towards the camera).

# Answer
I tried to replicate the scene in Unity, so I'm using its reference system but this solution can be adapted for any other development environment as well.

This is the camera setup I used:

* **Position:** `(0, 13, -20)`, offset relative to the object the camera is following.
* **Rotation:** `(30, 0, 0)`, looking slightly downwards over the scene.
* **FoV:** `30` degrees.

Rotation is in degrees. The position values are based on the assumption that the level consists of blocks of 1 world unit in size:

While world blocks are placed normally around the scene, 2D objects such as characters, foliage and trees must take camera orientation into account. They must behave like billboards and align with the camera plane.

If the camera only moves and never rotates, this can be simply done by tilting 2D objects the same amount as the camera in the same direction, so that they will align to the view plane. They won't be affected by perspective distortions, apart from the apparent size due to distance from the camera:

This is the final result I got, I think it's very close to the original style you posted (assets by Buch):
> 10 votes

---
Tags: camera, art
---


title: How to implement rollback

text:
# Question
Title: How to implement rollback
From what I've read, there's several components which go into rollback netcode and requirements.

1: Your game logic update (input/state update) has to be able to run independently of your rendering (draw stage/textures/etc) I think 7 times as fast?

2: The connections need to run over UDP p2p.

So my first question is, if my game draw is updating at once every 60 frames, does that mean my game logic, input, network read, has to update once every 8-9 fps?

And I imagine the loop looks something like this?

```
if(framecount%8==0){

pollnetwork();
updategamestate();
input = checkinput();
 if(input){
  sendinputacrossnetwork(input);
 }
}
if(framecount%60==0){
render();
}

```

I imagine the order in which those are called is irrelevant.

So I have that in place, but where do I go from there?

Do host and peer first have to synchronise gameframes? Then every time a packet is sent between the two, they have to check what frame they're currently on, which frame they received then rewind and replay?

For example, if host is on frame 18 then won't the client frame when received be on frame 9? Because it's always updating, say 9 frames. And if the server receives client's frame 9, we go back 9 frames and redraw everything from 9 frames ago to the current state depending on what the user provided as inputs?

There's a lot I don't understand about rollback netcode and I've read a lot too but there's small implementation details that I can't figure out. I might even be missing the bigger picture.

Edit: To give more info on this, I'm doing this in C++. I'm not using a game engine, rather writing it myself in SDL with GLFW and my own network library. And in my case the state should never change during the time of the render, it's all running on one thread. And since my network function returns instantly whether or not a packet is available, I dont' have to rely on callbacks.

I have my logic update decoupled from my draw rendering. So I can separate the two.

But I think I understand it now, if I have it correct:

I have an input structure and a frame stack. Assume the frame is currently at 30

```
30:[peer input: null][my input: x]
29:[peer input: null][my input: y]
28:[peer input: null][my input: null]
27:[peer input: null][my input: null]
26:[peer input: null][my input: null]

```

Now I receive a packet with frame# 27 and an input x, because I'm already on frame 30, I now have to rewind my frames back to frame 27, inserting an input x and assume that they're going to keep pressing x until I receve a frame that says otherwise; So I rewind the framestack and insert the x where it belongs while leaving my input untouched

```
30:[peer input: x][my input: x]
29:[peer input: x][my input: y]
28:[peer input: x][my input: null]
27:[peer input: x][my input: null]
26:[peer input: null][my input: null]

```

Now I run the logic loop 4 frames simulating the state as if they had pressed x each of those frames? Then I finally draw?

# Answer
> 1 votes
First up, the state of your game should be decoupled from your rendering.

The rendering loop should query the game state and display it on screen.

A separate loop (sometimes called a physics tick) is where you handle changes to the scene.

Many physics engines require consistent time steps between iterations, and other background tasks (like AI) shouldn't be impacted by how good the user's graphics card is.

Depending on what you're doing, this may require a little coordination (thread signalling) to ensure the game state isn't changing at the same time as the renderer is trying to display it.

You haven't specified what technology/engine/language you're using, nor the specific problem you're trying to solve, so let's pick an example and say there's a log rolling down a hill.

By default, the log will roll until it hits a door and breaks it.

It's possible for a player to shoot at the log and divert it.

You server has a physics tick every *n* milliseconds.

In that tick you calculate the movement of the log due to known forces.

If you receive a packet saying "the player fired at this spot at time X", you need to:

* "Rewind" the simulation to the first tick that would've been impacted by the event
* Add the physics effect from the shot to the simulation
* Run the simulation forward to the present time \[possibly re-processing every intervening tick\], being sure to handle all other player input you've received so far.
* Do it all quickly enough that it's not perceptible.

How exactly you do this is implementation- and use-case specific.

Some systems save state data for the last *n* ticks, so they can just discard everything since then and start from a known good state (can be memory intensive and puts a hard limit on how late packets can arrive).

Others have a physics simulation that can be run in reverse deterministically, so they can run time backwards and forwards without the simulation becoming unstable.

Yet others use clever algorithms to invalidate/recalculate only those physics objects potentially impacted by the event, cascading the calculations as needed.

However you do it, when you've worked out the world state, you update it in memory and the render picks it up. The log will appear to teleport from where it was to where it should be.

---
Tags: networking
---


# Question
Title: How to connect rockets to a space capsule?
I am trying to create a space capsule that has four rockets to balance the capsule.

The rockets and capsule have`Rigidbody2D` and `BoxCollider2D` components attached. The rockets have a script that calls `rbody.AddForce()` when the relevant key is pressed. Rockets are child objects of the capsule object.

But it is not working because rockets are separating when the capsule is rotating.

I added joints to connect the capsule and rockets, but this time the capsule stopped rotating.

I've tried to use all joint types, but I could not find a suitable joint. The objects are 2D. I guess that a script can be coded that changes the rotation of the capsule and its position based on calculations, but if it is possible, I want to not calculate this manually.

How can I create a game object that is used for adding force, and combine these objects with another object?

# Answer
> 1 votes
I would not give the rocket nozzles their own rigidbodies. I would instead attach them as children to the main rocket rigidbody so the whole thing becomes one single physics object. Then I would have the rocket nozzles use `rigidbody2d.AddForceAtPosition` in order to add forces not acting directly on the center of mass of the rigidbody but acting on the position of the respective nozzle.

Here is an example script. Put this on the "nozzle" game objects. **Do not** add a Rigidbody2D to the nozzles. Parent them to the rocket with the Rigidbody2D. The force is applied at the center of each nozzle and the x axis (red arrow) is the direction in which the force gets applied. Then set the desired thrust intensity and the key to control each nozzle in the inspectors of the nozzles.

```
using UnityEngine;

public class RocketNozzle : MonoBehaviour {
    private Rigidbody2D rb;
    public float thrust; // thrust power
    public KeyCode key; // keyboard key to activate thrust

    void Awake() {
        rb = GetComponentInParent<Rigidbody2D>();
    }

    void FixedUpdate() {
        if (Input.GetKey(key)) {
            var thrustVector = -transform.right * thrust;
            rb.AddForceAtPosition(thrustVector, transform.position, ForceMode2D.Force);
        }
    }
}

```

# Answer
> 0 votes
If you connect the rockets to the capsule with a `FixedJoint2D` and call

```
rbody.AddForce(new Vector2(rocketPower, 0))

```

in the rocket's script, it will work well.

Be sure to not tick any constraints, and set gravity scale zero.

---
Tags: unity, c#, 2d, physics
---


# Question
Title: The vector aiming to enemy is in wrong direction
In a 2d game, I am trying to shoot at a moving enemy and the vehicle that is shooting is also moving. However, the velocity of the bullet is not in the same direction as the position of the enemy. The bullet starting position is the position of the vehicle.

**My Code**

```
bullet_enemy_vec = self.world.enemy[0].pos - self.vel
        bullet_enemy_vec_new = self.vel + bullet_enemy_vec
        self.vel = bullet_enemy_vec_new
        self.vel.normalise()
        self.vel = self.vel * self.speed

```

# Answer
Subtract position, not velocity.

```
self.vel = self.world.enemy[0].pos - self.pos
self.vel.normalise()
self.vel = self.vel * self.speed

```
> 1 votes

---
Tags: physics, vector, python
---


title: Using MaterialPropertyBlock with tiles

text:
# Question
Title: Using MaterialPropertyBlock with tiles
I would like to make it so if the cursor enter a tile, it becomes "higlighted" (slightly whitened), like the left tile below.

I'm quite new to Unity, and after reading an article from Thomas Mountainborn (http://thomasmountainborn.com/2016/05/25/materialpropertyblocks/) I managed to do this with a simple shader on an `Object`, and changing a parameter in a `MaterialPropertyBlock` when the mouse enter or quit its collider.

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

public class Highlight: MonoBehaviour
{
    [SerializeField]
    private float baseHighlightFactor;

    private Renderer _renderer;
    private MaterialPropertyBlock _propBlock;
    private float _highlight;

    void Awake()
    {
        _propBlock = new MaterialPropertyBlock();
        _renderer = GetComponent<Renderer>();
        _highlight = 0;
    }

    private void Update()
    {
        // Get the current value of the material properties in the renderer.
        _renderer.GetPropertyBlock(_propBlock);
        // Assign our new value.
        _propBlock.SetFloat("_hooverFactor", _highlight);
        // Apply the edited values to the renderer.
        _renderer.SetPropertyBlock(_propBlock);
    }

    private void OnMouseEnter()
    {
        _highlight = baseHighlightFactor;
    }

    private void OnMouseExit()
    {
        _highlight = 0;
    }
}

```

I wondered if I could do the same with tiles, but with scriptable tiles I can't seem to do it, since the Renderer is a component of the Tilemap and not the Tile itself.

Am I going the wrong direction? I would not like to duplicate each sprite (highlighted/not highlighted) since I have a lot of them. I guess I could use `Objects` instead of `Tiles`, but `Tilemap` properties could be useful for other parts of my project.

# Answer
> 1 votes
Although tilemap is a whole, it can get the corresponding sprite through the mapping of world coordinates and grid coordinates.

Code:

```
using UnityEngine;
using UnityEngine.Tilemaps;

public class NewBehaviourScript : MonoBehaviour
{
    public GridLayout gridLayout;
    public Tilemap tilemap;
    private Vector3Int pLast;
    void Start()
    {
    }
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
        if (hit.collider != null)
        {
            Vector3Int p = gridLayout.WorldToCell(hit.point);
            if (p == pLast)
            {
                return;
            }
            if (tilemap.HasTile(p))
            {
                tilemap.SetTileFlags(p, TileFlags.None);
                tilemap.SetColor(p, Color.green);
                if (tilemap.HasTile(pLast))
                {
                    tilemap.SetColor(pLast, Color.white);
                }
                pLast = p;
            }
        }
    }
}

```

As for `MaterialPropertyBlock`, Basically it's a performance optimized way. It saves memory by having multiple spriteRenderers share a common material instance. In tilemap, This is already handled internally, you don't need to worry about it.

---
Tags: unity
---