# Question
Title: Mesh is displayed differently in Unity with some undesireable visual elements
I'm not sure what to make of this:

this is what it looks like in unity scene view/game view

This is, for example, the same upright triangle in microsoft's 3d object viewer:

I have no clue what to make of the undesirable, shadowed lines in unity.

How do I get rid of them?

Edit: Tried looking at face normals in blender, they seem fine to me

setting `Normals` to `None` on the mesh results in this:

Setting it to `Calculate` or `Import` doesn't seem to make a difference, and disabling/enabling mesh optimization or mesh compression doesn't seem to make a difference. Nor does disabling `Generate Lightmap UVs`

# Answer
> 1 votes
After playing quite a bit with the import settings, I decided to try setting `Smoothness source` to `None`.

Lo and behold!

Setting it to `From Smoothing Groups` (as opposed to `Prefer Smoothing Groups`) produces the same results.

I have no clue what to make of it.

---
Tags: unity, 3d-meshes
---


# Question
Title: How would you write a multithreaded gameloop in C++20 (+) or C++/WinRT?
What are the pros/cons of using either C++20 std:async or C++/WinRT's asynchronous thread and messaging support?

What would the code look like when implementing multithreaded game-loops that interoperate through asynchronous messaging?

Basically, I am considering starting up a bunch of different system component threads which would then each manage their own different multithreaded sub-jobs, (components like the UI, Audio, Chat, Network, World, etc). ***But regardless of how this can be designed, I would like to understand the different usages of the APIs to use asynchronous messaging for interoperation between system threads.***

Most game-loops are a bit different than this model in that they have a tight loop tied to framerate, etc. Although this still applies for UI components, it seems more ideal to separate the other game components from this loop.

# Answer
> 4 votes
When you are separating a game engine into threads, then there are two main concerns:

* Each worker-thread should have roughly the same amount of work to do
* Avoid communication and data sharing between threads as much as possible, because those cause slowdowns at best and impossible to reproduce bugs at worst (race conditions and deadlocks).

For that reason it is usually not a good idea to separate threads by system. Different systems will have vastly different CPU load, and it's often hard to anticipate which ones will be the biggest resource hogs. So there is a pretty good chance that one CPU core gets to do all the work while the others idle most of the time. That's not how you make efficient use of modern multi-core CPUs. Also, threads often have a lot of shared data. Network and input are pushing events for the game mechanics and the game mechanics are pusing events for the audio, ui and network, while the rendering loop tries to visualize a world that is at the same time being changed by the game mechanics. Lots of shared data structures, which means lots of opportunities for race conditions and deadlocks.

A better approach to utilizing multiple cores is to parallelize on the task level. Look for computationally expensive tasks in your game and break them into "jobs". A "job" is an operation that runs once on a well-defined piece of data. You then distribute those jobs onto worker-threads and have certain sync-points where you wait for all running jobs to finish.

For example, let's say you have a terrain erosion mechanic in your game that is very CPU-intensive. How do you benefit from parallelization in this case?

1. Separate the world into chunks.
2. Create jobs to calculate the erosion for each of those chunks.
3. Send those jobs to the worker threads
4. Wait at a sync-point for the erosion-jobs to finish
5. Write the changed data to the global world-state.

All of that happens each game tick.

Yes, you can run jobs in parallel that do vastly different things. This can improve performance by reducing sync-points and improving core utilization. But when you do that, you need to make sure that those parallel tasks don't share any data that gets changed at the same time.

---

Nevertheless, there are some systems that aren't really CPU-intense but still require their own threads due to real-time requirements. Those are often audio, input and networking. Although there are middlewares and libraries which can abstract those away. If you can use those, you should. But if you want to do them yourself (you are creating an own game engine in 2023, so you got to be really committed to the do-it-yourself mindset), then the usual way to communicate between those threads and the main game loop are event queues. When a network or input event occurs, that event gets pushed to a queue. At a controlled point of the main game loop, the main thread empties that queue. That queue needs to be thread-safe to avoid data corruption in case that an event gets pushed while the main thread empties it.

Do not react to such events immediately when they occur, because you don't know what the main thread is doing. It is very well possible that it currently reads data that gets written by the event handler, resulting in impossible to reproduce bugs.

---
Tags: c++, multithreading, async, c++cli, c++-winrt
---


# Question
Title: What is a good algorithm to detect collision between moving spheres?
If (for the purpose of collision detection) 3D objects are represented in a game by spheres, what is a good algorithm to detect a collision between spheres?

If each object has a position as of the last frame and a new (desired) position, what is a good algorithm that will identify collisions where the spheres didn't intersect in the previous frame, and they may not intersect in the second frame, but they did intersect somewhere in between?

# Answer
Basically you're looking for a trace.

This page will probably help you: http://www.realtimerendering.com/intersections.html

> Moving Sphere/Sphere: (location) Add the radius of the moving sphere to the static sphere, and treat the moving sphere as a ray. Use this ray to perform ray/sphere intersection. See Gomez; Schroeder for code (article has bug in derivation, code is fine); and RTR2, p. 622.
> 19 votes

# Answer
Use a sweep test as demonstrated in this Gamasutra article. (Or the port to gamedeveloper.com...)
> 8 votes

# Answer
Off the top of my head:

1. Create two line segments from the middle of each circle from where it started to where it moved to in that time step.
2. Find the min distance between those two line segments; as is explained here.
3. If that distance is less than or equal to the radius of the first circle plus the second then they collided; otherwise they did not.

And that is all there is to it, I would expect that to be pretty fast.
> 5 votes

# Answer
Answers here well explained the concept, but seems code answer was not posted yet:

```
// predicts collision time between two moving objects
// objects are spheres moving in 3D space with constant velocities
// returns PositiveInfinity if collision will never happen

float GetCollisionTime(WorldObject a, WorldObject b)
    {
    // relative velocity and position
    var rel_v = a.Velocity - b.Velocity;
    var rel_pos = a.Position - b.Position;

    float start_dist_squared = rel_pos.LengthSquared();
    double need_dist_squared = M.Pow(a.Radius + b.Radius, 2);

    // skip if already collide
    if (start_dist_squared <= need_dist_squared)
        return 0;

    float rel_dot = Vector3.Dot(rel_pos, rel_v);
    float rel_v_squared = rel_v.LengthSquared();

    // skip if they move away
    if (rel_dot > 0 || rel_v_squared == 0)
        return float.PositiveInfinity;

    float min_dist_t = -rel_dot / rel_v_squared;
    float min_dist_squared = (rel_pos + rel_v * min_dist_t).LengthSquared();

    // skip if they never touch
    if (min_dist_squared > need_dist_squared)
        return float.PositiveInfinity;

    double collide_dist_to_min_squared = need_dist_squared - min_dist_squared;
    float collide_t_before_min = (float)M.Sqrt(collide_dist_to_min_squared / rel_v_squared);

    return min_dist_t - collide_t_before_min;
    }

```

Squared distances are used only to optimize out slow root calculations.
> 3 votes

# Answer
Collision detection for moving object is typically called "Swept volume calculation", here are some codes / articles about this subject.

http://www.gpu-voxels.org/demos/ (Demo)

Source code libraries:

https://github.com/fzi-forschungszentrum-informatik/gpu-voxels

https://libigl.github.io/tutorial/#swept-volume

https://github.com/gradientspace/geometry3Sharp

Articles:

http://gamma.cs.unc.edu/SV/sm03.pdf

https://www.cs.columbia.edu/~allen/PAPERS/abrams.swept.pdf (No source code unfortunately)

http://www.realtimerendering.com/intersections.html (Rather heavy collection of links)
> 0 votes

# Answer
Speaking as someone who's done this: *it's not worth the hassle*. Unless your game design absolutely needs it, and it almost certainly doesn't, you'll spend far more effort getting sweeping working than you really expect. And it will be slower than you wanted it to be.
> -3 votes

---
Tags: collision-detection
---


title: Can a game use mythology-related names?

text:
# Question
Title: Can a game use mythology-related names?
For instance can a game for collecting pets (such as cats, dogs, dragons, etc.)include a list of mythological names and then name the pets using these names?

# Answer
> 0 votes
Yes it can.

But you can't dress the pet, or draw it in a similar fashion that has been done before. You can't name your cat pet Zeus and dress it like Zeus the Mighty, for instance.

IANAL.

# Answer
> 4 votes
When it comes to legal questions, then don't rely on opinions from anonymous strangers from the Internet like me. Before you publish such a project, get a consultation with a real lawyer who specializes in intellectual property law. But the way I as a legal layman understand copyright and trademark law is this:

Regarding **copyright**: Ancient mythology is free for the taking, because the authors are already dead for much longer than 70 years. Just be careful that what you take is really from *ancient* mythology and not from another much more recent pop culture adaptation of that mythology. For example, when you have the Norse god Thor in your game, that's OK. But if that Thor has lots of aspects that aren't from Norse mythology but actually adapted from the Marvel character of the same name, then you might get into trouble with the almighty legal department of The Mouse.

But then you still need to be wary of **trademarks**. Because with trademarks, the question is not "who invented it", but "who uses it in commerce".

The purpose of trademarks is to avoid consumer confusion. The legal argument that is made in court to get someone liable for trademark infringement is "Consumer who want to buy our product could get confused by the similar name of this competing product and buy that instead".

For example, if you would name a game "Hades", then you could probably get into trouble with Supergiant Games because consumers could mistake your game for theirs and thus cost them sales. The excuse "But the term Hades is a concept from Greek mythology that is thousands of years old" would probably not save you. However, if you have just a location named "Hades" in your game while the game itself is named something completely different, that's probably not a trademark violation, because with an entirely different title it's unlikely to lead to consumer confusion.

---

For more information on copyright and trademarks for game developers, I recommend this video presentation from GDC 2018: Practical IP Law for Indie Developers 301: Plain Scary Edition.

---
Tags: legal, copyright
---


# Question
Title: Unity on Linux dosen't show editor panels
I've recently installed Unity Hub on my Kubuntu 22.04 installation with the unofficial Appimage. I have tried this with the `unityhub` package too, and still have the same problem.

It's pretty simple; when I try to open something like "edit \> preferences" in the Unity editor, it doesn't show up. The "preferences" panel is there, because going to Window \> Panels shows me it's there, just clicking it does nothing.

I have tried to change the Layout to default, didn't do anything.

I have tried using a different Unity editor version, same problem.

When I had a fresh reboot, I opened up the project settings; that worked, and the shortcuts panel also showed up, but the preferences window did not and after that project settings also didn't show up (like the other panels, it exists, but I can't see it).

I have no idea what the problem is; desktop environment? compositor? NVIDIA settings? It seems to work for other people, as I didn't find anything related to this.

Any help would be appreciated.

# Answer
I have found the problem. The panels are out of the screen, that's why I can't see them.

I you use Kubuntu, you can hold your mouse to the top left corner of your screen and see all open windows. Select the "preference" Window e.g. and press `alt` \+ `F3` and `X` or `S` \+ `1`/`2` to select your screen.

It may be because I have a dual screen setup, but I don't know why the screens start in limbo.
> 2 votes

---
Tags: unity, linux
---


# Question
Title: Respawn Player to Respawn point when colliding with a Hazard
I have grid movement set up for the player within a set space. The player moves one unit at a time and can move several units when holding down a direction key. I would like the player to respawn back to a respawn point marked by an empty object when the player collides with a hazard's collider.

I have the GridMovement script on the player:

```
using System.Collections;
using UnityEngine;

public class GridMovement : MonoBehaviour {
    [SerializeField] private float forwardBoundary = 13f;
    [SerializeField] private float leftBoundary = -13f;
    [SerializeField] private float backBoundary = -13f;
    [SerializeField] private float rightBoundary = 13f;

    //[SerializeField] private Transform respawnPoint;

    private bool isMoving;

    //time it takes for player to move from originalPosition to targetPosition. In seconds (so 1/5th of a second)
    private float timeToMove = 0.2f;

    void Update() {

        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) StartMove(Vector3.forward);
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) StartMove(Vector3.left);
        if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) StartMove(Vector3.back);
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) StartMove(Vector3.right);
    }

    private bool StartMove(Vector3 direction) {
        if (isMoving) return false;
        StartCoroutine(MovePlayer(direction));
        return true;
    }

    private IEnumerator MovePlayer(Vector3 direction) {
        isMoving = true;

        float elapsedTime = 0;

        Vector3 originalPosition = transform.position;
        Vector3 targetPosition = originalPosition + direction;

        if (ValidateGridPosition(targetPosition) == targetPosition) {
            while (elapsedTime < timeToMove) {
                transform.position = Vector3.Lerp(originalPosition, targetPosition, (elapsedTime / timeToMove));
                elapsedTime += Time.deltaTime;
                yield return null;
            }
        }
        transform.position = ValidateGridPosition(targetPosition);

        isMoving = false;
    }

    private Vector3 ValidateGridPosition(Vector3 position) {
        if (position.x > rightBoundary) {
            position.x = rightBoundary;
        } else if (position.x < leftBoundary) {
            position.x = leftBoundary;
        } else if (position.z > forwardBoundary) {
            position.z = forwardBoundary;
        } else if (position.z < backBoundary) {
            position.z = backBoundary;
        }
        return position;
    }
}

```

The player has an empty script on it called Player because it is more scalable than using Tags in Unity. This is the Respawn script on the hazard:

```
using UnityEngine;

public class Respawn : MonoBehaviour {
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawnPoint;

    private void OnTriggerEnter(Collider other) {
        Debug.Log("We've collided!");
        Player p = other.GetComponent<Player>();
        if (p != null)
            player.transform.position = respawnPoint.transform.position;
    }
}

```

"We've collided!" displays in the console so I'm guessing the player isn't being teleported back to the respawn point because of Lerp in the GridMovement script? How do I interrupt that?

# Answer
I figured out if I wanted the player to move, collide with a hazard, stop moving, respawn and then be able to move again, I needed to write the following in the GridMovement class:

```
public Coroutine movePlayerCoroutine;

```

In the StartMove method I set:

```
movePlayerCoroutine = StartCoroutine(MovePlayer(direction));

```

Then I created these 2 methods:

```
public void stopMovePlayer() {
     StopCoroutine(movePlayerCoroutine);
}

public void startMovePlayer() {
     StartCoroutine(MovePlayer(this.transform.position));
}

```

stopMovePlayer() and startMovePlayer() creates public methods I can call in Respawn to stop and then start the coroutine once the player has respawned.

This is the updated Respawn class:

```
using UnityEngine;

public class Respawn : MonoBehaviour {
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawnPoint;

    private void OnTriggerEnter(Collider other) {
        Debug.Log("We've collided!");
        Player p = other.GetComponent<Player>();
        if (p != null)
            FindObjectOfType<GridMovement>().stopMovePlayer();
            player.transform.position = respawnPoint.transform.position;
            FindObjectOfType<GridMovement>().startMovePlayer();
    }
}

```
> 0 votes

# Answer
Before really setting the position, do something like disabling the script. You can easily do this by doing `GetComponent<GridMovement>().enabled = false` and when you're basically done setting the new position (respawning), do the opposite `GetComponent<GridMovement>().enabled = true`. Hope this helps :)
> 0 votes

# Answer
Just get a reference to the GridMovement component and tell it to stop running its coroutine.

In GridMovement:

```
public void Stop() {
    StopAllCoroutines ();
    isMoving = false;
}

public void TeleportTo(Vector3 position) {
    Stop();
    transform.position = position;
}

```

Then Respawn can look like this:

```
public class Respawn : MonoBehaviour {
    [SerializeField] private Transform respawnPoint;

    private void OnTriggerEnter(Collider other) {
        if (other.gameObject.TryGetComponent(out GridMovement player)) {

            player.TeleportTo(respawnPoint.transform.position);
        }
    }
}

```
> 0 votes

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


# Question
Title: Can player input be missed while yielding WaitForSeconds?
I just wanted to fact check myself on a scenario where the player may be locked out of input.

With this example, there is a chance that the player's input will not be received if they happen to press the button during WaitForSeconds(), correct?

```
private IEnumerator CheckForButton()
{
    // Check for player input at the beginning of the method
    if (GameEngine.Instance.InputController.playerActions.Menu.Select.WasPressedThisFrame())
        {
            // do stuff
            yield break;
        }

        // Is the player is locked out of input here?
        yield return NewWaitForSeconds(2f)
}

```

To avoid that, would using a loop as a timer and checking for player input like this be a more correct way?

```
private IEnumerator CheckForButton
{
    // Check for input at the beginning of the method
    if (GameEngine.Instance.InputController.playerActions.Menu.Select.WasPressedThisFrame())
    {
        // do stuff
    }
    float t = 0;
    float targetTime = 2f;

    // Also check for input while the timer counts down
    while(t < targetTime)
    {
        if (GameEngine.Instance.InputController.playerActions.Menu.Select.WasPressedThisFrame())
        {
            // do stuff
            yield break;
        }
        t += Time.deltaTime;

        yield return null;
    }
}

```

To be more concise, will the player be locked out of input if they press a button during WaitForSeconds()? Thanks!

# Answer
> 3 votes
Yes, that can definitely cause you to miss the input. Since you are manually checking `wasPressedThisFrame`, the only way to guarantee that you won't miss it is to run that line of code every frame.

The first snippet you posted does not do that; instead, it checks only once, then it reaches the `yield return NewWaitForSeconds(2f)` line, where it will stay until 2 seconds have passed, and then exits the function.

The other option, using a loop with `yield return null`, will work (yielding null just causes the execution to resume at the start of next frame, so there is no frame when the coroutine is just stopped). As a very minor point, with the code as written there is no need to check for input outside of the loop, as the first iteration of the loop is executed right away anyways.

Also, since I think you are using the new Input System, a potentially "better" solution (subjective, really) would be to use action callbacks with a delegate. Something like this, more or less:

```

private void DoStuff(InputAction.CallbackContext ctx)
{
    //process the input here
}
private IEnumerator CheckForButton()
{
    GameEngine.Instance.InputController.playerActions.Menu.Select.performed += DoStuff;
    yield return NewWaitForSeconds(2f)
    GameEngine.Instance.InputController.playerActions.Menu.Select.performed -= DoStuff;
}

```

And if you don't want to create a separate function for `DoStuff`, it can even be a local lambda:

private IEnumerator CheckForButton()
{
    System.Action<InputAction.CallbackContext> DoStuff = (_)=>{/* process the input here*/};
    GameEngine.Instance.InputController.playerActions.Menu.Select.performed += DoStuff;
    yield return NewWaitForSeconds(2f)
    GameEngine.Instance.InputController.playerActions.Menu.Select.performed -= DoStuff;
}

```

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


# Question
Title: How to handle Tilemap Collision with only the character's lower body, while the head is allowed to overlap tiles above?
I have just started working with Unity to simply learn how it works. I've been trying to get grid-based movement and collision with a tilemap working, and it's mostly there, but there's one bit that's not quite right and I'm unsure as to why.

Currently, the player sprite is moved in a grid-based fashion. When it approaches an obstacle, the movement script uses `Physics.OverlapCircle`, filtering on the collision layer, to determine whether the player can advance to the next grid cell. This works, save for the fact that it appears to be using the entire bounds of the sprite for collision detection, whereas I want to allow the top portion of the sprite (i.e. the head) to overlap and actually detect collision with the lower portion (the body).

Here is a screenshot of my editor, with the player selected. You can see that the player appears to be covering a 2x2 area of the grid (I think this has to do with the size of the sprite not matching the tilemap). The player sprite is 32x32 with `Pixels Per Unit` defined as 32, whereas the tilemap has a `Pixels Per Unit` defined as 16.

Here is my movement script, as well. The method at the bottom of the file, `CanMoveToTargetPosition` covers the overlap logic.

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

public class Movement : MonoBehaviour
{
    private const float movementSpeed = 5f;

    public Transform movementTarget;
    public LayerMask collisionLayer;
    public Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        movementTarget.parent = null;
    }

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

        if (ShouldCheckMovement())
        {
            CheckInputForMovement();
        }
    }

    private void MovePlayer()
    {
        transform.position = Vector3.MoveTowards(transform.position, movementTarget.position, movementSpeed * Time.deltaTime);
    }

    private bool ShouldCheckMovement() => Vector3.Distance(transform.position, movementTarget.position) <= .05f;

    private void CheckInputForMovement()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        float horizontalPositive = Mathf.Abs(horizontal);
        float verticalPositive = Mathf.Abs(vertical);

        var velocity = Vector3.zero;
        if (horizontalPositive == 1f)
        {
            velocity = new Vector3(horizontal, 0f);
        }
        else if (verticalPositive == 1f)
        {
            velocity = new Vector3(0f, vertical);
        }

        var targetPosition = movementTarget.position + velocity;
        if (!CanMoveToTargetPosition(targetPosition))
        {
            movementTarget.position = targetPosition;
        }

        animator.SetFloat("Horizontal", horizontal);
        animator.SetFloat("Vertical", vertical);

        float speed = Mathf.Clamp((horizontalPositive + verticalPositive) / 2f, 0f, 1f);
        animator.SetFloat("Speed", speed);
    }

    private bool CanMoveToTargetPosition(Vector2 targetPosition) =>
        Physics2D.OverlapCircle(targetPosition, .2f, collisionLayer);
}

```

The tilemap has an attached `TilemapCollider2D` component. I've tried including a `RigidBody2D` with a `CompositeCollider2D`, but this actually makes the result worse - the player collides with some parts of the collision layer, but can walk through others.

I've tried using a `BoxCollider2D` to allow me to define the actual collision area on the player, but I don't seem to be able to then get the overlap collision working with the tilemap.

Here is a view of my collision layer with the tilemap collision areas defined:

Finally, you can see a recording of my issue as a GIF or MP4.

I'm sure this is more to do with my lack of understanding of how the physics overlap, or colliders work in Unity, but I'm struggling to find any resources to help with this specific issue. So, any links for further reading would be appreciated! I did manage to get non-grid-based movement working with collision detection by just using a `Rigidbody2D` and `BoxCollider2D` on the player, and `TilemapCollider2D`, `RigidBody2D` and `CompositeCollider2D` on the tilemap. But I would like to retain the grid-based movement.

Any help would be appreciated! Thanks.

# Answer
I have managed to find an answer, though I am still open to any better answers.

By adding a child object to the player, I was able to position it (by initially adding a square sprite renderer with white colour, so I could see it). I positioned this child object in the area I wanted to collide. I changed my collision detection to be based on the position of this child but still moved the parent object as before.

Here is the updated example, where `colliderObject` is this child object.

```
using UnityEngine;

public class Movement : MonoBehaviour
{
    private const float movementSpeed = 5f;

    public Transform movementTarget;
    public LayerMask collisionLayer;
    public GameObject colliderObject;
    public Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        movementTarget.parent = null;
    }

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

        if (ShouldCheckMovement())
        {
            CheckInputForMovement();
        }
    }

    private void MovePlayer()
    {
        transform.position = Vector3.MoveTowards(transform.position, movementTarget.position, movementSpeed * Time.deltaTime);
    }

    private bool ShouldCheckMovement() => Vector3.Distance(transform.position, movementTarget.position) <= .05f;

    private void CheckInputForMovement()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        float horizontalPositive = Mathf.Abs(horizontal);
        float verticalPositive = Mathf.Abs(vertical);

        var velocity = Vector3.zero;
        if (horizontalPositive == 1f)
        {
            velocity = new Vector3(horizontal, 0f);
        }
        else if (verticalPositive == 1f)
        {
            velocity = new Vector3(0f, vertical);
        }

        var collisionTarget = colliderObject.transform.position + velocity;
        if (!CanMoveToTargetPosition(collisionTarget))
        {
            movementTarget.position = transform.position + velocity;
        }

        animator.SetFloat("Horizontal", horizontal);
        animator.SetFloat("Vertical", vertical);

        float speed = Mathf.Clamp((horizontalPositive + verticalPositive) / 2f, 0f, 1f);
        animator.SetFloat("Speed", speed);
    }

    private bool CanMoveToTargetPosition(Vector2 targetPosition) =>
        Physics2D.OverlapCircle(targetPosition, .2f, collisionLayer);
}

```

Here is a video of the solution in action:

I will keep this answer as unaccepted for now, in case anyone has any better answers.
> 0 votes

# Answer
In Unity, you usually don't need to check if the movement destination is free, because collision detection and resolution can be handled by the engine. When you use rigidbody movement, then the engine will do so automatically and just not move the rigidbody when there is an obstacle in the way. Or if that object has a dynamic rigidbody, it will push it out of the way in a physically correct manner.

But in order to do that, you actually have to use the `Rigidbody` / `Rigidbody2D` component for movement. When you use `transform.position = ...` then you are not *moving* the object, you are *teleporting* the object. Which means the engine will be perfectly fine with the object getting teleported through a wall or even into a wall.

If you want to move an object in a physical way, use `GetComponent<Rigidbody2D>().MovePosition(newPosition)`. This will move the object towards the position, and stop when there is another solid collider (with a static or kinematic rigidbody or a rigidbody-less collider with the "static" flag set on the gameObject) in the way. Colliders with dynamic rigidbodies will get pushed out of the way instead, but won't slow the player down.

If you want the player to be able to interact with other dynamic rigidbodies in a more physically realistic way, use `AddForce` instead of `MovePosition` to control its movement. Using forces instead of moving also allows you to make the object retain its momentum, which can sometimes result in a better game experience. But in most cases you might want to increase the linear drag of the rigidbody, as it otherwise often feels far too slippery (the default is intended for objects flying through the air, not for objects moving on a solid surface).

Here is a little demo which shows how different ways to implement movement work in Unity and how they affect gameplay.
> 1 votes

# Answer
First, a design question: Why. Why do you need physics? You could simply ask if the TileMap contains a certain tile that is not walkable, for example, and then, when you walk, check your character to see if he walks into that tile. The colliders seem overkill imho.

Or the other way around: why do you have the tilemap? If these were just prefabs with sprites, you could easily edit their colliders, and probably save you a lot of colliders.

From the video I would conclude that you want your character to be able to walk closer to objects and even behind the fence. So the fence collider should be lower and maybe edit your character to have a smaller collider for walking sake, like a small circle at the base where the feet are, so that his entire upper body can overlap what is behind him.

I suspect that none of your tiles really need a rigidbody component. Let the player do all the collision checks - it is not necessary for both game objects to have a rigidbody. They just need both colliders - if that's the way you want to do it anyway.
> 0 votes

# Answer
Attach Collider2D, RigidBody2D, CharacterController2D to player and use `Move` Method in FixUpdate. Meanwhile, properties of RigidBody2D: Body Type = Dynamic, Simulated = true, Gravity Scale = 0, Constraints - Freeze Rotation Z = true

```
using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class CharacterController2D : MonoBehaviour
{
    #region Move Var

    [SerializeField, Tooltip("Max speed, in units per second, that the character moves.")]
    float speed = 2;

    [SerializeField, Tooltip("Acceleration while grounded.")]
    float walkAcceleration = 20f;

    [SerializeField, Tooltip("Deacceleration while stopped.")]
    float deceleration = 80f;

    [SerializeField, Tooltip("Stop when move input smaller than stopThreshold")]
    float stopThreshold = 0.1f;

    private Rigidbody2D rg;

    private Vector2 velocity;

    public bool isMoving
    {
        get { return velocity != Vector2.zero; }
    }

    #endregion

    private void Awake()
    {
        rg = GetComponent<Rigidbody2D>();
    }

    public void Move(Vector2 moveInput)
    {
        // Move Logic

        if (moveInput.magnitude >= stopThreshold)
            velocity = Vector2.MoveTowards(velocity, speed * moveInput, walkAcceleration * Time.fixedDeltaTime);
        else
            velocity = Vector2.MoveTowards(velocity, Vector2.zero, deceleration * Time.fixedDeltaTime);

        if (velocity.magnitude <= stopThreshold)
            velocity = Vector2.zero;

        Vector2 curPos = new Vector2(transform.position.x, transform.position.y);
        Vector2 nextPos = curPos + velocity * Time.fixedDeltaTime;

        rg.MovePosition(nextPos);
}

```
> 0 votes

---
Tags: unity, 2d, collision-detection, grid
---


title: Weighting navigation mesh nodes for A*

text:
# Question
Title: Weighting navigation mesh nodes for A*
I'm trying to implement path finding for my game using a navigation mesh and A\* search. While I believe I got this working correctly I'm having trouble getting desired results because I don't know how to decide the cost between each node.

While the algorithm correctly chooses the path with the least amount of nodes. Sometimes the result can be quite nonsensical.

Here the entity would take take a detour(yellow) around the obstacle instead of using the more optimal path (green)

Right now each triangle/node has the same cost and I'm not sure how best to compute it since it depends on how the entity is going to travel through the triangles. I've been thinking about splitting the triangles further to make sure they have about the same size but this might not help in this case. For me it's not important that the Path is 100% the shortest possible, but I want to avoid such weird detours. How could I approach this issue?

Edit for clarification: I'm asking about how to compute the cost between nodes/triangles to help me compute the shortest path instead of just to least amount of nodes to travel.

# Answer
> 2 votes
Here I am assuming that you already know what is going on with A\* and heuristics, because it seems the problem is elsewhere.

> I'm having trouble implementing the heuristic that computes the cost between nodes since the way the entity will move depends on the final path.

Yes, The funnel algorithm is carried out after the path is selected. We can only find the shortest path before path straightening.

The path on the right in the figure is indeed shorter than the path on the left:

The accuracy of the final path depends on how uniform the mesh is, the more evenly all paths are straightened, the more correct the result. For example the path on the right can be selected largely because of a particularly thin triangle in a suitable place:

If you change the split shape of this triangle so that it is not so thin, things will be much better:

There happens to be an algorithm that is often used for navmesh generation called Delaunay triangulation. It can improve the shape of triangles inside the mesh and avoid some edge cases.

And some modern pathfinding suites use convex polygons instead of triangles as pathfinding nodes, which reduces the number of nodes and also reduces the impact of malformed triangles. The `Hertel-Mehlhorn Algorithm` is the standard approach for doing this.

In summary, you can:

1. Improve the shape of the mesh during the navmesh generation phase(by re-triangulation), making it more uniform, which will reduce the difference in shortest paths before and after straightening.
2. Artificially adding some vertices can also help.
3. You can also use polygonal meshes instead of triangular meshes.
4. Then use a heuristic function to find only the shortest path before straightening.
5. Finally straighten the path.

Edit:

Why do I use **midpoints of sides** instead of **triangle centers** as pathfinding nodes in the example graph?

This is actually to reduce the error before and after the path is straightened. When a path passes through two adjacent triangles, after being straightened, it must pass through the common side of the two triangles. Its intersection with the common edge may be anywhere along the edge. To minimize the error before and after straightening the path, or try to make the error of different paths more stable, we can minimize the error of this intersection point.

This is an example. If the midpoints of adjacent sides are used as nodes, then the maximum error is `|AB|/2`. If the center of the triangle is used as the node, then the maximum error is `>|AB|`. Using midpoints of triangle sides as nodes gives more stable results.

# Answer
> 2 votes
According to the comments, your A\* implementation does treat all edges equally and doesn't consider that different edges have a different traversal cost. When you do that, then the algorithm is always going to prefer routes with few long edges over routes with many short edges.

To fix that issue, the cost of each edge needs to be equivalent to how long it takes to traverse that edge. If we can assume that entities in your game are able to travel with a fixed velocity in any direction, then the time it takes to travel from `node1` to `node2` would be equivalent to their distance as calculated using the Pythagorean theorem \\$a^2 + b^2 = c^2\\$ or \\$c = \sqrt{a^2 + b^2}\\$. Or expressed in C-style programming language syntax:

```
float dist_x = node1.x - node2.x;
float dist_y = node1.y - node2.y;
float edge_cost = Math.sqrt(dist_x * dist_x + dist_y * dist_y);

```

To improve accuracy, you should do the "string pulling" step you usually have when using a navigation mesh after each path navigation step and revise the total cost of the path accordingly.

---
Tags: path-finding, navmesh
---


# Question
Title: Fair scoring system for multiple levels and multiple players
I have a parkour game with over 200 levels and I want to be able to compare players by assigning each one a score that is based on their overall performance on the levels (how fast they can finish the levels). This score then determines the "ultimate" leaderboard for who the best players are.

How I currently do it:

* I look at the leaderboard of each individual level and award points based on the position on that leaderboard. 1st player gets 10 000 points, 100th player gets 100 points - everyone else in between gets their points calculated from an exponential curve. Beyond position 100 players get 0 points
* I then divide everyone's points by the total number of levels to get an average - this is their final score I compare everyone with

I average the points because new levels are frequently added and I don't want the score to be inflated with the addition of new levels.

The problem:

* Some people are extremely good and are 1st on many levels but have only played about half of all levels. This gives them a decent score but the averaging process severely punishes them for not having finished all levels. Players that are noticeably worse but have played all levels and finished with a good (but not great) placement in the top100 are ranked higher in the final score.
* I thought about taking the average of only those levels that a player has actually finished, but then someone might get punished for trying a new level and not playing it a lot to get a good time, thus lowering their average points per level

Is there a way for how I can make this system fairer such that

* better players actually get a better score
* the score does not inflate with the addition of new levels
* finishing a level for the first time with a bad time doesn't decrease the players score

I'd be happy to hear your suggestions for how to improve my system.

# Answer
> 23 votes
I wouldn't actually consider it a bad idea to have a leaderboard that takes scores of all levels into account. Even those the player hasn't played at all, using a score of 0 for them.

* It avoids a global ranking that is dominated by "one trick ponies" who specialize in only a few selected levels and ignore the rest. Due to the difficulty of perfectly balancing the difficulty and scoring of over 200 levels, I would suspect that quite a lot of players will choose the same levels for this purpose, making this metagame rather boring. If you still want to encourage players to become masters at their one favorite level, then you can have level-specific leaderboards as well.
* It can't be exploited by players who create new accounts to only play the one level they are good at and ignore all the rest.
* It generates an incentive for players to play and master *all* the levels, because doing so can only increase their score. This results in more variety in their game experience.
* It increases player retention, because when new levels get released, then inactive players with good leaderboard positions will have to return to the game and get some good scores in the new levels as well in order to defend their rank.
* And if they choose not to, then that makes the game more attractive to new players. Inactive players won't be able to hog the leaderboard positions due to all the newly released levels making their score far less impressive. So new players who play the old *and* the new levels will be able to dethrone them. This is actually a reason why you *want* some score inflation and power creep in an online game. It gives new and active players a way to compete with old and inactive players.

# Answer
> 11 votes
You can use the same 1/x function you are using to calculate your score in a level to weigh score of your levels. You get 100% for your best level, then 50% for the next one and so on. This means that starting your 100th level will only net you 1/100 points you could get - so, you don't lose points no matter how bad you did, but you barely gain any new ones even if you are as high as in your other levels. Once you add levels, yup, score will keep increasing, but slowly. First 100 levels will give you 5.2x points (of a single level) while levels 101-400 - 3 times as many - will only improve your score by 1.4x - 1/3 of the first 100 levels.

Note that this combination of functions (scoring per level and weighing level score) means that rank 2 in 3 levels is still worse than rank 1 in one level - meaning if you want to be the best on the main leaderboard, getting to rank 1 in some levels matters the most - top players are going to be those that manage to be the best in some levels, even if they compete in (and completed) only 10 levels out of say 500.

A side note: I wouldn't make a cutoff for level points at top 100 players (unless you have some specific reason for that) - I would simply calculate score as 1/x as you are already doing, without any cutoff - yeah, your poor run that gives you only rank 20000 for that level only nets you 0.5 points, but that's still an improvement to your score, making you feel your level run wasn't a complete waste of time. Additionally, this should help for retention of non-top players. Yeah, you are fighting for spot around 1000 instead of top players battling for the top ones, but you still get a feeling of improvement as you climb up the ranks. When paired with 1/x function for level scoring, getting those 0.5 points, divided by say 100, means you don't actually improve your score meaningfully. But you still don't regress by trying new levels.

As mentioned by @quarague in comment, you can also change proposed function from 1/x (= x^-1) to something steeper or slower - steeper means fewer levels matter, slower means more matter. I believe sensible range for the exponent is between 0 and -2. 0 means that all levels matter the same, so you reward griding of all levels. -2 means the best level is worth more than all the rest combined and you shouldn't really bother with more than few. I believe you should probably try -1 or -1/2 first.

# Answer
> 5 votes
There won't be a perfect scoring system. There will be always someone who is unhappy or feels it is unfair.

How I would tweek it:

* Your score is calculated from the X best played games. This way, people can try out new levels without having to fear that their score drops. It does not even need to be an average that way. (If X is 10, sort all levels the player played by score and take the top 10 scores)
* Add a small bonus for each level played. The bonus gives a player the incentive to play more levels, even if they don't place well there. Just for a small increase in score.
* Keep the current leaderboard for each level to give the player a benchmark how good they are in comparison.
* Add maybe a small reward for the top player of a leaderboard that they are allowed to keep as long as they keep their position. (For example level 1-20 gives a green hat, 21-40 sun glasses, 41-60 a clown nose). Just some cosmetic extra with no playing benefit.

This way new players final score are fast done but it will take a lot of practise to get a top score. Players that play a lot still get a small increase compared to new players.

---
Tags: game-design, game-mechanics, leaderboards, scoring
---


# Question
Title: How to settle a rigid body to rest on flat surface
I am trying to simulate the behaviour of a rigid body, for example a cube, while it settles on a flat surface. Let's say it lends on an edge or even on a corner, and now it has to settle and remain on the surface. I am modeling this by rotating the body around contact line or a contact point, but I have a problem when the body needs to stop moving.

At the moment, the effect I got is that when it lands on the surface, it is still not perfectly aligned with it, so in my collision detection I am detecting that I still have just one contact point, so I am trying to generate rotations around this contact point.

After this, another edge or corner becomes the contact point, so it starts to rotate around that one and soon things become frantic; the cube is dancing wildly and not settling.

To explain a bit more, every frame I am collecting data about which of the corners is closest to the surface of interest and storing this data in a C++ type, `std::vector`. If I have a result that all four points(corners) are at the same distance, I put them all inside a vector. After the collision detection method is called inside my physics engine code, I try to resolve it, and I do this by returning the data about collision points and corners etc.

Any advice on how to approach this particular problem?

# Answer
> 0 votes
My guess is that this could be an issue of numerical accuracy that could be solved with generous rounding. Numerically you will never reach a point where multiple corners of the cube are exactly the same distance from the surface so you the cube will never reach a rest position. An easy fix would be to define all corners that are less then some suitable small epsilon away from the surface are treated as on the surface. You probably need to experiment a bit to find a suitable epsilon that produces good visual effects.

---
Tags: physics, collision-resolution, rigidbody
---


# Question
Title: Why is Reinforcement Learning so rarely used in pathfinding?
The venerable shortest-path graph theoretic algorithm A\* and subsequent improvements (e.g., Hierarchical Annotated A\*) is clearly the technique of choice for pathfinding in game development.

Instead, it just seems to me that RL is a more natural paradigm to move a character around a game space.

And yet I'm not aware of a single game developer who has implemented a Reinforcement Learning-based pathfinding engine. (I don't infer from this that the application of RL in pathfinding is 0, just that it's very small relative to A\* and friends.)

Whatever the reason, it's not because these developers are unaware of RL, as evidenced by the fact that RL is frequently used elsewhere in the game engine.

This question is *not* a pretext for offering an opinion on RL in pathfinding; in fact, i am assuming that the tacit preference for A\* et al. over RL is correct--but that preference is not obviously to me and i'm very curious about the reason for it, particularly from anyone who has tried to use RL for pathfinding.

# Answer
> 24 votes
I would imagine it's because, since you won't get any useful generalization of policy out of anything but toy problems, and the reward function is going to look suspiciously like an A\* heuristic, the prospect of using RL tends to look like a really overbuilt, inefficient way of getting results that are identical with A\*'s at best, but probably aren't going to be nearly that good.

This may be unfair to RL, and if so I'd be interested in hearing why, but I'm not really seeing anything to indicate that.

Many of us also remember what pathfinding was like in games before widespread adoption of A\*, and aren't eager to inflict anything resembling those days on players, or suffer the market consequences of doing so.

# Answer
> 7 votes
I'm confused by the suggestion that RL is "a more natural paradigm". I don't see how reinforcement learning maps to the problem domain anywhere near as cleanly or accurately as graph search does. Typically you don't want an agent to learn - you've assumed that they already know the route. Instead, you want them to pick and use the most direct route available, and graph search facilitates that in a near optimal way. If you were to use RL offline to calculate the best direction to take at any given node for any given destination, that would end up bring broadly equivalent to A\*, except requiring significantly more memory\* and also requiring that the developers were very careful to ensure that all nodes were adequately explored during training. And that training will just yield a value that we can already approximate very well with the Pythagoras equation, due to knowing in advance that the graph obeys Euclidean rules of distance. (This is, of course, not the case for all situations where graph search and/or reinforcement learning may be employed.)

(Regarding the memory issue: If you had 1000 possible quantised positions on a map, that's 1000 nodes plus 1000 * M edges (where M is the average number of nodes reachable from any other node.) That, plus the heuristic, is enough for A\* to operate. For reinforcement learning to work, at least in the way I envisage it, you'd also need 1000 entries for each of those 1000\*M edges, to score the reward value of following that edge for any of the 1000 possible destinations. That's a lot of data - and every single bit of it has to be reasonably accurate to avoid loops, detours, or dead-ends.

# Answer
> 5 votes
Without knowing much about RL, I'll attempt to answer your question with other questions:

Using RL, can you determine if it's possible to reach point A from point B?

Can RL guarantee reproducible/consistent/testable navigation behavior?

How does memory and CPU run time requirements compare vs. A\*? Likewise, how much can you precompute compared to, say, nav meshes?

How does RL fair in an environment with dynamic collision?

How much more difficult is it to understand and implement RL correctly vs, say, steering behaviors?

Are there any good middleware providers for RL?

Maybe those questions can help you with your answer.

# Answer
> 5 votes
Pathfinding is a relatively "solved" problem, RL is not.

With A\*, developers can create heuristics quickly and improve them over time. RL (I'm talking about Q-Learning, when referring to RL here), takes time to compute the best learning rates and discount factors (time worth spending on other aspects of the game).

# Answer
> 2 votes
It really depends on the types of the game. If everything in the game is static, it's more efficient to use A\* search. However, if there are other human players moving in the same area, A\* search is guaranteed failure. A\* search has no idea about where other players are heading. On the other hand, RL can model other players' behavior and find a better path which takes other players movement into consideration.

# Answer
> 0 votes
In general, I'd say that the choice between RL and A\* comes down to one major part of the setting: is the terrain known in advance or not? If it is, A\* should be used. If not, RL should be used.

---
Tags: algorithm, path-finding
---


# Question
Title: Unity Particles that only show up inside of a rectangular GameObject
It's easy enough to use the Unity Particle System to generate snow that falls from the top of a rectangle.

But how do I make snow only fall *inside* the rectangle? As in, once the snow hits the bottom of the rectangle, I'd like for it to disappear.

The curveball here is that the width of the rectangle can be dynamically resized at times, and I'd want the entire rectangle to always be snowing.

# Answer
You can use a **Box Collider** to define the volume where particles are drawn and tell the **Particle System** to destroy particles lying outside it.

The **Particle System** features the *Triggers* module that lets you define particle behaviour when they interact with **Colliders** in the Scene. You can use it to destroy particles when they move outside a **Collider** of choice (I suggest a **Box Collider** since you are generating particles from a rectangle):

1. Add a **Box Collider** Component to the **Particle System** GameObject.
    * Alternatively: create a Box GameObject as a child of the **Particle System** GameObject. (Parenting GameObjects allows you to move the System around the Scene.)
2. In the **Particle System**, enable the *Triggers* module.
3. Add a new trigger.
4. Drag and drop the **Box Collider** Component onto the trigger empty slot.
    * Alternatively: drag and drop the GameObject owning the **Box Collider** from the Hierarchy (be it a child GameObject or the **Particle System** GameObject itself).
5. Set the *Outside* trigger condition to "Kill" and the remaining conditions to "Ignore".

You can now define a dedicated shape for *generating* particles and a different one for *containing* them. In your case, you may want to place the rectangle (**Particle System**'s *Shape* module) so that it overlaps the top face of your **Box Collider**.

Here's a quick snapshot from the Inspector:

---

EDIT: If you want to resize the container volume without manually adjusting the shapes' position, you can use an Editor script to automatically update the emission shape's position based on the container volume size.
> 3 votes

---
Tags: unity, particles
---


# Question
Title: Faster approach to iterative pixel mapping in Unity
I need to take an initial Texture2D and, depending on four sliders, remap the RGBA channels. What I currently have *works*, but is not very performant, especially with larger images.

```
for (int x = 0; x < _tempIn.width; x++)
   for (int y = 0; y < _tempIn.height; y++)
   {
      _tempColorHold = _tempIn.GetPixel(x, y);

      r = (rSlider.value == (int)RGBA051.zero) ? 0f :
          (rSlider.value == (int)RGBA051.r) ? _tempColorHold.r :
          (rSlider.value == (int)RGBA051.g) ? _tempColorHold.g :
          (rSlider.value == (int)RGBA051.half) ? 0.5f :
          (rSlider.value == (int)RGBA051.b) ? _tempColorHold.b :
          (rSlider.value == (int)RGBA051.a) ? _tempColorHold.a :
          1f;

      g = (gSlider.value == (int)RGBA051.zero) ? 0f :
          (gSlider.value == (int)RGBA051.r) ? _tempColorHold.r :
          (gSlider.value == (int)RGBA051.g) ? _tempColorHold.g :
          (gSlider.value == (int)RGBA051.half) ? 0.5f :
          (gSlider.value == (int)RGBA051.b) ? _tempColorHold.b :
          (gSlider.value == (int)RGBA051.a) ? _tempColorHold.a :
          1f;

      b = (bSlider.value == (int)RGBA051.zero) ? 0f :
          (bSlider.value == (int)RGBA051.r) ? _tempColorHold.r :
          (bSlider.value == (int)RGBA051.g) ? _tempColorHold.g :
          (bSlider.value == (int)RGBA051.half) ? 0.5f :
          (bSlider.value == (int)RGBA051.b) ? _tempColorHold.b :
          (bSlider.value == (int)RGBA051.a) ? _tempColorHold.a :
          1f;

      a = (aSlider.value == (int)RGBA051.zero) ? 0f :
          (aSlider.value == (int)RGBA051.r) ? _tempColorHold.r :
          (aSlider.value == (int)RGBA051.g) ? _tempColorHold.g :
          (aSlider.value == (int)RGBA051.half) ? 0.5f :
          (aSlider.value == (int)RGBA051.b) ? _tempColorHold.b :
          (aSlider.value == (int)RGBA051.a) ? _tempColorHold.a :
          1f;

      _tempOut.SetPixel(x, y, new Color(r, g, b, a));
   }

```

Basically RGBA051 is an enum like this:

```
public enum RGBA051 { zero, r, g, half, b, a, one }

```

There are four `int` sliders that have have a value 0-7 selected, mapping to that enum. If the red channel has `zero` set, the red channel for *all* pixels will be set to zero. If the red channel has `r` set, it will get the red channel value for each pixel (it will remain the same), and so forth.

During the execution of this method, the slider cannot change, so the value of rSlider and gSlider and such will remain the same throughout the loop. It seems redundant to execute ternary operator during the assignment of each pixel, but I can't quite wrap my head around how to unpack that check while still setting each pixel properly.

# Answer
For additional testing, I've created a handful of CPU and ComputeShader methods as shown below. I definitely welcome any improvements in the comments.

`Texture2D_Mod.compute`:

```
#pragma kernel ChannelSwapFunc
#pragma kernel ChannelSwap4x4

RWTexture2D<float4> result;
Texture2D<float4> input;
uint channelSwapR;
uint channelSwapG;
uint channelSwapB;
uint channelSwapA;
matrix swapmatrix;
float4 swapmatrixoffset;

[numthreads(8,8,1)]
void ChannelSwapFunc(uint3 id : SV_DispatchThreadID)
{
    float r;
    float g;
    float b;
    float a;

    if (channelSwapR == 4)
        r = 0;
    else if (channelSwapR == 5)
        r = 0.5;
    else if (channelSwapR == 6)
        r = 1;
    else
        r = input[id.xy][channelSwapR];

    if (channelSwapG == 4)
        g = 0;
    else if (channelSwapG == 5)
        g = 0.5;
    else if (channelSwapG == 6)
        g = 1;
    else
        g = input[id.xy][channelSwapG];

    if (channelSwapB == 4)
        b = 0;
    else if (channelSwapB == 5)
        b = 0.5;
    else if (channelSwapB == 6)
        b = 1;
    else
        b = input[id.xy][channelSwapB];

    if (channelSwapA == 4)
        a = 0;
    else if (channelSwapA == 5)
        a = 0.5;
    else if (channelSwapA == 6)
        a = 1;
    else
        a = input[id.xy][channelSwapA];

    result[id.xy] = float4(r, g, b, a);
}

[numthreads(8, 8, 1)]
void ChannelSwap4x4(uint3 id : SV_DispatchThreadID)
{
    result[id.xy] = mul(input[id.xy], swapmatrix) + swapmatrixoffset;
}

```

`PerformFunction()` \- this is the standard CPU method, my initial attempt. Average time was 854.6ms:

```
private void PerformFunction()
    {
        if (valueIn != null)
        {
            float r;
            float g;
            float b;
            float a;

            Texture2D _tempIn = valueIn.DuplicateTexture();

            Color _tempColorHold = new Color();

            Texture2D _tempOut = new Texture2D(_tempIn.width, _tempIn.height);
            _tempOut.alphaIsTransparency = true;

            for (int x = 0; x < _tempIn.width; x++)
                for (int y = 0; y < _tempIn.height; y++)
                {
                    _tempColorHold = _tempIn.GetPixel(x, y);

                    r = (rSlider.value == (int)RGBA.r)    ? _tempColorHold.r :
                        (rSlider.value == (int)RGBA.g)    ? _tempColorHold.g :
                        (rSlider.value == (int)RGBA.b)    ? _tempColorHold.b :
                        (rSlider.value == (int)RGBA.a)    ? _tempColorHold.a :
                        (rSlider.value == (int)RGBA.zero) ? 0f               :
                        (rSlider.value == (int)RGBA.half) ? 0.5f             : 1f;

                    g = (gSlider.value == (int)RGBA.r)    ? _tempColorHold.r :
                        (gSlider.value == (int)RGBA.g)    ? _tempColorHold.g :
                        (gSlider.value == (int)RGBA.b)    ? _tempColorHold.b :
                        (gSlider.value == (int)RGBA.a)    ? _tempColorHold.a :
                        (gSlider.value == (int)RGBA.zero) ? 0f               :
                        (gSlider.value == (int)RGBA.half) ? 0.5f             : 1f;

                    b = (bSlider.value == (int)RGBA.r)    ? _tempColorHold.r :
                        (bSlider.value == (int)RGBA.g)    ? _tempColorHold.g :
                        (bSlider.value == (int)RGBA.b)    ? _tempColorHold.b :
                        (bSlider.value == (int)RGBA.a)    ? _tempColorHold.a :
                        (bSlider.value == (int)RGBA.zero) ? 0f               :
                        (bSlider.value == (int)RGBA.half) ? 0.5f             : 1f;

                    a = (aSlider.value == (int)RGBA.r)    ? _tempColorHold.r :
                        (aSlider.value == (int)RGBA.g)    ? _tempColorHold.g :
                        (aSlider.value == (int)RGBA.b)    ? _tempColorHold.b :
                        (aSlider.value == (int)RGBA.a)    ? _tempColorHold.a :
                        (aSlider.value == (int)RGBA.zero) ? 0f               :
                        (aSlider.value == (int)RGBA.half) ? 0.5f             : 1f;

                    _tempOut.SetPixel(x, y, new Color(r, g, b, a));
                }

            _tempOut.Apply(false, false);

            this.ValueOut = _tempOut;
            portOut.Value = this.ValueOut;
        }
    }

```

`PerformFunctionCompute()` \- this was the same basic principle, but run using `ChannelSwapFunc()` in the ComputeShader. Average time was 55.2ms:

```
private void PerformFunctionCompute()
    {
        shader = (ComputeShader)Resources.Load("Texture2D_Mod");
        int _kernelHandle = shader.FindKernel("ChannelSwapFunc");
        Texture2D _tempIn = valueIn.DuplicateTexture();
        RenderTexture _tex = new RenderTexture(_tempIn.width, _tempIn.height, 24);
        _tex.enableRandomWrite = true;
        _tex.Create();

        shader.SetTexture(_kernelHandle, "result", _tex);
        shader.SetTexture(_kernelHandle, "input", _tempIn);
        shader.SetInt("channelSwapR", rSlider.value);
        shader.SetInt("channelSwapG", gSlider.value);
        shader.SetInt("channelSwapB", bSlider.value);
        shader.SetInt("channelSwapA", aSlider.value);
        shader.Dispatch(_kernelHandle, _tempIn.width / 8, _tempIn.height / 8, 1);

        RenderTexture.active = _tex;
        Texture2D _result = new Texture2D(_tempIn.width, _tempIn.height);
        _result.ReadPixels(new Rect(0, 0, _tempIn.width, _tempIn.height), 0, 0);
        _result.Apply(false, false);

        this.ValueOut = _result;
        portOut.Value = this.ValueOut;
    }

```

`PerformFunctionMatrix4x4()` \- this was the `Matrix4x4` version from @DMGregory. Average time was 395.4ms:

```
private void PerformFunctionMatrix4x4()
    {
        if (valueIn != null)
        {
            Texture2D _tempIn = valueIn.DuplicateTexture();
            Color32[] pixelData = _tempIn.GetPixels32();

            var matrix = new Matrix4x4(
                ToMatrixRow((RGBA)rRGBA),
                ToMatrixRow((RGBA)gRGBA),
                ToMatrixRow((RGBA)bRGBA),
                ToMatrixRow((RGBA)aRGBA)
                );

            matrix = matrix.transpose;

            var offset = new Vector4(ToOffset((RGBA)rRGBA), ToOffset((RGBA)gRGBA), ToOffset((RGBA)bRGBA), ToOffset((RGBA)aRGBA));

            for (int i = 0; i < pixelData.Length; i++)
            {
                Vector4 c = (Color)pixelData[i];

                c = (matrix * c) + offset;

                pixelData[i] = (Color)c;
            }

            Texture2D _tempOut = new Texture2D(_tempIn.width, _tempIn.height);
            _tempOut.alphaIsTransparency = true;

            _tempOut.SetPixels32(pixelData);

            _tempOut.Apply(false, false);

            this.ValueOut = _tempOut;
            portOut.Value = this.ValueOut;
        }
    }

```

`PerformFunctionComputeMatrix4x4()` \- this is the ComputeShader version of the `Matrix4x4` version of the function. Average time was 54.5ms:

```
private void PerformFunctionComputeMatrix4x4()
        {
            if (valueIn != null)
            {
                shader = (ComputeShader)Resources.Load("Texture2D_Mod");
                int _kernelHandle = shader.FindKernel("ChannelSwap4x4");
                Texture2D _tempIn = valueIn.DuplicateTexture();
                RenderTexture _tex = new RenderTexture(_tempIn.width, _tempIn.height, 24);
                _tex.enableRandomWrite = true;
                _tex.Create();

                var matrix = new Matrix4x4(
                    ToMatrixRow((RGBA)rRGBA),
                    ToMatrixRow((RGBA)gRGBA),
                    ToMatrixRow((RGBA)bRGBA),
                    ToMatrixRow((RGBA)aRGBA)
                    );

                matrix = matrix.transpose;

                var offset = new Vector4(ToOffset((RGBA)rRGBA), ToOffset((RGBA)gRGBA), ToOffset((RGBA)bRGBA), ToOffset((RGBA)aRGBA));

                shader.SetTexture(_kernelHandle, "result", _tex);
                shader.SetTexture(_kernelHandle, "input", _tempIn);
                shader.SetMatrix("swapmatrix", matrix);
                shader.SetVector("swapmatrixoffset", offset);
                shader.Dispatch(_kernelHandle, _tempIn.width / 8, _tempIn.height / 8, 1);

                RenderTexture.active = _tex;
                Texture2D _result = new Texture2D(_tempIn.width, _tempIn.height);
                _result.ReadPixels(new Rect(0, 0, _tempIn.width, _tempIn.height), 0, 0);
                _result.Apply(false, false);

                this.ValueOut = _result;
                portOut.Value = this.ValueOut;
            }
        }

```
> 1 votes

# Answer
The operations you want to perform can be expressed as a single matrix multiplication plus an offset. You'll also get better speed operating on all pixels in one fell swoop, rather than getting and setting them one at a time.

```
Vector4 ToMatrixRow(RGBA051 value) {
    switch (value) {
        case RGBA051.r: return new Vector4(1, 0, 0, 0);
        case RGBA051.g: return new Vector4(0, 1, 0, 0);
        case RGBA051.b: return new Vector4(0, 0, 1, 0);
        case RGBA051.a: return new Vector4(0, 0, 0, 1);
        default: return Vector4.zero;
    }
}

float ToOffset(RGBA051 value) {
    switch(value) {
        case RGBA051.half: return 0.5f;
        case RGBA051.one : return 1.0f;
        default: return 0.0f;
    }
}

void RecolourTexture(Texture2D source, Texture2D destination,
                     RGBA051 r, RGBA051 g, RGBA051 b, RGBA051 a) {

    // Get all pixel data at once.
    // (To avoid allocation, you can use GetPixelData<T>(), but
    //  that requires different handling for each texture format)
    var pixelData = source.GetPixels32();

    // Construct a matrix with rows that route the desired input
    // channel to the desired output channel, or zero the output.
    var matrix = new Matrix4x4(
        ToMatrixRow(r),
        ToMatrixRow(g),
        ToMatrixRow(b),
        ToMatrixRow(a)
    );
    matrix = matrix.transpose;

    // Compute a vector of constants for the half/one values.
    var offset = new Vector4(ToOffset(r), ToOffset(g), ToOffset(b), ToOffset(a));

    for(int i =0; i < pixelData.Length; i++) {
        // Unpack 4 bytes 0-255 into 4 floats 0-1.
        Vector4 c = (Color)pixelData[i];

        // Apply the colour transformation.
        c = (matrix * c) + offset;

        // Convert the result back to the compact format.
        pixelData[i] = (Color)c;
    }

    // Set all pixels at once.
    destination.SetPixels32(pixelData);
    // Apply modified pixels
    // (false values here skip updating mipmaps & keep texture CPU-readable)
    destination.Apply(false, false);
}

```

As Philipp points out, this would be even faster to do in a shader, operating on all pixels in the image in parallel. You can do that with `Graphics.Blit()`, using the same matrix multiply and add technique in the fragment shader code.

---

Another thought that just occurred to me: since you only ever want to swap or wholly replace a channel, you could operate on them like this:

```
var channelValues = new byte[7];
channelValues[(int)RGBA051.zero] = 0;
channelValues[(int)RGBA051.one] = 255;
channelValues[(int)RGBA051.half] = 128;

// ... then, inside the pixel loop:

Color32 c = pixelData[i];

channelValues[(int)RGBA051.r] = c.r;
channelValues[(int)RGBA051.g] = c.g;
channelValues[(int)RGBA051.b] = c.b;
channelValues[(int)RGBA051.a] = c.a;

c.r = channelValues[(int)r];
c.g = channelValues[(int)g];
c.b = channelValues[(int)b];
c.a = channelValues[(int)a];

pixelData[i] = c;

```

That's 8 byte assignments instead of 4 byte-to-float conversions, 16 float multiplies, 16 float adds, and 4 float-to-byte conversions, so I'd expect it should run even faster, barring some pipelining shenanigans.

The advantage of the full matrix version above is that it's even more general, and can handle other image adjustments like brightness/contrast, desaturation, even a version of hue shifting, just by initializing the matrix with different coefficients.
> 2 votes

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


# Question
Title: How to convert slope handling code to work with AddForce instead of AddRelativeForce?
I an using the following code for handling slopes:

```
      private Vector3 PlayerSlope()
      {
          Vector3 calculatedPlayerMovement = _playerMoveInput;

          if (_playerIsGrounded)
          {
              Vector3 localGroundCheckHitNormal = _rigidbody.transform.InverseTransformDirection(_groundCheckHit.normal);

              float groundSlopeAngle = Vector3.Angle(localGroundCheckHitNormal, _rigidbody.transform.up);
              if (groundSlopeAngle == 0.0f)
              {
                  //if (_input.MoveIsPressed)
                  if (moveDirectionRaw != Vector3.zero && moveDirection != Vector3.zero)
                  {
                      RaycastHit rayHit;
                      float rayCalculatedRayHeight = _playerCenterPoint.y - _playerCenterToGroundDistance + _groundCheckDistanceTolerance;
                      Vector3 rayOrigin = new Vector3(_playerCenterPoint.x, rayCalculatedRayHeight, _playerCenterPoint.z);
                      if (Physics.Raycast(rayOrigin, _rigidbody.transform.TransformDirection(calculatedPlayerMovement), out rayHit, 0.75f))
                      {
                          if (Vector3.Angle(rayHit.normal, _rigidbody.transform.up) > _maxSlopeAngle)
                          {
                              Debug.Log(_playerMoveInput.y);
                              calculatedPlayerMovement.y = -_movementMultiplier;
                          }
                      }
                      //Debug.DrawRay(rayOrigin, _rigidbody.transform.TransformDirection(calculatedPlayerMovement), Color.green, 1.0f);
                  }

                  if (calculatedPlayerMovement.y == 0.0f)
                  {
                      calculatedPlayerMovement.y = _gravityGrounded;
                  }
              }
              else
              {
                  Quaternion slopeAngleRotation = Quaternion.FromToRotation(_rigidbody.transform.up, localGroundCheckHitNormal);
                  calculatedPlayerMovement = slopeAngleRotation * calculatedPlayerMovement;

                  float relativeSlopeAngle = Vector3.Angle(calculatedPlayerMovement, _rigidbody.transform.up) - 90.0f;
                  calculatedPlayerMovement += calculatedPlayerMovement * (relativeSlopeAngle / 90.0f);

                  if (groundSlopeAngle < _maxSlopeAngle)
                  {
                      //if (_input.MoveIsPressed)
                      if (moveDirectionRaw != Vector3.zero && moveDirection != Vector3.zero)
                      {
                          calculatedPlayerMovement.y += _gravityGrounded;
                      }
                  }
                  else
                  {
                      float calculatedSlopeGravity = groundSlopeAngle * -0.2f;
                      if (calculatedSlopeGravity < calculatedPlayerMovement.y)
                      {
                          calculatedPlayerMovement.y = calculatedSlopeGravity;
                      }
                  }
              }
              //#if UNITY_EDITOR
              //            Debug.DrawRay(_rigidbody.position, _rigidbody.transform.TransformDirection(calculatedPlayerMovement), Color.red, 0.5f);
              //#endif
          }

          return calculatedPlayerMovement;
      }

```

And then, in the FixedUpdate, it is applied as so:

```
    _playerMoveInput = PlayerMove(); //horizontal and vertical direction input multiplied by speed is returned from playermove
    _playerMoveInput = PlayerSlope();
    _rigidbody.AddRelativeForce(_playerMoveInput, ForceMode.Force);

```

My question is, how can I make the slope handling code work if instead I use AddForce in FixedUpdate? Like so: `_rigidbody.AddForce(_playerMoveInput, ForceMode.Force);`

If I just simply change `AddRelativeForce` to `AddForce` there, then the slope logic breaks and my rigidbody starts skipping down slopes again. So I know I should be changing code in `PlayerSlope()`, but I'm not sure what to change to make it work as an AddForce instead of AddRelativeForce.

Thank you.

# Answer
`AddRelativeForce` is basically just syntactic sugar over `AddForce`, transforming the force from local to world coordinates for you so you don't have to do that step explicitly. We could implement it like an extension method:

```
public static AddRelativeForce(this Rigidbody body,
                            Vector3 localForce,
                          ForceMode mode = ForceMode.Force) {

    var worldForce = body.transform.TransformVector(localForce);
    body.AddForce(worldForce, mode);
}

```
> 0 votes

# Answer
The difference between AddForce and AddRelativeForce is simple but critical to understand.

AddRelativeForce simply adds a force in a specified direction that's relative to the affected rigidbody's transform whereas AddForce uses world space.

One can use AddForce with this script pretty simply by first just converting the calculated input/force before calling AddForce.

`_rigidbody.AddForce(transform.TransformDirection(_playerMoveInput), ForceMode.Force);`
> 0 votes

---
Tags: unity, rigidbody
---


# Question
Title: Unity approaches for automatically setting pivots of each sub-gameobject at base center
I'm working with some free models online, which don't seem to have pivots properly set for any of its submodels.

* Is there a universal pivot fixer or something
* if not... The center seems correct for each submodel - can the pivot be set to the same local "xz" position but the y coordinate moved to the base of the model? To batch process this, how can one programmatically determine where the base is (assuming lowest y point)

# Answer
> 0 votes
I ran into this problem. In my case the assets were anchored to their Center or so and therefore not properly grounded. The bottom-most pixel was the correct ground. And for some reason the bounds wasn’t correct. No idea why.

So I created a script. I looped through all vertices in the mesh and found the bottommost one. Then I calculated its Y offset from the position of its transform. Then I created a new parent for this mesh’s transform at the same location. Then I adjusted the mesh’s transform’s local position to the offset calculated above.

# Answer
> 0 votes
Take all child objects out of the parent, and place the parent where you want it to pivot (make sure that it is not set to center, but rather pivot\[under scene menu\]). Then place the children back in.

---
Tags: unity, models, pivot
---


# Question
Title: Random NPC Movement & Stopping Within A Specific Distance
I'd like my NPC characters to move and stop randomly within a certain range.

Here's an example of how I'd like the orange NPC to be able to move and stop freely within the green box:

Is there a simple way to achieve this? Thanks!

# Answer
> 3 votes
DMGregory connected with me on Discord and clarified how this algorithm works.

To elaborate-

This algorithm creates a rectangle by defining the corners with min/max. The arguments to Random.Range define the corners of the rectangle, and the return value gives you one point randomly chosen between those corners.

So as an example, my game is 3D. So `new Vector3(Random.Range(minX, maxX), 0, Random.Range(minZ, maxZ))` gives a vector3 with random points between the corners (the min/max) of both the x-axis & the z-axis.

But he also went a step further and provided me with this extremely helpful script that draws a rectangle in the scene. This is great for visualizing where my NPC will be able to walk to. You can simply position the object in your scene and call GetRandomPoint().

```
public class RectangleZone : MonoBehaviour {
    public float width = 10f;
    public float depth = 10f;

    public Vector3 GetRandomPoint() {
        var local = new Vector3(
                        (Random.value - 0.5f) * width,
                        0,
                        (Random.value - 0.5f) * depth);

        return transform.TransformPoint(local);
    }

    void OnDrawGizmos() {
        Gizmos.color = Color.cyan;
        var cachedMatrix = Gizmos.matrix;
        Gizmos.matrix = transform.localToWorldMatrix;

        Gizmos.DrawWireCube(Vector3.zero, new Vector3(width, 0, depth));

        Gizmos.matrix = cachedMatrix;
    }
}

```

In the first method you can simply create a vector3 and use Random.Range twice like so:

```
Vector3 randomPoint = new Vector3( Random.Range(0f, 10f),
                                   0,
                                   Random.Range(0f, 10f) );

```

If you'd like to incorporate the second method that creates a visualized rectangle in your scene, you simply call the GetRandomPoint() function and it will return the new vector3:

```
Vector3 randomPoint = GetRandomPoint();

```

Whether you use the former or the latter, once you have the vector3 stored in a variable, you can use your preferred method of moving a gameObject to the new location. This can be done in update/coroutine with a for/while loop moving with MoveTowards,Lerp,etc... The implementation is flexible and this is is just one example:

```
while (transform.position != _targetLocation)
        {
            var step = _npcWalkSpeed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, _targetLocation, step);
            yield return null;
        }

```

Hope this helps someone else!

---
Tags: unity, ai
---


# Question
Title: Difference between Command Lists and Deferred context
I'm new to DirectX and I feel like I killed Google search but still cannot find information about the difference between these:

* Immediate context + Command Lists
* Immediate context + Deferred context (Command List)

As I understood from D3d docs, Deferred context is the same as Immediate, but it records all its API calls to the internal Command List. And then I should execute that list using an immediate context to apply all the commands to the GPU.

But from another side, in d3d docs, I found that a Command List can be created without a deferred context. Also on that page I found that the list has a huge amount of API methods like `DrawInstanced, DrawIndexedInstanced, etc.`

And, I wondered when I found this article, whether all those API methods can be actually used directly. I wondered because from D3D docs it sounds quite the opposite:

> A command list must be recorded by a deferred context

I'm stuck on this. Right now, for me, it sounds like I can solve 1 task using 2 identical ways:

1. Create a Command List, call commands on it (still don't understand is it valid to do so or not), and execute on an immediate context later to defer GPU calls.
2. Create a Deferred Context, call commands on it, and execute its internal list on an immediate context later.

So my question is, do those 2 items from the list produce the same result?

And if yes, then what is a Deferred Context then? What does it do that the Command List cannot?

Just now I cannot find the difference, but I'm sure that there is one.

# Answer
> 1 votes
There are a few things different, I will try to be concise.

Deferred Contexts allow you to run your command set up in separate threads as if you are calling immediate context. The commands are then queued against the deferred context, you can have a different Deferred Context per thread but you must execute the deferred command list from each thread in the main thread where you created your device and immediate context. The command lists are not pushed to the immediate context until you execute the command list, and they can be pushed in any order you desire.

What benefit does it give you? There are some optimisations that occur. On slower CPUs where you are command throughput limited it gives you some improvement in framerate if you are constrained. As long as the CPU is multicore, you may see some benefit in this scenario.

With immediate mode, each command or shader binding you do occurs in real time, that is it is pushed to your GPU pipeline and applied. As per above, this must be run in your main thread where your immediate and device contexts were created.

There is a link also to other constraints of Deferred, you can find them on this page put more succinctly than myself.

Deferred vs Immediate

---
Tags: directx, directx11, directx12
---


# Question
Title: Ensuring world curving shader is not affected by object scale
I've made a shader shown below which essentially acts as a "world bend / curve" shader by "bending" objects depending on their position from camera. It's a subgraph that outputs value for vertex position.

It works, but I am seeing strange behaviour on some items, they seem to bend much more than others despite being in a same position. After some digging around I figured out that it is due to some items having different scales. For example object with scale of 1,1,1 bends correctly where as object with scale like 1,0.2,0.5 bends either more extremely or less.

Is there a way to edit this shader so that it takes different scales into account and bends all objects in same manner despite their scales?

Parameters here are

`CurveX` \- How much to curve in x axis `CurveY` \- How much to curve in y axis `Curve Start Distance` \- How far from camera should curving effect start from

# Answer
> 1 votes
Choose 'Inverse Model' in 'Transformation Matrix' node instead of 'Model' in your shader and hit the 'Save Asset' button.

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


# Question
Title: Floor is made up of tiles with their own box colliders. Pushable item gets stuck on the "seams"
So I have a scene where the floor is made up of some tiled objects. All of these have the exact same height and exact same Y position. I also have a block with a rigidbody that you can push on the ground. It has a rigidbody with freeze rotation enabled for X, Y, and Z.

My issue is this: when pushing the block around, it sometimes gets stuck when reaching the seams of the tiled objects. I have tried giving it a friction of 0, but it still gets stuck sometimes. Is there any solution for this, other than manually creating a big collider that spans the entire floor?

# Answer
> 2 votes
By far the most efficient solution is what you said: combine the tiles into a single collider. You can do this manually, or write a script to automatically merge adjacent colliders into bigger boxes. There are a few existing questions about this latter approach.

If that's impractical for your case (say, tiles are created/destroyed/moving frequently) then the next best thing is to give your pushables a tiny bit of a radius. You can build a cubic cage of narrow capsule colliders, with box colliders inside. This means when you get a phantom collision with the seam, the curvature of the collision on your pushable will help it ramp up and over, instead of getting stuck. It's more colliders that way, of course.

One last thing you can try, as suggested in the Bennett Foddy talk linked above, is add an extra collider right along the seam, to help catch the penetrating shape from below instead of edge-on.

# Answer
> 1 votes
I recently had the exact same problem where it was entirely infeasible to combine colliders. Here is a fairly easy to implement and very effective solution:

Disable collision checking for edges that shouldn't ever be hit. In your case, the edges between the should never actually be collided with, so why check them at all?

It should just be a couple extra checks on initializing the tiles (and on ticks, if they move) to see which edges are "collidable", and then in your collision checker just ignore the unmarked edges

# Answer
> 0 votes
Try decreasing the Default Contact Offset in Edit/Project Settings/Physics

Changing it from 0.01 to 0.0001 worked for me

Edit: Source

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


# Question
Title: Godot parallax background is not covering the entire screen
I have started learning to use godot and I've created simple 2D scene with a spaceship that you can control. I want to add some background so that you can see if you're flying or stopped.

I made an image 846x846 pixels and created a ParallaxBackground and a ParallaxLayer in it. This is how I set up the layer:

I did not change anything else.

However, when I run the game the background fails to catch up, when I fly in one direction, I will reach uncovered area, then it will get covered few moments later:

This is what it looks like in the editor:

It seems that the parallax background repeats the contents 4 times only. That makes pretty much impossible to cover the entire screen in all instances, so I bet that is the problem.

# Answer
> 4 votes
For my project, the solution to this issue was to uncheck the `Centered` property in the Offset group of each sprite child of a `ParallaxLayer` node:

If you've set the `Mirroring` property of the ParallaxLayer to the correct dimensions (including accounting for any scaling on the Sprite2D nodes), this should align the textures correctly in the parallax background.

# Answer
> 2 votes
Incase someone's facing the same problem,

A solution is to enable repeat on your image in the import tab:

Then increase the sprite `region_rect` by \*2 (or multiply by whatever suites you):

and do the same in `ParallaxLayer` `mirroring` option

This *should* work, instead of manually increasing the texture resolution like an idiot which I definitely did not do for hours

---
Tags: godot, parallax-scrolling
---


# Question
Title: Collision Bounding Boxes Remain after Collisions
I am building a multiplayer snake game and I turned on debug mode to see more details of what was happening. After a collision with an apple, the collision bounding box seems to remain and multiple collision bounding boxes are created elsewhere. Is this a problem? If so, is there a way to remove the collision bounding boxes after the collision?

Here is a screenshot of it after only two collisions with the apple (the apple get's re-spawned every time a snake collides with it).

Here is some code that might help add some context to this question (this is part of the code that re-spawns the apple):

```
self.physics.add.overlap(self.ship, self.apple, function () {
        this.socket.emit('appleCollected');
}, null, self);

```

# Answer
> 0 votes
Depending on how you are removing the apples you would have to use, something like:

```
self.apple.destroy();

```

**OR**

```
self.apple.disableBody(true, true);

```

in the socket listener function of `appleCollected`.

---
Tags: phaser
---


# Question
Title: Loop through list of unlocked items in PlayerPrefs
I have a list of stickers and when a player completes a level they get awarded a sticker which I save into `PlayerPrefs`. I want to be able to return the list of sprites saved into `PlayerPrefs` on the awards scene.

I have not been to loop and match the `PlayerPrefs`. I am not sure how to go about this.

```
public class StickerManager : MonoBehaviour
{
    public List<Sprite> stickers = new List<Sprite>();
    public List<Sprite> unlockedStickers = new List<Sprite>();

    public void UnlockSticker (int id)
    {
        PlayerPrefs.SetInt("sticker", id);
    }

    public List<Sprite> LoadUnlockedSticker ()
    {
        int i = 0;
        foreach (Sprite spri in stickers)
        {
            if (PlayerPrefs.GetInt("sticker", i) == stickers[i])
                unlockedStickers.Add(stickers[i]);

            i++;
        }

        return unlockedStickers;
    }
}

```

# Answer
Each key in PlayerPrefs can store only one value, and the value has to be an integer, float, or string.

So when you do something like `PlayerPrefs.SetInt("sticker", 5);` it means "throw out whatever value you had been storing in the slot named `"sticker"` and replace it with the number 5.

If your stickers are always collected in a fixed order, then this can work - your `PlayerPrefs` value stores a count of stickers obtained so far, and you know every one with an index less than the current count has been unlocked.

If your stickers can be obtained in any order, then you need a different strategy. While you could store up to 32 independent sticker acquisitions as bitfield flags packed into a single integer, a simpler method would be to assign a distinct key to each sticker:

```
// This gives you a way to assign a serialized name for each sticker in the inspector.
// By not using the index or name of the sprite itself, this is more robust to changes.
[System.Serializable]
public struct StickerEntry {
    public string name;
    public Sprite sprite;

    // As the key, we'll add a prefix, to be sure this key doesn't collide with others we use.
    public string GetKey() {
        return string.Format("Sticker-{0}", name);
    }
}

public StickerEntry[] stickers;
public List<Sprite> unlockedStickers;

public void UnlockSticker(int id) {
    // A value of 1 means "unlocked".
    PlayerPrefs.SetInt(stickers[i].GetKey(), 1);
    unlockedStickers.Add(stickers[i].sprite);
}

public List<Sprite> LoadUnlockedStickers() {
    unlockedStickers.Clear();

    foreach(var sticker in stickers) {
        if(PlayerPrefs.GetInt(sticker.GetKey(), 0) > 0)
            unlockedStickers.Add(sticker.sprite);
    }

    return unlockedStickers;
}

```
> 2 votes

# Answer
PlayerPrefs is designed as a key/value store for singular values of the types int, string and float. That means every information needs an unique key. When you have a lot of information to store, this can quickly get hard to use, slow and take a lot of unnecessary space.

Now you could go so far and implement a proper savegame system using the local filesystem. And if you want to store more than a few kByte of data, then I would urge you to do so. But working with files can have some complications, concerns and unexpected pitfalls as well, so it might take quite a lot of time to implement properly. So a compromise solution between the flexibility of savegame files and the ease of use of PlayerPrefs is to serialize the whole savegame to a string and store that string in PlayerPrefs.

Now you could of course write your own encoder and decoder for your savegame data. But fortunately Unity already got a handy class for this that might be all you need: `JsonUtility`. This class can be used to convert an object to a string in JSON format, and then return that string back to an object. It doesn't support references to other objects, but it does support arrays. Here is an example (note that it does **not** inherit from `MonoBehaviour`):

```
[Serializable]
class Savegame {
    public bool[] stickerUnlocked;

    public void Save() {
        string savegameString = JsonUtility.ToJson(this);
        PlayerPrefs.SetString("savegame", savegameString);
    }

    public static Savegame Load() {
        string savegameString = PlayerPrefs.GetString("savegame");
        return JSONUtility.FromJson<Savegame>(savegameString);
    }
}

```
> 0 votes

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


# Question
Title: Drawing Sprites and Primitives with layers in MonoGame
I'm writing my own 2D engine using MonoGame and I want to be able to draw 2D primitives (using DrawPrimitives) along with sprites using SpriteBatch. But when I draw them, the primitives are always drawn below the sprites.

I tried to create a new Texture2D for each primitive, draw the primitives on these Texture2D's and draw these Texture2D's using SpriteBatch. That approach would allow me to draw primitives on any desired layer, but seems a little bit inflexible.

Simple Primitives, like rectangles and lines are already drawn using SpriteBatch and a 1x1 pixel sized Texture2D, stretched over the desired area. But more complex primitives would be difficult to draw.

In the image above you can see rectangles (outlined and filled), circles (outlined and filled) a line (on the right side) and a yellow curve. All of them are drawn using SpriteBatch. However, the white line in the middle of the screen is drawn using DrawPrimitives and it's below every one of the sprites. Also the yellow curve and the outlines of the circles aren't as pretty as when I drew them using DrawPrimitives.

I couldn't find any information, whether it's possible or not, to draw using DrawPrimitives and make use of layers, like with SpriteBatch. Does anyone know if it's possible, or if my approach is already the way to go when it comes to 2D primitives?

Some help or some useful links would be really appreciated. Thanks in advance.

# Answer
> 0 votes
Use the `layerDepth` parameter of `spriteBatch.Draw` to set the Z value of the generated primitive when batched.

Your custom primitives will be drawn with a Z value of 0.

I recommend splitting the spriteBatch into two separate foreground and background batches, if needed.

This value works irrespective of `Immediate` or `Deferred` draw modes.

---
Tags: 2d, monogame, draw-order
---


# Question
Title: "Slowing physics" only for certain objects?
I'm trying to simulate a time-slowing effect in Unity, which is supposed to slow down things like the physics engine, animator speeds etc. However, I also need certain GameObjects to be "immune" to this effect, so, as far as I understand, merely changing the value of `Time.timeScale` won't work.

The solution I've arrived at is to multiply certain values of non-immune rigidbodies by a factor (for example 0.1), and then divide by this factor when the slowdown effect ends to effectively reset them. I assumed doing this to the `velocity` and `gravityScale` of all non-immune rigidbodies, as well as the forces being applied to them, would be sufficient, but this does not seem to produce the desired effect.

As an example, jumping while time is slowed down produces a jump of 1/10th the height, that takes the same amount of time to complete (ie. reach the ground after jumping) when compared to jumping normally, when the desired effect is a jump of the same height, that takes 10 times longer to complete (assuming a slowdown factor of 0.1).

Any ideas on what other values must be changed in order to produce this effect? Or am I overthinking this and there is a simpler way to do it?

I'll gladly provide clarification/additional info if necessary. Thanks in advance.

# Answer
For a general vertical upward throwing motion, the highest point is reached when the velocity is 0. We have:

$$ S=\frac{v^{2}}{2g},t=\frac{v}{g} $$

Let the factors of velocity and gravity be `a` and `b` respectively:

$$ v'=av,g'=bg $$

Now we need the height to be the same and the time to expand `n` times

$$ S'=\frac{v'^{2}}{2g'}=\frac{a^{2}v^{2}}{2bg}=S=\frac{v^{2}}{2g} $$ $$ t'=\frac{v'}{g'}=\frac{av}{bg}=n·t=n·\frac{v}{g} $$ So we get： $$ a^{2}=b $$ $$ a=n·b $$ And: $$ a=\frac{1}{n},b=\frac{1}{n^{2}}(a,b,n,g≠0) $$

C# code:

```
using UnityEngine;

public class UnscaledObject : MonoBehaviour
{
    private Rigidbody2D rigidbody;
    private float factorA =1f;
}
private void Start()
{
    rigidbody = GetComponent<Rigidbody2D>();
}
private void SetTimeScale(float n)
{
    factorA = 1/n;
    var factorB = factorA*factorA
    rigidbody.gravityScale = factorB;
}
private void SetVelocity(Vector2 v)
{
    rigidbody.velocity = factorA * v;
}

```
> 2 votes

---
Tags: unity, physics
---