# Question
Title: How can you sync video files with animations within Unity?
I'm wondering if anyone might be able to offer some advice regarding an issue I am currently facing in trying to sync video files with animations within Unity.

Ideally my aim is to have a video file play whilst an animated camera (exported from blender) moves in sync with the rendered video file. I've nearly got this working, however there is a very slight delay between the two in which at certain points (quick rotations of the camera) the animation lags behind the video.

I have attempted to solve this issue by creating a script in which for every frame of the video, the animation component is accessed and the animation file frame set to its equivalent time with regards to the video player position. To do so I made use of 'animationState.normalizedTime' (mapping the video frame from its current position to a value of 0 - 1, so as to fit within the requirements of the normalized time function).

I'm also trying to make use of 'videoPlayer.frameReady' in order to set the animation with each new frame, with the idea being to try to only set the animator once a new frame is displayed.

The result I'm currently getting is that the animation is linked to the playback of the video, and will match up regardless of speed of playback, however there are parts in which the animation does not match up to the video. These are particularly noticeable when the camera makes a sudden movement, or when it is rotating. My current thoughts are that perhaps this could have something to do with camera easing settings (from blender to unity) or with the animation component settings. I've tried to remove animation compression and keyframe reduction, however am still having these issues unfortunately.

Does anyone have any ideas as to how this might be solved?

I've included my code below :

```
public class animationSync1 : MonoBehaviour
{

    // Animation component
    private Animation animator;

    // Video player (add via inspector)
    public VideoPlayer vp;

    // total frame count of video
    private float totalFrame;

    // current video frame
    private float currentFrame;

    // animation frame count
    private float animationFrame;

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

        // Animation component
        animator = GetComponent<Animation>();

        // get total number of frames from video file
        totalFrame = vp.frameCount;

        // start video playback
        vp.Play();

        // begin playback of animation
        animator.Play("Camera_entrance|Camera_entranceAction");
        // set animation speed to 0 in order to set the animation frame point manually in fixed update
        animator["Camera_entrance|Camera_entranceAction"].speed = 0f;

    }

    // Use of fixed update to call 30 times a second (to try to match up to video and animation playback)
    void FixedUpdate()
    {

        // get current video frame
        currentFrame = vp.frame;

        // get frame count between 0 - 1 from current video frame
        animationFrame = currentFrame / totalFrame;

        // set the animation position to that of the current video frame
        animator["Camera_entrance|Camera_entranceAction"].normalizedTime = animationFrame;

    }
}

```

# Answer
I think checking the frameReady event is the way to go. I managed to solve my stuttering issues by updating the camera animation every time the video frame had changed. In my case I was updating every frame anyway, so i didn't bother subscribing to the frameReady event.

I just checked the previous frame against the current one and updated the camera position then redrew my backplate quad that was drawing the video.

I'll test to see if there is better performance from using the frame ready event as well. But currently this seems to work fine for me as the video frame rate is well below my update frame loop.

The following code snippet works for me ;

```
    void Update()
    {
        float current_video_time = (float)videoplayerObj.time;
        if (current_video_time != previous_video_time)
        {
            Mesh mesh = planeObj.GetComponent<MeshFilter>().mesh;
            //enamble camera animation
            cameraAnimObj.Play();
            cameraAnimObj["Take 001"].time = myTimeoffset + (float)videoplayerObj.time;
            previous_video_time = current_video_time;
            //force camera position update
            cameraAnimObj.Sample();
            //stop camera animation
            cameraAnimObj.Stop();
        }
    }

```
> 1 votes

---
Tags: unity, animation, video
---


# Question
Title: How to create game database editor interface like Age of Empires' AGE
Age of Empires had this powerful AGE (Advanced Genie Editor) tool to let players mod the game data with ease. You could see all the game's databases through this tool and play with them to make your own mods in a pretty straightforward way, which I suppose was also used by the devs themselves to author their data.

I was wondering how can I implement a similar editing interface for my game database?

Are there tricks like this that Godot, Unity and Unreal users use to author their data? I feel like I missed something because no popular engine seem to support what I'm looking for out of the box.

If I can't do it in-engine, how should I go to make such a tool myself?

# Answer
All the tool does, I'm pretty sure, is unpack some data files (XML serialization is easy to set up), present it to you in a readable format, and pack the files back up again when you hit the save button.

The game then just uses those same data files while running.

AGE looks like it's made with Windows Forms or one of those other standard Microsoft UI development tools, but making a GUI inside Unity or other game engine is definitely possible. Writing a new GUI may be rather time-consuming though, so just storing your data in a format other people have already made editing tools for (spreadsheets can be great, for some things; XML is tolerable) is probably more practical for an indie game.
> 3 votes

# Answer
Unity in particular actually happens to provide some powerful tools for writing editor extensions and to create game-specific asset types (Scriptable Objects). So you can actually create pretty extensive content management tools tailored to your game within the engine itself.

But if your engine doesn't have such powerful customization features, then it can also be worth the time to create editors for your game data files which are completely separated from the engine. This would require that you pick up a technology stack for creating regular Windows UI applications (if you don't already have that know-how on your team).

The options for that are endless. Pretty much every programming language commonly used in game development has at least one UI toolkit in its standard library. Often there are several options to choose from. For example, if you are using C#, then Windows Forms, WPF, and WinUI are just those which are delivered out-of-the-box by Microsoft as part of the .NET Framework.

If you need any help while creating such tools, then stackoverflow will likely be able to help you much better than we would. The expertise for such toolkits is usually far higher among application developers than among game developers.
> 0 votes

---
Tags: gui, databases, modding, tools, workflow
---


# Question
Title: What options are there for developing on the Nintendo platforms?
I know of Wario Ware DIY but is this the only option?

# Answer
> 9 votes
Nintendo supports developers with their DSiWare and WiiWare for people wanting to make a game downloadable through the console or handheld.

The first step is to contact Nintendo to become a licensed developer (http://warioworld.com/). After you've made this important first step then Nintendo will be able to answer all of your questions.

Be prepared that they will want you to demonstrate your ability to make a fully playable game for the platform, as well as information about your company for approval.

# Answer
> 5 votes
You can write your own games from scratch for many of the Nintendo platforms. devkitPro provides devkitARM, which can compile for the Gameboy Advance and the Nintendo DS, as well as devkitPPC, which can compile for the GameCube and the Wii. There are also utility libraries to help you access the hardware.

Running your games is very simple on the GBA and NDS, you simply buy an adapter that will load the compiled games off of a microSD card. It takes a little more work for GameCube and Wii, but it's not too bad.

(Unfortunately as of this post, the devkitpro.org site seems to be in the middle of rebuilding? All the usual download links and info pages seem to be missing, it's just a plain forum.)

# Answer
> 1 votes
There is also Wiiware & You -could- run a homebrew game, but I really don't know much about it.

To develop for Wiiware you have to be approved as a licensed developer for Nintendo. Information on the process can be found here: http://www.warioworld.com/

# Answer
> 1 votes
Unity provides Wii and Wiiware licenses but, I'd imagine they come at a hefty price. Still if you have the cash, it is a great environment to work in.

# Answer
> 0 votes
If you want to do it free, there are three options I know of as of now.

1. The devkitPro toolchain has support for the Wii, GameCube, Switch, 3DS, DS, Gba, GP32, and PSP.
2. You could also you devkitadv which lets you develop for the GameBoy Advance, but no others. DevkitPro never worked for me, sadly. You could also get in through the Nintendo developer portal and Unity. However, that requires you to be 18 years or older. So if you are an enthusiastic teenager who wants to develop games for their 3ds or Wii U, you will not be able to do so through the Nintendo Developer Portal. Speaking of which, that method only supports the 3ds and Wii U at the moment. And when it comes to the 3ds, it also only supports the "New" variant.
3. There is finally, the option to program in a systems native assembly language. This is probably time consuming and less user friendly, but it is probably the most guaranteed to work. I am also not sure how accessible programming in the native assembly language would be. I hoped this gave you or another person some ideas for options when developing for Nintendo systems. I myself have never done it, but I know of a lot of options out there.

---
Tags: nintendo, console
---


# Question
Title: What is the most effective way of managing scene objects states in Unity?
I often see this kind of problem in projects: the scene contains many hierarchical objects that must be in a certain state to work correctly. If a disabled object has to be edited it has to be activated first, and if editing takes a long time it is difficult to remember its original state at the end, especially when there are several objects which states were changed. It leads to hidden bugs. I often take a screenshot of the expanded hierarchy before I start editing but I don't think this is a solution, it's more a method of minimizing the consequences.

So how to manage this problem correctly or what approaches you could recommend?

# Answer
> 1 votes
My solution to this problem is usually to have scripts which make sure that their children are in the correct activation state as soon as the game starts. For example, if I have an UIManger with several sub-objects representing windows of which only one should be open at game start, then the UIManager's `Start()` method would call `SetActive(false)` on all its children and then `SetActive(true)` on the main menu.

---
Tags: unity, architecture
---


# Question
Title: How to make a 'Picture-book Cutscene' in Unity 2D with simple 2D images?
I'm trying to implement a simple cutscene system in my Unity game, preferably one that allows cutscenes to play at the start and end of each of the levels.

What I was imagining was pretty similar to A Hat in Time's 'storybooks' from it's time rifts, but full-screen and advanced with a single key. The images are simple and comic-like, and I was wondering how to implement such a feature since it feels like it's a bit different to Unity's pre-existing Timeline system, as there isn't many moving parts.

How do I go about approaching this problem? At least, I don't know how to get the project to a state where a person can press a key to turn to the next page (whether or not there's a visual transition to the next is optional) and once it's done, to start the actual level/scene. Do I still use the Timeline for this? I know I could potentially use an empty game management prefab in order to set up when to play the cutscenes, however.

# Answer
> 1 votes
Here's a simple script that accomplishes an effect like the one in your video.

Put it on a UI object that's the parent container of your stack of images.

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public class CardStack : MonoBehaviour
{
    [Tooltip("What gamepad/keyboard button action ID should trigger the next card?")]
    public string advanceButton = "Jump";

    [Tooltip("Which image should be in front, starting from zero?")]
    public int cardToShow = 0;

    [Tooltip("How fast to flip cards (in cards per second)")]
    public float flipSpeed = 5f;

    [Tooltip("How many degrees should each card behind the top card rotate?")]
    public float rotationIncrement = -5f;

    [Tooltip("How far should the next card be offset from the top card position?")]
    public Vector2 fanIncrement = new Vector2(15, -15);

    [Tooltip("Where should the top card fly to when we skip past it?")]
    public Vector2 flipAwayOffset = new Vector2(-100, 0);

    [Tooltip("What should happen when we're left with an empty stack?")]
    public UnityEvent OnFinishedStack;

    Image[] _images;
    Vector2 _centerPosition;
    float _currentCard;
    bool _hasFinished;

    // Call this to move to the next card - you can hook this up to a UI button.
    public bool TryAdvance() {
        if(cardToShow >= _images.Length)
            return false;

        cardToShow++;
        return true;
    }

    void Start()
    {
        // Collect all the images inside this parent, ordered from front to back.
        _images = GetComponentsInChildren<Image>();
        System.Array.Reverse(_images);

        // Remember where the lead image is.
        _centerPosition = _images[0].rectTransform.anchoredPosition;

        // Update the display of the rest of the stack.
        Layout();
    }

    // Check input, advance/animate if needed.
    void Update()
    {
        if(Input.GetButtonDown(advanceButton)) {
            TryAdvance();
        }

        // Check if we've reached our target card and can stop animating.
        if (Mathf.Approximately(cardToShow, _currentCard)) {

            // Is our target card the end of the stack?
            if (cardToShow == _images.Length && !_hasFinished) {
                _hasFinished = true;
                Debug.Log("Finished stack!");

                // Fire an event - this way you can trigger sounds, scene changes, etc.
                if (OnFinishedStack != null)
                    OnFinishedStack.Invoke();
            }

            return;
        }

        // We haven't reached our target card, so animate toward that position.
        // This gives a linear slide, which can look mechanical; you can use easing for more juice.
        _currentCard = Mathf.MoveTowards(_currentCard, cardToShow, flipSpeed * Time.deltaTime);
        Layout();
    }

    // Update the layout of the cards for the current animation frame.
    void Layout() {
        // Iterate over all cards in the stack.
        for (int i = 0; i < _images.Length; i++) {
            var image = _images[i];

            // For the top card, t = 0. t = 1 for the next card, etc.
            // t < 0 means it's the card that's being removed from the stack.
            float t = i - _currentCard;

            // Fade out the cards we've removed from the stack.
            var color = image.color;
            color.a = Mathf.Clamp01(t + 1f);
            image.color = color;

            var trans = image.rectTransform;
            // Rotate cards so the current card is upright, and later cards fan out.
            trans.localRotation = Quaternion.Euler(0, 0, rotationIncrement *t);

            // If this is the card we're removing, slide to the flipAwayOffset.
            // Otherwise, shift it slightly from the previous card to fan it out.
            trans.anchoredPosition = _centerPosition + (t < 0f ?
                Vector2.Lerp(flipAwayOffset, Vector2.zero, t + 1f)
                : Mathf.Pow(t, 0.75f) * fanIncrement);
        }
    }
}

```

---
Tags: unity, 2d, gui, cutscene
---


# Question
Title: Procedural mesh comes out black in any shader
I wrote a script that Creates a mesh procedurally

```
        mr = gameObject.AddComponent<MeshRenderer>();
        mf = gameObject.AddComponent<MeshFilter>();
        //
        mf.mesh = new Mesh
            {
                vertices = GetVertices(),
                triangles = GetTriangles()
                uvs = UpdateUVMap();
            };

        //assign material + shader.
        mr.sharedMaterial = new Material( Shader.Find("Shader Graphs/surface") );

```

(the mesh is a sphere for this example)

I created my Shader in shader-graph (any shader seems to have the same result)

When played, all seems good except that the object is black. What's happening?

//basic uv map example from docs

```
    public Vector2[] UpdateUVMap()
    {
        Vector2[] uv = new Vector2[this.vertices.Count];

        for (int i = 0; i < uv.Length; i++)
        {
            uv[i] = new Vector2(vertices[i].x, vertices[i].z);
        }

        return uvs.ToArray();

        //uvs.Clear();
        //uvs.AddRange(uv);
    }

```

# Answer
If you don't explicitly provide normals to your newly-made mesh, they'll be left at their default values, and the default value of a `Vector3` is (0, 0, 0).

Any light vector dotted with a zero vector yields zero, so you effectively get no lighting this way: total blackness, just as you're observing.

If you want Unity to automatically compute normals for you based on the triangle information, call `mesh.RecalculateNormals();`

Note that this will give a smooth shading seam anywhere you have shared vertices, but it will create a hard crease where you have vertex splits (say, along a UV texturing seam). If that's not desired, you should compute your own normals and assign them the way you're doing with your vertex positions and texture coordinates.
> 3 votes

---
Tags: unity, c#, procedural-generation, 3d-meshes, unity-shader-graph
---


# Question
Title: (While using a cube map) box-like textures appearing around my scene whenever I move the camera
I've been learning about cube map and I implemented one into my program. It seemed to work well until I started moving the camera around the scene and zooming out. As you can see in the attached gif, there seems to be a problem with the cube map since this weird behavior is occurring:

https://gyazo.com/70ad4ce027d1e032bc19258e28def66f

Main program:

```
        unsigned int cubemapTexture = texo.loadCubeMap(faces);

        glDepthFunc(GL_EQUAL);
        bg.bind();
        skyBox.use();

        glm::mat4 projection = glm::perspective(glm::radians(fov), (float)scr_width / (float)scr_height, 0.1f, 100.0f);
        glm::mat4 view = camera.GetViewMatrix();
        skyBox.setUniformMat4("projection", projection);
        skyBox.setUniformMat4("view", view);

        glActiveTexture(GL_TEXTURE20);
        glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
        GLCall(glDrawArrays(GL_TRIANGLES, 0, 36));

```

loadCubeMap:

```
unsigned int Textures::loadCubeMap(std::vector<std::string> faces)
{
    unsigned int textureID;
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

    stbi_set_flip_vertically_on_load(false);

    int width, height, nrChannels;
    for (unsigned int i = 0; i < faces.size(); i++)
    {
        unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
        if (data)
        {
            glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
                0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data
            );

            stbi_image_free(data);
        }
        else
        {
            std::cout << "Cubemap tex failed to load at path: " << faces[i] << std::endl;
            stbi_image_free(data);
        }
    }

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    return textureID;
}

```

Vertex Shader:

```
#version 330 core

layout (location = 0) in vec3 aPos;

out vec3 TexCoords;

uniform mat4 view;
uniform mat4 projection;

void main()
{
    vec4 pos = projection * view * vec4(aPos, 1.0);
    TexCoords = aPos;
    //Setting z value to w (1.0) so that the cube map is always in the background
    gl_Position = pos.xyww;
}

```

Fragment shader:

```
#version 330 core

out vec4 FragColor;

in vec3 TexCoords;
uniform samplerCube skybox;

void main()
{
    FragColor = texture(skybox, TexCoords);
}

```

The problem probably originates from one of these snippets, but if you have any other ideas I can provide more info.

# Answer
glDepthFunc(GL\_EQUAL) - your skybox is z-fighting against itself; changing the depth func to GL\_LEQUAL will fix this.
> 0 votes

---
Tags: opengl, camera, cubemap
---


# Question
Title: Question-Answer Game with coin rewards, how to validate answer?
I'm making a game that is basically a typical question-answer type. With coins as reward per answered question.

Stacks and requirements:

1. UI frameworks of iOS and Android, no game engine.
2. REST API.
3. No offline feature.

I'm a newbie in making games, and so my questions are:

1. Is it okay if I let the client side validate the answer and let it decide how much coins to add in the database?
2. Or do I make the client side ask for validation of the answer in the server? But I'm thinking this is not ideal because in the game, when you choose an answer, and if the answer is right, the congratulations screen must be instantly popped out.

# Answer
A little bit of both. This comes again and again. Your search terms are client-side prediction and client-side simulation. However, if I point you there, you are going to get something much more complicated than what you need for this simple case...

So, here are the basics:

* The client sends the request to the server
* The client starts playing an animation (if the client can predict what will happen, then it can play the corresponding animation, otherwise, have the client play some busy animation※).
* The client receives the response from the server.
* If the client did a prediction, it compares it with the server response. If they match※※, we are done. Otherwise, the client has to adjust to what happened※※※.

Why do we ask the server? Because cheat prevention. It would be relatively easy to modify the client to tell the server whatever. *Relatively easy compared to hacking the server, assuming state of the art access control.*

Why do we play an animation despite waiting for the server? Because responsiveness. We want the client to react instantly. Do not give the impression that the game didn't register the input, or is otherwise stuck.

Assuming the client knows the right answer, there should be no reason for the prediction to be wrong. Which means this would only affect people trying to cheat. However… If the client knows the right answer, there could be a way to extract it, if there is, well, there you have another way to cheat. Thus, for cheat prevention, you just don't tell the client and let the server decide.

What are you asking the server for anyway? Is it for the right answer? Or for the amount of coins? Let us say we do not care about cheating to get the right answer. We might still not want the client getting more coins than they should. In that case you can say "congratulations", but ask the server for the coins.

Or you do not care about cheating at all.

---

※: For example play the animation of a character opening a chest while waiting for the server response about what is inside.

※※: The server might know things that the client does not. For example it might know that the character you were shooting actually has a shield, and thus the shot won't kill him.

※※※: And then you might see a glitch. These are prevalent on real time games when there is high latency. Another search term for you: lag compensation.
> 4 votes

---
Tags: client-server, validation
---


# Question
Title: How do I set bullets to shoot from the correct position on the sprite?
How can I set the bullets start position to shoot from the front right of the sprite?

It is currently shooting from the top of the sprite.

P.S. I'm doing a tutorial online with the sprite shooting upwords. I'm trying to change the direction of the bullet to shoot sideways to the right, which I got but the starting position isn't correct.

Here's my the code:

```
// Extending bullets sprite to funtion in the game
class Bullet extends Sprite {
    constructor(divName, assetDesc, position) {
        super(divName, position, assetDesc.fileName, new Size(assetDesc.width, assetDesc.height));
        this.life = GameSettings.bulletLife;
        this.dead = false;
        this.addToBoard(true);
    }

// Defining the bullets funtions to update throughout the game & bullet direction
update(dt) {
    let inc = dt * GameSettings.bulletSpeed;
    this.incrementPosition(inc, 0);
    this.life -= dt;
    if (this.life < 0) {
        this.killMe();
    }

}
    killMe() {
        this.dead = true;
        this.removeFromBoard();
    }
}

// Collection of bullets & how many added to player
class BulletCollection {
    constructor(player) {
        this.listBullets = [];
        this.lastAdded = 0;
        this.player = player;
        this.total_bullets = 0;
    }

    reset() {
        for (let i = 0; i < this.listBullets.length; ++i) {
            this.listBullets[i].removeFromBoard();
        }
        this.listBullets = [];
        this.lastAdded = 0;
        this.total_bullets = 0;
    }
// Bullets update
    update(dt) {
        for (let i = this.listBullets.length - 1; i >= 0; --i) {
            if (this.listBullets[i].dead == true) {
                this.listBullets.splice(i, 1);
            } else {
                this.listBullets[i].update(dt);
            }
        }
        this.lastAdded += dt;

// Detection to whether we need to add bullet to the game
        if (this.lastAdded > GameSettings.bulletFireRate &&
            this.player.state != GameSettings.playerState.hitFlashing) {
                this.lastAdded = 0;
                this.listBullets.push(
                    new Bullet(
                        'bullet_' + this.total_bullets,
                        GameManager.assets["burrito_dog"],
                        new Point(this.player.position.x + (this.player.size.width / 2),
                        this.player.position.y)
                    )
                );
                this.total_bullets++;
            }
    }
}
```

Thank you for the support!

Here's an img for reference:

# Answer
It looks like the origin of your sprites might be in the top-left, with y increasing downwards.

This bit of code spawns a new bullet:

```
new Bullet(
    'bullet_' + this.total_bullets,
    GameManager.assets["burrito_dog"],
    new Point(
        this.player.position.x + (this.player.size.width / 2),
        this.player.position.y
    )
)

```

You can see the bullet spawns at the player's position (top-left of the player sprite), shifted to the right by half the player sprite's width - that puts it at roughly the top center, as observed in your screenshot.

Try changing the point to....

```
new Point(
    this.player.position.x + this.player.size.width,
    this.player.position.y + this.player.size.height / 2
)

```

We'll shift right the full width of the sprite, to take us all the way from the left side to the right side, and shift down half the height of the sprite, to take us to the vertical midpoint.

You might need to play with these offsets a little to get it to align just the way you want. For instance, the edge of your saucer might be three-quarters of the way down your sprite, rather than exactly halfway.
> 0 votes

---
Tags: javascript, html, support
---


# Question
Title: Should 3D transformations be represented by a 4x4 matrix or a 3x4 matrix?
Since 3D transformations are represented by **4x4** homogeneous matrices we know that their last row is always **(0,0,0,1)**, and as such the behavior of this final row is implied so long as we know whether or not the transformation is operating on a vector (a **4x1** matrix with a *w* element of 0) or a point (a **4x1** matrix with a *w* element of 1).

If we have classes that represent points and vectors separately as **3x1** matrices with implied *w* coordinates then we can overload the * operator so that its behavior on both classes is separate and thus there is no need to store the final row of the transformation matrix in memory.

Now I can see how this would be a great optimization at first as it increases cache coherency instead of adding what is essentially padding to each transformation matrix. On the other hand, we will have to eventually use a full **4x4** matrix to handle the projection and perspective divide later on so is it worth it to store a transformation matrix as a **3x4** matrix only to later convert it into a full **4x4**? Or would a good solution here be to make the projection matrix a **4x4** matrix and make the product of a transformation matrix and a **4x4** matrix another **4x4** matrix?

I'm sorry if this seems basic or like a question that answers itself but I was reading a book on game engine development and it used implications to handle interactions between transformation matrices with points and vectors, and other transformations separately, never multiplying by the final row and using implications instead. But on creation they would still stored the final row as **(0,0,0,1)** in memory to only be used in multiplication between a transformation matrix and a **4x4** matrix specifically and so I'm mostly just wondering if there may have been a good reason for that or not. Thanks in advance for the help.

# Answer
> Since 3D transformations are represented by 4x4 homogeneous matrices

Correction: Might be represented by 4x4 matrices ;)

> Now I can see how this would be a great optimization at first as it increases cache coherency instead of adding what is essentially padding to each transformation matrix.

I don't think that cache coherence is a major issue here. More relevant are the computations that you can avoid. A 4x4 matrix multiplied with a 4 element vector results in 16 multiplications and 12 additions. If you use a 3x4 matrix it is only 12 multiplications and 9 additions. So you have 25% less of the computational costs. You also save some memory but I don't think it is as relevant as the computational savings.

I can remember having a similar discussion about this topic on www.gamedev.net. It was going even further by just using 3x3 matrices and handling translations separately by vector addition (computations: 9 multiplications, 9 additions) . If I remember correctly the conclusion was, that 4x4 matrices are easier to use, since they contain translations and also handle point vs vector issues for you. This "luxury" comes with a performance impact. However, I can also remember that people stated, that this performance impact is negligible most of the time since the matrix multiplications are done during vertex processing and this is usually not a bottleneck in a game engine. To be sure, you have to benchmark it.

> On the other hand, we will have to eventually use a full 4x4 matrix to handle the projection and perspective divide later on so is it worth it to store a transformation matrix as a 3x4 matrix only to later convert it into a full 4x4? Or would a good solution here be to make the projection matrix a 4x4 matrix and make the product of a transformation matrix and a 4x4 matrix another 4x4 matrix?

I think you are approaching this a little bit too complicated. You have probably something in mind like this:

$$v\_p = P \cdot T \cdot v$$

where P is the 4x4 projection matrix and T an arbitrary 3x4 transformation matrix. v is the Vertex that should be transformed and v\_p the fully transformed vertex. If I understood you correctly, then your problem here is, that 4x4 matrices can't be multiplied with 3x4 matrices, so you think about introducing a special operation for that. However, since v times a matrix always yields a vector, you can simply do the following (GLSL like pseudo-code):

```
vec3 v_t = T * v;
vec4 v_p = P * vec4(v_t, 1.0);

```

So just extend the vector by one element after the 3x4 multiplication and multiply the 4x4 projection matrix afterward. However, there is one other problem with 3x4 matrices. You can't multiply them with each other and you can't multiply them with the result of a preceding 3x4 matrix-vector multiplication since they yield a `vec3` but can only be multiplied with a `vec4`. So you have a problem in case you have multiple 3x4 transformation matrices. You can solve this exactly the same way as in the previous example by doing one matrix-vector multiplication at a time and extending the result vector to 4 components, but I don't think this is a smart solution. This is why you should either use 4x4 matrices or 3x3 matrices and handle translations by vector addition. However, since the 4. column of a 3x4 matrix is identical to the translations in this special case, you can still use it as a storage format and just separate it into a 3x3 matrix and a translation vector during the calculations.

> classes that represent points and vectors separately as 3x1 matrices

Note, that you have to use 3x3 matrices during multiplication if you want to use vectors of size 3 since you can't multiply a 3x4 matrix with a 3x1 matrix. So I assume that you or the book you are reading separates a 3x4 matrix into a 3x3 matrix and a translation before using it.

**Conclusion**

Using 3x3 matrices + translations or alternatively 3x4 matrices gives you performance and storage benefits by omitting redundant operations and values but 4x4 matrices are more comfortable to use. The performance benefits might also not be noticeable if your game is not utilizing the full corresponding hardware capacity, so benchmark it, if you are not sure if this is relevant for you. In the end, it is a design decision where you trade more comfortable/readable code against some (possible!) performance gain.
> 3 votes

---
Tags: c++, matrix, transformation, optimization, linear-algebra
---


# Question
Title: Rotate Rigidbody to face away from camera with AddTorque
I have a camera that rotates around an object with "Look At" .

I want the object to rotate to face the direction the camera is pointing (Camera.main.transform.forward) using AddTorque, but I can't understand how.

I tried to create a rotation in which the more the object's forward vector rotates towards the camera, the more it should slow down the rotation until it stops. But it only works in sections, when I use the rotation of the camera the object rotates and then stops, as if it detects only one part of the rotation, while the other is a blind spot.

What equation can I use to rotate the object well?

```
var currentR = rb.rotation.y;
var targetR = Camera.main.transform.rotation.y;
rb.AddTorque(transform.up * 1000f * (targetR - currentR));

```

@DMGregory♦ I put your script as it is in a separate new script on a new object, equipped with a rigidbody. I post the script how I entered it. At "targetOrientation" I gave the value of "Quaternion.LookRotation (Camera.main.transform.forward);" because I want the object to follow the direction of that camera. The result is that all the axes of the rigidbody are influenced by the rotation (if I lift the camera the object turns towards the ground, etc.), and above all that the rotation works even if I block the axes with Freeze Rotation, and with this script the object is no longer affected by external forces.

```
public class rotation : MonoBehaviour
{
    private Rigidbody rb;
    public Transform direction;
    // Start is called before the first frame update
    void Start()
    {
      rb = GetComponent<Rigidbody>();
    }

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

     Quaternion targetOrientation = Quaternion.LookRotation(Camera.main.transform.forward);
    Quaternion rotationChange = targetOrientation * Quaternion.Inverse(rb.rotation);

    rotationChange.ToAngleAxis(out float angle, out Vector3 axis);
    if (angle > 180f)
        angle -= 360f;

    if (Mathf.Approximately(angle, 0)) {
        rb.angularVelocity = Vector3.zero;
        return;
    }

    angle *= Mathf.Deg2Rad;

    var targetAngularVelocity = axis * angle / Time.deltaTime;

    float catchUp = 1.0f;
    targetAngularVelocity *= catchUp;

    rb.AddTorque(targetAngularVelocity - rb.angularVelocity, ForceMode.VelocityChange);

     }
    }

```

I set a command \[if (Input.GetKeyDown (KeyCode.T)) rb.AddTorque (transform.up * 5500f, ForceMode.Impulse);\] to rotate the object with an impulse and this does not work when your rotation script is active. I also place a video where you see the object before activating the rotation script, and after it is active, to see how it does not react to the impulse with T, and how it rotates reacting on all rotation axes, while I want only that the rigidbody only rotates its Y-axis of rotation, in the direction of the camera (as a person does when turning in one direction). In the video The axes of rotation X and Z are on freeze (otherwise without fixed the rotation the object falls moving). I also put a video of the desired effect taken from a game so as to explain me better.

My video desired rotation

# Answer
> 2 votes
If you want to orient an object to face away from the camera, the first step is to compute the orientation you want it to have. You can use a "Turret Look Rotation" convenience method like this one to form an orientation perpendicular to a particular surface, while facing toward a particular direction.

```
// If your ground has hills/ramps, you might want to update this with your ground normal
// from your ground check raycast/shapecast.
Vector3 _groundNormal = new Vector3(0, 1, 0);

Quaternion GetOrientionAwayFromCamera() {
    // To face in the direction of the camera axis, use this.
    Vector3 approximateForward = Camera.main.transform.forward;

    // To face away from the camera object, use this. It only makes a difference if your character
    // can be off-center in the frame, facing leftward when they're on the left side of the screen.
    // Vector3 approximateForward = transform.position - Camera.main.transform.position;

    return TurretLookRotation(approximateForward, _groundNormal);
}

```

Now the easiest way to get a rigidbody to face that new orientation is with `MoveRotation`:

```
var targetOrientation = GetOrientationAwayFromCamera();
rigidbody.MoveRotation(targetOrientation);

```

But if you'd prefer to compute the torque to reach this orientation yourself, it's:

```
// Compute the change in orientation we need to impart.
Quaternion rotationChange = targetOrientation * Quaternion.Inverse(rigidbody.rotation);

// Convert to an angle-axis representation, with angle in range -180...180
rotationChange.ToAngleAxis(out float angle, out Vector3 axis);
if (angle > 180f)
    angle -= 360f;

// If we're already facing the right way, just stop.
// This avoids problems with the infinite axes ToAngleAxis gives us in this case.
if (Mathf.Approximately(angle, 0)) {
    rigidbody.angularVelocity = Vector3.zero;
    return;
}

// If you need to, you can enforce a cap here on the maximum rotation you'll
// allow in a single step, to prevent overly jerky movement from upsetting your sim.
// angle = Mathf.Clamp(angle, -90f, 90f);

// Convert to radians.
angle *= Mathf.Deg2Rad;

// Compute an angular velocity that will bring us to the target orientation
// in a single time step.
var targetAngularVelocity = axis * angle / Time.deltaTime;

// You can reduce this parameter to smooth the movement over multiple time steps,
// to help reduce the effect of sudden jerks.
float catchUp = 1.0f;
targetAngularVelocity *= catchUp;

// Apply a torque to finish the job.
rigidbody.AddTorque(targetAngularVelocity - rigidbody.angularVelocity, ForceMode.VelocityChange);

```

This will try to rotate the entire difference in a single physics timestep, but for very large turns or short timesteps you might run up against the maximum angular velocity limit, forcing the rotation to spread out over multiple ticks. If you observe this happening, you can raise the limit under Project Settings -\> Physics.

---
Tags: unity, physics, rotation, rigidbody
---


# Question
Title: Creating palette from irregular sprites in Unity
I want to create a palette based on a number of PNGs in Unity 2D. I am struggling to understand the slicing logic. Let's say I have a sprite 588x547, and I set PPU to 128. So obviously the sprite cannot be divided into 128-parts:  So the right and the bottom part are not going to appear on my palette. Now I would like the grid to start in the center. The tiles on the sides are not "full" tiles, but I still want them on my palette in the end, so I kind of want Unity to fill up the border tiles for me with void till they reach the 128x128 size:  Is there a way to achieve this? Or am I conceptually misunderstanding something? Given a bunch of PNGs, all of them different pixel sizes, none dividable by 128, how do you create a palette from them to paint on a 128 PPU grid? I had a look at external tools like TexturePacker and Showbox, but did't manage to achieve a nice 128-dividable grid from my sprites.

# Answer
The easiest way to do this by using a tile palette or just resizing the image by not cutting it up. So you can change the image to Point (No filter) instead of Bilinear. After that you choose (Grid by cell size). Then you get a series of cut p parts (Also, you should probably choose a power of 2 or a multiple of two). Then click create, 2d, tile map. Then, you can go to Window, 2d, and Tile Palette. Click create tile palette and select the series of images that you want to be to create the image. Then you can place the correct part at the correct place. Hope this helps! (also, you can use the original image and create a box collider if that's what you want. you can do that by just choosing Automatic instead of Cell by Grid size). Let me know if you want more help.
> 1 votes

# Answer
Well, I could not figure it out with Unity, so I ended up resizing all my sprites to 128-divisible sizes by adding transparent borders, so that to be able to cut them with Unity nicely. For this I used ImageMagic and the following command:

```
convert {file} -background transparent -gravity center -extent {targetW}x{targetH} {outputPath}

```

In order to go through all the files in the directory and calculate the next best 128-divisible size I wrote a small app in C#:

```
class Program
{
    static void Main(string[] args)
    {
        var sourcePath = @"d:\png";
        var targetPath = @"d:\png\output";

        var files = Directory.GetFiles(sourcePath);
        foreach (var file in files)
        {
            var img = Image.FromFile(file);
            var w = img.Width;
            var h = img.Height;
            var targetW = FindNextSize(w);
            var targetH = FindNextSize(h);

            Process.Start(
                @"...path to ImageMagic...\convert.exe",
                $@"{file} -background transparent -gravity center -extent {targetW}x{targetH} {Path.Combine(targetPath, Path.GetFileName(file))}");
            Thread.Sleep(200);
        }
    }

    private static int step = 128;

    private static int FindNextSize(int actualSize)
    {
        var result = step;
        while (result <= actualSize)
        {
            result += step;
        }

        return result;
    }
}

```

Not too pretty all of it, but it did what I wanted.
> 0 votes

---
Tags: unity, spritesheet, palette
---


# Question
Title: How to collect objects from map in blueprints
I have a plate with trigger(TriggerVolume) on it. When it overlapped cubes from map deleting. I've manually created references on cubes in blueprint to delete them but it seems very hard-coded. Is there any way to collect all references with "for loop"? And for more clarity - I'm using FPS template for this project.

# Answer
So, I've found solution: I've just found out that there are two different types of tags. One for components and one for actors. Here is my solution below.
> 0 votes

---
Tags: c++, unreal-4, blueprints
---


# Question
Title: How could you use mirror in unity to network across multiple networks rather than only LAN (Port Forwarding?)
I've been working on a game for my friends and I to play during quarantine but I can't figure out or find any information on networking using mirror. Everything I see gives vague answers to even vaguer questions that assume you have prior knowledge of networking. Could anyone give me any sort of direction on how to port forward using mirror or if there's a better solution?

# Answer
> 0 votes
This video solved my issue, give it a watch if you had the same issue!

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

The main points of the video to my understanding are the following:

Port forwarding is a way to connect several lan networks together. To port forward, start by opening command prompts and entering ipconfig. Then, copy your default gateway ip into whatever browser you use. From there, you can find the default password for your router at https://www.routerpasswords.com/ . From there, it differs depending on what brand of router you own but you need to look for something that says port forwarding. The default port for mirror is 7777 so enter that where it asks for the port and pick your computer where it asks for a device. Now, wherever you type an ip to connect using unity just have your friends enter your public ip. You can find it by typing "What is my IP address" in your browser.

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


# Question
Title: Making animations not smooth while using Record button
In my 2D sidescroller game, I want to separate the animations for the head and the body of my character.

While idling, my charcter's body bounces slightly up and down (kind of a breathing motion). Thus, the head should keep up. However, when I press `Record` and make adjustments for the head, the head moves up and down smoothly instead of following the body frame by frame.

How can I remove the smooth transitions from one position to the other?

Here is a screenshot from Unity demonstrating the hierarchy and the animation keyframes.

# Answer
> 1 votes
I am new to the platform of GameDev, so I am not able to comment, but you will not be able to control or record it the way you want. Unity makes smooth animations with the record button. So you can probably make a sprite sheet of some sorts and use that instead, but the way you want it to work is quite impossible with the record button. Also, I think you should use Anima2d instead of the record button because the record button is too limited.

---
Tags: unity, animation
---


title: 2d navigation for physics-based car

text:
# Question
Title: 2d navigation for physics-based car
i'm making a game, one npc is a car with spear in head, he try to hit the enemy (yellow pot in image) with the spear point.

here is the promble ,the car is physics-based , it has veloctiy ,max angular velocity ,can turn around the car's center, the npc can only change drive direction. since the positions of car and enemy can be very random (the enemy will not move once respawn), how can the car make the spear hit?

# Answer
> 1 votes
There are a few ways to achieve that, here's what I found to be the easiest:

By saving the location of your npc and the center of the car you can calculate the direction using a vector (x,y). In this image, the direction you want to drive in is (c-a, d-b). If you don't have the direction that the npc is driving at, you can calculate it by saving the previous position and the current position and getting a vector the same way we did before.

Note: To make sure the vectors are the same length you can use this: $$Normalize (x,y) \rightarrow \sqrt{x^2+y^2} = 1$$

By the end you cant the two vectors to be the same (in the same direction). If you want your npc to have a smooth rotation towards the enemy, use a smooth variable and set it to a small value, then, add this value until you reach the direction you want.

Alternatively, instead of a vector you can create a linear line between these two points by using the linear line formula:

Linear line between two points (a,b) (c,d): $$ y = mx + b \rightarrow y-a = \frac{d-b}{c-a}(x-b) , when - m= \frac{d-b}{c-a} $$

And then you want the "m" to be the same.

Note: If you'er using a game engine, try to find some useful functions that can do that for you (for example, "LookAt" in unity).

---
Tags: mathematics, simulations
---


# Question
Title: Ray Caster - How do I fix fish eye effect on side walls?
I've come here because I can't seem to find out what's wrong with my ray tracer.

I fixed the fish eye effect when looking straight on at walls, but the effect remains when the player is looking at walls to the side.

I think it's because most of the rays hit the surface close to the player, while fewer and fewer rays hit more distant walls, resulting in a curve. The only problem is I don't know how to make it appear linear.

```
    float dist = distance*cos(angle); //fix distorted distance
    float rat = (depth-(dis))/depth; //calculate ratio for wall height
    float h = 64*rat; //calculate height
    PImage slice = sprites[0].get((int)(inter/2),0,1,16); //get image slice
    image(slice,i*4,768-h/2,4,h); //display image slice

```

In this example, the top screen is the raw data while the bottom screen it the ray traced 2.5D image. I've made the rays visible.

Edit: I changes "rat" to be 192/dis. This seems to look a bit better, but is still slightly curved...

# Answer
> 1 votes
It appears to me that you're having a problem because you're not doing any ray tracing, you are trying to simplify the "all purpose calculation" into a "specific" calculation that can hit vertical walls.

First, obtaining a 3d ray direction should not come from an angle; but from the vector that links the current iterated pixel to the camera.

After that, evaluating the closest intersection hit, per ray, should loop on all the scene objects, calculate all distances and keep the smallest one (with the associated object hit at that smallest distance.) to be able to shade it.

The hit in your case seems to be a plane equation with 2 vertical limits (ground and up).
So you need to solve `ax+by+cz=-d` with (abc) the normal vector of the wall, and `d` its smallest distance to the world's origin. Together as a system of 2 equations, the other one being your ray, expressed as `ray=t*direction` for `t` that makes it so that `point-on-wall = camera + t * direction`

That solution involves a division indeed, which you already sensed as necessary.
Here is what you need: https://nerdparadise.com/math/lineintersectsaplane (or that)
Presented as:  For code, Trillian's answer will do: https://stackoverflow.com/a/23976134/893406

For your case you can replace some 3d components by knowns, like your walls will always have 0 in y. If they are always aligned to the axis, they will always have either 0 or 1 in x or z. That creates 2 types of solutions, one solution for x aligned walls, and one solution for z aligned walls. (or you can keep the generic version for diagonal walls)

---
Tags: raycasting, processing
---


# Question
Title: Unity - move with WASD in the way the camera is facing
I have this C# code for rotating the camera with the mouse:

```
public float mouseSensitivity = 100.0f;
public float clampAngle = 80.0f;

private float rotY = 0.0f; // rotation around the up/y axis
private float rotX = 0.0f; // rotation around the right/x axis

void Start()
{
    Screen.lockCursor = true;
    Vector3 rot = transform.localRotation.eulerAngles;
    rotY = rot.y;
    rotX = rot.x;
}

void Update()
{
    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = -Input.GetAxis("Mouse Y");

    rotY += mouseX * mouseSensitivity * Time.deltaTime;
    rotX += mouseY * mouseSensitivity * Time.deltaTime;

    rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

    Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
    transform.rotation = localRotation;
    transform.parent.transform.rotation = Quaternion.Euler(0.0f, rotY, 0.0f);
}

```

The script is on the camera, and camera object is a child to the player object. Now I want to move the player object in the direction the camera is facing, how do I do this?

# Answer
Just add a *CharacterController* component to the player (the parent of the camera), and use this script:

```
public float mouseSensitivity = 100.0f;
public float clampAngle = 80.0f;

private float rotY = 0.0f; // rotation around the up/y axis
private float rotX = 0.0f; // rotation around the right/x axis

GameObject player;
public CharacterController controller;
public float speed = 6f;

void Start()
{
    Screen.lockCursor = true;
    Vector3 rot = transform.localRotation.eulerAngles;
    rotY = rot.y;
    rotX = rot.x;

    player = this.transform.parent.gameObject; // Getting the parent object.
    controller = player.GetComponent<CharacterController>(); // You can use the getcomponent in child instead
}

void Update()
{
    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = -Input.GetAxis("Mouse Y");

    rotY += mouseX * mouseSensitivity * Time.deltaTime;
    rotX += mouseY * mouseSensitivity * Time.deltaTime;

    rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

    Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
    transform.rotation = localRotation;
    transform.parent.transform.rotation = Quaternion.Euler(0.0f, rotY, 0.0f);

    float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");
    Vector3 Direction = (player.transform.forward * vertical + player.transform.right * horizontal).normalized;

    controller.Move(Direction * speed * Time.deltaTime);

}

```

This will move the player with the ASDW or the arrows with the speed you want (using the *speed* variable).
> 2 votes

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


# Question
Title: Two Gameloops instead of one, wouldn't it be better?
I have been thinking about this a lot and don't know if i'm thinking incorrectly.

Most games have one game loop that can be split into three functions. A basic game loop would look something like this:

```
while(true){
    handle_Input();
    update();
    render();
}

```

It's good when the handle\_Input() and update() function are called as often as possible to create more responsive controls. But there is no point in calling the render() function more often then your monitor refresh rate. You could of course limit the speed of the loop in order to hit your monitor refresh rate but it would make the controls less responsive.

Wouldn't it be better to create two game loops?

The first game loop would call the handle\_Input() and update() function as fast as possible, while the second game loop would take the latest frame the first game loop calculated and only call the render() function. The speed at which the secend game loop runs would be limited by the monitor refresh rate. In order for the concept to work, the game loops should be running on separate processor cores.

Wouldn't this create a lot less overhead for both the CPU and GPU by not wasting time on the worthless render() calls? And allow the game to either run with a higher fps count or better graphics? Wouldn't it also allow to give unbalanced systems, which have a weak GPU compared to the CPU, a more playable experience, because the weak GPU would only limit the fps you see but not the handle\_Input() and update() calls?

I have never seen somebody implement a concept like which make me think something like this wouldn't work.

# Answer
That's an interesting idea, however...

With multi-threading, you lose your advantage because you have to *stop the update thread* when you update your graphics.

Think about it: if you render at the same time you update you simulation and your scene graph, chances are that at some point you'll be updating it *while you're rendering it*. What will happen? You'll draw some nodes twice because they'll have changed position in the scene graph? Two nodes that should never be drawn together will be drawn because of the order in which they're updated by your logic and the order they are drawn in the scene graph does not really match?

A lot of things could go wrong with your rendering.

So basically you'd have to suspend your update thread for the time you're rendering your scene, just to make sure that nothing goes wrong.

Then why do you need threads?

You don't.

Glenn Fiedler wrote an interesting (and very popular) article in 2004 titled Fix Your Timestep. He also suggests to use two loops. But they're nested, not parallel.

The idea is roughly to update the physics until it's time to draw, then draw, then rinse and repeat:

```
while( ! quit ):
  while time for this frame is not up:
    updateAndPhysicsForOneStep()

  render()

```

The article explains it much better than I would.

Additionally, threads add another layer of complexity (not talking about the headaches) of an already complex piece of software, so if you can achieve something with only one thread, you should favour that instead of a multi-threaded approach.
> 5 votes

# Answer
Just to expand on the other answers a bit:

Unity and Unreal both use separate threads for update (typically called the "game thread") & render, specifically to keep them from slowing each other down. You'll typically see the game rendering lagging a frame behind update / physics because of this.

In Unity, graphics operations are internally queued up in a device & API-agnostic queue in the main thread, and then dispatched by the render thread. The CPU overhead for that is minimal. This also allows the render thread to fast-forward through the queue if the render thread gets too far behind. Nothing new here, but synchronization can be challenging. Typically, the time to populate the queue is minimal, and takes far less than actually dispatching to the GPU.

This two-thread arrangement is very common. But, things are changing.

In Unity's Job system, candidate operations can be automatically vectorized to take advantage of all available CPU cores. This typically means SIMD-style vectorization on different GameObjects & components.

I'm not sure of the current state of Epic's threading model but, last I checked, this is a competitive advantage of Unity.

Implementing this in your own engine is not impossible, nor even extremely difficult. Keeping your thread sync points to a minimum, use of lightweight synchronization primitives and data structures and a very detailed sequence diagram will help.

If using multiple render threads, be aware that only the explicit APIs support actually rendering in that fashion, and it can actually be slower in some circumstances. My preferred approach is that used by Unity: threads populate a priority queue, while a dedicated thread actually dispatches the commands to the GPU driver. Keeping things in the proper order can be an issue, but is a solvable problem.
> 2 votes

# Answer
I was, and I am thinking about this a lot. A couple of years ago I did some browser project and separating the loops, it was OK.

And if you for example have a server/client game, there are already at minimum 2 game loops. The server loop is calculating and keeping the state, sending changes to the client and then the client renders them in its own loop.
I'm not an expert and I think the only problem can be when some object should be rendered only very short time that it can be already destroyed in the game loop and never shows in the render loop, but I think it can be achieved by other solutions.

Here are some references for separating loops ideas:

and I found some references for nested loops:
> 0 votes

---
Tags: game-loop, multithreading
---


# Question
Title: Unity: AddForce in transform.forward direction not working as expected
I am building a very simple car-driving game in Unity.

I have a Player object, which looks like this:

As you can see, I have a Rigidbody2d component attached to this object, as well as a script, called "PlayerScript".

Here is this script:

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

public class PlayerScript : MonoBehaviour
{
    Rigidbody2D carRigidbody;
    Vector3 turnVector;
    Vector3 forwardDirection;
    // Start is called before the first frame update
    void Start()
    {
        carRigidbody = GetComponent<Rigidbody2D>();
        turnVector = new Vector3(0, 1, 0);
    }

    // Update is called once per frame
    void Update()
    {
        //transform.lo
        Debug.Log(string.Format("Transform.rotation is {0}", transform.localRotation.eulerAngles));
        Debug.DrawRay(transform.position, transform.forward, Color.yellow);
        if (Input.GetKey(KeyCode.UpArrow))
        {
            carRigidbody.AddRelativeForce(transform.forward * 10);
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            carRigidbody.AddRelativeForce(transform.forward * -10);
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.Rotate(turnVector);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Rotate(-turnVector);
        }
    }
}

```

I would expect for this code to make my Player object move forward in its **local** coordinate space when I hold the up-arrow on the keyboard, and move backward in the same space when I hold the down-arrow. Also, The left and right arrows should simply rotate the player-object (changing the forward direction in its local coordinate space).

Rotating left and right seems to work, but moving forwards and backwards seems to only work in the world coordinate space for some reason. Not sure If I am missing something. Here is a gif of what happens.

As you can see, initially, moving forward and backward using the up and down arrow keys works. I then use the left arrow key to rotate the object left, which also works. But when I then try and add a force in the forward or backward direction, the object is not moving in the object's local forward direction, but instead, in the same forward direction as before.

What am I missing and how can I fix this?

# Answer
> 1 votes
Your title asks about how to use `transform.forward` with `AddForce`, but you don't need to do anything special there:

```
carRigidbody.AddForce(transform.forward * 10);

```

Your problem is that you're *not* using `AddForce`. You're using `AddRelativeForce`. `AddRelativeForce` expects an input in the rigidbody's local coordinate space, but `transform.forward` is a vector in world space. Its local equivalent is just `Vector3.forward` or just the constant `new Vector3(0, 0, 1)`.

So, if you want to continue using `AddRelativeForce`, use a local space input:

```
carRigidbody.AddRelativeForce(0, 0, 10);

```

Or, if you want to continue using world space input, use the world space version, `AddForce`:

```
carRigidbody.AddForce(transform.forward * 10);

```

---
Tags: unity, c#, physics, movement, coordinates
---


# Question
Title: Box2d RopeJoint bug - fix or alternative solution?
What I am trying to do is to create rope game. Below you can find a movie how it looks like now.

https://youtu.be/QTULCGNF70I

I am using RopeJoint and I am reducing maxLength each frame to be able to accelerate. Everything seems fine, but the problem appears for bubble kind of ball. I realized that shortening rope does not increase balls velocity. For example if I throw the rope fully vertical and the only "force" is from shortening the rope, the velocity is 0,0. Seems like, body movement is not simulated?

After I let the rope go the momentum is lost. The bubble can fly, but the factor from rope shortening is ignored.

I don't know if you understand what I mean. The movie should clarify it better.

Workarounds I tried:

* Good idea was to use prismaticJoint, but the rotation is fixed, so it doesn't work. I couldn't swing
* Another idea was to use wheelJoint and make use of it's frequency parameter. However here there's a problem that rope becomes rubber. Swing feeling is bad, when it can extend more than initial length, it should always only shorten.

Solutions I see, but they are not available

* RopeJoint which keeps body momentum from rope shortening
* PrismaticJoint without fixed rotation
* WheelJoint with possibility to set max length or create the rope with it's max length, not the rest position.

# Answer
> 1 votes
I want to share with you how I handled it finally.

1. I shoot a "ropeBullet" which is small circular box2d body, by setting it's velocity and angle. I render a rope graphic between bullet and ball.
2. When bullet reaches wall, I get from contactListener the point of contact
3. I connect the bullet and the wall with revoluteJoint, based on bullet center and contact point. Thanks to such solution, the bullet may rotate and swinging on the rope is possible.
4. On the other end of the rope I created "rotor" which is similar circular body. It is connected to the ball body all the time with another revoluteJoint to two centers. It allows the ball to rotate freely.
5. Now I connect ropeBullet and the rotor with prismaticJoint. Axis i set by calculating the vector between them and normalizing it.
6. I set up a prismatic joint limits, motor speed and max force according to my needs.
7. The ball is touched by the gravitation force of the world, so I had to made one more trick to make it satisfying. I described the problem and the trick on box2d reddit so I refer to it: https://www.reddit.com/r/box2d/comments/gpdmoc/prismatic\_joint\_behaves\_like\_rubber/

---
Tags: libgdx, box2d
---


# Question
Title: OnCollisionEnter2D and OnCollisionStay2D not detecting anything or being called unless i turn off 'Is Trigger'
I was attempting to create a simple button prompt where when you are inside a 2d box colider it will give you the option to press the button within that range, below is the short code used to test this.

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

public class ButtonScript : MonoBehaviour
{

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("ENTER");
    }

    private void OnCollisionStay2D(Collision2D collision)
    {
        Debug.Log("Stay");
        if (collision.gameObject.tag == "Player")
        {
            Debug.Log("PLayer Detected");
            if (Input.GetKeyDown(KeyCode.E)) {
                Debug.Log("E pressed");
            }
        }
    }
}

```

However this does not output any Debug Messages at all. Maybe i have a misundestanding of the Is Trigger function and colliders in general but when i have it turned off it does nothing, when i have it on it acts as a box (which i dont want) but when i push againsts the box it will send out the debug messages.

# Answer
A Trigger collider does not generate collision response (which is what the `OnCollisionEnter`/`Stay`/`Exit` messages and their `2D` versions handle).

It only participates in overlap checks, which are handled by the `OnTriggerEnter`/`Stay`/`Exit` messages and their `2D` versions.

So replace your code with:

```
private void OnTriggerEnter2D(Collider2D other)
{
    Debug.Log("ENTER");
}

private void OnTriggerStay2D(Collider2D other)
{
    Debug.Log("Stay");
    if (other.CompareTag("Player"))
    {
        Debug.Log("PLayer Detected");
        if (Input.GetKeyDown(KeyCode.E)) {
            Debug.Log("E pressed");
        }
    }
}

```

Just watch out that in the physics step (when these collision/trigger callback messages are fired), the key press events you're receiving are those from the *previous* frame. In recent Unity versions, the freshest input isn't available until `Update`.

Also note that these messages are sent only if one of the participating colliders is attached to a `Rigidbody` / `Rigidbody2D` \- check the collision action matrix for the full details.
> 1 votes

---
Tags: unity, c#, 2d, collision-detection
---


# Question
Title: How to create a solid cross-scene game manager in the editor of unity?
I have been checking dozens of known 'solutions' for how to create a game manager in Unity, but none leave me satisfied.

I know I can create a singleton GameManager.Instance() that would have data to persist across multiple scenes, but it doesn't show up in the editor unless I assign it to a game object. The problem is, this game object would then be destroyed upon loading a new scene except if I use DontDestroyOnLoad().

However, when I use DontDestroyOnLoad(), and I open up a new scene in the editor, this GameManager Object doesn't exist in the new scene. The DontDestroyOnLoad() method assumes that the program entry point will always be the main/first scene, which is often not the case when working in the editor. This isn't great.

Example:

When I have events within scene2 (say a button or something), I cannot reference the gameobjects in scene1 in the Unity Editor (most importantly, the game manager).

Instead, I have to first attach a settings.cs script to my UI Button GameObject. When pressed, the Button will then call a function from the settings.cs void ChangeInput() {GameManager.Instance().ChangeInput();}. This feels quite clunky because the Button Element cannot reference the GameManager directly, since the Button is scene-specific but the gamemanager is not.

Is there a proper solution for issues like this?

# Answer
> 3 votes
Your `DontDestroyOnLoad` is exactly how I did it in Cognizer. I have hooks in the first script of each scene that will create the Game Manager object if it doesn't already exist. So I can start any scene, and everything works fine.

Cognizer doesn't work unless the player has selected game settings through `MainMenu`, so each scene has BootToMainMenu.cs attached:

```
public class BootToMainMenu : MonoBehaviour
{
    void Awake ()
    {
        GameObject globalObj = GameObject.Find("Globals");
        if(globalObj == null)
        {
            SceneManager.LoadScene("Splashes");
            return;
        }
    }
}

```

The Splashes scene has Booter.cs:

```
public class Booter : MonoBehaviour
{
    void Start ()
    {
        Application.targetFrameRate = 30;
        GameObject obj = GameObject.Find("Globals");
        if(obj == null)
        {
            obj = new GameObject("Globals");
            GameObject.DontDestroyOnLoad(obj);
            SharedData sharedData = obj.AddComponent<SharedData>();
            sharedData.Initialize();
            obj.AddComponent<AnalyticsHandler>();
            ...

```

And the Splashes scene has Splashes.cs which includes this:

```
void Update()
{
#if UNITY_EDITOR
    if(Input.GetMouseButtonDown(0))
    {
        SceneManager.LoadScene("MainMenu");
    }
#endif
    ...

```

So running any scene in Cognizer in the editor loads the Splashes scene, which prepares the `DontDestroyOnLoad` object, and allows a single click to skip straight to the main menu.

# Answer
> 3 votes
One way to handle functions that don't logically belong to any one scene is to put them into an object that doesn't live in a scene at all, but rather as an asset in your assets folder.

For instance, we could make our manager a `ScriptableObject`:

```
[CreateAssetMenu(fileName = "GameManager.asset", menuName = "Managers/Game Manager")]
public class GameManager : ScriptableObject
{
    public void ChangeInput(string input) {
        // TODO: act on the input change in some way
        // (the more you tell us in your question,
        // the better we can tailor our examples)
    }
}

```

Then you can make a new Game Manager via the Assets \> Create menu or by right-clicking in your project window.

Drag that game manager into your button's `OnClick` event, and you can access its methods directly - no extra "glue" script needed:

One thing to watch for with assets that aren't inside your scene: changes to them that you make in play mode aren't automatically undone when you exit play mode. So if you want to maintain an initial state that's unaffected by runtime changes, you can do so with a nested struct or class.

```
[System.Serializable]
public struct GameManagerState {
   // TODO: put all your necessary state information here.
}

// Set this in the inspector to configure the starting state of your script,
// but treat it as "read-only" in your code, so it's preserved unmodified.
[SerializeField]
GameManagerState _initialState;

// Use this as your read-write copy at runtime to handle any mutation you need.
// Peek at this in the inspector to view runtime changes to your state.
[SerializeField]
GameManagerState _currentState;

void Awake() {
    // Shallow copy. Do a deep copy if you have mutable nested data
    // that needs to be separated from the initial template.
    _currentState = _initialState;
}

```

# Answer
> 3 votes
The current setup I'm using is to have a scene dedicated to GameManager objects (input, audio, game services, etc). Obviously that means I'm using a multi-screen setup. It looks like this:

* Loading scene
* Game Manager scene
* Main menu scene
* UI scene
* Base level scene (used by all levels)
* Unique scene per level

At runtime, the Loading scene scene is set as the default and loads any other needed scenes (`SceneManager.LoadSceneAsync(names[index], LoadSceneMode.Additive)`): Game Managers, UI then Menu.

In the editor, only the Loading scene needs to be loaded at all times then any of the other scenes I want to be working on. When I hit play, the Loading scene again takes care of loading the rest of the stuff as needed. There is one catch however: you must prevent the scenes opened in the editor from calling their children's Awake() before they should (the order being Loading -\> Game Manager -\> UI).

To solve that, I have a script attached to the root of each scene that detects `PlayModeChanged` and disable the children until the right moment. I've attached my version of that script below to give an idea.

Finally, here is how to load the scenes in the proper order. This is a SceneManager (not to be confused with Unity's SceneManager). It needs to be able to load a scene additively, remove loaded scenes and detect scenes already loaded. I've removed that code since for clarity.

```
   IEnumerator Start () {
      isLoadingAfterInitialLoad = false;

      yield return StartCoroutine(LoadSceneDirect(SceneType.Manager));
      yield return StartCoroutine(LoadSceneDirect(SceneType.UI));

      // are we already in table or menu for development?
      if( IsSceneActive(SceneType.Menu || IsSceneActive(SceneType.TableBase) )
         yield break;

     yield return StartCoroutine(LoadSceneDirect(SceneType.Menu));
    }

```

The EditorRunningHelper (needs a better name!) below

```
    /// <summary>
/// Utility to help run the game in the editor. On device, the game always starts at the Loading scene, but not so much
/// in the editor. We want to be able to test by running the scene we are in. This helps us do that by disabling entire scenes
/// that would normally be loaded much later.
///
/// Also, using multi-scene we are not garanteed anymore that the Awakes will be called in the proper order ACROSS scenes. It
/// appears that each scene present in the editor when Play is pressed will execute in an undeterminate order. In each scene,
/// Awake call order is respected.
/// </summary>
public class EditorRunningHelper : MonoBehaviour {

   [SerializeField]
   bool waitForGameContextToBeReady = false, waitForUI = false, waitForTable = false, waitForTableBase = false;

   [SerializeField]
   bool debug = false;

   #if UNITY_EDITOR
   static EditorRunningHelper()
   {
      UnityEditor.EditorApplication.playModeStateChanged += PlayModeChanged;
      //      UnityEditor.EditorApplication.update += OnEditorUpdate;
   }

   //   static List<EditorRunningHelper> helpers;
   //   static bool hasStartedHelpers = true;
   //   static bool firstTime = false;

   static void PlayModeChanged(UnityEditor.PlayModeStateChange state)
   {

      if (!UnityEditor.EditorApplication.isPlaying && UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode) {
         //         Debug.Log("About to enter play mode...");
         foreach (EditorRunningHelper helper in GameObject.FindObjectsOfType<EditorRunningHelper>()) {
            //            Debug.Log("Found: " + helper.name);
            helper.SetChildrenActive(false);
         }
      } else if (!UnityEditor.EditorApplication.isPlaying) {
         //         Debug.Log("Editor has stopped");
         foreach (EditorRunningHelper helper in GameObject.FindObjectsOfType<EditorRunningHelper>()) {
            helper.SetChildrenActive(true);
         }
      }
   }

   void SetChildrenActive(bool value)
   {
      foreach (Transform t in transform) {
         t.gameObject.SetActive(value);
      }
   }

   void Awake()
   {
      //      // if the scene was not loaded when we pressed play, we need to turn off the children. Let's just do it in all case, it doesn't hurt
      //      SetChildrenActive(false);
      StartCoroutine(Wait());
   }

   WaitForSeconds s = new WaitForSeconds(0.1f);

   IEnumerator Wait()
   {
      if( debug )
         Debug.Log(name + ": started waiting");
      if (waitForGameContextToBeReady && !Managers.GameContext.isReady)
         yield return s;

      if (waitForUI && FindObjectOfType<MadeOfBits.UI.UIRoot>() == null)
         yield return s;

      if (waitForTable && FindObjectOfType<PinballEngine4.TableSerializer>() == null)
         yield return s;

      if (waitForTableBase && FindObjectOfType<TableBaseTag>() == null)
         yield return s;

      if( debug )
         Debug.Log(name + ": done waiting");
      SetChildrenActive(true);
   }
#endif
}

```

---
Tags: unity, architecture
---


# Question
Title: Moving a GameObject to a position, waiting, and then moving it again
Hello hello :) Ive been attemping to move a platform (a door basically), and it has partually worked. What works so far is i can move an object from A to B and wait, however it will not move it towards C afterwards, here is my code (note that all of the Debug.Logs work). Here is my code.

```
 public class OpenDoor : MonoBehaviour
{
    public Transform origPos;
    public Transform targetPos;
    public float speed;
    public GameObject button;
    private ButtonScript bs;

    private void Start()
    {
        bs = button.GetComponent<ButtonScript>();

    }

    void Update()
    {
        if (bs.buttonActive) {
            Debug.Log("Button Active 2");
            StartCoroutine(MovePlatform());
            bs.buttonActive = false;
        }
    }

    IEnumerator MovePlatform()
    {
        float step = speed * Time.deltaTime;
        bool arrived = false;
        while (!arrived)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPos.position, step);
            if (Vector3.Distance(transform.position, targetPos.position) == 0)
            {
                Debug.Log("DISTANCE 0");
                arrived = true;
            }
            yield return null;
        }
        if (arrived) {
            Debug.Log("Arrived");
            yield return new WaitForSeconds(1);
            Debug.Log("Waited");
            transform.position = Vector3.MoveTowards(transform.position, origPos.position, step);
        }

    }
}

```

Any assisstance would be greatly appreciated :)

# Answer
> 3 votes
You can do this more simply by having one coroutine that expresses the sequence of actions you want to perform:

```
IEnumerator MovePauseAndReturn() {
    yield return MoveTo(targetPos);
    yield return new WaitForSeconds(1);
    yield return MoveTo(origPos);
}

```

And a workhorse that performs the move:

```
IEnumerator MoveTo(Transform destination) {
    while (transform.position != destination.position) {
        transform.position = Vector3.MoveTowards(transform.position, destination.position, speed * Time.deltaTime);
        yield return null;
     }
}

```

Since the same code is doing the work of moving there and moving back, you don't have to repeat yourself, and you can't introduce bugs where one move works but the other doesn't.

Note that you shouldn't pre-cache the `step` at th start of the coroutine: because frame rate can vary, this can lead to you using too long a timestep on short frames or vice versa, if the frame you started on isn't the same length as every subsequent frame the coroutine runs.

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


# Question
Title: What is the signifigance of the Dot Product in World to Local Transformations?
Looking for help understanding why this World to Local Space function works.

I'm working my way through Buckland's Programming Game AI By Example The following function is used in the book to convert a point from world space to an agent's local coordinate space (its i hat and j hat are AgentHeading and AgentSide respectively)

```
    inline Vector2D PointToLocalSpace(const Vector2D &point,
                             Vector2D &AgentHeading,
                             Vector2D &AgentSide,
                              Vector2D &AgentPosition)
{

    //make a copy of the point
  Vector2D TransPoint = point;

  //create a transformation matrix
    C2DMatrix matTransform;

  double Tx = -AgentPosition.Dot(AgentHeading);
  double Ty = -AgentPosition.Dot(AgentSide);

  //create the transformation matrix
  matTransform._11(AgentHeading.x); matTransform._12(AgentSide.x);
  matTransform._21(AgentHeading.y); matTransform._22(AgentSide.y);
  matTransform._31(Tx);           matTransform._32(Ty);

  //now transform the vertices
  matTransform.TransformVector2Ds(TransPoint);

  return TransPoint;
}

```

I've been learning about vectors and matrices for the last three weeks and still I'm having a *lot* of trouble understanding why this works in terms of vectors and matrices. What is the reason for using a a dot product in the translation coordinates? Why is it the dot product of the agent's position and its heading? What does this dot product correspond to geometrically?

Why not just translate by the Agent's position?

Are there any simpler ways of representing this algorithm?

# Answer
> 2 votes
This is a vector projection. Dotting a vector like `AgentPosition` with a unit direction vector like `AgentHeading` or `AgentSide` gives you the signed length of the component of that vector parallel to that direction.

Doing it with each perpendicular axis direction lets you express a point from one coordinate system in a new coordinate system with those direction vectors as its basis.

So `AgentPosition.Dot(AgentHeading)` answers "how far is the agent from the origin, along the heading direction?" and `AgentPosition.Dot(AgentSide)` does the same for the side direction. Negating these flips the question: "how far is the origin from the agent, along this direction?"

Combined, `Tx` and `Ty` now hold the position of the world origin, from the perspective of the agent's local coordinate system, where +x is its heading, and +y is its side.

A simpler version of this algorithm (assuming the heading and side vectors are perpendicular unit vectors, so no scaling or shearing) would be:

```
inline Vector2D PointToLocalSpace(const Vector2D &point,
                             Vector2D &AgentHeading,
                             Vector2D &AgentSide,
                              Vector2D &AgentPosition)
{
  // Get the world space vector from the agent to the point.
  Vector2D offset = point.Subtract(AgentPosition);

  // Project this offset onto our heading & side directions to put it in local space.
  Vector2D local;
  local.x = offset.Dot(AgentHeading);
  local.y = offset.Dot(AgentSide);

  return local;
}

```

If you expand out the math, you'll find this is equivalent to the original function:

```
local.x = offset.x * AgentHeading.x + offset.y * AgentHeading.y
        = (point.x - AgentPosition.x) * AgentHeading.x + (point.y - AgentPosition.y) * AgentHeading.y
        = (point.x * AgentHeading.x + point.y * AgentHeading.y) + -1 * (AgentPosition.x * AgentHeading.x + AgentPosition.y * AgentHeading.y)
        = point.Dot(AgentHeading) + -1 * AgentPosition.Dot(AgentHeading)
        = Result of multiplying the point with the first column of matTransform

```

We've just done the subtraction first, before we multiplied by the heading/side. In the matrix version, the subtraction happens after the multiplication by heading/side, so we need to "pre-multiply" the contribution of the heading & side vectors into it, to accomplish the same outcome.

---
Tags: c++, vector, matrix, transformation, linear-algebra
---


# Question
Title: Detect which tile in a tile palette a player is colliding with
I have a megaman-style platformer that I've been working on for a while now. I'd like to have my scene set up so that when a player interacts with certain tiles, it will have some sort of effect on the player.

This could easily be achieved with creating individual sprites for the aforementioned interactables, but I'd ideally like to be able to have a portion of my script handle it so that everything besides the player and enemies would be tilemaps.

For instance, I have a tile that would act as a treadmill that moves the player along in one direction. Another tile would be bouncy, and another would deal damage.

I have the game set up right now to detect when the player is touching a tile, but I have no way of being able to tell which tile the player is touching. Is there a way to be able to compare programmatically which tile from a tile palette my player's hitbox is currently touching?

# Answer
> 1 votes
If you want to know what tile is at a particular location, you can just ask the tilemap. Then you can use that tile to look up into a mapping of which effect to call:

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

public class TileCollisionEffect : MonoBehaviour
{
    // Define what kind of script methods can handle our tile collision events.
    [System.Serializable]
    public class CollisionEvent : UnityEvent<Collision2D> { }

    // Create a data structure to pair up a particular tile with a particular effect.
    [System.Serializable]
    public struct TileEffect {
        public TileBase tile;
        public CollisionEvent effect;
    }

    // Expose in the inspector a list of tile-effect mappings.
    public TileEffect[] effects;
    Dictionary<TileBase, CollisionEvent> _effectMap;

    // Pack our map of tile effects into a dictionary for ease of lookups.
    private void OnEnable() {
        if (_effectMap != null)
            return;

        _effectMap = new Dictionary<TileBase, CollisionEvent>(effects.Length);
        foreach (var entry in effects)
            _effectMap.Add(entry.tile, entry.effect);
    }

    private void OnCollisionEnter2D(Collision2D collision) {
        // If you know in advance what tilemap you're going to collide with,
        // you can cache this reference instead of searching for it with GetComponent.
        var map = collision.collider.GetComponent<Tilemap>();
        var grid = map.layoutGrid;

        // Find the coordinates of the tile we hit.
        var contact = collision.GetContact(0);
        Vector3 contactPoint = contact.point - 0.05f * contact.normal;
        Vector3 gridPosition = grid.transform.InverseTransformPoint(contactPoint);
        Vector3Int cell = grid.LocalToCell(gridPosition);

        // Extract the tile asset at that location.
        var tile = map.GetTile(cell);

        if(tile == null)
            return; // No valid tile! Abort!

        // Check if we have an effect for this tile type. If so, fire it!
        if (_effectMap.TryGetValue(tile, out CollisionEvent effect) && effect != null)
            effect.Invoke(collision);
    }

    public void Conveyor(Collision2D collision) {
        // TODO: apply conveyor effect.
        Debug.Log("Conveyor effect!");
    }

    public void Bounce(Collision2D collision) {
        // TODO: apply bouncy effect.
        Debug.Log("Bounce effect!");
    }
}

```

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


# Question
Title: How to properly manage game music and sounds?
I'm developing a WinForms customized version of Pac-Man for a Software Engineering project and I reached the point where I have to implement music and sound effects. I used the MVC architectural pattern, so almost every entity in the game has: a model, a view and a controller (for example, I have a MainMenuModel, a MainMenuView and a MainMenuController).

In order to play music and sounds I decided to use the System.Windows.MediaPlayer class (because the System.Media.SoundPlayer one cannot play two sounds simultaneously). More specifically, I put in every controller the related MediaPlayer objects. So, for example, in the MainMenuController I put: the MenuBackgroundMusicPlayer, the MenuItemSelectionSoundPlayer and the MenuItemOpeningSoundPlayer.

This solution works fine, but I would like to know if it is considered bad design to have multiple instances of MediaPlayer spread all over the controllers, instead of having a single static centralized MediaPlayer instance that handles everything. The problem with having a single instance is that I don't know then how to play two or more sounds simultaneously, because a single MediaPlayer object can handle a single media at a time.

# Answer
> 0 votes
The design pattern of "having a single static centralized instance" is called a "Singleton". See description here

There are some classes from microsoft who are supposed to be used as a singelton for resource and caching reasons. Like HttpClient

For System.Windows.Media.MediaPlayer there seems to be no limitation of this kind. In this case I dont see any reason to use it as a singleton. For a more detailed discussion of the pros and cons of singletons look e.g. here

Its considered bad design to use a singleton without very good reason. This is because singletons are hard to unittest and limit your design possibilities in the future.

---
Tags: c#, game-design, audio, windows-forms
---


# Question
Title: How do I slow down my character while running?
```
 void Movement()
{
    transform.Translate(Vector3.forward * 10 * Time.deltaTime);

    if(Input.GetKey(KeyCode.S))
    {
        transform.Translate(Vector3.forward * 3 * Time.deltaTime);
    }

    if(Input.GetKeyUp(KeyCode.S))
    {
        transform.Translate(Vector3.forward * 10 * Time.deltaTime);
    }
}

```

I tried this code but seems to me, it didn't work as I expected it to.

What I expect:

* my character moves along at a speed of 10 automatically
* when the S key is held, the character slows down to a speed of 3 instead
* when the S key is released, the character goes back to their default speed of 10

What I observe:

* the character does not slow down when the S key is pressed

How can I fix this?

# Answer
> 0 votes
It looks like you're trying to switch between two speeds: 10 when no key is pressed, and 3 when the `S` key is pressed. (S for "Slow"?)

The trouble is that the first line of your function has already moved the object at speed 10, no matter what the state of the keys might be. Then if `S` is pressed/held, you move *again* at speed 3, for a total movement of speed 13! So you sped up instead.

Lastly, if the `S` key was released this frame, you move again at speed 10, in addition to the movement at the start of the function, giving you a momentary burst of 20 speed just as the key is released.

A clearer way to write what it looks like you mean would be...

```
// Expose Inspector variables for clarity and ease of tuning,
// rather than "magic number" constants you need to edit in code.
public float fastSpeed = 10f;
public float slowSpeed = 3f;

void Update() {
    // By default, use the fast speed.
    float currentSpeed = fastSpeed;

    // But if the player has the S key held, choose the slow speed instead.
    if(Input.GetKey(KeyCode.S))
        currentSpeed = slowSpeed;

    // Move at the chosen speed.
    transform.Translate(0, 0, currentSpeed * Time.deltaTime);
}

```

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


title: What does this all mean for the enemy?

text:
# Question
Title: What does this all mean for the enemy?
This enemy JS file in a space shooting game was part of tutorial but there was no explanation to what is does and more importantly **Why**.

Can you please help me explain what the following mean in the code?

* "dt"
* "Math.abs"

```
moveTowardPoint(dt) {
        let inc = dt * this.speed;
        this.incrementPosition(inc * this.targetWayPoint.dir_x, inc * this.targetWayPoint.dir_y);

        if(Math.abs(this.position.x - this.targetWayPoint.point.x) < Math.abs(inc) &&
        Math.abs(this.position.y - this.targetWayPoint.point.y) < Math.abs(inc)) {
            this.updatePosition( this.targetWayPoint.point.x,  this.targetWayPoint.point.y);
        }

        if(this.position.equalToPoint(this.targetWayPoint.point.x, this.targetWayPoint.point.y) == true) {
            if (this.targetWayPointNumber == this.lastWayPointIndex) {
                this.killMe();
                console.log('reached end');
            } else {
                this.setNextWayPoint();
            }
        }
    }
```

Small points are more than enough. I have an overall understand that the file needs to do.

Thank you!

# Answer
`dt` is very likely a shorthand for "delta time", the time in seconds which expired since the last time this method was called. It is not easy to ensure that a function in JavaScript gets called in *exact* time intervals. It is usually easier to just schedule it to be executed when opportune (like on `requestAnimationFrame`) and take the time since the last update into account.

`*` is the symbol for multiplication in JavaScript. `let inc = dt * this.speed;` means "the variable inc is the speed of this object, multiplied with delta time". Speed multiplied by time is distance. So it appears to be the distance by which something is supposed to move during this update.

The purpose of `Math.abs` can be found in the documentation (Which I, by the way, just accessed by entering "Math.abs JavaScript" into my browsers search bar). It removes the minus-sign from numerical values. `Math.abs(-3)` is 3. `Math.abs(3)` is also 3. In this case it is used to measure the difference between two values. The author does not care which number is bigger and which one is smaller, they just want to know how far the two points are apart from each other. So they subtract the two values from each other and run the result through `Math.abs`. That way they get the same value for `6 - 3` as they get for `3 - 6`.
> 1 votes

---
Tags: javascript, support
---


# Question
Title: How to increase fighting stats of a player without increasing HP?
I'm currently making a simple game that requires a fighting system. The game consists of many (more than 100) levels that the player needs to go through to get to the end. In each level you get to fight creatures and monsters, and you evolve your skills by doing so (there are also other ways to do that but they're not relevant for the purpose of this post). The problem I'm having is that when the player reaches the higher levels, the fights become very hard to balance:

To calculate the damage the player does to the enemy, I was basing it on the player's fighting skill (which goes up with each fight) and the opponent's fighting skill (which is based on the level). However, if I make it so the damage is proportional to the ratio of the skills, when both skills are high, neither of them will do much damage. On the other hand, if I base it on the difference of these skills, a player with less stats than a monster can't to any damage to it (which is not what I want, as some monsters may have more fighting skills but you have more health, and vice-versa).

My question is if there's any easy way to calculate the damage that would scale well when both parties are very strong.

# Answer
I don't know the right way to do this.

But:

1. For balancing you can use Machinations, this is an interactive tool and now it's free. It's interesting alternative for balancing tables.
2. Maybe analyzing the fighting system (especially system of counter picks and balancing on different levels) of Pokemon game series can help you. Probably, if you have several types of fighters in your game and, for example, as fire pokemon has bonuses in battle with water pokemon, swordsman can have increased stats or more critical hit probability in battle with archer.
3. Final Fantasy 7 has unusual progress system: when you upgrade the player, you get material orbs. Each orb affects on different stats, but anytime you can shift them and turn your warrior player into support player or mage and vise versa. So to win the battle you need to choose orbs properly.
> 1 votes

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


# Question
Title: How to run 'Call in Editor' Functions that are implemented in Level Blueprints?
I have a `Blueprint Function` within a `Level Blueprint`, marked as `Call In Editor`.

How can I run `CallInEditor` functions in Level Blueprints?

# Answer
I don't think that's possible. Direct quote from the offical docs on " Calling Blueprints in the Editor"

> The steps described below work for any Blueprint class that you can place in a Level—that is, any class that derives directly or indirectly from Actor.

Source: https://docs.unrealengine.com/en-US/Engine/Editor/ScriptingAndAutomation/Blueprints/CallInEditor/index.html

If possible I'd suggest placing an empty actor into your level and creating your function there and make it editor-callable. This should work fine and won't render any problems as far as I can assess the situation.
> 3 votes

---
Tags: unreal-4, unreal, blueprints, editors
---