# Question
Title: Collision detection between moving objects (in pygame)
I am trying to work out how to detect and resolve collisions between moving sprites in pygame, I followed the logic of this video: https://www.youtube.com/watch?v=VpSWuywFlC8

The basic idea is that I track the current rectangle position as well as the previous rectangle position for each sprite and use that to detect where collisions have come from.

For example, to check if the player has collided at the bottom I use: player.rect.bottom \>= sprite.rect.top and player.old\_rect.bottom \< sprite.old\_rect.top that way I know that the player's bottom is in the other sprite and that it was above it in the previous frame.

The problem I have is that the collision detection only works sporadically and thus also breaks the collision resolution. Although, if I only look at a collision on a single side it does work. I am just not sure what the problem is with the collision detection. So any help how to fix the collisions method would be greatly appreciated.

(Also, any resource on collision detection for moving rectangles/objects would be really appreciated. I struggle to find good resources on it)

Code so far:

```
import pygame, sys

class StaticObstacle(pygame.sprite.Sprite):
    def __init__(self,pos,size,groups):
        super().__init__(groups)
        self.image = pygame.Surface(size)
        self.image.fill('yellow')
        self.rect = self.image.get_rect(topleft = pos)
        self.old_rect = self.rect

class MovingVerticalObstacle(StaticObstacle):
    def __init__(self,pos,size,groups):
        super().__init__(pos, size, groups)
        self.image.fill('green')
        self.direction = pygame.math.Vector2((0,1))
        self.speed = 8

    def update(self):
        self.old_rect = self.rect.copy()

        if self.rect.bottom >= 600 or self.rect.top <= 120:
            self.direction.y *= -1

        self.rect.y += self.direction.y * self.speed

class MovingHorizontalObstacle(StaticObstacle):
    def __init__(self,pos,size,groups):
        super().__init__(pos, size, groups)
        self.image.fill('purple')
        self.direction = pygame.math.Vector2((1,0))
        self.speed = 6

    def update(self):
        self.old_rect = self.rect.copy()
        if self.rect.right >= 1000 or self.rect.left <= 600:
            self.direction.x *= -1

        self.rect.x += self.direction.x * self.speed

class Player(pygame.sprite.Sprite):
    def __init__(self,groups,obstacles):
        super().__init__(groups)

        # image
        self.image = pygame.Surface((30,60))
        self.image.fill('blue')

        # position
        self.rect = self.image.get_rect(topleft = (640,360))
        self.old_rect = self.rect.copy()

        # movement
        self.direction = pygame.math.Vector2()
        self.speed = 5
        self.obstacles = obstacles

    def input(self):
        keys = pygame.key.get_pressed()

        # movement input
        if keys[pygame.K_UP]:
            self.direction.y = -1
        elif keys[pygame.K_DOWN]:
            self.direction.y = 1
        else:
            self.direction.y = 0

        if keys[pygame.K_RIGHT]:
            self.direction.x = 1
        elif keys[pygame.K_LEFT]:
            self.direction.x = -1
        else:
            self.direction.x = 0

    def collisions(self):
        collision_sprites = pygame.sprite.spritecollide(self,self.obstacles,False)
        if collision_sprites:
            for sprite in collision_sprites:
                if self.rect.top <= sprite.rect.bottom and self.old_rect.top > sprite.old_rect.bottom:
                    print('top collision')
                    self.rect.top = sprite.rect.bottom
                elif self.rect.bottom >= sprite.rect.top and self.old_rect.bottom < sprite.old_rect.top:
                    print('bottom collision')
                    self.rect.bottom = sprite.rect.top
                elif self.rect.right >= sprite.rect.left and self.old_rect.right < sprite.old_rect.left:
                    print('right collision')
                    self.rect.right = sprite.rect.left
                elif self.rect.left >= sprite.rect.right and self.old_rect.left < sprite.old_rect.right:
                    print('left collision')
                    self.rect.left = sprite.rect.right

    def update(self):
        self.old_rect = self.rect.copy()
        self.input()

        self.rect.topleft += self.direction * self.speed
        self.collisions()

# general setup
pygame.init()
screen = pygame.display.set_mode((1280,720))
clock = pygame.time.Clock()

# group setup
all_sprites = pygame.sprite.Group()
collision_sprites = pygame.sprite.Group()

# sprite setup
StaticObstacle((100,300),(100,50),[all_sprites,collision_sprites])
StaticObstacle((800,600),(100,200),[all_sprites,collision_sprites])
StaticObstacle((900,200),(200,10),[all_sprites,collision_sprites])
MovingVerticalObstacle((200,300),(200,60),[all_sprites,collision_sprites])
MovingHorizontalObstacle((850,350),(100,100),[all_sprites,collision_sprites])
Player(all_sprites,collision_sprites)

# loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill('black')
    all_sprites.update()
    all_sprites.draw(screen)

    pygame.display.update()
    clock.tick(60)

```

# Answer
> 2 votes
You can use masks, they provide a pixel perfect collision and they're easy to use with both moving and stationary objects.

You can check this post for more information, but here is the method briefly :

First of all, you need to make a mask object for the objects you want to check collision between and there are 2 possibilities for each one:

I. If your object is a rect object, then you need `pygame.mask.Mask()` to create the mask object:

```
# In the constructor
self.mask = pygame.mask.Mask((self.width, self.height), True)

```

II. If your object is an image, simply use the `pygame.mask.from_surface()` method:

```
# In the constructor
self.mask = pygame.mask.from_surface(self.image)

```

Once you've done that, make a function that calculates the offset (You can put it in your self made classes if you want, as you'll need to call it everytime you perform a mask collision detection) :

```
def offset(mask1, mask2):
    return int(mask2.x - mask1.x), int(mask2.y - mask1.y)

```

Now, in the collision detection section, just check if the two masks collide with each other :

```
if obj1.mask.overlap(obj2.mask, offset(obj1, obj2)):
    print('Collision !!!')

```

Btw, if you use this `overlap` method for the `obj1`, then `obj1` must be the **first** parameter of the `offset` function and vice versa (as seen in the code snippet)

## IMPORTANT NOTE :

If any of your objects has multiple sprites, then you need to make a method for its mask object because it will vary as the current sprite varies :

```
@property
def mask(self):
    return pygame.mask.from_surface(self.sprites[self.current_sprite]))

```

---
Tags: python, pygame
---


# Question
Title: Change speed of rotation (magnitude) without changing direction (sign)
I have this code that rotates my object:

```
      private void FixedUpdate()
        {
            transform.Rotate(0, 0, Speed * Time.deltaTime);
            Debug.Log(Speed);
        }

```

When I call this function, I want the object to start rotating in the opposite direction (this works):

```
        public void changeDir()
        {
            Speed = -Speed;
        }

```

When I call these functions, I want to change the speed of rotation, while keeping the direction (clockwise or counterclockwise) the same. But these always make the object rotate to the right instead of left:

```
        public void ZoomSpeed()
        {
            Speed = 330f;
        }

        public void ZoomNormal()
        {
            Speed = 125f;
    }

```

How do I maintain the same direction (sign) when changing the rotation speed?

# Answer
> 0 votes
I'm guessing you might be looking for something like this?

```
public void ZoomSpeed()
{
    Speed = 330f * Mathf.Sign(Speed);
}

public void ZoomNormal()
{
    Speed = 125f * Mathf.Sign(Speed);
}

```

That is, you want to change the magnitude of the `Speed` variable, while keeping its sign? (So if `Speed` was less than zero before calling `ZoomSpeed()`, it will be -300 afterward, instead of +300?)

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


title: for loop problem

text:
# Question
Title: for loop problem
So it works first time when the player dies. But when it dies twice the for loop doesn't work.

if winner == "Team DeathMatch" then
    local player = game:GetService("Players").LocalPlayer
    local allplrs = game:GetService("Players"):GetPlayers()
    for _,v in pairs(allplrs) do
        local h = v.Character:FindFirstChild("Humanoid")
        h.Died:Connect(function()
            local red_cf = CFrame.new(28.859, 8.588, 104.769)
            local blue_cf = CFrame.new(-148.635, 8.115, 104.769)
            warn("someone ded")
            local function o()
                return v.team.Value
            end
            warn("work here i guesss")
            local x = o()
            if x == "blue" then

                warn("hi")

                v:LoadCharacter()

                v.Character:SetPrimaryPartCFrame(blue_cf)
                game.ReplicatedStorage.remotes.tdstuff:FireClient(v)
            elseif  x == "red" then

                warn("hi")

                v:LoadCharacter()

                v.Character:SetPrimaryPartCFrame(red_cf)
                game.ReplicatedStorage.remotes.tdstuff:FireClient(v)

            end
        end)
    end
    wait(150)
    for i,plr in pairs(game.Players:GetPlayers()) do
        plr:LoadCharacter()
    end
end
```

# Answer
Looks like this code runs after voting on a game mode. That probably means it doesn't run again until the match is over. My guess is that `game:GetService("Players"):GetPlayers()` gives you a list of players that exist throughout the match, but their humanoid (`v.Character:FindFirstChild("Humanoid")` only exists until they die.

If that's correct, then `h.Died:Connect(function() ...` only sets the Died callback for the character that each player starts with. So when players get a new character (after they die and respawn), the Died callback isn't hooked up again.

You'll have to look for something like a Spawn callback on the player (`v`) and setup the Died callback there instead.
> 2 votes

---
Tags: lua, roblox
---


# Question
Title: Keep aspect ratio on window resize in Unity
**What is my problem?**
I have started a new 2d game project in Unity and would like to allow for resizing of the window by the player. When resizing, I don't want black bars at any of the 4 sides (I think that's called letterboxing?) in windowed mode. Instead I would like that height or width of the window (it depends what the user input is) is adjusted to the other metric, so that one aspect ratio is always kept when resizing. If possible I'd like to use built-in functionality of Unity and not external code packages.

**What solutions have I considered so far and why they don't work (for me):**

* The first animated image of the readme of this github project explains what I would like to accomplish:
As stated in the readme however, this code only works for windows.
* In this stackoverflow post and this gamedev stackexchange post the advised solution is to constantly use Screen.SetResolution() in the Update() method. This solution however seems very resource intensive, so if there's a way to only update this when the screen is actually resized, please tell me.
* In a lot of gamedev stackexchange and stackoverflow posts the recommended solution is often to use a canvas or something like that. As my problem is not the UI itself but the whole game, I think this solution wouldn't suit my needs.

**Other info you might need to help me:**
Here is a screenshot of my current camera configuration (URP):

Here are my resolution and presentation settings:

# Answer
> In this stackoverflow post and this gamedev stackexchange post the advised solution is to constantly use Screen.SetResolution() in the Update() method. This solution however seems very resource intensive, so if there's a way to only update this when the screen is actually resized, please tell me.

This is actually a very good solution in my opinion but what you should do is to declare two variables: `LastWidth` and `LastHeight`

And whenever one of them wasn't equal to the current width/height, just use `Screen.SetResolution` and then set `LastWidth`/`LastHeight` to the current width/height.

Of course, it's not efficient as you have to do two checks every frame, but Unity doesn't have anything for resizing (wish there was an OnWindowResize() or something) so
> 1 votes

---
Tags: unity, c#, 2d, aspect-ratio
---


# Question
Title: In physics engines, what are the differences between moving an object with transform.translate and using RigidBody related functions like AddTorque?
I'm trying to recreate the ball maze puzzle game from Breath of the Wild with Unity. This is what I currently managed to make:

As you can see, it's not nearly as smooth and I feel like I lack the understanding to manipulate things the way I want.

At first, I used `Transform.Translate()` to move it around but it wasn't working well. I googled and read that `Translate()` is like a "teleport" and you should be using `Rigidbody` physics. This is cool, but I want to understand why it's like a teleport and how do functions like `AddTorque` work? What is it adding exactly, how is adding it, when to use what and why etc...

# Answer
> 2 votes
* RigidBody is just Newtonian physics. It means that you add a force to an object and it moves according to physics (you can say that the object is being moved by forces rather than it is moving on its own).
* Transform translate/rotate/position is changing the object transform instantaneously, so velocity is not regarded in any way (if you don't implement it explicitly).
* Movement can be done also with Character Controller component. It does not use physics in a way RigidBody does, but still makes use of velocity and collision (which transform modifying does not).

Important thing to know is you should use ONLY one of the options. You can use RigidBody on an object and spawn it once using transform.position, but if you intend on moving it around continuously with transform or character controller, the RigidBody component will mess up the movement badly not expecting you to move the object this way.

In a nutshell, generally speaking:

* RigidBody is for sliding cubes, rolling balls, throwing objects in an arch, character movement like in fall guys (can simulate feeling like your character has slow reflexes or is drunk)
* Character controller is for precise movement of the main character for platformers, racing games etc.
* Transform modifications are for spawns, lock-on rotations towards an target, or can simulate some on-purpose jittery movement.

For the cube in your game, I would suggest using RigidBody.

# Answer
> 2 votes
`Transform.Translate()` seems to behave like teleportation because it simply moves a Transform *without any knowledge* of underlying physics. It could be enough for moving a simple object, but it is likely to interfere with a more complex simulation. The "not as nearly smooth" feeling you are experiencing is due to *inconsistencies* between the object's rendering and physics states.

### How is physics done?

Game engines simulate rigid-body physics via numerical integration. The starting idea is to consider an initial position and velocity \\$(x\_0, v\_0)\\$, then take a small step forward and compute the position and velocity \\$(x\_t, v\_t)\\$ at a future time. Finally, repeat this process using the result from previous calculations as the new initial data. Although we consider time continuous, computer numbers are finite, and integration must use discrete time steps.

Many physics engines take several properties into account: mass, friction, density, etc. All these are plugged into the equations and contribute to a better simulation. Eventually, they can be wrapped together (in a data structure) and considered a **physics state**. The engine will use a given physics state \\$S\_t\\$ to compute the next physics state \\$S\_{t+1}\\$:

```
// Example physics state
struct State {
    Vector3 position;
    Vector3 velocity;
    // ...
}

// Example integrator
State Integrate(State fromState, float dt) {
    State toState = State();
    toState.velocity = fromState.velocity + ( forces / mass ) * dt;
    toState.position = fromState.position + toState.velocity * dt;
    // ...
    return toState;
}

```

### When is physics updated?

The above function is a naive example of what modern engines implement in their physics update routines. You achieve movement by applying forces and torque to rigid bodies, and the engine updates the physics.

However, we don't usually think in terms of Newtonian forces. A more natural way to think about movement is by considering velocity. Therefore, we may use `Rigidbody.AddForce()` with the `ForceMode.VelocityChange` parameter and obtain a character-like controller. Or, we could get rid of the RigidBody component and write our custom movement code.

Whatever choice, the order of execution is paramount here. A game loop updates physics, reads user input, renders graphics, and more. Code execution during these phases must be as much consistent as possible. Engines enforce this consistency by exposing game loop events. These events are each intended for specific use cases.

### When do inconsistencies rise?

In Unity's event execution order, you can see that the internal physics update has a specific order in the flowchart: it comes after `FixedUpdate()` and before `Update()`. `FixedUpdate()` is intended for applying forces to rigid bodies; forces will transform into motion subsequently. Alternatively, you can code your custom physics inside `FixedUpdate()` to make it go along with the engine's time step. Either way, the Rigidbody component will update the Transform position before rendering.

If you translate a rigid body during `Update()`, you overwrite the latest integrated position with a new one. At least, this is only true for its Transform component. As said above, a rigid body keeps track of its internal physics state, and so does in Unity. `Transform.Translate()` changes the object's Transform position without affecting other components, such as a Rigidbody component.

There we have an inconsistency between Transform and Rigidbody states. Physics updates Rigidbody; Rigidbody updates Transform; we update Transform. Finally, the GameObject renders at Transform position. Then, the loop continues, but we aren't updating Transform anymore. However, we witness strange behaviour. The object abruptly changes position or starts moving at high speed with no apparent reason. This happens because physics resume from `Rigidbody.position` to simulate the next state, completely ignoring `Transform.position`.

---

It's okay to control a kinematic character via custom code and switch to ragdoll physics when they die. We can also combine kinematic and physics objects in the same environment (e.g. player moving around crates). When it comes to physics, we must choose **only one** update method per object. Or at least only one approach **at any given time**.

---
Tags: unity, physics, physics-engine
---


# Question
Title: Can't save texture on tileset resource in Godot
New to Godot so sorry if this is a dumb question, but I haven't seen tutorials that explain this. Godot is running as admin in Windows.

I have a scene and a tilemap node and a tileset resource. When I add a texture to the tileset, I can configure it no problem and saving gives no problematic messages. However, if I navigate away from the tileset or double click on the same tileset, the texture disappears. I cannot begin to edit my tilemap because no tiles are recognized. On top of that if I add readd my texture, the snap options are set correctly already so this means that my configuration is being saved somewhere, just not in my tileset right?

Why is my texture being deleted from the tileset? Why is my work not saved?

# Answer
> 1 votes
When you add textures to the `TileSet` you need to define tiles in them. Adding a texture does not automatically make it a tile (in fact, you might define multiple tiles in the same texture).

You have three options to define tiles:

* "New Single Tile": Lets you define tiles one by one
* "New Autotile": Lets you define a group of tiles for, well, autotiling.
* "New Atlas": Lets you define tiles in batch.

You can read more about this in Creating a TileSet.

*Once you created the tiles, you can define their collider, navigation polygons and so on.*

Any textures that doesn't have tiles defined will not be saved with the `TileSet`. So, if you are adding the textures, but not defining tiles in them, they will disappear from the editor.

---
Tags: godot
---


title: How to generate join codes?

text:
# Question
Title: How to generate join codes?
I'm hoping to use a four character join code so people can join a game. I was thinking of making random codes, which would be about 1.4 million different possible codes. I like the idea but I don't want to repeat one by accident.

I'm using Firebase for my database, so I was thinking of just storing all the combinations in a document and grabbing the next in line.

These both sound not-so-great. It seems like there's a better way. Thoughts?

# Answer
> 5 votes
Store the active codes in the database. Once they are no longer active, you remove them.

To create a new code, you can generate the code by whatever means you want (I'm going to suggest to use a random so people can't guess what the next code will be). Then you want to add it to your database as long as it was not there already. If it was already there, then generate again.

---

*I'm assuming these codes can be claimed by anybody. I want to encourage to add password support. Because even if people would have a hard time guessing the codes, that only gives you security by obscurity.*

---
Tags: multiplayer, matchmaking, firebase
---


title: _Input and _Process runs twice

text:
# Question
Title: _Input and _Process runs twice
Please note that my Godot version is 3.3 so that could be a reason.

I tried to create a script to shoot bullets.

First I tried using the input function

```
func _input(event):
    # Mouse in viewport coordinates.
    if event is InputEventMouseMotion:
        #print("Mouse Motion at: ", event.position)
        look_at(event.position)
    if event is InputEventMouseKey:
        direction = event.position
        print("Mouse Click/Unclick at: ", get_global_mouse_position())
        var shoot = bullet.instance()
        get_parent().add_child(shoot)
        shoot.global_position = global_position
        yield(get_tree().create_timer(0.08), "timeout")

```

Then I tried using `event.isEcho()` and a state (also used `Input.is_just_pressed()`)

```
enum {
IDLE
SHOOTING
}

```

Here is my current code: Sprite code (player/gun)

```
extends Sprite

onready var bullet = preload("res://bullet.tscn")
onready var direction = null

var pos = null

# Called when the node enters the scene tree for the first time.
func _ready():
    pass

func _process(delta):
    if Input.is_action_just_pressed("click"):
        direction = get_global_mouse_position()
        print("Mouse Click/Unclick at: ", get_global_mouse_position())
        var shoot = bullet.instance()
        get_parent().add_child(shoot)
        shoot.global_position = global_position
        yield(get_tree().create_timer(0.08), "timeout")

func _input(event):
    # Mouse in viewport coordinates.
    if event is InputEventMouseMotion:
        #print("Mouse Motion at: ", event.position)
        look_at(event.position)

```

Bullet: (not so relevant as my question is why process and input runs twice)

```
extends KinematicBody2D

var direction = Vector2.ZERO
var MAX_SPEED = 20
var ACCELERATION = 5
var velocity = Vector2.ZERO

onready var tween = $Tween

func _ready():
    direction = mouse.direction
    # (81, 23)
    tween.interpolate_property(self, 'position', position, direction, 0.8, Tween.TRANS_LINEAR, Tween.EASE_OUT)
    tween.start()
    yield(get_tree().create_timer(0.8), "timeout")
    queue_free()

```

I changed the code to:

```
func _process(delta):
    if Input.is_action_pressed("click"):
        set_process(false)
        direction = get_global_mouse_position()
        print("Mouse Click/Unclick at: ", get_global_mouse_position())
        var shoot = bullet.instance()
        get_parent().add_child(shoot)
        shoot.global_position = global_position
        yield(get_tree().create_timer(0.08), "timeout")
        set_process(true)

```

Still doesn't work.

The \_input is run exactly at the same time so that's probably why.

Log:

```
Mouse Click/Unclick at: (453, 177)
Mouse Click/Unclick at: (453, 177)

```

Result: One bullet comes from (0, 0) going to some random place (I think), and another goes to the right position.

Sprite 2 is the gun. sprite is the player character.

After one click

# Answer
> 1 votes
**About your first attempt**

Your first attempt is making little sense to me. What is `InputEventMouseKey`? I know `InputEventMouseButton`.

Anyway, I don't think `event.isEcho()` works for mouse. As echo is - at least historically - a keyboard thing.

And don't use `Input.is_just_pressed()` in `_input`. I have a detailed explanation of that elsewhere.

---

**About your second attempt**

In your second attempt you do this:

```
func _process(delta):
    if Input.is_action_just_pressed("click"):

```

And this should work. The code you put inside the `if` statement should only run once per `"click"`. Meaning that the game has to get a release and a new press for the code inside the `if` statement to run again.

*The code inside the `if` statement should not be running twice, unless there were two `"click"`. If it is running more times than you expect, I would suspect your - I'm guessing - mouse is faulty.*

---

**What does `yield` do?**

Why are you using `yield` on a timer at the end?

```
yield(get_tree().create_timer(0.08), "timeout")

```

This is what the line of code actually does:

1. Create an `SceneTreeTimer` that will emit a `"timeout"` signal after `0.08` seconds.
2. Schedule the continuation of the method (from that point of the code onwards) to execute after it gets the `"timeout"` signal from the `SceneTreeTimer`.
3. Return. *It returns a `GDScriptFunctionState`.*

To reiterate, `yield` takes an object (in the above example `get_tree().create_timer(0.08)`) and the name of a signal (in the above example `"timeout"`). And it will schedule the execution to continue after that object emits that signal. In other words `yield` awaits the signal form the object (and I say *await* and not *wait* to emphasize that `yield` is not blocking). *I hope this gives you an appreciation for what `yield` does.*

So, when the `SceneTreeTimer` emits the `"timeout"` signal, the execution of the method will resume from that point in the code. *And since that point in the code is at the end of the method, it accomplishes nothing.*

---

Look at this:

```
tween.interpolate_property(self, 'position', position, direction, 0.8, Tween.TRANS_LINEAR, Tween.EASE_OUT)
tween.start()
yield(get_tree().create_timer(0.8), "timeout")

```

Are you trying to await until the tween completed? Write what you mean:

```
tween.interpolate_property(self, 'position', position, direction, 0.8, Tween.TRANS_LINEAR, Tween.EASE_OUT)
tween.start()
yield(tween, "tween_completed")

```

---

And just in case, I'll also say that `yield` is not preventing further calls to `_process` to run. *Just like using `return` does not prevent further calls to the same method to run, and I remind you that `yield` actually returns.* Thus, other calls to `_process` can still happen, and you should be getting one per graphics frame, unless we do something about that.

---

**Disabling `_process`**

If your goal is to stop getting calls to `_process`, then we can do something about that. In particular we can disable `_process`. To do that, you can call `set_process(false)`. And remember you need to call `set_process(true)` to enable it again.

Can we do that with the timer? Sure. It would be something like this:

```
set_process(false)
yield(get_tree().create_timer(0.08), "timeout")
set_process(true)

```

So, `set_process(false)` will disable calls to `_process`, until the call `set_process(true)`. And the call `set_process(true)` will only happen after the timer completed. *I hope that makes sense.*

# Answer
> 0 votes
For anyone viewing this question, my solution was:

Making the bullet get the mouse position

Making a singleton and making bullet get the pos variable in the player singleton, I updated pos in \_process().

Using `Input.is_action_just_released()` instead of the event check because the event is run if the mouse button is clicked AND released (which caused the Input to be ran twice)

---
Tags: godot
---


# Question
Title: Unity shader to turn top-down view of scene into a stylized "minimap" view?
I'm working on a **tile based** isometric game and the **minimap** right now is just a **top-down camera**.

Usually I just attach some markers to the top of the objects in the world, which are only visible by the minimap camera.

But I want a better approach than this, so some kind of a **stylized shader**.

I guess I have to **render only the floors** in this camera... and then I'm stuck.

How could I **turn the "real, ingame view of the floors"** into some "**stylzed/procedural textured"** versions like the examples below?

Thanks in advance!

# Answer
> 2 votes
When your project uses the standard render pipeline, then you can use a script on the minimap camera which sets a replacement shader. But you would still render the whole scene twice, which could in the worst-case scenario cost you half of your FPS.

A better solution would be to have two completely separate visual representations for each object which is supposed to show up on the minimap.

1. Create a new layer called "MinimapObject"
2. Configure the culling mask of your main camera to render everything **except** the "MinimapObject" layer
3. Configure the culling mask of your minimap camera to render **only** the "MinimapObject" layer
4. Attach a child-object to every game object which is supposed to show up on the minimap.
5. Set the layer of those child-objects to "MinimapObject"
6. Create the visual representation on the minimap in the "MinimapObject" child. In the case of level geometry, that would mean a lower detail version of the regular mesh with your stylized shader material. You could also represent points of interest (like quest objectives, for example) as sprites or add text labels to your minimap as world-space canvases.

---
Tags: unity, shaders
---


# Question
Title: How I can solve "Object reference not set to an instance of an object" problem in my code?
It's simple turret rotating code. The problem is when the Player is destroyed by enemies, I get this error message below: "NullReferenceException: Object reference not set to an instance of an object LookAtPlayer.Start () (at Assets/Scrpits/Transform/LookAtPlayer.cs:15)".

I understand why I get this error, but somehow cannot solve it. All turret must look at the last position of the Player, I tried something but couldn't solve again.

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

public class LookAtPlayer : MonoBehaviour {

public float rotateSpeed = 2f;

private Transform player;
private Vector3 lookDir;

// Use this for initialization
void Start()
{
    player = GameObject.FindGameObjectWithTag("Player").transform;
}

// Update is called once per frame
void Update()
{
    if (player != null)
    {
        lookDir = player.position - transform.position;
        lookDir.y = 0f;

        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(lookDir), rotateSpeed * Time.deltaTime);
    }
}

```

}

# Answer
I am assuming that your enemies are spawning even after your player is destroyed thus it throws exception as it couldn't find one and you're directly accessing transform of null object.

```
// Use this for initialization
    void Start()
    {
        GameObject go = GameObject.FindGameObjectWithTag("Player");
        if(go != null)
        {
            player = go.transform;
        }

    }

```
> 1 votes

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


# Question
Title: How to change LookRotation so the y axis will always face the target position
I have this script that points a missile's z+ axis at its target:

```
 public class Missile : MonoBehaviour
 {
     Vector3 target;
     public Transform car;

     void Update()
     {
         car = GameObject.FindGameObjectWithTag("Cube").transform;
         target = Vector3.Normalize(car.position - transform.position);
         Quaternion direction = Quaternion.LookRotation(target);
         transform.rotation = Quaternion.Slerp(transform.rotation, direction, 4*Time.deltaTime);
         transform.position = transform.position + 10* transform.up* Time.deltaTime;

     }
}

```

But my missile model has its "front" pointing in the direction of the y+ axis, not z.

How can I convert the `LookRotation` code above to rotate the y axis to my target, instead of the z? If possible, I'd love to see a diagram that explains how the conversion works.

I have referred to some previous answers about this topic, but still couldn't understand how to do it in this case.

# Answer
> 3 votes
Let's see if I can write a version of this answer so general-purpose that I never have to write another one.

```
public static Quaternion OmniLookRotation(
             Vector3 exactAxis,       Vector3 exactTarget,
             Vector3 approximateAxis, Vector3 approximateTarget
) {
    // Compute a rotation that takes the z+ and y+ axes to our custom axes.
    var zyToCustom = Quaternion.LookRotation(exactAxis, approximateAxis);
    // Invert this, to map our custom axes to z+ and y+.
    var customToZY = Quaternion.Inverse(zyToCustom);

    // Compute a rotation that takes the z+ and y+ axes to our target directions.
    var zyToTarget = Quaternion.LookRotation(exactTarget, approximateTarget);

    // Chain these two rotations so that exactAxis maps to exactTarget,
    // and approximateAxis maps as closely as it can to approximateTarget.
    var customToTarget = zyToTarget * customToZY;

    return customToTarget;
}

```

So, let's say I want to point my local y+ axis (`Vector3.up`) exactly toward my target (let's call that `toTarget` to distinguish this offset from the target's absolute position), while pointing my local x+ axis (`Vector3.right`) as close as possible toward world "down" (`Vector3.down`). I'd write it like this:

```
var targetRotation = OmniLookRotation(
                       Vector3.up,    toTarget,    // "point my y+ at target"
                       Vector3.right, Vector3.down // "and my x+ down"
                   );

// This is already a non-linear, not correctly time-adjusted blend,
// so if we're being approximate anyway we may as well use Lerp
// and save the added cost of Slerp.
transform.rotation = Quaternion.Lerp(
                       transform.rotation,
                       targetRotation,
                       4*Time.deltaTime
                   );

```

# Answer
> 1 votes
A quick and easy way to deal with a model not being lined up the way you want it is to make the game object with the model be a child of the game object that has the movement script. In this case, Change the local rotation of the child to orient the model's y axis along the parent object's z axis. That way, as your movement script points the parent object, the child will move with it. No fancy math needed.

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


# Question
Title: How is it possible to mod a game whose source code isn't publicly available?
I can understand that if you obtain the source code for a game (for example, if you cloned it from GitHub), then you could edit the code yourself, and have a working copy of the original game with your edits incorporated (a 'mod').

But I'm not sure how mods can exist for games whose code isn't publicly available. How is it possible?

# Answer
This question/answer is designed to be a community effort. Feel free to improve some aspects of it.

---

How a game can be modded when the source code is not available is a really broad topic.

It will depend on a lot of factors, including the type of modification you want to make to the game, and how the game is built.

What type of mod are you looking for? Different kinds of mods have different implementations.

* A simple reskinning?
* New level, enemy behaviour?
* Quality of life improvements?

Some games are made in such a way that modding can be done by:

* adding/swapping data/asset files or plaintext scripts without affecting compiled code
* decompiling the game and reverse engineering pars of it, then recompiling your own modified version
* allowing separate programs to modify the runtime behaviour of the original unaltered code, eg. via DLL injection, network packet sniffing, or manipulating the game's internal data states in RAM

Further resources:
> 6 votes

---
Tags: modding
---


# Question
Title: How to animate game object using entities?
I am having issues with some of the DOTS stack in unity (mostly the rendering and animation) and was hoping I could use gameobjects for those parts. Not sure how to use entities inside a regular gameobject though, is it possible to do entity queries inside a gameobject to feed an animation statemachine? Or perhaps modifiying gameobjects inside entity queries and using the results in animation state machine that way? I would like to use animation rigging as well.

# Answer
> 1 votes
I managed to get it working after selecting "Convert And Inject Game Object"

```
using System;
using Unity.Entities;
using UnityEngine;

namespace Assets.Components
{
    [GenerateAuthoringComponent]
    [Serializable]
    public struct InputComponent : IComponentData
    {
        public bool IsJumping;
        public bool IsRunning;
        public bool IsCrouching;
        public Vector2 DeltaLook;
        public Vector2 DeltaMove;
        public double DeltaRotate;
    }
}

```

```
using Assets.Components;
using Unity.Entities;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Assets.BehaviorSystems
{
    public partial class InputActionsUpdatesInputComponent : SystemBase
    {
        InputActions inputActions;

        protected override void OnCreate()
        {
            base.OnCreate();

            inputActions = new InputActions();
            inputActions.Enable();
        }

        protected override void OnUpdate()
        {
            InputSystem.Update();

            InputComponent input = new InputComponent
            {
                IsJumping = inputActions.MainCharacter.Jump.IsPressed(),
                IsRunning = inputActions.MainCharacter.Run.IsPressed(),
                IsCrouching = inputActions.MainCharacter.Crouch.IsPressed(),
                DeltaLook = inputActions.MainCharacter.Look.ReadValue<Vector2>(),
                DeltaRotate = inputActions.MainCharacter.Rotate.ReadValue<float>(),
                DeltaMove = inputActions.MainCharacter.Move.ReadValue<Vector2>()
            };

            this.Entities
                .WithAll<InputComponent>()
                .ForEach(
                    (ref InputComponent entity) =>
                    {
                        entity.IsJumping = input.IsJumping;
                        entity.IsRunning = input.IsRunning;
                        entity.IsCrouching = input.IsCrouching;
                        entity.DeltaLook = input.DeltaLook;
                        entity.DeltaRotate = input.DeltaRotate;
                        entity.DeltaMove = input.DeltaMove;
                    }
                )
                .Run();
        }
    }
}

```

```
using Assets.Components;
using Unity.Entities;
using UnityEngine;

namespace Assets.BehaviorSystems
{
    public partial class InputComponentUpdatesAnimator : SystemBase
    {
        protected override void OnUpdate()
        {
            this.Entities
                .WithAll<Animator, InputComponent>()
                .ForEach(
                    (Animator animator, in InputComponent input) =>
                    {
                        animator.SetBool("IsJumping", input.IsJumping);
                        animator.SetBool("IsRunning", input.IsRunning);
                        animator.SetBool("IsCrouching", input.IsCrouching);
                        animator.SetFloat("DeltaLook.x", input.DeltaLook.x);
                        animator.SetFloat("DeltaLook.y", input.DeltaLook.y);
                        animator.SetFloat("DeltaMove.x", input.DeltaMove.x);
                        animator.SetFloat("DeltaMove.y", input.DeltaMove.y);
                        animator.SetFloat("DeltaRotate", (float)input.DeltaRotate);
                    }
                )
                .WithoutBurst()
                .Run();
        }
    }
}

```

---
Tags: unity, entity-component-system, unity-dots
---


# Question
Title: How can I allow my players to create, save and use moves?
I want to create a system to allow the players to create, save then use moves in Roblox Studio.

My first thought was to do this by letting them create animation files in Roblox Studio, but I'm not sure how this would be done, if possible, or if there were better ways to achieve this.

It's an rpg game, it will have a unarmed combat and sword combat, and like in character customization where do you see your character standing on the screen and you select accessories and skin color, you could move the limbs of you character and save this "animation" to use later in the game in a combat.

# Answer
> 1 votes
I'm not sure about Roblox Studio, but you could have players create animations in-game.

Breaking down your plan:

> where do you see your character standing on the screen, select accessories and skin color

I assume you have this sorted.

> move the limbs of your character

Pick points on the character (likely the joints) and put buttons on them. When the player clicks and holds a button, start moving the joint (and button) around.

> save this "animation"

Serialize all of the joint positions. See serpent for a lua way to serialize. Roblox may have their own built in. If you let them just position the body, that's called a "pose". You could store multiple poses as "frames" of animation.

> use later in the game in combat

Deserialize the joint positions and tween from your idle pose to the animation pose. To support multiple frames of animation, you'll have to lerp between each frame and figure out what to do when you reach the end (loop or transition back to idle).

In addition to the positions of the joints, you may want to allow rotation and then you'll want to use "slerp" to tween between your rotations.

---
Tags: lua, roblox
---


# Question
Title: Unity Build is showing GooglePlayGamesManifest.androidlib' is Missing.?
I was trying to build my unity project but it is showing this GooglePlayGamesManifest.androidlib' is missing AndroidManifest.xml file. UnityEngine.GUIUtility:ProcessEvent (int,intptr)

some more information i used cloudOnce but deleted that from my project

# Answer
your problems sounds like this one where the problem was the folder name.

All you have to do is change the name of `GoogleMobileAdsPlugin` folder in `Plugins/Android` into `GoogleMobileAdsPlugin.androidlib` and the problem should be solved
> 1 votes

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


# Question
Title: Getting a CineMachine FreeLook Camera to work with a GamePad(joystick)
I have no idea how to get the FreeLook cam to work with the second stick on a gamepad. The docs seem to have nothing on the topic. Has anyone done this before ?

# Answer
Turns out it's rather easy. You just need to delete the Axis names from the FreeLook component and create a small script like this :

```
using Cinemachine;
using UnityEngine;
[RequireComponent(typeof(CinemachineFreeLook))]
public class FreeLookUserInput : MonoBehaviour {

    private CinemachineFreeLook freeLookCam;
    // Use this for initialization
    void Start () {
        freeLookCam = GetComponent<CinemachineFreeLook>();

    }

    // Update is called once per frame
    void Update () {
        freeLookCam.m_XAxis.Value = Input.GetAxis("Right Stick X");
        freeLookCam.m_YAxis.Value = Input.GetAxis("Right Stick Y");

    }
}

```
> 2 votes

# Answer
This actually inputs a value for the Cinemachine Freelook controller to work with, directly changing the value as mentioned above has no dampening etc

```
using Cinemachine;
using UnityEngine;
[RequireComponent(typeof(CinemachineFreeLook))]
public class FreeLookUserInput : MonoBehaviour {

private CinemachineFreeLook freeLookCam;
// Use this for initialization
void Start () {
    freeLookCam = GetComponent<CinemachineFreeLook>();

}

// Update is called once per frame
void Update () {
    freeLookCam.m_XAxis.m_InputAxisValue = Input.GetAxis("Right Stick X");
    freeLookCam.m_YAxis.m_InputAxisValue = Input.GetAxis("Right Stick Y");

}

```

}
> 0 votes

---
Tags: unity, input, cinemachine
---


# Question
Title: How to AddForce to an object towards the direction of the mouse from the position of the object in 3D
This is what happens now: https://www.dropbox.com/s/91u32eifzl3f8c5/Unity\_Xx8GuSCuM5.mp4?dl=0

As you can see, it's not going towards the mouse position, sometimes vaguely.

Basically, to get the direction I want the ball to go in which is: Ball --------\> Mouse Position, I'm casting a ray from the camera to the ground, based on the mouse position, and then substracting the intersection of that ray with the ground from the ball's position and storing that in a vector3 variable.

```
pointToHit = pointToLook - ball.transform.position;

```

My code:

```

    float rayLength;
    Vector3 mousePos;
    Vector3 pointToLook;
    Vector3 pointToHit;
    public GameObject ball;

    private void RotatePlayerToMousePos()
    {
        //Casts a ray from camera to the ground then stores the intersection of the ray with the ground in pointToLook
        cameraRay = mainCamera.ScreenPointToRay(mousePos);
        Plane groundPlane = new Plane(Vector3.up, Vector3.zero);

        if (groundPlane.Raycast(cameraRay, out rayLength))
        {
            pointToLook = cameraRay.GetPoint(rayLength);
        }

        //Rotates player to the positioned where the ray intersects with the ground
        transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));

    }

 private void HitBallToMousePos()
    {
        ball.transform.position = attackPointOrigin.transform.position;

        pointToHit = pointToLook - ball.transform.position;
        ball.GetComponent<Rigidbody>().velocity = pointToHit - ball.transform.position;

        //Maintains velocity in all directions.
        if (pointToHit.x > 0 && ball.GetComponent<Rigidbody>().velocity.x < 0)
        {
            ball.GetComponent<Rigidbody>().velocity = new Vector3(
                ball.GetComponent<Rigidbody>().velocity.x * -1,
                ball.GetComponent<Rigidbody>().velocity.y,
                ball.GetComponent<Rigidbody>().velocity.z);
        }
        else if (pointToHit.x < 0 && ball.GetComponent<Rigidbody>().velocity.x > 0)
        {
            ball.GetComponent<Rigidbody>().velocity = new Vector3(
                ball.GetComponent<Rigidbody>().velocity.x * -1,
                ball.GetComponent<Rigidbody>().velocity.y,
                ball.GetComponent<Rigidbody>().velocity.z);
        }

        if (pointToHit.z > 0 && ball.GetComponent<Rigidbody>().velocity.z < 0)
        {
            ball.GetComponent<Rigidbody>().velocity = new Vector3(
                ball.GetComponent<Rigidbody>().velocity.x,
                ball.GetComponent<Rigidbody>().velocity.y,
                ball.GetComponent<Rigidbody>().velocity.z * -1);
        }
        else if (pointToHit.z < 0 && ball.GetComponent<Rigidbody>().velocity.z > 0)
        {
            ball.GetComponent<Rigidbody>().velocity = new Vector3(
                ball.GetComponent<Rigidbody>().velocity.x,
                ball.GetComponent<Rigidbody>().velocity.y,
                ball.GetComponent<Rigidbody>().velocity.z * -1);
        }

        //Adds force to ball from hit
        ball.GetComponent<Rigidbody>().AddForce(pointToHit.normalized * hitForce, ForceMode.Impulse);
    }

```

# Answer
> 1 votes
This is a classic mix-up of points/positions and displacements/offsets/directions.

This is a point: a specific position in the world.

```
pointToLook = cameraRay.GetPoint(rayLength);

```

This is NOT a point. It is a displacement, a *difference* between two positions. It is not itself a position in the world, but an offset you'd apply to get from one position to another.

```
pointToHit = pointToLook - ball.transform.position;

```

So, name it something else, like:

```
offsetToMouse = pointToLook - ball.transform.position;

```

Now that we've renamed the variable, errors like this become easier to spot:

```
ball.GetComponent<Rigidbody>().velocity = offsetToMouse - ball.transform.position;

```

Uh oh. We're subtraction a position from something that isn't a position! This doesn't make any geometric sense. (In some game libraries, positions in space and offsets are even different data types so that errors like this will cause a type error and refuse to compile).

It looks like you forgot that you'd already subtracted the ball's position, so you subtracted it again. Effectively now you're computing the velocity you'd need if the ball were twice as far away from the origin as it actually is.

So what you really want is just this:

```
ball.GetComponent<Rigidbody>().velocity = offsetToMouse;

```

This computes the velocity the ball would need to reach the mouse in 1.0 seconds.

Or, if you want to use an impulse, you can use:

```
ball.GetComponent<Rigidbody>().AddForce(offsetToMouse.normalized * hitImpulse, ForceMode.Impulse);

```

Do not both set a velocity and add an impulse, or they'll stack in a way that will be harder for you to reason about. So pick one method or the other. (And if your variable represents an impulse, definitely don't call it a force).

And don't use any of the code you had in those `if` statements checking the signs of each component. You don't need it.

---
Tags: unity
---


# Question
Title: I want to use a number that I got using Debug.Log, and use it later in a game over screen to show a score
How can I save this number as a variable to use in a game over screen?

This is my code to get the number

```
    public void StopCount ()
{
    Debug.Log(disRun);
}

```

# Answer
> -1 votes
I figured it out, I just needed to create a new public int called anything, then put it under the the function as it only happens once like this:

```
    public void StopCount ()
{
    Debug.Log(disRun);
    endscore = disRun;
}

```

I don't know why I didn't think of this.

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


# Question
Title: DooM P_BulletSlope function , how does it works
I'm trying to understand how DOOM source code works, the problem is I don't understand a few things, why is it 16 * 64 * FRACUNIT ? , i don't get it.

```
static void P_BulletSlope(mobj_t *actor)
{
    if (usemouselook && !autoaim)
        bulletslope = PLAYERSLOPE(viewplayer);
    else
    {
        // killough 08/02/98: make autoaiming prefer enemies
        int mask = MF_FRIEND;

        do
        {
            angle_t an = actor->angle;

            // see which target is to be aimed at
            bulletslope = P_AimLineAttack(actor, an, 16 * 64 * FRACUNIT, mask);

            if (!linetarget)
            {
                bulletslope = P_AimLineAttack(actor, (an += (1 << 26)), 16 * 64 * FRACUNIT, mask);

                if (!linetarget)
                {
                    bulletslope = P_AimLineAttack(actor, an - (2 << 26), 16 * 64 * FRACUNIT, mask);

                    if (!linetarget && usemouselook)
                        bulletslope = PLAYERSLOPE(viewplayer);
                }
            }
        } while (mask && (mask = 0, !linetarget));  // killough 08/02/98
    }
}

```

another function (P\_AimLineAttack) .

```
fixed_t P_AimLineAttack(mobj_t *t1, angle_t angle, fixed_t distance, int mask)
{
    fixed_t x2, y2;

    if (!t1)
        return 0;

    angle >>= ANGLETOFINESHIFT;
    shootthing = t1;

    x2 = t1->x + (distance >> FRACBITS) * finecosine[angle];
    y2 = t1->y + (distance >> FRACBITS) * finesine[angle];
    shootz = t1->z + (t1->height >> 1) + 8 * FRACUNIT;

    // can't shoot outside view angles
    topslope = (VANILLAHEIGHT / 2) * FRACUNIT / (VANILLAWIDTH / 2);
    bottomslope = -(VANILLAHEIGHT / 2) * FRACUNIT / (VANILLAWIDTH / 2);

    attackrange = distance;
    linetarget = NULL;

    // killough 08/02/98: prevent friends from aiming at friends
    aim_flags_mask = mask;

    P_PathTraverse(t1->x, t1->y, x2, y2, (PT_ADDLINES | PT_ADDTHINGS), &PTR_AimTraverse);

    if (linetarget)
        return aimslope;

    return 0;
}

```

# Answer
> 1 votes
A few observations without prior familiarity with the DOOM source:

They are using fixed point numbers. Note that fixed point numbers are not built in, so `fixed_t` and associated constants would be defined somewhere in the source. If that doesn’t explain the concept of fixed point, you can read about that elsewhere.

I suspect `FRAC_UNIT` corresponds to 1 in `fixed_t`. So the distance passed to `P_AimLineAttack` is effectively `1024.0`. Then inside `P_AimLineAttack`, the fractional bits of `distance` are thrown away by shifting down by `FRAC_BITS`.

Without digging deeper it’s hard to say why they chose that particular value. As a guess, since I have never heard of DOOM bullets not reaching their target due to distance, it might just be an arbitrary large enough value that allows hitting any visible enemy in any level.

As to why it was expressed as `16 * 64` instead of `1024`, I suspect someone added the `16` quickly, in a way that would be easy to undo, and then left it.

---
Tags: collision-detection, mathematics, 2.5d
---


# Question
Title: Why doesn't my coroutine pick up input while running and how can I fix it?
I have this coroutine that waits for the player input to drop out of a while loop as well as some `if` statements that expect input as well. However the `Input.KeyCode` doesn't work in the coroutine, or rather just returns `false`, even if I press the right key...

I checked it in the normal `FixedUpdate` and there it works.

There must be a simple thing I yet don't understand about coroutines.

```
private IEnumerator TabThroughPotentialSoldiersRightCoroutine()
{
    Debug.Log("InCoroutine!");
    while (!Input.GetKeyDown(KeyCode.Return))
    {
        Debug.Log("InWhile!");
        if (Input.GetKeyDown(KeyCode.Tab))
        {
            Debug.Log("potentialAttckGroupMembers: " + potentialAttackGroupMembers.Count);
            if (potentialAttackGroupMembers.Count > 0)
            {
                attackGroupRight.Add(AI.GetClosestEnemyGameObject(potentialAttackGroupMembers, GameObject.Find("MC")));
                potentialAttackGroupMembers.Remove(AI.GetClosestEnemyGameObject(potentialAttackGroupMembers, GameObject.Find("MC")));
                Debug.Log("Add to attackGroup: " + AI.GetClosestEnemyGameObject(potentialAttackGroupMembers, GameObject.Find("MC")));
            }
        }

        if (Input.GetKeyDown(KeyCode.Tab) && Input.GetKeyDown(KeyCode.LeftShift))
        {
            if (attackGroupRight.Count > 0)
            {
                attackGroupRight.Remove(AI.GetClosestEnemyGameObject(attackGroupRight, GameObject.Find("MC")));
                potentialAttackGroupMembers.Add(AI.GetClosestEnemyGameObject(attackGroupRight, GameObject.Find("MC")));
                Debug.Log("Remove from atckGroup:" + AI.GetClosestEnemyGameObject(attackGroupRight, GameObject.Find("MC")));
            }
        }
        yield return new WaitForEndOfFrame();
    }
    potentialAttackGroupMembers.Clear();
}

```

# Answer
The doc for `Input.GetKeyDown` says that it returns `true` during the frame. But your coroutine is working after the frame has ended due to: `yield return new WaitForEndOfFrame();`

So you need to change to something like this:

```
yield return null;

```

In that case your coroutine will wait until next update moment during next frame. That should help.

Also it looks like that there is another problem in your code:

```
if (Input.GetKeyDown(KeyCode.Tab) && Input.GetKeyDown(KeyCode.LeftShift))

```

Probably your intention with this code was to do something when both `LeftShift` and `Tab` keys has been pressed. But that code won't work as you expecting. The problem is the same `GetKeyDown` will return true only during the frame. That means that code would work only in case when both keys has been pressed in the same frame (moment), that probably very difficult to achieve if possible. So you should change this line to something like this:

```
if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Tab))

```

According to the doc `GetKey` will return true while the user holds down the key identified by name. So it should work as you need.
> 1 votes

# Answer
```
yield return new WaitUntil(() => Input.GetKey(KeyCode.Return));

```

Try this instead of while.

Another thing I tried was changing "GetKeyDown" to just "GetKey", and that seemed to work.
> -1 votes

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


# Question
Title: Change Minecraft Drowned sounds with resource pack?
I'm trying to change the Drowned sound effects in Minecraft Java edition 1.18, but they don't change. What file structure and files are needed change the sounds? I tried putting the files under both

/resource\_pack\_folder/assets/minecraft/sounds/entity/drowned /resource\_pack\_folder/assets/minecraft/sounds/mob/drowned

The files I put are ambient.ogg, ambient\_water.ogg, death.ogg, death\_water.ogg, hurt.ogg, and hurt\_water.ogg.

These are named according to the list of sound effects for the Drowned found in the wiki:

https://minecraft.fandom.com/wiki/Drowned#:~:text=a%20player%20underwater.-,Sounds,-Sound

# Answer
I think your problem is that you have not added the "sounds.json" file under this directory:

```
<packname>/assets/minecraft/

```

The structure of this file should be like this example:

```
{
    "entity.drowned.ambient": {
        "subtitle": "drowning something",
        "replace": false,
        "sounds": [
            {
                "name": "custom/something",
                "volume": 1,
                "weight": 1,
                "pitch": 1,
                "attenuation_distance": 16,
                "stream": false,
                "preload": false
            }
        ]
    }
}

```

Basically, this example sounds.json file does the following:

```
"entity.drowned.ambient"

```

is the original sound to replace.

```
"subtitle": "drowning something"

```

the subtitle that shows if you have them enabled

```
"sounds": [
    {
        "name": "custom/something"

```

the path to your sound; in my example I would put my sound under

```
soundpack.zip/assets/minecraft/sounds/custom/something.ogg

```

(omit .ogg in json file)

```
"volume": 1,
"weight": 1,
"pitch": 1,

```

I have not messed with these, but you can if you like

```
"attenuation_distance": 16,

```

the distance from the source that you can hear the sound, in blocks

```
"stream": false,
"preload": false

```

I haven't messed with these either

If you want to make more changes to other sounds, you just continue the json structure. You can use https://jsoneditoronline.org to easily create, edit, and export .json documents in code or tree mode.
> 0 votes

---
Tags: minecraft-modding
---


# Question
Title: Model normals change when importing from Blender to Unity
I created an Object in Blender and it looks fine in it.

These are the vertex normals:

These are the surface normals:

However, after importing in Unity, the emission color looks entirely distorted:

I tried to adjust settings in the directional light panel, but I'm still not able to get visuals that look as above. Is there any other setting in Unity that can help to achieve results as the 1st picture? (I inserted a color script on all the white segments so that they turn yellow at runtime).

# Answer
> 2 votes
Normals and tangents of your model may differ between Unity and Blender due to import settings. In the Model Import Settings window in Unity, you can find an option to re-calculate normals for the model on import.

From the docs:

> You can exercise control over how Unity handles the Normals and Tangents in your Model with the Normals, Normals Mode, Tangents, or Smoothing Angle options.

Try to force importing source normals, or tweak the settings to re-compute normals within Unity until you get the desired results.

---
Tags: unity, blender
---


# Question
Title: Unreal Engine 4: How to select value for FName uproperty from array of FNames by dropdown list in editor details?
I have an actor class which have a FName UPROPERTY and also an array of strings loaded from config. I need to select a value from that array in editor details of that actor and assign it to that property instead of entering that string manually.

I need the same behaviour as UENUM value selection but for FName.

How to do it?

# Answer
I solved it. The solution is very easy

```
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (GetOptions = "GetNameOptions"))
FName Name;

UFUNCTION(CallInEditor)
TArray<FString> GetNameOptions() const
{
    return { TEXT("N1"), TEXT("N2"), TEXT("N3") };
}

```
> 3 votes

# Answer
The way I have done this is with a `DetailsView` widget.

In the object you are editing, add a

```
UPROPERTY(EditAnywhere)
FNameSelector CustomProperty;

```

which will be the custom property exposed in the editor details view. Then define `FNameSelector` and add a custom property for it.

Make a struct to hold the name value:

```
USTRUCT()
struct FNameSelector
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere)
    FName Name;

    FAssetCategoryNameSelector()
    {}

    FAssetCategoryNameSelector(const FName& InName) :
        Name(InName)
    {}
};

```

Make a class with the `IPropertyTypeCustomization` interface, and put your string data in it somehow,

```
class FSomeClass: public IPropertyTypeCustomization

```

In the `PropertySelectionChanged` callback, set `CustomProperty.Name` of your object.

In your module, add a custom property type for your object and the selector class that you just made.

```
Module.RegisterCustomPropertyTypeLayout("NameSelector", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FSomeClass::MakeInstance));

```
> 2 votes

---
Tags: unreal-4
---


# Question
Title: How to properly handle hundreds of layers of tiles
### GOAL

I am making a top-down tile-based sandbox game, and it will have 400 layers of destroyable terrain, It will not use chunks, it will store the map in memory like Terraria, but only render the tiles on-screen, I don't want to take the approach that Dwarf Fortress does. Where it only renders one layer at a time. I want the player to be able to see a valley from the top of a mountain, not just the peak they are standing on.

### PROBLEMS

I am not sure how i would store the 400 layers on disk, I think a file for each layer would be a nightmare for loading times.

Even if i only render the tiles on-screen, it would still probably cause lag, because it is still rendering 400 layers.

# Answer
> 1 votes
*For the loading time... Why not chunks? CHUNKS!*

---

You don't need to render 400 layers. You only need to render the top one for each tile. That is, for each visible tile iterate over the layers, top to bottom, find the first one with something visible, and render that one.

Also, what was visible last frame, is probably the same that is visible this frame. And to paraphrase David Wheeler:

> All problems in computer science can be solved by another level of indirection layer.

So, let us have a "visible layer layer", where annotate what is the top visible layer for each tile. So you don't need to iterate over all the layers every frame, you only do it once and reuse it. And update it when building or destroying.

If you have a cutout layer (e.g. to see underground), then when moving the cutout layer downwards, you only need to recompute any tile where the layer is higher than the cutout layer. And when moving the cutout layer upwards, you only need to check between the old cutout layer and the new one, if there is something to render.

---
Tags: tilemap, tiles, layers, rust
---


# Question
Title: How to rotate the transform smoothly to 0,0,0 using lerp/slerp?
The reason why I need to use a coroutine for the rotation is that the object I throw to the target will move to the target and back once and then when the object return back I want the object also to be rotating facing forward but to be rotating smoothly slowly. first, I want the object to look at the target rotate to the target smooth slowly in the Throw method then in the ThrowBack method to rotate facing the parent.

I'm using coroutines because I want to make things once. for example, move to the target and back and then rotate but if I will make the rotation in the update it will keep rotating and I need the object to be able to rotate later too so I think it's better to make the rotation in a coroutine.

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

    public class ThrowObject : MonoBehaviour
    {
        public Transform objectToThrow;
        public Transform target;
        public Transform objectToThrowParent;
        public float throwingSpeed;
        public bool go = false;

        private Animator anim;
        private bool startThrowAnimationOnce = true;
        private Vector3 originPos;

        private void Start()
        {
            anim = GetComponent<Animator>();
            originPos = objectToThrowParent.position;
        }

        private void Update()
        {
            if (anim != null && startThrowAnimationOnce))
            {
                anim.SetTrigger("Throw");

                startThrowAnimationOnce = false;
            }

            if (go)
            {
                objectToThrow.parent = null;

                StartCoroutine(Throw());

                go = false;
            }
        }

        public void ThrowEvent()
        {
            go = true;
        }

        IEnumerator Throw()
        {
            while (objectToThrow.position != target.position)
            {
                objectToThrow.position = Vector3.MoveTowards(
                      objectToThrow.position,
                      target.position,
                      throwingSpeed * Time.deltaTime
                 );

                yield return null;
            }

            objectToThrow.position = target.position;

            yield return new WaitForSeconds(10f);

            StartCoroutine(ThrowBack());
        }

        IEnumerator ThrowBack()
        {
            while (objectToThrow.position != objectToThrowParent.position)
            {
                objectToThrow.position = Vector3.MoveTowards(
                      objectToThrow.position,
                      objectToThrowParent.position,
                      throwingSpeed * Time.deltaTime
                 );
                yield return null;
            }
            objectToThrow.position = objectToThrowParent.position;

            objectToThrow.parent = objectToThrowParent;
            objectToThrow.localPosition = new Vector3(0, 0, 0);
            //objectToThrow.localRotation = Quaternion.Euler(0, 0, 0);
        }
    }
```

# Answer
First of all, don't use `(objectToMove.position != objectToMoveParent.position)` instead try `Vector3.Distance(objectToMove.position, objectToMoveParent.position) >= 0.1f` because there's always a small distance between the two points.

And you don't need any coroutine to smoothly rotate the object, just use this line: `GetComponent<Rigidbody2D>().MoveRotation(Quaternion.RotateTowards(from, to, maxDegreesDelta));` (or `Vector3.RotateTowards`). `from` and `to` are two `quaternion`s which determine the start angle and the end angle; `maxDegreesDelta` means how many degrees per second the object rotates (don't forget to use `Time.deltaTime`), or in other words, controls the speed of rotation.

Here are the links to unity documentation if you need to look: RigidBody.MoveRotation and Vector3.RotateTowards
> 1 votes

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


# Question
Title: What statistical test to use for CPU time?
I've created two simulations using Unity that perform the same functions, but using two different programming paradigms (object-oriented and data-oriented) to demonstrate the performance benefits of one paradigm over the other. I've collected CPU speed values (which measures the time between each loop in the simulation) for both simulations. I've compiled two arrays that contain these CPU speed values for 300 iterations of the simulations and I want to perform a statistical analysis on these two arrays to determine whether there is a significant difference in performance between the simulations.

My current issue is that I am not sure how to classify my data. My best guess is that my data is parametric (and I'm *really* unsure about that) and that I should be using an independent t-test, but I've also read a few things about the Kruskal Wallis and the Mann Whitney that make me question whether or not the t-test is the appropriate avenue for approaching this problem.

Any help would be much appreciated! I'm not much of a stats guy, so I'm not very confident in this aspect of game development research.

# Answer
> 3 votes
To answer the question, in case anyone else finds themselves in a similar situation, the correct test in this particular case is a Wilcoxon Rank-Sum test. I determined that my data was non-parametric, after which is just the non-parametric version of the independent t-test.

---
Tags: unity, statistics
---


# Question
Title: Issue with rotating character's spine bone in the late update
I want to make my character's spine rotate to look up and down. It's animated, so I have to rotate in the LateUpdate, not Update. The only I need to do is just simply rotate the chest bone through the z-axis.

```
private float m_SynchronizedNeckRotation; // This value came from network

void LateUpdate() {
    Vector3 spineRotation = m_SpineTransform.localRotation.eulerAngles;

    m_SpineTransform.localRotation = Quaternion.Euler(
        spineRotation.x,
        spineRotation.y,
        spineRotation.z - m_SynchronizedNeckRotation
    );
}

```

This works but rotating its body is kind of lagging, unnatural. So I tried to interpolate the rotation like this:

```
void LateUpdate() {
    Vector3 spineRotation = m_SpineTransform.localRotation.eulerAngles;
    m_CurrentSpineRotation = Mathf.Lerp(m_CurrentSpineRotation, m_SynchronizedNeckRotation, Time.deltaTime * 5);

    m_SpineTransform.localRotation = Quaternion.Euler(
        spineRotation.x,
        spineRotation.y,
        spineRotation.z - m_CurrentSpineRotation
    );
}

```

Running this code makes my character rotate his body backward, like 180 degrees. So I tried to use quaternion instead:

```
void LateUpdate() {
    Vector3 spineRotation = m_SpineTransform.localRotation.eulerAngles;

    Quaternion targetRotation = Quaternion.Euler(
        spineRotation.x,
        spineRotation.y,
        spineRotation.z - m_SynchronizedNeckRotation
    );

    m_SpineTransform.localRotation = Quaternion.Slerp(m_SpineTransform.localRotation, targetRotation, Time.deltaTime * 10);
}

```

But from this code, now my character can barely rotate his chest. Also used SlerpUnclamped, but the result was the same.

I'm not sure why this won't work. Is there anything that I missed from this approach?

# Answer
> 0 votes
@DMGregory had a pretty good answer on how to use Quaternion on unity a while back. It's still on the forums if you'd like to take a look. But basically, it's better to use RotateTowards instead of Slerp.

https://answers.unity.com/questions/717637/how-do-you-smoothly-transitionlerp-into-a-new-rota.html

---
Tags: unity, rotation, quaternion, third-person-view
---


title: Sandbox game: TCP or UDP

text:
# Question
Title: Sandbox game: TCP or UDP
I know that UDP and TCP are not to be used at the same time, so I should only use one. I have read in this site that TCP should be used for a sandbox game. The problem is, My game is going to have fast-paced combat, I feel like using TCP would ruin that, But I don't want to use UDP because I need the packets of a placed/destroyed block to come through 100% of the time. I have heard that Terraria uses TCP, so maybe I can get away with it, if I disabled Nagel's Algorithim.

# Answer
> I know that UDP and TCP are not to be used at the same time, so I should only use one.

Lies. You are not going to use them both on the same socket. Just like you are not going to use two ports on the same socket. But that does not mean you cannot write a game that uses both kinds of sockets.

> I have read in this site that TCP should be used for a sandbox game

Sounds like a half truth. They probably mean you need reliability, do you? And TCP provides such reliability. But that does not mean TCP is the only option…

> The problem is, My game is going to have fast-paced combat, I feel like using TCP would ruin that

Depends. It is probably fine for LAN where you are not going to have tons of users, nor tons of lost packages, nor high latency. For online play… I don't know. But - because of what I explain below - going with TCP will be easier, so I suggest you start with TCP and get something working.

> But I don't want to use UDP because I need the packets of a placed/destroyed block to come through 100% of the time

So you need reliability. Well, you can build it on top of UDP. The trade-off is that you would have to implement a more complex net-code and in exchange you will have control over reliability.

The simplest solution is to have the receiver peer reply with an acknowledge for everything message they get, and the sender peer send messages again if they don't get an acknowledge after a timeout period. So the sender will keep sending all messages for which it didn't get an acknowledge.

You may also care about the order of messages. For example, it is not the same "add block" followed by "remove block" than "remove block" followed by "add block". In this case if the receiver peer gets messages out of order (the messages are numbered, and the receiver keeps track if they skip a number) it must hold onto them until it receives the ones in between.

That leads us to something else. You can have the receiver peer tell the sender peer what messages it is missing - instead of having the sender peer keep track of which it didn't get an acknowledge. In this scenario, the sender peer would only keep sending the latest message until it gets its acknowledge, and only resend older messages if said acknowledge also says some old messages are missing.

But that does not work for everything. For example, if you are sending the position of a player, you don't really care if the receiver peer got all the messages… You only care if they got the latest one. So there is no point in retrying obsolete messages.

Thus, if you have a stream of data (you could be sending multiple streams of data over the same socket), it is better for the receiver peer to reply with the number of the latest message of the stream they got. That way they don't need to send an acknowledge for every message they get. And the sender peer would still know if they are up to date.

Now you can imagine another version of this where the receiver peer send a heartbeat, in which it will send what was the latest message it got. If the sender peer stops receiving the heartbeat for a while it will assume a disconnection. Now, if the sender peer signals if a stream must be reliable or not, the receiver peer can send on its heartbeat which messages it didn't get, but only for the reliable streams. *A drawback of only using a heartbeat is losing the ability to measure RTT (Round Trip Time) - which you will later find out you need, but I'll leave lag compensation out of this answer - a workaround is to have a dedicated message to test that.*

And with the sender peer having some idea of the receiver peer disconnected, it can decide to stop sending messages… And when it hears from the other peer again it can decide to send a whole update instead of all the steps. Imagine, when a player joins the game, the server would send the state of the map, instead of the sending all the "add block" and "remove block" to make it. Same thing here, instead of sending all the messages that the receiver peer missed, just send the final state. *And you don't have to send the whole map. Just the chunks in the intimidate vicinity of the player. CHUNKS!*

*Of course, this isn't a complete description. But I want to point out that with UDP you can accomplish reliability patterns that are not possible with TCP, but it will require more work to implement them. So I would still recommend you start with TCP. And if it is actually a problem and you need to switch to UDP, I hope I gave you an idea of what you could do.*

> I have heard that Terraria uses TCP

Yes. It is fine.

> so maybe I can get away with it, if I disabled Nagel's Algorithim.

Sure, you can set `TCP_NODELAY`. *Be aware that more messages, means more acknowledges. On the flip side: implement your own buffer, and make network IO a step in your game loop.*
> 2 votes

---
Tags: networking, performance, udp
---


title: How to define custom coordinate space?

text:
# Question
Title: How to define custom coordinate space?
I'm trying to build small UI framework. And I want it to have a coordinate space such that origin is placed in top left corner (x increases to right, y increases to down). I think for UI it should be better and easier to work with (but still I have some concerns about this decision). But how to accomplish this right?

What I've tried:

* I made class Box that creates a mesh like this:

```
Vector2[] uv = new Vector2[4]
{
    new Vector2(0, 1),
    new Vector2(1, 1),
    new Vector2(0, 0),
    new Vector2(1, 0)
};

Vector3[] vertices = new Vector3[4]
{
    // 0 --- 1
    // |  /  |
    // 2 --- 3
    new Vector3(0, 0, 0),
    new Vector3(width, 0, 0),
    new Vector3(0, height, 0),
    new Vector3(width, height, 0),
};
mesh.vertices = vertices;

int[] triangles = new int[6]
{
    0, 1, 2,
    1, 3, 2
};
mesh.triangles = triangles;

Vector3[] normals = new Vector3[4]
{
    -Vector3.forward,
    -Vector3.forward,
    -Vector3.forward,
    -Vector3.forward
};

```

then for such box I'm creating `MeshRenderer` object. Then I apply box position to `MeshRenderer.transform`. And then to be able to render it not fliped I change camera matrix:

```
Matrix4x4 translate = Matrix4x4.Translate(new Vector3(screenWidth * .5f, screenHeight * .5f));
Matrix4x4 scale = Matrix4x4.Scale(new Vector3(1, -1, 1));
_camera.worldToCameraMatrix = (_worldToCameraMatrix * translate * scale).inverse;

```

And it looks like it works. But probably there are some issues with this (I'm not aware about all of them right now), but I've already faced with one: when you look at your mesh renderer in Scene view it's flipped vertically. That's a behavior that I don't want. I need it to look at it in Game view.

Also, I've tried doing something like this:

```
Vector3[] vertices = new Vector3[4]
{
    new Vector3(tx, ty, 0),
    new Vector3(tx + width, ty, 0),
    new Vector3(tx, ty + height, 0),
    new Vector3(tx + width, ty + height, 0),
};

```

and it also works but it feels wrong that we need to change mesh when just position changed. Also what if someone need to render one mesh several times at different positions?

* The other thing I've tried is `Graphics.DrawMesh` instead of `MeshRenderer`. This is better because I can specify matrix for drawing. I haven't spent to much with this but probably this one also has some drawbacks. The other reason not to use is that all UI libraries that I checked (like nGUI, Fairly GUI, and other) uses `MeshRenderers` for drawing. So probably there is a reason for that.
* The other thing is to create a game object container for MeshRenderers and change its transform accordingly, I haven't tried it, but it seems everything will be flipped in Scene view either;

So, my questions:

* How to properly define custom coordinate space? What options do I have? What issues I may face with?
* The other concern is that I'm going to use standard sprites but they geometry are in unity space (y increases up) that means I will need to flipped it somehow to be able to use it? The same may goes with uvs and so on. Is there a way to avoid this complexity somehow? The same issue may be with text?
* Should I go with top left coordinate space? Or maybe there is no reason for this? Some complexities or it's OK? And shouldn't be that difficult? How will you do this?

I've tried to google and search SO and SE but didn’t find anything. So, any advice very appreciated.

Basically I want to be able to write code like this:

```
var stage = new Stage();
var box = new Box();
box.width = 100;
box.height = 120;
box.color = Colors.red;
box.x = 0;
box.y = 0;
stage.addChild(box);

```

And if I run the code I should see my red box in top left corner of the screen. That's it.

Basically I need just the same as here but for Unity. Is this called a change of basis? (I'm not sure). I've looked how it's done in LibGDX, and it looks like not only `y` is mirrored but `z` is also. Besides that texture coordinates are also mirrored, but I don't see any changes to meshes (or didn't find). How can I flip `uv` coordinates? In unity they are not always a rectangle, so I think, I can't just flip them somehow as it's done in LibGDX. It seems (from what I've tested) mesh vertices also should be flipped. How to this?

So how can I accomplish this?

Upd:

This is my progress so far:

```
using System.Linq;
using System.Text;
using UnityEngine;

public class BoxRenderer : MonoBehaviour
{
    public float width = 1;
    public float height = 1;

    public bool useMeshRenderer = true;
    public bool useSpriteGeometry = true;

    public Sprite sprite;

    public Vector3 position;

    [SerializeField]
    private Mesh _mesh;
    private Matrix4x4 _matrix;
    private Material _material;

    private MeshFilter _meshFilter;
    private MeshRenderer _meshRenderer;

    private void Awake()
    {
        _mesh = new Mesh();
        _material = new Material(Shader.Find("Sprites/Default"));

        UpdateState();
    }

    private void OnValidate()
    {
        if (!Application.isPlaying || _mesh == null || !enabled)
            return;

        UpdateState();
    }

    private void UpdateState()
    {
        Mesh mesh = _mesh;
        mesh.Clear();

        // 0 --- 1
        // |  /  |
        // 2 --- 3

        Vector3[] vertices = new Vector3[4]
        {
            new Vector3(0, 0, 0),
            new Vector3(width, 0, 0),
            new Vector3(0, height, 0),
            new Vector3(width, height, 0)
        };

        int[] triangles = new int[6]
        {
            0, 1, 2,
            1, 3, 2,
        };

        Vector3[] normals = new Vector3[4]
        {
            -Vector3.forward,
            -Vector3.forward,
            -Vector3.forward,
            -Vector3.forward
        };

        Vector2[] uv = new Vector2[4] {new(0, 0), new(1, 0), new(0, 1), new(1, 1)};

        if (sprite != null && (sprite.uv.Length == 4 || useSpriteGeometry))
        {
            uv = sprite.uv;
            _material.mainTexture = sprite.texture;
        }

        if (sprite != null && useSpriteGeometry)
        {
            vertices = sprite.vertices.Select(v => (Vector3) v).ToArray();
            triangles = sprite.triangles.Select(t => (int) t).ToArray();
            normals = sprite.vertices.Select(_ => -Vector3.forward).ToArray();

            Vector2 pivot = sprite.pivot / sprite.pixelsPerUnit;
            float spriteHeight = sprite.rect.height / sprite.pixelsPerUnit;

            for (int i = 0; i < vertices.Length; ++i)
            {
                vertices[i].x += pivot.x;
                vertices[i].y = spriteHeight - (vertices[i].y + pivot.y);
            }
        }

        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.normals = normals;
        mesh.uv = uv;

        Camera camera = Camera.main;

        Vector3 min = camera.ViewportToWorldPoint(Vector3.zero);
        Vector3 max = camera.ViewportToWorldPoint(Vector3.one);

        float screenWidth = Mathf.Abs(max.x - min.x);
        float screenHeight = Mathf.Abs(max.y - min.y);

        Vector3 s = new Vector3(1, -1, 1);
        Vector3 t = new Vector3(-screenWidth * .5f, screenHeight * .5f);
        Matrix4x4 scale = Matrix4x4.Scale(s);
        Matrix4x4 translate = Matrix4x4.Translate(t);
        _matrix = translate * scale;

        if (useMeshRenderer)
        {
            if (_meshFilter == null)
            {
                _meshFilter = gameObject.AddComponent<MeshFilter>();
                _meshRenderer = gameObject.AddComponent<MeshRenderer>();
                _meshRenderer.transform.localScale = new Vector3(1, -1, 1);
            }
        }
        else if (_meshFilter != null)
        {
            Destroy(_meshFilter);
            Destroy(_meshRenderer);
            _meshFilter = null;
            _meshRenderer = null;
        }
    }

    private void Update()
    {
        if (useMeshRenderer)
        {
            _meshFilter.mesh = _mesh;
            _meshRenderer.sharedMaterial = _material;
            transform.position = _matrix.MultiplyPoint(position);
        }
        else
        {
            Matrix4x4 m = _matrix * Matrix4x4.Translate(position);
            Graphics.DrawMesh(_mesh, m, _material, 0);
        }
    }
}

```

It kind of works but... `DrawMesh` part looks much better, but `MeshRenderer` part doesn't feel good. Also it looks like I will have issues with other transformations. I will need to extract that info from matrix? This doesn't feel good. It's probably should be a better solution.

# Answer
> 1 votes
```
public Canvas myCanvas;
transform.position = mousePos * myCanvas.scaleFactor;

```

This is how I designed some UI elements. Basically this grabs my mousePos in screen space and makes it proportional to the current canvas scale. If you are making a UI framework, you should consider other screens. The canvas scales with the screen size, if set up properly. You should be able to do `box.width = 100 * myCanvas.scaleFactor`. stage.Add just needs to put the game object on the canvas, and give it a reference.

This was a huge pain to find out myself. I dug through docs and google for an entire day as well. This was a self made solution, and the only one that I could find.

As far as designing your vertices, I think that's a rabbit hole not worth chasing. You can just move the anchor to where you need it on the box, and move it into position. All it would need is coordinates and a size.

---
Tags: unity, gui, matrix, coordinates
---


# Question
Title: Does OIT Rendering work for semi-transparent textures with opaque parts?
I'm Work ing on a minecraft-like game (in OpenGL with c++) and I'm tryping to Implement Transparency for Blocks like windows, ice, leafs and water. I've tried to implement Weighted Blended Order-Independent Transparency as it's explained at LearnOpenGL. It basicly seems to work, but all Textures, rendered with the transparent Shader lose their opaqueness, even the Texels with Alpha=1.0.

**So my Question is:** Is this the normal behavior of this OIT technique?

And do you have any Ideas how I could work around this?

The gray glas frames should be opaque, but you can see the leafs from behind. (Ice, leafs and glass are all rendered using the transparent shader)

This is the Fragmentshader im using to dispaly transparent Textures.

```
#version 400 core
layout(location = 0) out vec4 accum;
layout(location = 1) out float reveal;

in float v_lightValue;
in vec2 v_texCoord;
uniform sampler2D u_texture;
uniform vec4 u_color;
const vec4 fogcolor = vec4(0.6, 0.7, 1.0, 1.0);
const float fogdensity = 0.0003;

void main(){
// Calculation of the Colors including 'fog' if the fragment are further away
    vec4 texColor = texture(u_texture, v_texCoord);
    float z = gl_FragCoord.z / gl_FragCoord.w;
    float fog = clamp(exp(-fogdensity * z * z+1)/2, 0.0, 1.0);
    vec4 color = mix(fogcolor, vec4(texColor.xyz * v_lightValue, texColor.w), fog);

// the weight function from learnopengl.com
    float weight =
        max(min(1.0, max(max(color.r, color.g), color.b) * color.a), color.a) *
        clamp(0.03 / (1e-5 + pow(z / 200, 4.0)), 1e-2, 3e3);
    // blend func: GL_ONE, GL_ONE
    // switch to pre-multiplied alpha and weight
    accum = vec4(color.rgb * color.a, color.a) * weight;
    // blend func: GL_ZERO, GL_ONE_MINUS_SRC_ALPHA
    reveal = color.a;
}

```

Please tell me if there is any further information needed to answer this question. As you can see, I'm new to StackExchange :)

# Answer
> 2 votes
As documented in the link you cite:

> Both new methods guarantee correct coverage of *background*

ie. they promise that the right amount of the opaque pixels behind all the transparent objects will be obscured. Note that they make no such promise that the foreground will be correct. There, they only say it's "improved", not correct:

> ...and strictly improve color representation over the previous methods.

This is an obvious and necessary consequence of the way this solution works:

> ...alter the compositing operator so that it is order independent...

At the time that you draw the translucent-but-full-alpha glass frame, it does not know whether the colour values/weights already in the buffer came from objects behind it or in front of it. And when you draw the foliage, if does not know whether the colour values and weights written by the glass frame came from something in front or behind. So either way, they have to hedge, and assume some fraction - but not all - of the colour in the buffer is between them and the viewer. This assumption is often wrong, but by construction, the operator has no way to discern this and correct for it.

You will never get correct sorting of opaque foreground objects using this method, and should consider rendering these parts with alpha testing rather than blending, or using conventional sorting and blending.

# Answer
> 2 votes
I found a suprisingly simple solution for my Problem. Now I don't add my Texures that have either fully transparent or opaque Pixels to the transparent mesh/buffer, but instead to the mesh for solid blocks and use ALPHA\_TESTING as suggested by DMGregory♦(just use `discard;` in my fragment shader if the transparency is smaller then 0.5 or so). After the semi transparent Faces are rendered and the blocks appear in the correct order. (for the semi transparent Blocks i can continue to use the OIT i implemented previously:))

---
Tags: opengl, rendering, glsl, transparency, alpha-blending
---


title: Height in 2D game

text:
# Question
Title: Height in 2D game
I'm working on a 2D top-down game (like the picture below) and am wondering what can I do for "jumping"

So far, I've done these:

* adding two events in jumping animation (one for when the enemy is in the air and one for when it's coming back to the ground)
* the events turn enemy's colliders off and on

And it worked well, the enemy dodged the attacks and all but upon more testing, I found out some serious issues:

1. the enemy can pass objects like trees but it shouldn't
2. explosions should affect enemies even if they are on air but without any colliders, it is not possible

So what I want to know is how I can add "jumping" to my game? Is there any "standard" way to do this in top-down games? I don't want a piece of code or something like that, just an explanation of how I can achieve this is enough. Thanks in advance!

# Answer
> 2 votes
So, the way jumping works in Zelda is kind of unintuitive at first, but if you think about it, it makes a lot of sense.

In modern games, sprites and models ARE the game objects, so we've become used to manipulating the thing as a whole whenever we need to do something. But in older games, sprites are only a visual representation of what is going on in the background.

Whenever you jump in Zelda, a flag (bool) gets set to indicate that the player is in the air, but the collider isn't affected. Whenever that "in air" flag is set, the player collider simply ignores the effects of other colliders like pits or enemies, but the collider still moves along the ground like normal.

While that's happening in the background, the sprite is just being moved up and down in a way that looks like jumping, while still following the position of the collider underneath, but it has no actual impact on what is happening in the background.

So, what I'm saying is that you should separate the collider from the sprite, then add your jumping animation to the sprite, and an "in air" bool to your collider interactions.

Though depending on how you've set up your code it might be easier to switch the object to a different layer.

# Answer
> 1 votes
For prototyping purposes, you could always use a coroutine. It will get things moving, but I would try to structure your code so physics are in a fixed update, eventually.

A coroutine is basically a process that runs on the side. It gives you enough flexibility to get the jump working while you fix your enemies. Be careful with coroutines though, I have seen some get way out of hand. You don't want too many, or too much going on in one. Memory leaks can happen here.

This is not how I would handle a jump, but it works. I would consider utilizing a state pattern for your character (even a small pseudo pattern could work.) This is not a terrible approach to a jump, though.

I am not in a place where I can test this, so this is just an example off the top of my head to show you what the syntax would look like.

```
void Update(){
  HandleInput(this);
}

private void HandleInput(IControllable controller){
  ...
  if(controller.jump)
    StartCoroutine(HandleJump());
}

// jumpHeightVector is a vector 3 with y being your jump height applied, the rest 0
private Vector3 jumpHeightVector = (0, jumpHeight, 0);

// every 10th of a second increments current time by 1
private float jumpInterval = 0.1f; // this would be responsible for a choppy movement
[SerializeField] jumpTime; //serialize this to show in inspector

private IEnumerator HandleJump(){

  // Important: let update know that this method is off limits
  controller.jump = false;
  anim.SetBool("jump", true);
  curJumpTime = 0;

  while(curJumpTime < jumpTime)
  {

    // may need better validation for landing in the right spot
    if(curJumpTime * 2 < jumpTime) Transform.Translate(jumpHeightVector); // up
    else Transform.Translate(-jumpHeightVector); // down

    // this always creates a new wait for seconds, consider assigning one of these in Start()
    yield return new WaitForSeconds(jumpInterval);

    curJumpTime++;
  }
  anim.SetBool("jump", false);
}

```

We have a coroutine that loops through a while loop while current jump time `curJumpTime` is less than our allowed jump time `jumpTime` . if we are less than half of the way through our jump, move up. If we are less than half, move down. When our elapsed jump time is equal to our allowed jumptime, we break the while loop. We also set our animation bool (you could even just use `anim.Play("jump")`.

---
Tags: unity, 2d, jumping, top-down
---


# Question
Title: Render Streaming Received Sample is not getting my stream in unity
I am just testing the **new render streaming package in unity 2020.3.22** but sadly the receiver (HTML page) is not receiving my camera stream. While both consoles (web and unity) are clear there is no error. Currently, I have a Main camera which has a camera Stream Sender is attached and its is showing two pieces of info:

While on another empty object I have attached

1. Render Streaming
2. Broadcast
3. Broadcast Sample

One strange thing I found is that the sample scene (Receiver) is working fine. But the same setup which I have made is not working. Probably the reason is given in the above screenshot. why it is happening?

While the original documentation has also been missed that you have to attach the broadcast sample script.

# Answer
Hi I have same issue and I drag the script component instead of maincamera gameobject and issue is solved. try this.

Thanks
> 2 votes

---
Tags: unity
---


title: Get Angle with respect to 360 degree

text:
# Question
Title: Get Angle with respect to 360 degree
I have fixed object, around its an object is moving in circular shape. Now i am willing to get my moving object angle with respect to fixed boject like form 0 to 360. How can i do this.

i tried this code snippet

```
Vector3 targetDirection = camHead.transform.position - transform.position;
            angle = Vector3.Angle(targetDirection, transform.forward);

```

But it is not giving what i need. Sorry i am null in vector math and trigonometry, a trick will be prefer with explanation.

# Answer
> 3 votes
@kolenda is right, but his answer is incomplete.

Here is an utility function to have a signed angle (using `atan` inside this function would have been possible). You will have to provide a normal vector in order to be able to know the sign of the angle :

```
public static float SignedAngle( Vector3 from, Vector3 to, Vector3 normal )
{
    // angle in [0,180]
    float angle = Vector3.Angle( from, to );
    float sign = Mathf.Sign( Vector3.Dot( normal, Vector3.Cross( from, to ) ) );
    return angle * sign;
}

```

Be "careful", this function will return the angle between -180 and 180, not 0 and 360 (just add 180 to the result)

# Answer
> 2 votes
Use Mathf.Atan2

In general atan2 is an extension of typical arctan function which gives you the correct result in all 4 quarters of a circle, so you don't need to use if's with arctan to compute the angle. You just pass two params - X and Y of your direction vector and you get the angle in Radians.

# Answer
> 1 votes
You can use Mathf.Atan2 like this and then clamp:

```
return Clamp0360(Mathf.Atan2(movingPos.y - fixedPos.y, movingPos.x - fixedPos.x) * Mathf.Rad2Deg)

```

and Clamp0360 function:

```
public static float Clamp0360(float eulerAngles)
{
    float result = eulerAngles - Mathf.CeilToInt(eulerAngles / 360f) * 360f;
    if (result < 0)
    {
        result += 360f;
    }

    return result;
}

```

But one notice: in my approach, degree will grow counterclockwise, but not like on your picture, when you have grow in clockwise.

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