# Question
Title: How to simplify collision code when I have a lot of objects
Im trying to make a maze-like game and I need to simplify the code for when my player(picture box) collides with the walls of the maze(label). The code I have so far is

```
if pictureBox1.Bounds.IntersectsWith(label1.bounds) or _ pictureBox1.Bounds.IntersectsWith(label2.bounds) then

    (pretend code is here)

end if

```

and basically repeat that for 68 different walls. would there be any way to simplify that to make it shorter?

# Answer
> 2 votes
Anytime you start appending numbers to your variable names, it's a good sign that what you really want is an array. Something like:

```
Dim pictureBoxes(1 to 50) as Object
Dim pictureCount as Integer

Dim labels(1 to 50) as Object
Dim labelCount as Integer

' Assign your picture boxes and labels to those arrays

Dim i as Integer
Dim j as Integer

For i = 1 To pictureCount
    For j = 1 to labelCount
        If (pictureBoxes(i).Bounds.IntersectsWith(labels(j).bounds) Then
            ' Handle the collision
        End If
    Next j
Next i

```

This block of code handles checking the bounds of any number of picture boxes against any number of labels.

---
Tags: vb.net
---


# Question
Title: Sprite with transparency: Create box collider (ignoring transparent area)
I have a sprite which has a transparent area in it. The non-transparent area is a free-form graphic (red). I would like to create a box collider around it (yellow), but ignoring the transparent area.

Some notes to the image above:

* **Left:** This is what happens, if I apply a `PolygonCollider2D`. The yellow line represents the area covered by the `PolygonCollider2D`. This is not what I want.
* **Middle:** This is what happens, if I apply a `BoxCollider2D`. The yellow line represents the area covered by the `BoxCollider2D`. This is also not what I want, as it includes the transparent area of the sprite.
* **Right:** This is what I want: Have a `BoxCollider2D` outside my free-form graphic.

Here's how I currently load my sprite data into the game during runtime:

* My sprites are located in the `/Assets/Resources/SceneData/...` folder structure of my project. The graphics are stored as `.png` files.
* When loading a level, I load the required graphics as sprites like this:

```
    var sprite = Resources.Load<Sprite>("SceneData/AfternoonAtTheBeach/DragAndDrop/Graphics/Level1/ElephantWithIceCream");

```

"ElephantWithIceCream" is the `.png` file (`Resource.Load` wants me to refer to this file without file extension)

* After that, I create a new game object and attach a `SpriteRenderer` component to it. The sprite is assigned to the `SpriteRenderer` by setting the `sprite` attribute of the `SpriteRenderer` component.

My first thought on how to solve my problem was to do something like this:

* Create a `PolygonCollider2D` and try to convert it into a `BoxCollider2D`. But I was not able to find code examples on how to do this.

After that, I thought of trying it to do like this:

1. Create a `PolygonCollider2D` and try to extract some useful information out of it (such as bounds, center, extents, etc...).
2. Delete the `PolygonCollider2D` and create a `BoxCollider2D`. Use the previously extracted info to create the `BoxCollider2D`.

But I fail doing so. I am also a bit confused as sometimes they refer to world space or local space. Does anyone have a working recipe for doing something like this? I do not really understand how to work with center, bounds and extents. If there is any better way of doing this, I am highly interested. Thanks a lot for your help!

# Answer
I would recommend using photoshop PSB importer package. You design your sprites in photoshop/illustrator, position them properly there, and when imported into unity, the resulting sprites will be cropped to size of the non-transparent area of the layers by default, just as you've shown above. The result will also keep relative positions perfectly.

The default box-collider will be exactly what you have drawn above.
> 1 votes

# Answer
Posting late to the party just to provide my 2 cents on this matter.

As @DMGregory has mentioned, unless you have some absurd number of sprites to generate prefabs from (in which case, automation may be something worth investing in), doing it manually could be the way to go.

That said, I've run into a similar issue and I wanted to share some advice that really helped me come up with a solution for my project.

**Invest some time / thought into how your asset pipeline is going to work.** This involves everything from:

1. where are your sprites getting created (Photoshop, Aesprite)?
2. how are you exporting them (file format, etc...)?
3. how are you bringing them into Unity (folder structure / organization)?
4. what is the structure of the prefabs that display these sprites?

I'm not familiar with your project, but maybe it turns out you don't need those transparencies in the first place. So maybe your issue resides within point 2 above. Maybe you might choose to export your images as tight as possible, so then you can generate colliders directly to the bounds of the sprite (if you're using the sprite renderer component, check out `SpriteRenderer.Bounds`).

Maybe you do need those transparencies though. While you may have to generate these colliders by hand, you can still alleviate some pain points by defining a process for how to make your prefabs.

For instance, if you have some sprites that have transparencies, can you use the sprite editor to auto slice, and then generate your collider using the sliced image?

This is a bit off topic, but I've also found that defining some rules about each sprite having a fixed border size can really help, especially when it comes to playing animations. It can be really useful to define each sprite has having their center of the free form shape be at the center of the entire image (or some other fixed point that is consistent from sprite to sprite).

Hope that helps!
> 0 votes

# Answer
https://docs.unity3d.com/ScriptReference/MeshCollider.html

as your mesh-collider is generated automatically, based on above reference, you can get the list of vertices and also bounds of collider you have.

just check the Bigget X,Y and Lowest X,Y to set bounds of your 2d box-collider.
> 0 votes

---
Tags: unity
---


# Question
Title: How to properly set up a lives system for a side-scroller in pygame
I have a game where the player has to dodge asteroids coming towards it, and I would like to incorporate a life system. Unfortunately, when I tried this, it still killed my player immediately. I printed out the player's lives as a test, and it is going from 3 to -7 whenever an asteroid hits it. How would I make it so that only one life is subtracted?

Here is my code:

```
import pygame, random

from pygame.locals import (
    RLEACCEL,
    K_UP,
    K_DOWN,
    K_SPACE,
    K_ESCAPE,
    KEYDOWN,
    QUIT,
)

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super(Player, self).__init__()
        self.surf = pygame.image.load("ship.png").convert()
        self.surf.set_colorkey((255, 255, 255), RLEACCEL)
        self.rect = self.surf.get_rect()
        self.lives = 3

    def update(self, pressed_keys):
        if pressed_keys[K_UP]:
            self.rect.move_ip(0, -5)
        if pressed_keys[K_DOWN]:
            self.rect.move_ip(0, 5)

        if self.rect.top <= 0:
            self.rect.top = 0

        if self.rect.bottom >= SCREEN_HEIGHT:
            self.rect.bottom = SCREEN_HEIGHT

class Asteroid(pygame.sprite.Sprite):
    def __init__(self):
        super(Asteroid, self).__init__()

        self.surf = pygame.image.load("asteroid.png").convert()
        self.surf.set_colorkey((255, 255, 255), RLEACCEL)
        self.rect = self.surf.get_rect(
            center=(
            random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
            random.randint(0, SCREEN_HEIGHT),
            )
        )

        self.speed = random.randint(5,20)

    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            self.kill()

    def remove(self):
        self.kill()

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

ADDENEMY = pygame.USEREVENT + 1
pygame.time.set_timer(ADDENEMY, 250)

player = Player()

enemies = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)

clock = pygame.time.Clock()
running = True

while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False

        elif event.type == QUIT:
            running = False

        elif event.type == ADDENEMY:
            new_Asteroid = Asteroid()
            enemies.add(new_Asteroid)
            all_sprites.add(new_Asteroid)

    pressed_keys = pygame.key.get_pressed()
    player.update(pressed_keys)

    enemies.update()

    screen.fill((0,0,0))

    for entity in all_sprites:
        screen.blit(entity.surf, entity.rect)

        if pygame.sprite.spritecollideany(player, enemies):
            player.lives -= 1
            print(player.lives)
            if player.lives == 0:
                player.kill()
                running = False

    pygame.display.flip()
    clock.tick(30)

```

UPDATE: After trying out the first answer, here is the code for colliding:

```
        if pygame.sprite.spritecollideany(player, enemies): # Check if collided
            if not new_Asteroid.collided_with_player: # Check if the asteroid has already collided with the Player
                # Substract a life, set the asteroids collided player to True so it does not substract more than one, and play some sfx
                player.lives -= 1
                new_Asteroid.collided_with_player = True
                move_sound.stop()
                hit_sound.play()

                # If there are no lives left
                if player.lives == 0:
                    heart1.kill()
                    player.kill()
                    running = False

```

(In the asteroid class I have the collided\_with\_player set to False by default)

# Answer
> 3 votes
The player loses many lives because you don't tell your game to ignore collisions after the first frame there is a collision. Since there is a collision detected each frame, another life will be removed each frame until the collision no longer occurs (e.g. the Asteroid went through the Player).

I see two ways to fix it:

1. Once a collision with an Asteroid is detected, have the Player lose a life and *destroy* the Asteroid with a great boom! ()
2. If the Asteroid must not be destroyed because of the needs of your game design, add a flag `collided_with_player` on your Asteroid object (set to `False` by default), and once a collision with an Asteroid which has the `collided_with_player` set to `False` is detected, have the Player lose a life and set `collided_with_player` to `True`. This way you'll ignore future collisions between the player and this Asteroid.

Keep in mind that you have a flaw in your code. You're checking for collisions with *any* enemy, so you are unable to single out which enemy has hit the player (or rather, you're always affecting the last generated enemy). For this, you can change your code to *something* like this:

```
for enemy in enemies:
    screen.blit(enemy.surf, enemy.rect)

    if enemy collides with player and not enemy.collided_with_player:
        enemy.collided_with_player = True
        player.lives -= 1
        print(player.lives)
        if player.lives == 0:
            player.kill()
            running = False

screen.blit(player.surf, player.rect)

```

---
Tags: collision-detection, python, pygame
---


# Question
Title: Unity3d - How to freeze a Animation in the Editor
Is it possible to freeze my Animation in the Editor at a specific frame?

I made a simple camera animation, I try to select a specific frame inside of that animation and pause it, so I can work in the editor with everything positioned at the current positions at that specific frame.

This does not work at the moment. If I select my desired frame and then select another object, then my animation is set to start again.

This makes it very hard to work in the editor and prepare the animation.

---

**EDIT:**

Ok I try to explain it more simple. Let's assume I am animating the main camera and I have three animation points, A, B, and C. (I know I have more, but lets just assume it for this example to simplify it)

At **A** the camera is obviously at the start position:

At at **B** it is somewhere in between A and C:

At **C** the camera is at the end position:

What I need is to pause the animation at **B**, so my animation object stays at this position the whole time, even though when it has no focus and another object is selected. This would make it much easier for me to place objects exactly where I need them.

What actually happens is that my animated object (maincamera) is set to it's "start position", but I need it to stay in place, so I can place other objects perfectly.

I hope that was clear enough.

(side note: as you can see this is bugged, the rotation is weird now...)

# Answer
> 3 votes
Click the little lock icon in the top right of the animation window. It will 'lock' the selection (and the animation preview) even when you select something different in the scene or inspector views. (You can also use the lock to have multiple different inspector views.)

# Answer
> 2 votes
What do you mean for "freeze" the animation? Maybe i know what to do: Press ctrl+6 to open the Animation window Select the object that you animated Press the red record button in the animation window Select the frame you want to modify Make your changes Press again the red button

Done!

EDIT:

Oh alright then. I've done some investigation about this and i've actually tried it myself. Unfortunately if you are animating an object in unity, and you select another one while animating, the animated object returns to the default position.

I have an idea to solve this problem:

-You put the camera as a child of another gameobject(that you call something like Animation or something similar), create an animation for that gameobject, select the camera object(which is the child) and animate that one instead. all the objects you are going to want to move etc.. must be children of the "Animation" gameobject.

Try this and let me know!

# Answer
> 2 votes
This desirable workflow isn't well supported, but here is my trick for it:

* Create a new camera (name it 'test\_cam01' or similar)
* Copy the Camera component values from your original camera (right-click at the top of the component / "Copy Component") + Paste onto new cam's Camera component.
* Make new cam a child of original cam in the hierarchy + zero-out its transform (0s in all Pos and Rot fields and 1s in all scale fields)
* Animate original cam to the spot you want to edit the scene at
* In hierarchy window, remove test cam from original cam (make test cam a child of some other static object in the scene)
* Now, with 'Game' viewport visible, select the test cam, and toggle the 'Camera' component enabled checkbox (not the game object enabled checkbox at the very top of the object, but rather the checkbox ON the camera component itself). Toggling this makes it the active cam for the Game window.
    + You can now edit the scene (just open the scene viewport in a separate spot to use simultaneously), and view it through this static camera without losing your view
    + You can do the same thing with several static test cams along the animation path in order to see views along the way at various points.

GOOD LUCK

# Answer
> 0 votes
This workflow isn't well supported in Unity even in the most recent versions (as of 2022) as the other answers say but there are some tools on the Unity Asset Store that may be-able to help you.

For example: Editor Animation Freezer on the Unity Asset Store lets you freeze many different Animators in a specific frame in the Editor.

---
Tags: unity
---


# Question
Title: What would be a correct ID3D11Query design for occlusion testing?
I've tried looking for tutorials or samples related to the topic - but all that I could find are either scientific papers or vague posts on forums. As I understand it - I need to dedicate a whole pass to rendering simple AABBs to depth buffer only - to fill it first with depth data which will later be used in a separate pass for occlusion queries? OK I do that.

So how do I go about it in that separate, querying pass? When I render the same AABB a second time - I get the correct 0 pixels drawn result when it's out of view or covered by other objects in the scene - but I get incorrect results when the AABB is actually in the view - because it occludes itself from the previous pass and thus "pixels drawn" result is all over the place.

But I need the correct result to get the percentage of pixels drawn to produce smooth sun lens flare fading effect for example as its AABB gets gradually occluded increasing flare's transparency.

What am I missing here? What is the correct sequence to do Direct3D11 occlusion querying? Maybe some (pseudo-code) example?

# Answer
OK, I think I found a good enough balance between performance and pop-ins that did improve framerate for me by 20% vs. not doing occlusion/culling at all in a simple scene - should be even better in a complex one. Maybe it will help someone or maybe you will further help me improve it / correct it by answers in this thread?

Initialization:

1. On mesh creation/loading I generate a dedicated AABB mesh for the parent mesh.
2. I create a dedicated ID3D11Query object for each parent mesh with D3D11\_QUERY\_OCCLUSION desc and have each parent mesh object have an UINT64 query result variable.
3. I add a special UINT m\_framesElapsed variable to introduce the delay between querying and getting the results because getting the results in the same frame obliterates performance

Mesh objects have their class methods BeginQuery(), EndQuery(), GetQueryResult(). BeginQuery() and EndQuery() execute only on m\_framesElapsed 0 and GetQueryResult() executes on m\_framesElapsed 2 (the lowest I could go in my case), if it's not 2 - it would increase frame count by one and reset it to 0 if it's 2.

Now in the main rendering pass I first render all high detailed meshes as usual, straight into both render and depth buffers - then in the occlusion path down the line I render AABB meshes only to depth buffer and query them against the high detailed meshes there: BeginQuery(), DrawCall(), EndQuery(), GetQueryResult() - and write the result into that high detailed mesh's UINT64 variable so next frame it will either be shown or get occluded. The good effect here is that because AABBs take more space than high detailed mesh due to being boxes - they introduce a margin of error that helps with pop ins / pop outs as a high detailed mesh will be guaranteed to be fully occluded by the time AABB is fully occluded. However because of 2 frames delay - there are still notable pop-ins on multi-node/multi-mesh complex models which right now I don't know how to deal with or how to eliminate (maybe cheat by increasing the scale/size of AABBs?), but the performance increase is quite notable.

Another thing I'm thinking about is before doing an AABB occlusion pass I'd copy a full-res depth buffer, downscale it, output it to a new, much smaller resolution depth buffer and then do AABBs rendering/occlusion testing pass against that buffer. Maybe it will save even more performance as copying/resizing is basically free compared to querying a buffer that has 4 times the pixels, hmm?

It's an interesting study case either way.
> 0 votes

---
Tags: c++, directx, directx11
---


# Question
Title: How do I convert 2d character rigging animation to frame by frame sprite animation?
In this video after about the 8th minute, he says he converted them from character rigged animation to the frame by frame animation, so I searched but couldn't find any answers on google. How do I convert rigged 2d animations to frame-by-frame animations?

# Answer
> 2 votes
There are no built-in tools to do that I'm afraid. I've made this simple tool to do this kind of export automatically.

Hope you'll find it helpful!

# Answer
> 1 votes
It's impossible to be sure, but he likely used a 3rd party tool like Esoteric Software's Spine to create both the bone and frame-by-frame animation for the dog.

There are no built in tools or features in Unity to render 2D bone based animations as individual sprites at the moment.

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


title: Implement the snake movement in unity

text:
# Question
Title: Implement the snake movement in unity
I am developing a bullet-hell game and struggling to implement the snake movement logic. I try to record the head's positions and update bodies with these positions.

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

namespace Saltyfish.Logic
{
    public class SnakeMovement : MonoBehaviour
    {

        [SerializeField]
        private SnakePath m_SnakePath = new SnakePath(10);

        [SerializeField]
        private List<Unit> m_Bodies = new List<Unit>();

        public List<Unit> Bodies => m_Bodies;

        [SerializeField]
        [Range(0, 5)]
        private float m_BodySpace;

        public Unit Head => m_Bodies.SafeGet(0);

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

        protected virtual void OnUpdate()
        {
            UpdatePath();
            UpdateBodies();
        }

        protected void UpdateMovement(Vector2 direction)
        {
            if (Head == null)
                return;
            Vector2 curPos = transform.position;
            var nextPos = curPos + direction * Head.GetSpeed() * Time.deltaTime;
            transform.position = new Vector3(nextPos.x, nextPos.y, transform.position.z);
        }

        private void UpdatePath()
        {
            if (m_SnakePath.Count == 0)
            {
                if(Head != null)
                {
                    m_SnakePath.AddPoint(Head.transform.position);
                }
            }
            else
            {
                var tailPoint = m_SnakePath.Head.Value;
                var distance = Vector2.Distance(Head.transform.position, tailPoint);
                if(distance >= m_BodySpace)
                {
                    m_SnakePath.AddPoint(Head.transform.position);
                }
            }
        }

        public void SetBodyCapacity(int capacity)
        {
            m_SnakePath?.Resize(capacity);
        }

        private void UpdateBodies()
        {
            if (m_Bodies.Count <= 1)
                return;
            var headPoint = m_SnakePath.GetPoint(0);
            if (!headPoint.HasValue)
                return;
            float headMoveDistance = (Head.transform.position - headPoint.Value).magnitude;
            for (int i = 1;i < m_Bodies.Count; ++i)
            {
                if (m_Bodies[i].IsDead)
                    continue;
                var prevPoint = m_SnakePath.GetPointOrTail(i);
                var nextPoint = m_SnakePath.GetPointOrTail(i - 1);
                if (!nextPoint.HasValue || !prevPoint.HasValue)
                    continue;
                var nextPos = nextPoint.Value;
                var prevPos = prevPoint.Value;
                m_Bodies[i].transform.position = Vector3.Lerp(prevPos, nextPos, headMoveDistance);
            }
        }

        public void InitBodies(IList<Unit> units)
        {
            m_Bodies.Clear();
            if(units.Count > m_SnakePath.MaxCapacity)
            {
                Debug.LogWarning("body is too long");
            }
           for(int i = 0;i < units.Count && i < m_SnakePath.MaxCapacity; i++)
            {
                m_Bodies.Add(units[i]);
            }
        }

        public void PushBody(Unit unit)
        {
            if(m_Bodies.Count >= m_SnakePath.MaxCapacity)
            {
                Debug.LogWarning("not enough capacity for new body");
                return;
            }
            if(m_Bodies.Contains(unit))
            {
                return;
            }
            m_Bodies.Add(unit);
        }

        public void InsertBody(Unit unit, int pos = 0)
        {
            if (pos < 0 || pos >= m_Bodies.Count)
                return;
            if (m_Bodies.Count >= m_SnakePath.MaxCapacity)
            {
                Debug.LogWarning("not enough capacity for new body");
                return;
            }
            m_Bodies.Insert(pos, unit);
        }

        public Unit GetBody(int pos)
        {
            var unit = m_Bodies.SafeGet(pos);
            return unit;
        }

        public bool RemoveBody(Unit unit)
        {
            return m_Bodies.Remove(unit);
        }

        public void RemoveAt(int pos)
        {
            m_Bodies.RemoveAt(pos);
        }

#if UNITY_EDITOR

        private void OnDrawGizmos()
        {
            for(int i = 0;i < m_SnakePath.Count; i++)
            {
                Gizmos.DrawSphere(m_SnakePath.GetPoint(i).Value, 1);
            }
        }
#endif
    }
}

```

```
using Saltyfish.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Saltyfish.Logic
{
    [Serializable]
    class SnakePath
    {
        [SerializeField]
        private List<Vector3> m_PathPoints = new List<Vector3>();

        public int MaxCapacity { get;  private set; }

        public int Count => m_PathPoints.Count;

        public Vector3? Head
        {
            get
            {
                if (m_PathPoints.Count == 0)
                    return null;
                return m_PathPoints[0];
            }
        }

        public Vector3? Tail
        {
            get
            {
                if (m_PathPoints.Count == 0)
                    return null;
                return m_PathPoints[m_PathPoints.Count - 1];
            }
        }

        public SnakePath(int capacity)
        {
            MaxCapacity = capacity;
        }

        public void Resize(int capacity)
        {
            if (capacity <= 0)
                return;
            if (m_PathPoints.Count > capacity)
                m_PathPoints.RemoveRange(capacity, m_PathPoints.Count - capacity);
            MaxCapacity = capacity;
        }

        public void AddPoint(Vector3 point)
        {
            m_PathPoints.Insert(0, point);
            if (m_PathPoints.Count >= MaxCapacity)
                RemoveAt(m_PathPoints.Count - 1);
        }

        public void RemoveAt(int idx)
        {
            m_PathPoints.RemoveAt(idx);
        }

        public Vector3? GetPoint(int idx)
        {
            if (idx < 0 || idx >= m_PathPoints.Count)
                return null;
            return m_PathPoints[idx];
        }

        public Vector3? GetPointOrTail(int idx)
        {
            if (m_PathPoints.Count == 0)
                return null;
            var point = GetPoint(idx);
            if (point == null)
                point = m_PathPoints[m_PathPoints.Count - 1];
            return point;
        }
    }
}

```

But the current movement is less smooth if the gap(bodyspace) becomes larger.

So I searched a lot for a better implementation and I found these below.

Snakemovement tutorial on youtube

Snake tail follow

Another Snake follow solution

They are very helpful, but I think there are still some defects in these solutions.

Defect 1. All of the create-body 's scripts in these solutions used a delay time to keep a fixed gap between bodies. What if the snake's speed is various, which leads to different gaps between body parts?

Defect 2. How could I insert a body to the snake or swap a body with another and makes the snake apply the change automatically? ( all of these solutions are simply appending a body to the tail, which will also cause same problem in defect 1 if the snake speed has changed).

How could I implement a smooth snake movement with a dynamic body management?

# Answer
> 1 votes
I found a solution that uses backtracking.

It records the snake route every frame, and the bodies trace the route back to find their property position.

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

namespace Saltyfish.Logic
{
    public class SnakeMovement : MonoBehaviour
    {
        [SerializeField]

        private List<SnakePoint> m_SnakePath = new List<SnakePoint>();

        [SerializeField]
        private List<Unit> m_Bodies = new List<Unit>();

        public List<Unit> Bodies => m_Bodies;

        [SerializeField]
        [Range(0.1f, 5)]
        private float m_BodySpace;

        public Unit Head => m_Bodies.SafeGet(0);

        private bool m_Moved;

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

        protected virtual void OnUpdate()
        {
            UpdateBodies();
        }

        protected void UpdateMovement(Vector2 direction)
        {
            if (Head == null)
                return;
            Vector2 curPos = transform.position;
            var nextPos = curPos + direction * Head.GetSpeed() * Time.deltaTime;
            transform.position = new Vector3(nextPos.x, nextPos.y, transform.position.z);
            // Optimization 1 : Only update path when moved
            if(direction != Vector2.zero)
            {
                UpdatePath();
            }
            // Optimization 1
        }

        private void UpdatePath()
        {
            if (Head == null)
                return;
            var curPoint = new SnakePoint(Head.transform.position);
            if (m_SnakePath.Count > 0)
            {
                var lastPoint = m_SnakePath[m_SnakePath.Count - 1];
                curPoint.deltaDistance = Vector3.Distance(curPoint.Position, lastPoint.Position);
            }
            m_SnakePath.Add(curPoint);
        }
        private void UpdateBodies()
        {
            if (m_Bodies.Count <= 1)
                return;
            for (int i = 1; i < m_Bodies.Count; ++i)
            {
                if (m_Bodies[i].IsDead)
                    continue;
                float remainDistance = Mathf.Clamp(m_BodySpace, 0.1f, 5) * i;
                for (int j = m_SnakePath.Count - 1; j > 0; j--)
                {
                    if (remainDistance <= m_SnakePath[j].deltaDistance)
                    {
                        float LerpProgress = 0;
                        if (m_SnakePath[j].deltaDistance > 0)
                        {
                            LerpProgress = remainDistance / m_SnakePath[j].deltaDistance;
                        }
                        m_Bodies[i].transform.position = Vector3.Lerp(
                            m_SnakePath[j].Position,
                            m_SnakePath[j - 1].Position,
                            LerpProgress);
                        // Optimization 2 : remove the points before the waypoint that last body has reached
                        if (i == m_Bodies.Count - 1)
                        {
                            m_SnakePath.RemoveRange(0, j - 1);
                        }
                        // Optimization 2
                        break;
                    }
                    remainDistance -= m_SnakePath[j].deltaDistance;
                }
            }
        }

        public void InitBodies(IList<Unit> units)
        {
            m_Bodies.Clear();
            for (int i = 0; i < units.Count; i++)
            {
                m_Bodies.Add(units[i]);
            }
        }

        public void PushBody(Unit unit)
        {
            if (m_Bodies.Contains(unit))
            {
                return;
            }
            m_Bodies.Add(unit);
        }

        public void InsertBody(Unit unit, int pos = 0)
        {
            if (pos < 0 || pos >= m_Bodies.Count)
                return;
            m_Bodies.Insert(pos, unit);
        }

        public Unit GetBody(int pos)
        {
            var unit = m_Bodies.SafeGet(pos);
            return unit;
        }

        public bool RemoveBody(Unit unit)
        {
            return m_Bodies.Remove(unit);
        }

        public void RemoveAt(int pos)
        {
            m_Bodies.RemoveAt(pos);
        }

        private void OnGUI()
        {
            GUIStyle textStyle = new GUIStyle();
            textStyle.fontSize = 35;
            GUI.Label(new Rect(25, 25, 200, 100),"BodySpace", textStyle);
            m_BodySpace = GUI.HorizontalSlider(new Rect(25, 100, 200, 80), m_BodySpace, 0.1F, 5);
        }

    }
}

```

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Saltyfish.Logic
{
    [Serializable]
    public class SnakePoint
    {
        public Vector3 Position;

        public float deltaDistance;

        public SnakePoint(Vector3 pos)
        {
            Position = pos;
        }
    }
}

```

Although the route point list grows endlessly, the memory cost is acceptable because a single game lasts only 5 minutes. And I can clear the list before the next game begins.

EDIT:

1. The list does not need to be updated if the movement is stopped.
2. The points before the last body point can be removed as Zibelas suggested.

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


title: Low poly terrain on godot

text:
# Question
Title: Low poly terrain on godot
I'm new to game development and stuck on an issue . Question is : Considering the RAM usage , will it be better to use low - poly terrain ? (which i assume yes as it has lower level of details)

**Which way should i opt for making terrain of low poly nature to make it efficient when RAM is being considered ??**(godot specific , without blender)

# Answer
> 1 votes
I'll chip in a bit; some other folks could provide even better answers.

> Considering the RAM usage

Graphics generally impact the *video* RAM (the VRAM), not the system RAM as you seem to mention. Often, computers will have much more system RAM than video RAM. Also, VRAM will often be occupied more by *textures* than by actual vertices that compose the mesh. If you have a low-poly mesh and a hi-res texture, you could bust your (V)RAM.

> will it be better to use low - poly terrain

We can't answer that.

What kind of game do you want to make? Would it make sense to have a low-poly terrain and a hi-poly main character(s)? Depending on the game, you can "cheat" and load dynamically only the terrain that is visible to the camera and what's immediately surrounding it; you unload what's not visible, freeing up the memory for what matters.

Keep in mind that using low-poly terrain can be an advantage w.r.t. physics. The less polygons there are, the simpler the collision checking (where a completely flat ground is the simplest).

It's a balancing act between all your needs.

---
Tags: terrain, godot
---


# Question
Title: Tilemaps not showing up on Android build
I'm having trouble developing a 2d game for Android. I use tilesmaps for the ground and a few other things. On the editor, everything works fine and dandy. But, when I deploy to a phone(Build and Run), the tiles aren't there. It's like they never existed. I go back to the editor and they're there. I play the game directly from the editor and they're there. I even play the game while running unity remote, on the test phone, and the tiles are there. No idea what's going on. This only happens with tilemaps. Everything that isn't a tilemap is visible. I'm running Unity 2019.3.0f6

# Answer
> 0 votes
Never mind I got rid of the tilemap and went with a more tedious approach we were I utilize the snapping feature of unity. This video is a great source of how to use the snapping feature https://www.youtube.com/watch?v=QeEecOc4roI

# Answer
> 0 votes
I found your post a bit late but this might help some others.

I was in the same situation, working fine on Simulator but not on device. Turns-out it was a silly Z position problem due to the different phones resolutions.

Setting the main camera (assuming you're using an orthographic one) a bit further back in your scene did the trick for me.

Hope that helps!

---
Tags: unity, android
---


# Question
Title: Rotate an object relative to the player to face another object
Essentially, in my game, I have 3 objects: a player, a shield and a puck. I want to have the shield orbit the player to automatically face the puck. (So the position will change with the rotation).

`Transform.LookAt()` works for having the shield look at the puck, but I can't seem to figure out the mathematical wizardry required to apply that rotation to the relative position of the player.

```
public class Shield : MonoBehaviour
{
    [SerializeField]
    private GameObject playerObject;

    private GameObject puck;
    private Vector3 offset;

    void Start()
    {
        GetPuckObject();
        offset = transform.position - playerObject.transform.position;
    }

    void LateUpdate()
    {
        transform.position = playerObject.transform.position + offset;

        if (!puck)
        {
            if (!GetPuckObject())
                return;
        }

        transform.LookAt(puck.transform);
    }

    bool GetPuckObject()
    {
        puck = GameObject.FindWithTag("Puck");
        return puck;
    }
}

```

I feel so dumb for asking for help with this and I'm sure it's been asked before but I can't find anything which yields the behaviour I describe (possibly because I'm struggling to describe it). I think it's a case of translating the rotation to a position but not sure how to approach this.

**Edit**
This moves in relation to the rotation but doesn't work properly past 180 degrees (and is questionable before that)

```
  void LateUpdate()
    {
        if (!puck)
        {
            transform.position = playerObject.transform.position + offset;
            if (!GetPuckObject())
                return;
        }
        transform.position = playerObject.transform.position + offset;
        Quaternion lookRotation = Quaternion.LookRotation(puck.transform.position - transform.position);
        transform.rotation = lookRotation;
        transform.Translate(transform.forward);
        Debug.Log(transform.forward);
    }

```

# Answer
> 2 votes
The relative distance between the shield and the player is a fixed length instead of a fixed offset. Record this fixed length and calculate the position according to the rotation.

```
public class Shield : MonoBehaviour
{
    [SerializeField]
    private GameObject playerObject;

    private GameObject puck;
    private float offset;

    void Start()
    {
        GetPuckObject();
    }

    void LateUpdate()
    {
        if (!puck)
        {
            if (!GetPuckObject())
                return;
        }
        var lookRotation = Quaternion.LookRotation(puck.transform.position - transform.position);
        transform.position = playerObject.transform.position + lookRotation * (Vector3.forward * offset);
        transform.rotation = lookRotation;
    }

    bool GetPuckObject()
    {
        puck = GameObject.FindWithTag("Puck");
        offset = (transform.position - playerObject.transform.position).magnitude;
        return puck;
    }
}

```

---
Tags: unity, mathematics, rotation
---


# Question
Title: How to animate sprite swapping with changeable equipment sprites?
I know that this is a very old Unity issue. I'm doing a 2D pixel art rpg and I want to sprite swap whenever the player gets an armor (helmet,vest,boots...).

I created an empty game object and parented all armor game objects to it.

After a long research, I found the Unity Sprite Library Asset that can swap the sprites of a category. I have a helmet idle sprites and registering this to the sprite library, and I can successfully swap the head helmet. The problem is that when I animate this, I can't swap the sprites because the animation keyframes animates only one sprite. I don't really know how to use the sprite library asset to change not only the single sprite render but all the sprites in the animation (I have sprite for each keyframe because I update the sprite, I don't use things like 2D bones)

That's the idle player animation:

That's the hat animation.

That's how I configured the equipment objects (sprite renderer):

Is there a way to help with my code?

# Answer
If I understand your problem correctly, you are trying to reskin your character with different visuals. In that case, using the Sprite Library Asset is a good choice because it will allow you to create animations once and they should work fine after swapping the visuals.

Looking at your screenshots, it looks like you are animating the Sprite reference directly in your Sprite component. This is not right, because when working with Sprite Library Assets you want to animate the **Sprite Resolver** component instead. That way, your animation will be correct even after swapping to a different Sprite Library.

For more information you can check out the documentation of the 2D Animation package here. Hope this helps!
> 3 votes

---
Tags: unity, sprites, spritesheet
---


# Question
Title: Possible to have Composite Collider 2D detect colliders in grandchildren?
I have a number of GameObjects with 2 child GameObjects:

* Sprite
* Words

There is a a BoxCollider2D on both the Sprite child and the Words child. The parent has a Composite Collider 2D on it, which uses those BoxColliders. It automatically calculates perfect polygon colliders, and is working great.

My GameObjects can sometimes nest. You can see an example in the attached pictures, where a Snake GameObject has a Zebra GameObject nesting under it.

The Composite Collider 2d for the Snake is not picking up on the Box colliders for the grandchildren nodes (Zebra/Sprite and Zebra/Words). I am guessing that's because a Composite Collider will only combine colliders from Box Collider 2D or Polygon Collider 2D, and not from another Composite Collider.

Is it possible to have a Composite Collider (or some other collider aggregator) pick up the colliders for not only child nodes but also grandchildren nodes? And great grandchildren, etc. My whole data model currently uses nesting of GameObjects, so it'd be great to be able to continue with that while also taking advantage of a Composite Collider. Thanks!

# Answer
> 2 votes
> Is it possible to have a Composite Collider (or some other collider aggregator) pick up the colliders for not only child nodes but also grandchildren nodes?

Yes, the CompositeCollider2D component will pick up all children and grandchildren (and all others down the hierarchy) with Box Collider 2D or Polygon Collider 2D. The problem in your setup is that Zebra has its own Composite Collider and a Rigidbody 2D and it's combining its own children into a single collider.

> My whole data model currently uses nesting of GameObjects, so it'd be great to be able to continue with that while also taking advantage of a Composite Collider.

Would you be able to disable remove a Composite Collider and Rigidbody2D on nested objects? That should fix your issue.

---
Tags: unity, collider
---


# Question
Title: UI quality drops when changing canvas resolution in Unity
I am making a game for android using unity. The problem is that the resolution of the UI drops drastically when the canvas resolution is changed(for testing purposes).

Joystick(UI component) with resolution set to 1920 x 1080:

Joystick with resolution set to 800 x 480:

It's obvious that this happens due to changes in the resolution of the canvas, but is there a way that does not affect the quality of UI components while changing the canvas resolution?

Like different devices have different resolutions, and many games still have clear UI on these devices.

Import settings(Right) and the inspector(Left) of the sprite:

As suggested in one of the comments below, I tried generating min maps(*Import Settings \> Advanced \> Generate Min Maps*). It looks better but still not on the point.

At 800 x 480 after generating min maps:

*My Intention: Different mobile devices have different screen sizes and hence, different resolutions. So, if a device has the resolution 1920x1080, the UI would look fine, but if with a different resolution, the UI would either shrink or expand to fit the screen size. That is fine but this expansion and contraction would affect the quality of UI. A UI component that would fit clearly with devices of different resolutions is my intention.*

Any alternatives would also be appreciated.

(This is a 3D game)

# Answer
The lower quality you're observing is due to texture sampling artifacts.

The sprite's texture stores what colour each pixel should be when the sprite is displayed at exactly its original size. When you shrink the sprite to cover fewer pixels, you can cause spatial aliasing \- you're sampling the underlying texture's signal at a lower frequency than the highest frequencies it contains.

Mipmapping can help with this, by pre-computing smaller versions of the sprite, so the graphics card can select the one closest to the actual display size and reduce aliasing. (This also improves texture cache performance and can actually speed up rendering, despite the extra memory cost)

But mipmapping and bilinear filtering work by averaging nearby pixels, which can make the result look slightly fuzzy.

To avoid this, the best thing you can do in general is to author sprites at their intended display resolution, and display them at that size. Unity has features that will allow you to switch between sprite assets depending on your display resolution, to ensure you're using the best match for your current display.

For single-colour UI sprites like this though, we can take another approach and render them using a signed distance field. In this form, instead of storing the colour to draw at each point, the sprite texture stores each pixel's distance inside or outside the shape to be drawn, measured from the closest edge. This distance field interpolates and scales better than a raw colour image. We then use some shader math to determine how close each screen pixel is to the edge of the shape, and correctly anti-alias it.

The distance field can look like this:

To make this, I created the shapes I wanted in a vector drawing program, and set the stroke around the shapes to be a black-to-white gradient.

Each frame, the shader interprets those gradients vs the sprite's scaling to dynamically draw an anti-aliased edge in the right place.

Here's an SDF shader compatible with Unity's sprite and UI image renderers:

```
Shader "SDF/Sprite"
{
    Properties
    {
        [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
        _Color("Tint", Color) = (1,1,1,1)
        _Dilate("Dilate", Range(-0.45, 0.45)) = 0
        [MaterialToggle] PixelSnap("Pixel snap", Float) = 0
        [HideInInspector] _RendererColor("RendererColor", Color) = (1,1,1,1)
        [HideInInspector] _Flip("Flip", Vector) = (1,1,1,1)

        [HideInInspector] _StencilComp("Stencil Comparison", Float) = 8
        [HideInInspector] _Stencil("Stencil ID", Float) = 0
        [HideInInspector] _StencilOp("Stencil Operation", Float) = 0
        [HideInInspector] _StencilWriteMask("Stencil Write Mask", Float) = 255
        [HideInInspector] _StencilReadMask("Stencil Read Mask", Float) = 255
        [HideInInspector] _ColorMask("Color Mask", Float) = 15
    }

    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment SDFSpriteFrag
            #pragma target 2.0
            #pragma multi_compile_instancing
            #pragma multi_compile_local _ PIXELSNAP_ON
            #pragma multi_compile _ ETC1_EXTERNAL_ALPHA

            #include "UnityCG.cginc"
            #include "UnityUI.cginc"

#pragma multi_compile_local _ UNITY_UI_CLIP_RECT
#pragma multi_compile_local _ UNITY_UI_ALPHACLIP

            sampler2D _MainTex;
            fixed4 _Color;
            fixed4 _TextureSampleAdd;
            float4 _ClipRect;
            float4 _MainTex_ST;
            float _Dilate;

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color : COLOR;
                float2 texcoord  : TEXCOORD0;
                float4 worldPosition : TEXCOORD1;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            v2f vert(appdata_t v)
            {
                v2f OUT;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
                OUT.worldPosition = v.vertex;
                OUT.vertex = UnityObjectToClipPos(OUT.worldPosition);

                OUT.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);

                OUT.color = v.color * _Color;
                return OUT;
            }

            fixed4 SDFSpriteFrag(v2f IN) : SV_Target
            {
                fixed4 c = IN.color;

#ifdef UNITY_UI_CLIP_RECT
                c.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);
#endif

                float a = tex2D(_MainTex, IN.texcoord).r;

                float2 gradient = float2(ddx(a), ddy(a));

                float gradientLength = length(gradient);

                float pixelsFromEdge = (a - 0.5f + _Dilate) / gradientLength;

                c.a *= smoothstep(0, 1, pixelsFromEdge + 0.5f);

                c.rgb *= c.a;
                return c;
            }
            ENDCG
        }
    }
}

```

This lets you get crisp vector-like edges for single-colour sprites, over a wider range of resolutions than a single conventional sprite texture. It also makes it easier to apply special effects, like dilating or thinning the shapes, adding glows or shadows, etc.

Text Mesh Pro uses this technique to support font rendering in Unity.
> 2 votes

---
Tags: unity, user-interface
---


# Question
Title: Changing the target of a button that takes a gameobject as a parameter
I'm working on a point and click system in Unity and I have a contextual menu that appears when you right click on an object. In this menu, there's a button called "search" that moves the player to the object and opens a menu representing that object's contents. The Search Button calls a method that takes a gameobject as a parameter; in other words, the object that the player treats as the target to which it moves and then searches.

All of this is working just fine, but there's one problem: Currently I have two test containers, a crate and a barrel. The crate is the object that the button is taking as a parameter, so if I right click the barrel and select "search", the player will go to search the crate.

How do I dynamically change the gameobject target of the button so that the search button will know the correct object it should be targetting, I.E. whichever object the player right clicked?

# Answer
Have a variable on the context menu or a selection manager that stores what object was right-clicked.

Set that variable when you run the code that shows the context menu.

When searching, don't call the player's search method directly. Ask the context menu to invoke the search (no arguments needed), and it can inject the target object into the call when it forwards it on to the player:

```
public class ContextMenu : MonoBehaviour {

    GameObject _contextMenuTarget;

    public void OpenContextMenuOn(GameObject target) {
        _contextMenuTarget = target;
        // Put code that shows the menu here.
    }

    public void InvokeSearch() {
         Player.Search(_contextMenuTarget);
    }
}

```
> 0 votes

---
Tags: unity, unity-ui
---


# Question
Title: OnDrag is not invoked with a small dragging movement in Unity
I implemented mobile rotation control with IPointerDownHandler and IDragHandler. It seems fine if the movement is fast enough, but there's a serious flaw that the OnDrag event never invoked if the dragging amount is very tiny.

Here's the code.

```
using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof(CanvasGroup))]
public class MobileFPSRotationPanel : MonoBehaviour, MobileFPSUIElement, IPointerDownHandler, IDragHandler, IEndDragHandler {
    ...

    public void OnDrag(PointerEventData eventData) {
        Debug.Log("Drag"); <- It's not invoked if the dragging is too small.
       eventData.Use();

       Vector2 currentTouchPosition = eventData.position;
       m_Movement = currentTouchPosition - m_PreviousTouchPosition;
       m_PreviousTouchPosition = currentTouchPosition;
   }

   public void OnEndDrag(PointerEventData eventData) {
       Debug.Log("EndDrag");
       m_Pressing = false;
       m_Movement = Vector2.zero;
   }

   public void OnPointerDown(PointerEventData eventData) {
       Debug.Log("PointerDown");
       if (Interactable == false) {
           return;
       }

       eventData.Use();

       m_Pressing = true;
       m_Movement = Vector2.zero;
       m_PreviousTouchPosition = eventData.position;
   }

   ...
}

```

I reported a lot of people have been annoyed by this glitch, which makes it hard to precise aiming. Is this a glitch or an intended feature of Unity? If it's intended, then how should I detect every drag movement even if it's super tiny?

Using Unity 2019.4.3f1.

# Answer
> 4 votes
You can simply set the *drag threshold* of the event system:

> The Drag Threshold property represents the number of pixels a UI object can be moved before it is considered being "dragged". People don't have perfectly steady hands, so when they are trying to click or tap a UI item their mouse or finger may move slightly. This Drag Threshold allows the player to move their input slightly (or a lot if you make this number high) before the item they are selecting is being "dragged" rather than "clicked".

Or you can simulate the drag yourself by `update()`:

```
using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof(CanvasGroup))]
public class MobileFPSRotationPanel : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private bool isDragging;
    void Update()
    {
        if (!isDragging)
        {
            return;
        }
        OnPointerMove(Input.mousePosition);
    }
    public void OnPointerMove(Vector3 position)
    {
        Debug.Log(position);
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        isDragging = true;
    }
    public void OnPointerUp(PointerEventData eventData)
    {
        isDragging = false;
    }
}

```

---
Tags: unity, mobile
---


# Question
Title: Player movement script based on a given symmetry
I'm trying to make a game where the movement of the second player is based on the first player's movement but with a given line of symmetry. For example, if the inputted symmetry was y=x, then when player 1 moves to the left, player 2 moves down. Problem is, I'm a novice and don't know how to do that. Can someone help me figure out what I need to change in my script to achieve this?

<pre><code> using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class PlayerMovement : MonoBehaviour
 {
     // Start is called before the first frame update

     public float moveSpeed = 5f;

     public Rigidbody2D rb;
     public Animator animator;

     Vector2 movement;

     // Update is called once per frame
     void Update()
     {
         movement.x = Input.GetAxisRaw("Horizontal");
         movement.y = Input.GetAxisRaw("Vertical");

         animator.SetFloat("Horizontal", movement.x);
         animator.SetFloat("Vertical", movement.y);
         animator.SetFloat("Speed", movement.sqrMagnitude);
     }

     void FixedUpdate()
     {
         rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
     }
 }
```
</code></pre>

# Answer
> 1 votes
First define an axis of symmetry. Defining an axis(or a line) in space requires two arguments: the direction(or slope) of the line, and a point that this line passes through.

Then find the symmetry point of a point by Reflect.

Code:

```
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public Vector3 symmetryPoint = Vector3.zero;
    public Vector3 symmetryAxis = new Vector3(1, 0, 1);
    public GameObject player1;
    public GameObject player2;
    void Update()
    {
        var v1 = symmetryPoint - player1.transform.position;
        var v2 = Vector3.Reflect(v1, symmetryAxis.normalized);
        player2.transform.position = symmetryPoint + v2;
    }
}

```

Edit:

Symmetrical velocity instead of position:

```
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Vector2 symmetryAxis = new Vector2(1, 1);
    public float moveSpeed = 5f;
    public Rigidbody2D rb;
    public Rigidbody2D rb2;
    private Vector2 movement = Vector2.zero;
    void Update()
    {
        movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized;
    }

    void FixedUpdate()
    {
        var v1 = movement * moveSpeed;
        var v2 = Vector2.Reflect(-v1, symmetryAxis.normalized);
        rb.MovePosition(rb.position + v1);
        rb2.MovePosition(rb2.position + v2);
    }
}

```

There are two problems with the previous code:

1. You should use the normalized value of the moving direction, otherwise the speed will become sqrt(2) when walking diagonally.
2. You should not use `Time.fixedDeltaTime` inside `FixedUpdate()`, it will be used automatically.

---
Tags: unity, movement, single-player
---


# Question
Title: "Fix Your Time Step" Variable or Fixed Physics "timeStep" parameter for Step in Box2D?
I have seen multiple contradictory articles on this topic. Have been trying to implement the Should the function call

```
b2World->Step(timeStep, velocityIterations, positionIterations);

```

have timeStep as a constant value? Or should the timeStep vary based on a frame time accumulator, like in "https://gafferongames.com/post/fix\_your\_timestep/"?

My question comes from gameplay that seems 'too fast', whereas before I 'fixed' my timestep sometimes the physics would would run at a smooth rate.

# Answer
You'll get the most consistent physics behaviour if you use a fixed timestep (constant value).

The "Fix Your Timestep" article you linked does *not* recommend using a varied timestep for physics. It says exactly the opposite. The variable time component is used only for interpolation and display, not simulation.
> 1 votes

---
Tags: c++, box2d
---


# Question
Title: Apply a mocap to multiple different models? -> modify gltf directly?
I am currently struggling with an animation I made that I would like applied to multiple models, all different, but from the same vertices. I already have a custom gltf importer ready but I need to polish my exporter. Hence the question.

The first model has been exported to gltf and is fine.

My question is: is there a simple, programmatic, way to edit this GLTF file to place the bones of the next model at different locations (that I know) to still benefit from a correct animation or not? That would be easier/faster than manual adjustments.

I played with vertices position inside the GLTF, but the result is a distorted model. Tried to modify the animation matrices directly as well: same ugly result (this is just an excerpt showing that I push all ancestors and then start from the root, down to my bone of choice):

```
while ( 1 ){

        chain.push_back( node_idx );

        if ( armature[node_idx].parent == CONDITION_STOP ){

                break;

        }

        node_idx = armature[node_idx].parent;

}

for ( auto curr = chain.rbegin(), curr_end = chain.rend(); curr != curr_end; ++curr ){

        u32 node_idx = *curr;
        // skipped: select the right animation indices, then:
        mat4 mmat_current = compose( translation, rotation, scale);

        mat = multiply( mat, mmat_current );
        // keep going with mat

}

```

Maybe there is something to try with the inversebindmatrix\[i\] but I really need a pointer here. So, what are my options please? What did I get wrong?

Thanks,

Edit: picture of the problem. The skeleton is the same size, despite the model being different:

How on earth can I drag the bone to their 3D position (I know the final 3D position **in the global world** each bone should have) ?

I tried to only play with translation matrices: fail.

# Answer
> 1 votes
I ran into a very similar problem. But using very different tools. The solution for me was something like this:

1: set skeleton/meshes to standard T pose. 2: import mesh of 2nd body (tall person). 3: copy skeleton of first body to tall body 4: set bone coordinates to known world coordinates. I made sure the T pose meant that world coordinates = vertex coordinates. 5: re-set the “bind poses” for the mesh. This is what they were called in the tools I was using. But it’s referring to the stored offsets between the vertexes and the bones they are associated to.

Then, once that was complete, the new rig was done and ready to animate. My apologies, it’s been a few years so I don’t remember every detail.

The reason the meshes looked so bad for me was due to the linear blendskinning being applied to the bones with the wrong offsets when the joints were moved. So for example it thought that the elbows were bent way more than they actually were. Resetting the bind poses made it understand the correct offsets to use.

For #4, I accomplished this by reading up on how my tool was doing the bones. It was a set of nodes in a tree graph. Similar to Transforms in Unity. I found a way to edit this set Of matrices manually to match the new person’s T pose.

The keyword for me to read up on was Bind poses. I know some tools call them different things. But that really was the key to figuring out the whole process of transferring skeletons to other bodies.

If you want to look into how I did it a bit more it was for an open source tool that does exactly what you’re doing. Unfortunately only for non-commercial use. But you can still take a look at the code for inspiration. https://biomotionlab.github.io/SUP/

Hope that helps in your scenario.

---
Tags: matrix, skeletal-animation
---


# Question
Title: How to fix the character flip when using an orthographic camera in libGDX
I used an orthographic camera to follow the character (player), but the problem is that my character is flipped. There are no tutorials on how to fix this. Please help as fast as possible.

Here is my create method:

---

public void create () {

```
    batch = new SpriteBatch();
    float width=Gdx.graphics.getWidth();
    float height=Gdx.graphics.getHeight();
    camera=new OrthographicCamera();
    camera.setToOrtho(false,width,height);
    camera.update();
    tiledMap= new TmxMapLoader().load("assets\\untitled.tmx");
    tiledMapRenderer=new OrthogonalTiledMapRenderer(tiledMap);
    player=new Player(new Vector2(0,0));
    sr= new ShapeRenderer();

```

}

---

Here is my render method: public void render () {

```
    Gdx.gl.glClearColor(0, 0, 0.2f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA,GL20.GL_ONE_MINUS_SRC_ALPHA);
    player.update();
    camera.position.set(player.getPosition().x,player.getPosition().y,0);
    camera.update();
    tiledMapRenderer.setView(camera);
    tiledMapRenderer.render();
    sr.begin(ShapeRenderer.ShapeType.Line);
    sr.setColor(Color.BLUE);
    sr.rect(player.getPosition().x,player.getPosition().y,player.getCurrentFrame().getRegionWidth(),player.getCurrentFrame().getRegionHeight());

    sr.end();
    batch.begin();

    batch.draw(player.getCurrentFrame(),player.getPosition().x, player.getPosition().y);
    batch.setProjectionMatrix(camera.combined);
    batch.end();
}

```

# Answer
> 2 votes
It's been a bit since I used LibGDX, but doesn't the `setToOrtho` function have a boolean that defines whether the camera is flipped or not? It looks like your whole screenshot is flipped, so instead of `camera.setToOrtho(false, width, height);` try using `camera.setToOrtho(true, width, height);`.

If it is just the player that is flipped (which I'm guessing is a sprite), you can just use `player.flip(false, true)` to flip it vertically.

# Answer
> 0 votes
the code above works but change camera.setToOrtho(false,width,height); to camera.setToOrtho(true,width,height); it was just that i had a resize method and had in it camera.setToOrtho(false,width,height);

# Answer
> 0 votes
If it is the entire viewport that is flipped; Similar to what QualityPixels' suggestion, I solved my issue with `camera.setToOrtho(true, -width, height)`. You can flip the camera by setting the width and/or height to be negative. I would follow what he suggested if it's the character and not the viewport.

---
Tags: libgdx, camera
---


# Question
Title: A point on a sphere surface needs to be converted to origin coordinate
I have a central point, a planet is moving around it on the orbit A (a circle)

And the planet is rotating at a certain speed on its axis ( B )

I have a Data Structure representing the Base Mesh information that is static and calculated around the origin point that is static.

Think:

```
float3[] pointsList

```

Where all the point are calculated around 0,0,0 instead of where the planet is ( it's easier to convert 1 point on a frame rather than a list with thousands of point each frame )

Around that planet, I have a collider to be able to catch raycasts on it. The sphere collider is roughly the size of the mesh so it matches well.

Here is what I need :

How can I convert the point from the raycast back to an "origin" state.

Here is an illustration :

From My understanding I would need :

To Revert the rotation on the Axis (A) BUT following the (C) Line along the surface to find the base point as if the mesh did not rotate at all and then Translate the point so it is in the origin referential. (Around 0,0,0 , where the base mesh have been calculated)

Now...what are the maths that I need to do behind the scenes to do that?

TLDR: I am trying to convert a raycast point on the surface of a sphere back to an "origin" kind of point to do stuff behind with it with the base mesh coordinates.

Edit : Adding representation of the planet VS the stored point Array ( please note that A is at 0,0,0 ) :

Here : B is the representation of the points array and is STATIC & A Is the position of the planet with the collider & the mesh created from B's Points, all rotating on it's axis ( cf : Other screenshot )

So how do I "revert" a point from the collider around the mesh to get a point as if the raycast Happened on the A sphere ?

Edit 2 : Result with InvertTransform

```
        if (!Physics.Raycast(MainCamera.ScreenPointToRay(Input.mousePosition), out hit))
        {
            return;
        }
        RaycastHit hit;

        Vector3 localHit = TargetPlanet.transform.InverseTransformPoint(hit.point);
        GameObject rayCastHit = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        rayCastHit.name = "RayCastHit";
        rayCastHit.transform.position = hit.point;
        rayCastHit.transform.localScale = new Vector3(0.025f,0.025f,0.025f);

        GameObject targetLocal = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        targetLocal.name = "TargetLocal";
        targetLocal.transform.position = localHit;
        targetLocal.transform.localScale = new Vector3(0.025f,0.025f,0.025f);

        Vector3 planetHit = TargetPlanet.transform.TransformPoint(targetLocal.transform.position);
        GameObject targetPlanet =GameObject.CreatePrimitive(PrimitiveType.Sphere);
        targetPlanet.name = "TargetPlanet";
        targetPlanet.transform.parent = TargetPlanet.transform;
        targetPlanet.transform.position = planetHit;
        targetPlanet.transform.localScale = new Vector3(0.025f,0.025f,0.025f);

```

Then Clicking on the same point again and again without mooving the mouse give me that :

For the raycast hit :

For The TargetLocal : ( On the reference Sphere at origin )

For The TargetPlanet: ( On the Surface of the planet & the view of the collider )

Both the hit on the surface & on the reference seems OFF and never hit the same point

Edit 3 : Movement Code :

```
public float3 EvaluatePlanetOrbit(int planetID, float t)
{
  float angle = t * 360 * Mathf.Deg2Rad;
  float x = math.sin(angle) * Orbits[planetID].XAxis; // Orbits[planetID].XAxis -> Float
  float z = math.cos(angle) * Orbits[planetID].ZAxis; // same

  return new float3(x, 0, z);
}

//That is the code managing the movement of the planet

planetData.OrbitalProgress += time * (1 /planetData.CurrentOrbit) * planetData.OrbitalSpeed;
PlanetGridGameObject.transform.position = EvaluatePlanetOrbit(planetData.PlanetID, planetData.OrbitalProgress);

// Rotations
planetData.CurrentAngleRotation += time * GameSettings.RotationPlanetSpeed;
planetData.CurrentAngleRotation %= 360;

Quaternion rotationAboutAxis = Quaternion.Euler(0, planetData.CurrentAngleRotation, 0);
Quaternion tiltOfAxis = Quaternion.Euler(0, 0, GameSettings.RotationPlanetAxis);

PlanetGameObject.transform.rotation = (Quaternion) tiltOfAxis * rotationAboutAxis ;

```

# Answer
You're moving your planet with its Transform component, but then detecting hits with its Collider component, which is part of the physics system. This separately tracks the position and orientation of colliders within the physics simulation space that's used for collisions and raycasts.

Data is only copied from the Transform into the physics simulation once per physics step. If you move the Transform in Update, the collider is still sitting in the position it was as of the last physics tick.

Calling Physics.SyncTransforms forces the latest Transform changes to be propagated to the physics simulation immediately. Now the collider is where you expect it to be, so the raycast hits the correct point.

After that, you just need Transform.InverseTransformPoint to convert the world space hit point into the planet's local coordinate system.
> 1 votes

---
Tags: unity, c#, 3d, mathematics, rotation
---


# Question
Title: Informing clients of player actions in 2d platformer
I'm creating an online game (2d platformer) and I'm having some trouble understanding what to send clients. I'm sampling each player's input and sending it to the server after a set amount of time. The input is then sent to other clients, while the position is sent to the local player (since that client is already aware of inputs).

This is all fine. However, everything I have read about online games has said to only send the position of the player. How do I inform clients about the actions the player took?

For example, if player A uses a dash skill, I need to render that on client B, and accelerate the player at that time. I could send client B data about the position and physics state before and after the skill was used, as well as the name of the skill, but isn't that overkill? It seems easier to me to simply send input data. Something like this: \[{key: right, time: 5}, {key: dash}\].

One problem with this though is if I'm sending the data using UDP, client B will not render the player's skill if the packet is lost, unless I send the information until client B has inform the server it has been seen, but surely that defeats the purpose? Should I be using TCP for crucial information such as player abilities?

And if sending just position data, how does one deal with acceleration? Wouldn't I have to send the physics state of the player as well? Do other games do this, or do they just interpolate positions instead of calculating the momentum of other entities?

I'm not sure if I'm missing something but if someone could help me understand how I need to go about updating clients I would really appreciate it.

# Answer
I have an interest but limited experience with the development of online / networked games primarily in C but also in Python. I don't know what "everyone else" does.

I would stick with UDP to keep the network overhead down, especially if it's online. You should craft your communications between the client and the server in such a way that it won't matter if a packet gets lost. Don't mix UDP and TCP channels for communications between the clients and the server.

I wouldn't send each player's inputs to the other clients. Let the clients manage their own states. A client *probably* does not need to know that another client is using "dash", just that the other player is moving much more quickly. Have the clients fully process their own inputs, update their own location, direction, and speed, and send that to the server; then have the server send that already-processed information to the other clients. It's okay if the packet gets lost because the next one will update with the latest position, direction, and speed information. You'll have to decide if you want the information for every player sent to every client, or if you want to sent only the information for the other players who are within display distance of the client.

It's not generally necessary for other clients to know what skill you're using at any particular time, merely the results of using that skill: faster movement, higher jump, etc. What you should send is information about how the character should be displayed: health bar, shielded, magic aura, hunger bar, etc. Yes, you may need to send the client's physics state, I suppose, but I think that the physics state should be sent in absolute terms rather than relative terms, but I still think it would be better if you could encode that information in terms of position, direction, and speed.

The topic of "persistence" does change the relationship between server and client quite a bit, but doing things this way has helped my own designs.
> 0 votes

---
Tags: networking, platformer, server, online, client
---


title: Inverse Spot light

text:
# Question
Title: Inverse Spot light
A central mechanic in my game involves shining a flash light on a glass sphere, which then focuses the light like a magnifying glass in order to burn enemies. The flash light was easy to implement - it's just a spot light - but the focused beam is turning out to be a little harder, since Unity doesn't seem to have any built-in light type that converges to a single point.

Currently, I'm using a flipped spot light. With that the illusion falls apart pretty quickly, since it casts shadows in the wrong direction and doesn't illuminate things the way you would expect it to.

Am I missing a light type that does what I need, or is there a trick to achieve such an effect?

# Answer
> 2 votes
Here's a simple fix: multiply the material's normal by -1 and light it with a spot light in the opposite direction. Let's start with a Lambert surface shader with a main texture and a normal texture.

```
Shader "Example/Diffuse Bump" {
    Properties {
        _MainTex ("Texture", 2D) = "white" {}
        _BumpMap ("Bumpmap", 2D) = "bump" {}
    }
    SubShader {
        Tags { "RenderType" = "Opaque" }
        CGPROGRAM
        #pragma surface surf Lambert
        struct Input {
            float2 uv_MainTex;
            float2 uv_BumpMap;
        };
        sampler2D _MainTex;
        sampler2D _BumpMap;
        void surf (Input IN, inout SurfaceOutput o) {
            o.Albedo = tex2D (_MainTex, IN.uv_MainTex).rgb;
            o.Normal = UnpackNormal (tex2D (_BumpMap, IN.uv_BumpMap))*-1;//<- multiply by -1
        }
        ENDCG
    }
    Fallback "Diffuse"
}

```

But this affects all types of lighting, including directional lights. So if you only need to deal with spot light, you need to implement a multi-light lighting model yourself, like this and this.

In the lighting model, it will be judged whether the angle between the reflected light direction and the observe direction is \> 90°(dot \< 0), like:

```
max(0.0, dot(reflect(-lightDirection, normalDirection),viewDirection))

```

If the light is a point light or a spot light, change its normal direction to:

```
max(0.0, dot(reflect(-lightDirection, -normalDirection),viewDirection))

```

---
Tags: unity, lighting
---


# Question
Title: How to play a sound when changing the value of a tkinter scale
I'm making a settings menu for my game, and would like to know if it is possible to play a sound every time a value of a scale is changed. For example, the user changes the scale from 1 to 2, a sound would play.

# Answer
> 0 votes
You are looking for callback function of tkinter `Scale()`. Check API

> **command**: A procedure to be called every time the slider is moved. This procedure will be passed one argument, the new scale value. If the slider is moved rapidly, you may not get a callback for every possible position, but you'll certainly get a callback when it settles.

So you can do something like this:

```
def callback(value=None):
    # play a sound here

s = Scale( *other parameters*... , command=callback)

```

---
Tags: python, sound, sound-effects
---


# Question
Title: How to check the font on a Text Mesh Pro component
I have a GameObject with a Text Mesh Pro component.

I want to check if the Font applied to the Text Mesh Pro component is a particular font (let's say it's Comic Sans)

I can get the font name by first using Get Component and then calling Get Font.

But the output of Get Font is the font asset itself. So I can't use a simple string Equality (or Contains) to check if the font matches Comic Sans.

Can I turn the output of Text Mesh Pro Get Font into a string? Or is there another way to check if the font matches a particular font?

Thanks!

# Answer
> 1 votes
You can get the name of the font asset with `GetComponent<TextMeshProUGUI>().font.name`. That will return the name of the font asset in the same way as it appears in the "Project" window.

---
Tags: unity, fonts
---


title: How can I remove Unity Hub in Ubuntu?

text:
# Question
Title: How can I remove Unity Hub in Ubuntu?
I installed Unity Hub 1.4.0 and it works well. For now I want to update the version of Unity. I need to install hub 2.0.0. But when I download the 2.0.0 hub and intsall it always link to 1.4.0 and I want the version Unity 2019.1.10f1. I can't find some uninstall files. How can I remove Hub 1.4.0?

# Answer
> 2 votes
from https://docs.unity3d.com/hub/manual/InstallHub.html#install-hub-linux

Uninstalling the Hub: To remove the Unity Hub from the system, run the following command:

```
$ sudo apt-get remove unityhub

```

# Answer
> 1 votes
Try deleting the following directories:

```
/home/{your_user_name}/.config/UnityHub

/home/{your_user_name}/.config/Unity Hub

```

---
Tags: unity, linux
---


# Question
Title: Detect Child Trigger inside Parent Script
I want to detect when a Child's collider is being triggered to apply the damage to the thing being hit. But currently I'm confused about how it works.

Does the Parent's `OnTriggerEnter` detect the trigger events of the Child Object ? And how do I know the trigger come from the Child and not the Parent, and know which Child's collider got triggered?

The Parent's collider is not a trigger, but the Child's collider is.

# Answer
Triggers don't create OnTriggerXXX messages, only rigidbodies do. If child doesn't have a rigidbody, basically its collider is considered a child collider of the parent node (compound collider). Now we come back to the question:

> Does the Parent's OntriggerEnter detect the trigger event of the Child Object ?

If child object doesn't have a rigidbody, yes.

> And how do I know the trigger come from the Child and not the Parent and know which Child's collider got triggered ?

They need their own rigidbody and script with `OntriggerEnter`, which is not recommended.

In fact, you don't need to get the physical events from the attack box, simply set it to another layer, such as "attack", and all attack events are handled by the attacked party (character's body, with rigidbody and script, layer "be\_attacked").
> 2 votes

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


# Question
Title: How to load DontDestroyOnLoad object from menu scene when testing other scenes?
I have an audio manager that plays background music for a game I'm making in Unity. Since the music persists between some scenes, I've set up a means of not destroying the audio manager between all scenes and just changing the track whenever the scene changes to one that has a different track. I've accomplished this by implementing my audio manager on the main menu screen, but none of the subsequent levels, since I don't want multiple managers. However, when I launch a scene from Unity, I have a difficult time debugging with no audio manager. Is there a way to instantiate an audio manager if there is none in a scene? Thanks!

# Answer
> 2 votes
To make Marunia's suggestion more explicit, you can use a "lazily-initialized" singleton pattern to spawn your audio manager just-in-time when someone asks for it, even if it wasn't in the scene to begin with. That could look like this:

```
public class PersistentManager<T> : MonoBehaviour where T : PersistentManager<T> {

    static T _instance;
    public static T Instance {
        get
        {
            if (_instance == null) {
                _instance = FindObjectOfType<T>();
                if (_instance == null) {
                    _instance = (new GameObject(typeof(T).Name)).AddComponent<T>();
                }
            }
            return Instance;
        }
    }

    void Awake() {
        if (_instance != null) {
            // We've loaded back to a scene that already includes this
            // object! Destroy ourselves to let the existing instance stay.
            Destroy(gameObject);
            return;
        }

        DontDestroyOnLoad(gameObject);
        _instance = (T)this;
    }
}

```

Then you can declare your audio manager class as

```
public class AudioManager : PersistentManager<AudioManager>

```

and other scripts could get (or create on demand) a reference to the solitary instance of it and access its properties and methods like so:

```
AudioManager.Instance.DoAThing();

```

There are a couple of problems with this lazy spawning approach though:

* When we can't find a matching manager in the scene, we spawn a new one with default settings. That will prevent a null reference exception, but it won't play music you'd assigned to your manager in the inspector in your Menu scene or in a prefab. If the manager depends on child objects to function, those won't be spawned by this script either.

We could partially address this by searching the assets folder for a matching prefab, and instantiating that, or hard-coding a path to load it from. But that still leaves another issue:
* Your manager won't exist until someone asks for it. That might not be a problem for managers whose only job is to service requests, but if the manager is supposed to be doing something passively in the background - like playing music - that background activity won't start until the first time the manager is requested. So that could create a weird silence at the start of your level, or force you to put unnecessary `AudioManager.Instance` calls in places just to kickstart the manager if it's absent.

Here's another strategy that addresses these problems. We'll make a `ScriptableObject` asset that keeps track of what managers we want spawned in any scene we load:

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

// Split out the part that we only use for in-editor testing.
#if UNITY_EDITOR
using UnityEditor;

[CreateAssetMenu(fileName = "ManagerSpawner.asset", menuName = "Utilty/Manager Spawner")]
public partial class ManagerSpawner : ScriptableObject
{
    // Uncheck to stop auto-spawning.
    //This lets you switch between different sets of objects for testing.
    [SerializeField] bool enabled = true;

    // Fill this with references to the prefabs you want to spawn.
    [SerializeField] PersistInAllScenes[] objectsToSpawn;

    // When we enter play mode, spawn the desired managers.
    [RuntimeInitializeOnLoadMethod]
    static void SpawnManagers() {
        if (_alreadySpawned) return;

        string[] guids = AssetDatabase.FindAssets($"t:{typeof(ManagerSpawner).Name}");
        foreach (var guid in guids)
        {
            string path = AssetDatabase.GUIDToAssetPath(guids[0]);
            var asset = AssetDatabase.LoadAssetAtPath<ManagerSpawner>(path);
            if (asset.enabled) {
                foreach(var item in asset.objectsToSpawn) {
                    Instantiate(item);
                }
            }
        }
    }
}
#endif

// The rest is just a stub to turn it off when needed.
public partial class ManagerSpawner : ScriptableObject
{
    static bool _alreadySpawned = false;

    public static void CancelSpawn() { _alreadySpawned = true; }
}

```

Now in your Assets \> Create menu, you can create a Manager Spawner asset in your project folder, and use the inspector to load it up with references to the prefabs that should be spawned in every scene.

On those prefabs, you just need a simple script:

```
public class PersistInAllScenes : MonoBehaviour
{
    void Awake() {
        // Usual persistence path: DontDestroyOnLoad.
        DontDestroyOnLoad(gameObject);

        // Tell the manager spawner it doesn't need to do anything.
        // (In case we loaded the menu scene where these objects already live.)
        ManagerSpawner.CancelSpawn();
    }
}

```

This turns off the spawn-on-start-up behaviour if you entered play mode in a scene that already contained your persistent objects.

By using `[RuntimeInitializeOnLoadMethod]`, we ensure these managers are present as we enter play mode, not delayed until the first request. And since we're loading them from prefabs, they'll come in with any inspector setup or dependencies they need to do their work. And we managed to do that without an expensive search through all prefabs, or hard-coding any asset paths. You can have multiple different versions of your manager prefabs, or multiple different sets of managers, and swap between them during testing by explicitly controlling which ones should be spawned.

# Answer
> 1 votes
> Is there a way to instantiate an audio manager if there is none in a scene?

Yes - you can check if your audio manager already exists by calling Object.FindObjectOfType(). You could then do something like this:

```
var audioManager = Object.FindObjectOfType<YourAudioManager>();
if(audioManager == null)
{
    // Instantiate your audioManager
}

```

Another way would be to use some static reference e.g., a Singleton pattern to track your audio manager instance.

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


# Question
Title: Implementing ability system with ability parameters
I am trying to implement an ability system in Unity for a game similar to XCOM (turn based, team consists multiple of units, grid based). Every unit have X action points per turn.

**I would like to do it in the way that everything that unit can do per turn is an "ability"**

* Moving is an "ability"
* Attack is an "ability"
* Spell is an "ability", etc...

I searched and found out that that it would be suitable to use Scriptable objects. The idea is there would be a base abilty class from which other abilities inherit.

```
public class AbilityBase : ScriptableObject
{
    public string desc;
    public int actionCost;
    public virtual void Execute(){};
}

```

And other abilities would look like this

```
public class HealAbility: AbilityBase
{
    public virtual override void Execute()
    {
        //GetComponent<Unit>()
        //Check if Unit has enough action points
        //If so then apply heal
    };
}

```

Which would propably work fine. Every unit would have some sort of **AbilityManager** which would hold references to the ScriptableObjects abilities.

**The problem with this solution is:**

* Some abilities (Taking cover, healing) can be applied on caster itself. It can get a reference from inside **Execute** method.
* Some others needs to have targed in form of a unit (Attack on another unit)
* Some needs a target in form of a grid Node (throwing a granade, AOE spell)

The **Execute** method takes zero argument and inherited classes cannot modify that.

**Questions:**

1. How could I solve this problem with missing target references? (How to pass target into a ability?) The target of abilities could also be of a different type.
2. Abilities that takes target needs to pick it first. So it should indicate that to the player (for example other units light up). Same with an ability that takes a grid node (Allowed nodes would light up). Should this be implemented from inside the ability itself or should it handle the parent script that uses abilities?

**My possible solution to questions:**

1. Since the game is grid based, the all the targets will propably be on an grid node. So theoretically passing an grid node or an array of nodes to the **Execute** method could work. `void Execute(GridNode[] nodesToCastOn)` Then the **Execute** method would look up which unit is standing on the nodes and apply its effect on them.
2. I think it should not handle the ability script, because it the ability should not wait for player input.

If anyone managed to read this far I thank you. Do you thing my solutions would be ***Correct***? If no, could you elaborate why not and/or breafly explain your solution?

I will be thankfull for any insight from you guys.

# Answer
> 1 votes
Make subclasses:

```
public abstract class AbilityBase : ScriptableObject {
    public string desc;
    public int actionCost;
}

public abstract class UntargetedAbility : AbilityBase {
    public abstract void Execute();
}

public abstract class UnitTargetedAbility : AbilityBase {
    public abstract bool IsValidTarget(Unit candidate);
    public abstract void Execute(Unit target);
}

public abstract class LocationTargetedAbility : AbilityBase {
    public abstract bool IsValidTargetZone(Location candidate, List<Location> area);
    public abstract void Execute(GridLocation target);
}

```

Extend the appropriate one for each effect.

Then your code for selecting an ability might look something like this:

```
bool TrySelect(AbilityBase ability)
{

    if (ability.actionCost > actionBudget) return false;

    switch(ability) {

        case UntargetedAbility untargeted:
            actionBudget -= ability.actionCost;
            untargeted.Execute();
            return true;

        case UnitTargetedAbility unitTargeted:
            GameStateManager.EnterTargetPickingState(unitTargeted);
            // Don't deduct cost yet - player may cancel before selecting target.
            return true;

        case LocationTargetedAbility locationTargeted:
            GameStateManager.EnterLocationPickingState(locationTargeted);
            // Again, don't deduct cost when it can still be cancelled.
            return true;

        default:
            throw new System.NotImplementedException($"Unknown ability type {ability.GetType().Name}");
    }
}

```

Here I'm assuming you have something like a `GameStateManager` state machine that can hold the reference to the selected ability while in the target picking state, invoking the `IsValidTarget` / `IsValidTargetZone` predicates to display appropriate selection feedback, and then carry on to executing the ability (and deducting the cost) once a valid target has been selected.

---
Tags: unity, c#, architecture, design-patterns, turn-based
---


# Question
Title: How to vary the Glow settings for a Text Mesh Pro font
I've added a Text Mesh Pro component to my GameObject, as shown here:

I'd like to programmatically vary the value of the Power setting under Glow, in order to create a pulsating effect for my text. Someone posted a related bit of code on the Unity Forum:

> m\_TextMeshPro.fontSharedMaterial.SetColor(ShaderUtilities.ID\_GlowColor, new Color32(255, 240, 0, 100));

But in my case, I'd like to programmatically change the Glow parameters (specifically the Power one) to go from 0 to 1 and then back again... to create a pulsating effect.

I can't find out how to change these parameters. I am beginning to suspect that I need to edit the TextMeshPro/Distance Field Shader in order to to programmatically change the glow. Does anyone know if that is true... and if so, how to do it? Thank you!

# Answer
> 1 votes
When you don't know how to access a parameter of a shader in code, click the "Edit" button next to the material type selector to open its shader code.

Search for "Glow" and you'll find the property declarations for the glow parameters:

```
[HDR]_GlowColor     ("Color", Color) = (0, 1, 0, 0.5)
_GlowOffset         ("Offset", Range(-1,1)) = 0
_GlowInner          ("Inner", Range(0,1)) = 0.05
_GlowOuter          ("Outer", Range(0,1)) = 0.05
_GlowPower          ("Falloff", Range(1, 0)) = 0.75

```

So now we know the power parameter is called `_GlowPower` under the hood. We can convert that to an ID using:

```
static readonly int ID_GlowPower = Shader.PropertyToID("_GlowPower");

```

Although it seems like the ShaderUtility you're already using includes that ID out of the box.

Since this is a float (range) property, we can set it with:

```
 m_TextMeshPro.fontSharedMaterial.SetFloat(ShaderUtilities.ID_GlowPower, value);

```

---
Tags: unity, text-mesh-pro
---


# Question
Title: SFML: Object's shape not rendered on the window
I want to be able to render `sf::CircleShape` (representing pointwise charges) when pressing mouse buttons on the window. The problem is easy enough, however the shapes that I want to draw are attributes of a class `Charge`. The `Scene` class implements window management and event polling/ rendering methods and it has an attribute `std::vector<Charge> distribution`.

The idea is to update the `distribution` variable everytime the event `sf::Mouse::isButtonPressed` is recorded and then draw the charges' shapes within such vector. For some reason I cannot make it work and I think it's due to the object being created and destroyed within the event loop.

I have a main that looks like this

```
#include "Scene.h"

int main(){

  Scene scene;

  while(scene.running())
  {
    scene.update();
    scene.render();
  }
  return 0;
}

```

with the header `Scene.h` declaring the class methods for window management and event polling

```
#include "Charge.h"

class Scene
{
    private:
        sf::RenderWindow* window;
        sf::Event event;
        std::vector<Charge> distribution;

public:
        Scene();
        virtual ~Scene();

        bool running();
        void polling();
        void render();
        void update();
};

```

The definitions of the methods instantiated in the game loop are

```
void Scene::update(){this -> polling();}

void Scene::polling()
{
    while(this -> window -> pollEvent(this -> event))
    {
        switch(this -> event.type)
        {
            case sf::Event::Closed: this -> window -> close();
                break;

            case sf::Event::MouseButtonPressed:
                this -> distribution.push_back(Charge(*this -> window, sf::Mouse::getPosition(*this -> window));
                std::cout << "Distribution size = " << distribution.size() << "\n";
                break;
        }
    }
}

void Scene::render()
{
    this -> window -> clear(sf::Color::Black);

    for(auto charge: this -> distribution)
    {
        charge.render(*this -> window);
    }

    this -> window -> display();
}

```

The `window` object is instatiated in the cosntrutor of `Scene`. Now `Charge.h` declares the class

```
class Charge
{
    private:
        sf::CircleShape shape;

    public:
        Charge(const sf::RenderWindow& window, sf::Vector2i position);
        virtual ~Charge();

        void render(sf::RenderTarget& target);
};

```

and the definition of its methods is the following

```
Charge::Charge(const sf::RenderWindow& window, sf::Vector2i position)
{
    std::cout << "Charge's object created!" << std::endl;
    this -> shape.setOrigin(sf::Vector2f(static_cast<float>(position.x), static_cast<float>(position.y)));
    this -> shape.setFillColor(sf::Color(255,50,50));
    this -> shape.setRadius(25.f);
}

Charge::~Charge(){std::cout << "Charge's object destroyed!" << std::endl;}

void Charge::render(sf::RenderTarget& target)
{
    target.draw(this -> shape);
}

```

I added printing on terminal in the constructor and destructor. The execution of the program does not render any of the objects' shapes when mouse buttons are pressed. The terminal however reports

```
Charge's object created! # <-- Here I pressed the mouse's button
Charge's object destroyed!
Distribution size = 1
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed!
Charge's object destroyed! # <-- And it goes on and on as long as the window is not closed.

```

I tried to approach the problem in various ways but none have worked so far. Any idea?

# Answer
> 1 votes
This block of code will be copying each object of type `Charge` for every iteration and assigning to the variable called `charge`.

```
  for(auto charge: this -> distribution)
  {
      charge.render(*this -> window);
  }

```

You need to change `auto` to `auto&` because you want to use a reference to the object itself not a copy of it. In most cases, this is the right approach in range-based for loops.

```
  for(auto& charge: this -> distribution)
  {
      charge.render(*this -> window);
  }

```

The first "Charge's object destroyed!" message is coming from the `push_back` method from the vector. Use `emplace_back` instead. It constructs the object inside the vector without doing any copying. It 'moves' the data to be exact.

```
this->distribution.emplace_back(*this -> window, sf::Mouse::getPosition(*this -> window));

```

There should not be any problems with the rendering in general. I don't see any issues with that. If you can show the problem in a gif, that would be better.

---
Tags: c++, rendering, game-loop, sfml, oop
---