# Question
Title: Deferred shader for transparency. Working or not?
many people are saying defered shader is not accurate for transparency. I've done some with a small demo (Directx11) and would like to know the limit of this strategy when rendering opaque+transparent objects in deferred shaders. I would also like to know if it is possible to draw the shadow maps in the same MRT pass (provided there is 4 rendertargets) using maybe geometry shaders to change the transformed vertex output from world to light space? Note: because there's only one light i've found convenient to optimize one MRT as a single 8 bit (R8\_UNIFORM) containing already calculated Dot3(N.L) and a specific blend ops for (let say ) good results. The colored shadow map comes from an explained demo seen somewhere in the web. The white color is needed to have correct colors for transparent shadows (otherwise they look darker). This technique is convenient for distant objects but not when they are too close because of possible self shadowing that is visible with transparent objects.

As I mention there is only one light used for this demo. This is why I'm using only R8 chanel to store dot3NL instead of the normal. This may save some resources and bandwitdh. Of course for many lights this will be a limitation of up to 4 lights per texture if you use RGBA chanels. regarding the code it's quite simple in VSchader output.norm = mul(input.norm, (float3x3(world)) in pShader flot L = dot(input.norm, lightdir) Output.Color1 (dot3map) = (Input.Col.a==1)?L:Input.Col.a\*(1+L*0.5f) here for opaque object the dot3 is taken as such. for transparent object the dot result is modulated to take into account the transparency. Using just L value gives to transparent object an opaque darkness where light is not facing. Using Input.Col.a*(1+L\*0.5f) insures that the dark part of the transparent object is still transparent. Modulating the 1 and 0.5 value gives different transparent lighting results.
This result is also dependent on the blending operation. Using Op ONE/ZERO Add and AlphaOp SRC\_ALPH/INV\_SRC\_ALPHA Max gives darker blending than the one I used previously. As a result the object looks more like its shadow.This is what I'm using in the second image demo2 (with bump and reflexion added)

# Answer
> 0 votes
What you are doing here is *not* deferred rendering. It is forward rendering with extra steps.

In deferred rendering, we do not consider lights during the G-Buffer pass. *At all*. All lighting calculations are delayed (deferred) to follow-up passes. This way, we spend no time computing lighting on surfaces that end up occluded by other opaque objects by the time all the geometry has been drawn.

Instead, a deferred renderer stores the normal direction into a G-Buffer texture, not the \\$\vec n \cdot \vec l \\$ term, along with the unlit, unshadowed, raw albedo colour of the objects.

We then follow up by rendering the bounding volumes of each light visible in the camera frustum, and performing our lighting computations only on the pixels in that volume that pass the depth test. This way, the lighting costs are proportionate to the number of unoccluded pixels those light volumes occupy on the screen. We've decoupled the lighting cost from the geometry complexity of the scene, since by the time we do lighting, the scene geometry is just a raster, and it doesn't matter how many different objects or triangles went into it. Lights that affect only a small part of the scene have only a small cost, even if they shine onto many objects in that small area.

But of course, doing lighting after the fact like this only works on opaque objects — otherwise you'd need to store layers of information in a single pixel, to be able to light the surface behind the transparency and the transparent surface in front of it independently. For that reason, deferred renderers usually use a forward pass at the end to layer any transparent objects on top.

Because your approach needs to consider all the lights at the time it builds the G-Buffer, it's effectively a forward renderer: your complexity scales as the *product* of the number of objects times the number of lights, rather than the sum. Not a big deal when you have only 1-4 lights, but it doesn't give you the ability to scale to very large numbers of lights like a deferred renderer does.

Storing only the \\$\vec n \cdot \vec l \\$ term is also only good for rendering the diffuse component of the lighting. Specular components will need a reflection vector too. So, you could either devote more G-Buffer space to storing specular info, or just accept that what you have is forward rendering and scrap the G-Buffer altogether. Use the dot products you've computed for your 1-4 lights and write the full shaded result straight to the frame buffer in one pass, as a normal forward renderer would. If you need to add extra lights, you can re-render the objects with your new light set, blending the results additively to account for the extra illumination these other lights provide on top of the first set.

---
Tags: transparency, deferred-rendering
---


# Question
Title: Unity Follow Object Movement in Local Space?
I have two objects in my scene each at different positions and rotations in the scene. In this example, object A (the leader) moves according to controls. I need object B (follower) to follow the leader's movement, but in its own space, and I'm having a ton of trouble with it.

For example, if the Leader moves 1 unit in its forward direction, I want the follower to move one unit in its own forward direction even if the two are facing different ways. The same goes for the other axes as well (Y/up/down works fine though).

I have tried seemingly every combination of Transform.Translate on the follower, but still, the forward/back/left/right axes get mixed up. It moves correctly when they're both facing the same way, but when the rotation changes (particularly on the Y-axis) things get messy. Here's my code at the moment. Any help would be appreciated:

```
        private void SetStartPos()
        {
            // these are two cached Vector3 variables
            startPos = leader.localPosition;
            startRot = leader.eulerAngles;
        }

        private void Update()
        {
            Vector3 posOffset = leader.localPosition - startPos;
            Vector3 rotOffset = leader.eulerAngles - startRot;

            SetStartPos();

            // because this runs in update, this check just prevents huge
            // instant offset glitches at the beginning.
            if (posOffset.x > 3 || posOffset.y > 3 || posOffset.z > 3 || rotOffset.y > 5f)
                return;

            follower.transform.eulerAngles += rotOffset;
            follower.transform.Translate(posOffset, Space.Self);
        }

```

To clarify, if needed, the goal is to get them to move by the same amount in the same direction relative to themselves. For some reference, this is being used for matching an AR device's 3D position to the position of a GameObject being streamed over a local network for a basic tracking setup.

Thank you very much in advance!

UPDATE: After doing some more digging, I did find a solution that works for the tracking/following, but there seems to be an issue where it immediately jumps to a seemingly arbitrary position and rotation when it begins. And, if I disable `track`, then reenable it, the follower will snap to the rotation of the leader, rather than continuing from it's current rotation as needed.

```
        private Vector3 leaderStart, followerStart;
        private Quaternion rotationDiff;
        private bool isFirstTrack = false;
        private bool track = true;

        private void SetStartPos()
        {
            leaderStart = leader.localPosition;
            followerStart = follower.position;
        }

        void CalculateObjectDiff()
        {
            followerStart = follower.position;
            Quaternion origYRot = Quaternion.Euler(0, follower.rotation.eulerAngles.y, 0);
            Quaternion origProxyRot = Quaternion.Euler(0, leader.rotation.eulerAngles.y, 0);
            rotationDiff = origYRot * Quaternion.Inverse(origProxyRot);
        }

        private void Update()
        {
            if (!track)
                return;

            if (isFirstTrack)
            {
                SetStartPos();
                CalculateObjectDiff();
                isFirstTrack = false;
                return;
            }

            follower.position = followerStart + rotationDiff * (leader.position - leaderStart);
            follower.rotation = rotationDiff * leader.rotation;
        }

```

# Answer
> 0 votes
To answer my own question after doing much research and help from other devs: The trick was to set the leader's position (and rotation if needed) to zero before beginning the tracking. This prevents any jumping and rotational issues. In my use-case this works perfectly, but for other situations where the leader object shouldn't be set to `(0,0,0)` then you just want to reset it to its starting position as shown in the code below.

```
    private Vector3 leaderStart, followerStart;
    private Quaternion rotationDiff;
    private bool isFirstTrack = false;
    private bool track = true;

    private void SetStartPos()
    {
        leaderStart = leader.localPosition;
        followerStart = follower.position;
    }

    void CalculateObjectDiff()
    {
        followerStart = follower.position;
        Quaternion origYRot = Quaternion.Euler(0, follower.rotation.eulerAngles.y, 0);
        Quaternion origProxyRot = Quaternion.Euler(0, leader.rotation.eulerAngles.y, 0);
        rotationDiff = origYRot * Quaternion.Inverse(origProxyRot);
    }

    private void Update()
    {
        if (!track)
            return;

        if (isFirstTrack)
        {
            leader.position = Vector3.zero;
            SetStartPos();
            CalculateObjectDiff();
            isFirstTrack = false;
            return;
        }

        follower.position = followerStart + rotationDiff * (leader.position - leaderStart);
        follower.rotation = rotationDiff * leader.rotation;
    }

```

# Answer
> 1 votes
As a general rule, don't try to add and subtract rotations with Euler angles. Unless you're working with something restricted like an FPS camera, prefer quaternions for rotation calculations.

```
public class LocalMimic : MonoBehaviour
{
    public Transform leader;

    IEnumerator Start() {
        Quaternion lastOrientation;
        Vector3 lastPosition;

        while (true) {
            // Cache the leader's transformation.
            lastOrientation = leader.rotation;
            lastPosition = leader.position;

            // Wait till next frame.
            yield return null;

            // Compute leader's local transformation change since last frame.
            Quaternion undoOrientation = Quaternion.Inverse(lastOrientation);
            Quaternion localRotationChange = undoOrientation * leader.rotation;

            Vector3 worldTranslation = leader.position - lastPosition;
            Vector3 localTranslation = undoOrientation * worldTranslation;

            // Apply that same local change in our own local space.
            transform.Translate(localTranslation);
            transform.rotation = transform.rotation * localRotationChange;
        }
    }
}

```

---
Tags: unity, movement, vector, transformation, quaternion
---


# Question
Title: How to create instances of a Unity UI Toolkit template from code?
I'm using Unity UI Toolkit in Unity 2021.2.

Looking at the following example:

```
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
  <!-- Creates our template and gives it a name for future reference. -->
  <ui:Template src="Assets/Editor/Resources/ButtonTemplate.uxml" name="button-template" />
  <!-- Creates a parent VisualElement inside which we will use our button template. -->
  <ui:VisualElement class="buttons-container">
    <!-- Instantiates the template multiple times. Each time, we give it a name for future reference. -->
    <ui:Instance template="button-template" name="Cube"/>
    <ui:Instance template="button-template" name="Sphere"/>
    <ui:Instance template="button-template" name="Capsule"/>
    <ui:Instance template="button-template" name="Cylinder"/>
    <ui:Instance template="button-template" name="Plane"/>
  </ui:VisualElement>
</ui:UXML>

```

The question is if/how one can create those instances of a template from code instead of having to add them manually. The final result I would like to use it on is not a button, but a different template. Another criterion is that it should be buildable while not in editor window, because that is somewhat explained here

# Answer
> 3 votes
##### Solution

You can use a VisualTreeAsset. It's a serialized Visual Element Tree. Instantiate it and child the resulting root node to the UIdocument of your scene. Then you can query for elements and change values procedurally.

```
class TestMono : MonoBehaviour{
        //TODO: assign these members in the inspector
        [SerializeField] VisualTreeAsset myTreeAssetMember;
        [SerializeField] UIDocument UIDocument;

        private void Start()
        {
            TemplateContainer myUI = myTreeAssetMember.Instantiate();

            //an example of querying for the root element of a button template with the id "submit"
            Button button = myUI.Q<Button>("submit");
            if (button != null)
             button.clickable = new Clickable(() => Debug.Log("Stub submit button clicked."));
            else
                Debug.LogWarning($"Could not find \"submit\" button.");

            //child the template to the UIDocument so it will be rendered and updated
            UIDocument.rootVisualElement.Add(myUI);
        }
    }

```

##### On Asset Loading Concerns

> I want to do that, but the code to load such a VisualTreeAsset that i found previously only work in the editor mode :( `AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/menu.uxml"); EditorGUIUtility.Load("Assets/menu.uxml") as VisualTreeAsset;` if you know another way that doesn't require the editor, I'm all ears

Because a VisualTreeAsset is serializable you can use what's called a "direct reference" in Unity:

* Prefix a VisualTreeAsset member with `[SerializeField]`
* Assign the field in the inspector.

Now Unity will include it, and any other directly referenced assets, in the build. It will automatically be loaded into memory with everything else in that scene. You won't have to use the AssetDatabase, or any other APIs only available when the `UNITY_EDITOR` is present. If for whatever reason you can't use a direct reference but still need a solution which works on device you can look into Unity's Resource API for something simple or Addressables for a more robust and scalable solution.

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


# Question
Title: Get count of players in room by room name
I'm trying to make a multiplayer game where there are multiple levels. All these levels will have different rooms, each with a max player count of 4.

Basically,

1. player selects a level
2. check if there is an existing room for that level that hasn't met the max player count
3. if there is such room, join the room; if not, create a new room for the level
4. wait until the room's player count reaches 4
5. start game

I know that Photon has something called `JoinOrCreateRoom` with max player options, but with this, wouldn't there be no way to create rooms with different names?

My idea is that the room names would be: `levelNumber + "_" + orderOfTheRoomInLevel` For example, the 3rd room of level 1 would be named 1\_3. This way, I could keep track of how many rooms there are per level by increasing the number whenever the player creates a room.

My code is:

```
public void StartRoomMatch(int level)
{
    roomList = PhotonNetwork.GetRoomList().ToList();
    RoomOptions options = new RoomOptions();
    options.MaxPlayers = 4;
    options.EmptyRoomTtl = 1;

    if(CheckIfRoomExists(level + "_" + roomNumsPerLevel[level]))
    {
        if(player count of room by name < 4)
        {
            PhotonNetwork.JoinRoom(level + "_" + roomNumsPerLevel[level]);
        }
        else
        {
            PhotonNetwork.CreateRoom((level + "_" + (++roomNumsPerLevel[level]), options, TypedLobby.Default);
        }
    }
    else //this is the first room being created in the level
    {
        PhotonNetwork.CreateRoom((level + "_" + roomNumsPerLevel[level], options, TypedLobby.Default);
        roomNumsPerLevel[level]++;
    }
    // PhotonNetwork.JoinOrCreateRoom(level + "", options, TypedLobby.Default);
}

private bool CheckIfRoomExists(string roomName)
{
    RoomInfo room  = roomList.FirstOrDefault(r => r.Name == roomName);
    return (room != null);
}

```

The problem is, I don't know what to fill in in the second if statement.

Is this an effective way of level matchmaking? If not, what would be a good way? (It is my first time using Photon Server so I would appreciate a detailed explanation) If yes, how do I get the player count of a room by the room's name?

# Answer
> 1 votes
You cannot change the name of a room once you've created it. While you can still use the room/level naming convention for the name of the room, you will have to create another script to display the player count in each room. You could use the `PhotonNetwork.CurrentRoom.PlayerCount` function in that separate script, I think that would help you more.

---
Tags: unity, server, photon
---


# Question
Title: How do I change only the angle of a certain PNG relative to the position of the mouse? (Python, Pygame)
Basically, I'm doing a game for a school project and I am not really sure how to make a player point towards the mouse pointer in a pygame tab. also if anyone has ideas of how i could point a bullet towards the mouse and then fire in the direction of the mouse after i click fire (without continuously changing angles towards the mouse pointer) that would be awesome

Here is my code:

```
import pygame
import os

WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('First Person Shooter')

WHITE = (255,255,255)

FPS = 60
VEL = 5
BULLET_VEL = 7

CHARACTER_PLAYER_ONE = pygame.image.load(os.path.join('Python', 'player_one.png'))
CHARACTER_PLAYER_ONE = pygame.transform.rotate(pygame.transform.scale(CHARACTER_PLAYER_ONE, (55, 40)), 90)

def draw_window(one):
    WIN.fill(WHITE)
    WIN.blit(CHARACTER_PLAYER_ONE, (one.x, one.y))
    pygame.display.update()

def one_handle_movement(keys_pressed, one):
        if keys_pressed[pygame.K_a] and one.x - VEL > -15: # left
            one.x -= VEL
        if keys_pressed[pygame.K_d] and one.x + VEL + one.width < 925: # right
            one.x += VEL
        if keys_pressed[pygame.K_w] and one.y - VEL > -15: # up
            one.y -= VEL
        if keys_pressed[pygame.K_s] and one.y + VEL + one.height < 500: # down
            one.y += VEL

def main():
    one = pygame.Rect(100, 300, 55, 40)

    bullets = []

    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    bullet = pygame.Rect()

        keys_pressed = pygame.key.get_pressed()
        one_handle_movement(keys_pressed, one)
        draw_window(one)

    pygame.quit()

if __name__ == '__main__':
    main()

```

I would really appreciate help if you are willing to provide it!

P.S. i didn't really define the bullets yet, but the player one sprite is the main thing im looking for at the moment

Much of this code is as shown in *https://www.youtube.com/watch?v=jO6qQDNa2UY*

-Luckee365-

# Answer
> 0 votes
**Math:** `tan(angle) = dy/dx` so `angle = arctangle(dy/dx)`

And as `dx, dy` you can use differnce between mouse position and gun/player position.

---

Get positions for mouse and gun/player.

```
mouse_x,  mouse_y  = pygame.mouse.get_pos()
player_x, player_y = player_rect.center

```

Calculate distance (dx, dy) between mouse and gun/player

```
dx = mouse_x - player_x
dy = mouse_y - player_y

```

Now `dy/dx` should give `tangle or angle` so I can use `arctangle` to get `angle` (in `radians`).

```
angle_radians = math.atan2(dy, dx)

angle = math.degrees(angle_radians)

```

And now rotate image with `-angle` (to rotate in correct direction).

```
player_image = pygame.transform.rotate(original_player_image, angle).convert_alpha()

```

To get better quality of rotated image you should always use original image.

You also have to use `convert_alpha()` to get colors in `RGBA` with transparent background.

And new `Image` needs new `Rect` with position from previous `Rect`.

```
player_rect = player_image.get_rect(centerx=player_x, centery=player_y)

```

---

Full working code. It rotates player to mouse position (even when it moves).

I used `set_caption` to display positions and angle in window's title.

```
import pygame
import os
import math

# --- constants ---  # PEP8: `UPPER_CASE_NAMES` for constants

WIDTH, HEIGHT = 900, 500

WHITE = (255, 255, 255)
RED   = (255, 0, 0)

FPS = 60
VEL = 5
BULLET_VEL = 7

# --- main ---  # PEP8: `lower_case_names` for variables

pygame.init()

WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('First Person Shooter')

#CHARACTER_PLAYER_ONE = pygame.image.load(os.path.join('Python', 'player_one.png'))
original_player_image = pygame.surface.Surface((100, 100)).convert_alpha()
original_player_image.fill((255,0,0,255))
original_player_image = pygame.transform.rotate(pygame.transform.scale(original_player_image, (55, 40)), 90)

player_image = original_player_image.copy()
player_rect  = player_image.get_rect(centerx=100, centery=300)

def draw_window():
    WIN.fill(WHITE)
    WIN.blit(player_image, player_rect)
    pygame.display.update()

def one_handle_movement(keys_pressed, one):
        if keys_pressed[pygame.K_a] and one.left   - VEL > -15: # left
            one.x -= VEL
        if keys_pressed[pygame.K_d] and one.right  + VEL < 925: # right
            one.x += VEL
        if keys_pressed[pygame.K_w] and one.top    - VEL > -15: # up
            one.y -= VEL
        if keys_pressed[pygame.K_s] and one.bottom + VEL < 500: # down
            one.y += VEL

def main():
    global player_image
    global player_rect

    bullets = []

    clock = pygame.time.Clock()
    run = True
    while run:

        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    bullet = pygame.Rect()

        # get positions

        mouse_x,  mouse_y  = pygame.mouse.get_pos()
        player_x, player_y = player_rect.center

        # get angle
        dx = mouse_x - player_x
        dy = mouse_y - player_y

        angle = math.degrees(math.atan2(dy, dx))

        pygame.display.set_caption(f"player: {player_x}, {player_y} | mouse: {mouse_x}, {mouse_y} | angle: {angle}")

        # rotate

        player_image = pygame.transform.rotate(original_player_image, -angle).convert_alpha()

        # assign original center to new rectagle

        player_rect = player_image.get_rect(centerx=player_x, centery=player_y)

        # ---

        keys_pressed = pygame.key.get_pressed()
        one_handle_movement(keys_pressed, player_rect)

        draw_window()

    pygame.quit()

if __name__ == '__main__':
    main()

```

---

**EDIT:**

Pygame has pygame.math.Vector2.angle\_to() to calculate angle (in degrees) between two verctors (points) but for some reason I got wrong results and couldn't find mistake.

```
mouse  = pygame.mouse.get_pos()
player = player_rect.center

angle = pygame.math.Vector2(player).angle_to(mouse)

```

BTW: today pygame doc is not accessible so I used link to its copy on archive.org.

---

**EDIT:**

This gives correct `angle`

```
mouse  = pygame.mouse.get_pos()
player = player_rect.center

dist  = pygame.math.Vector2(mouse) - pygame.math.Vector2(player)

angle = pygame.math.Vector2().angle_to(dist)

```

---

def main():
    global player_image
    global player_rect

    bullets = []

    clock = pygame.time.Clock()
    run = True
    while run:

        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    bullet = pygame.Rect()

        # get positions

        mouse  = mouse_x,  mouse_y  = pygame.mouse.get_pos()
        player = player_x, player_y = player_rect.center

        # get angle

        wrong_angle = pygame.math.Vector2(mouse).angle_to(player)   # gives results different then I expect

        dist  = pygame.math.Vector2(mouse) - pygame.math.Vector2(player)
        angle = pygame.math.Vector2().angle_to(dist)   # gives results different then I expect

        pygame.display.set_caption(f"player: {player_x}, {player_y} | mouse: {mouse_x}, {mouse_y} | angle: {angle} | wrong: {wrong_angle}")

        # rotate

        player_image = pygame.transform.rotate(original_player_image, -angle).convert_alpha()

        # assign original center to new rectagle

        player_rect = player_image.get_rect(centerx=player_x, centery=player_y)

        # ---

        keys_pressed = pygame.key.get_pressed()
        one_handle_movement(keys_pressed, player_rect)

        draw_window()

    pygame.quit()
```

---
Tags: python, pygame, mouse, shooter
---


# Question
Title: How can I make a hitbox around my image?
I'm really new to PyGame and trying to program a game, and I can't figure out how to make a hitbox that when this image hits the edge, the game stops it from going past the edges

import pygame
from pygame.math import Vector2

pygame.init
dis_width=1000
dis_height=1000
dis=pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption("Snowperson game")
white=(255,255,255)
cyan=(153,255,255)
red=(255,0,0)

dis.fill(cyan)

class Snow:
    def __init__(self,newX, newY):
        self.x = newX
        self.y = newY
        self.image = pygame.image.load("Snowperson1.png")
        self.vel = Vector2(0,0)
        self.pos = Vector2(pos)
        self.rect = self.image.get_rect(center=pos)

    def x(self):
        self.x

    def y(self):
        self.y

    def draw(self, window):
        window.blit(self.image,(self.x,self.y))

    def snowRight(self):
        self.x +=10

    def snowLeft(self):
        self.x -=10

    def snowUp(self):
        self.y -= 10

    def snowDown(self):
        self.y += 10

pygame.key.set_repeat(100,100)

snowman = Snow(50,50)

while True:
    dis.fill(cyan)
    snowman.draw(dis)
    pygame.draw.rect(dis, red, (0,0, 1000, 1000), 2)
    pygame.display.update()
    snowman.snowLeft == True

    for event in pygame.event.get():

        if event.type==pygame.QUIT or (event.type==pygame.KEYUP and event.key==pygame.K_ESCAPE):
            pygame.quit()

        elif event.type == pygame.KEYDOWN:

            if event.key == pygame.K_UP:
                snowman.snowUp()
            elif event.key == pygame.K_DOWN:
                snowman.snowDown()
            elif event.key == pygame.K_RIGHT:
                snowman.snowRight()
            elif event.key == pygame.K_LEFT and snowman.snowLeft == True:
                snowman.snowLeft()

    if snowman.rect()== 0:
        while True:
            snowman.snowLeft == False
```
</code></pre>

# Answer
The simplest is to use `self.rect` in `Snow` and compare with window rect which you can get `dis.get_rect()`

```
dis_rect = dis.get_rect()

if snowman.rect.left < dis_rect.left:
   snowman.rect.left = dis_rect.left:

if snowman.rect.right > dis_rect.right:
   snowman.rect.right = dis_rect.right:

if snowman.rect.top < dis_rect.top:
   snowman.rect.top = dis_rect.top:

if snowman.rect.bottom < dis_rect.bottom:
   snowman.rect.bottom = dis_rect.bottom:

```

but this also need to keep position in `self.rect` instead of `self.x`, `self.y`

```
    def move_right(self):
        self.move(10, 0)

    def move_left(self):
        self.move(-10, 0)

    def move_up(self):
        self.move(0, -10)

    def move_down(self):
        self.move(0, 10)

    def move(self, dx, dy):
        self.rect.x += dx
        self.rect.y += dy

```

BTW: there is no need to use prefix `snow` in functions and variables in `Snow`. Later it can be simpler when all objects have the same names of functions - ie. `.move_left()` \- because you can put all of objects on list and use `for`-loop to run the same function for all of objects. PyGame has even `pygame.sprite.Group()` for this.

---

`Rect` has also method to detect

* collision with point

```
snowman.rect.colliderect(mouse_pos)

```

which you can use to detect mouse on object or click on button
* collision with other rect

```
snowman.rect.colliderect(zombie.rect)

```

but it gives only True/False but it doesn't give information if it was collision on left, right, top or bottom - so common method is to check it in two steps. First move left/right and check collision - and if there was collision then: if speed\_x \> 0 (so you move right) then collision on right, if speed\_y \< 0 (so you move left) then collision on left. Second move top/bottom and check collision again - and if there was collision then: if speed\_y \> 0 (so you move down) then collision on bottom, if speed\_y \< 0 (so you move up) then collision on top.

---

**EDIT:**

Full working code

<pre><code>import pygame
#from pygame.math import Vector2

# --- constants ---  # PEP8: `UPPER_CASE_NAME` for constants

DIS_WIDTH  = 1000       # PEP8: spaces around `=`
DIS_HEIGHT = 1000

WHITE = (255, 255, 255)
CYAN  = (153, 255, 255)

RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = (  0,   0, 255)

# --- classes ---  # PEP8: `CamelCaseName` for classes
                   # PEP8: `lower_case_name` for functions

class Snow:
    def __init__(self, x, y, color):
        #self.image = pygame.image.load("Snowperson1.png")

        self.image = pygame.Surface((25, 75))
        self.image.fill(color)

        self.rect = self.image.get_rect(centerx=x, centery=y)

        self.vel_x = 0
        self.vel_y = 0

    def draw(self, window):
        window.blit(self.image, self.rect)

    def move_right(self):
        self.vel_x = 10

    def move_left(self):
        self.vel_x = -10

    def move_up(self):
        self.vel_y = -10

    def move_down(self):
        self.vel_y = 10

    def update(self, zombie):

        #print(self.vel_x, self.vel_y)

        # --- X ---

        self.rect.x += self.vel_x

        # window border - left,right

        if self.rect.left < dis_rect.left:
            self.rect.left = dis_rect.left

        if self.rect.right > dis_rect.right:
            self.rect.right = dis_rect.right

        # collisions with zombie - left,right

        if self.rect.colliderect(zombie.rect):
            if self.vel_x > 0:
                self.rect.right = zombie.rect.left
            elif self.vel_x < 0:
                self.rect.left = zombie.rect.right

        # --- Y ---

        self.rect.y += self.vel_y

        # window border - top,bottom

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

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

        # collisions with zombie - top,bottom

        if self.rect.colliderect(zombie.rect):
            if self.vel_y > 0:
                self.rect.bottom = zombie.rect.top
            elif self.vel_y < 0:
                self.rect.top = zombie.rect.bottom

# --- main ---

pygame.init()

dis = pygame.display.set_mode((DIS_WIDTH, DIS_HEIGHT))
dis_rect = dis.get_rect()

pygame.display.set_caption("Snowperson game")

pygame.key.set_repeat(100, 100)  # PEP8: space after comma

# - objects -

snowman = Snow(50, 50, BLUE)     # PEP8: space after `,`
zombie = Snow(150, 150, GREEN)  # PEP8: space after `,`

# - mainloop -

while True:

    # - draw -

    dis.fill(CYAN)

    snowman.draw(dis)
    zombie.draw(dis)

    pygame.draw.rect(dis, RED, (0, 0, 1000, 1000), 2)
    pygame.display.flip()

    # - move -

    snowman.vel_x = 0
    snowman.vel_y = 0

    for event in pygame.event.get():

        if event.type==pygame.QUIT:
            pygame.quit()

        elif event.type == pygame.KEYDOWN:
            if  event.key==pygame.K_ESCAPE:
                pygame.quit()

            elif event.key == pygame.K_UP:
                snowman.move_up()
            elif event.key == pygame.K_DOWN:
                snowman.move_down()
            elif event.key == pygame.K_RIGHT:
                snowman.move_right()
            elif event.key == pygame.K_LEFT:
                snowman.move_left()

    # - update - move and check collision -

    snowman.update(zombie)
```

> 1 votes

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


# Question
Title: circles originating from player position not showing up on pygame window
I'm kinda new to python and pygame, anyone know why this won't show bullets coming out from my character?

```
from curses import window
import sys
from tkinter import Y
from turtle import speed
import pygame
import os
import math

WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('First Person Shooter')

WHITE = (255,0,0)

FPS = 60
VEL = 5
BULLET_VEL = 7

CHARACTER_PLAYER_ONE = pygame.image.load(os.path.join('Python', 'player_one.png'))
CHARACTER_PLAYER_ONE = pygame.transform.rotate(pygame.transform.scale(CHARACTER_PLAYER_ONE, (55, 40)), 90)

class PLAYERPOSITION:
    def __init__(player, x, y):
        player.x = x
        player.y = y

def draw_window(one):
    WIN.fill(WHITE)
    WIN.blit(CHARACTER_PLAYER_ONE, (one.x, one.y))
    pygame.display.update()

class PlayerBullet:
    def __init__(self, x, y, mouse_x, mouse_y):
        self.x = x
        self.y = y
        self.mouse_x = mouse_x
        self.mouse_y = mouse_y
        self.speed = 15
        self.angle = math.atan2(self.mouse_y, self.mouse_x)
        self.x_vel = math.cos(self.angle) * self.speed
        self.y_vel = math.sin(self.angle) * self.speed
    def main(self, display):
        self.x -= int(self.x_vel)
        self.y -= int(self.y_vel)

        CHARACTER_PLAYER_ONE.main(display)

        for bullet in player_bullets:
            bullet.main(display)

        pygame.draw.circle(display, (0,0,0), (self.x, self.y), 5)

        playerx = x_movement
        playery = y_movement

display_scroll = [0,0]

def x_movement(keys_pressed, one):
        if keys_pressed[pygame.K_a] and one.x - VEL > -15: # left
            one.x -= VEL
        if keys_pressed[pygame.K_d] and one.x + VEL + one.width < 925: # right
            one.x += VEL

def y_movement(keys_pressed, one):
        if keys_pressed[pygame.K_w] and one.y - VEL > -15: # up
            one.y -= VEL
        if keys_pressed[pygame.K_s] and one.y + VEL + one.height < 500: # down
            one.y += VEL

player_bullets = []

def main():
    one = pygame.Rect(100, 300, 55, 40)

    clock = pygame.time.Clock()
    run = True
    while run:

        clock.tick(FPS)

        mouse_x, mouse_y = pygame.mouse.get_pos()

        draw_window(one)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    bullet = pygame.Rect(5,5,5,5)

            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    player_bullets.append(PlayerBullet(x_movement, y_movement, mouse_x, mouse_y))

        keys_pressed = pygame.key.get_pressed()

        x_movement(keys_pressed, one)
        y_movement(keys_pressed, one)

    pygame.quit()

if __name__ == '__main__':
    main()

```

I'm trying to get it to shoot small black circles, but it just doesn't want to seem to do it

# Answer
> 1 votes
You add `PlayerBullet` to list `player_bullets` but you never draw these bullets.

```
def draw_window(one):
    WIN.fill(WHITE)
    WIN.blit(CHARACTER_PLAYER_ONE, (one.x, one.y))

    for item in player_bullets:  # <---
        item.draw(WIN)           # <---

    pygame.display.update()

```

It also need function `draw()` in `PlayerBullet`

```
class PlayerBullet:

    # ... code ...

    def draw(self, display):
        pygame.draw.circle(display, (0,0,0), (self.x, self.y), 5)

```

---

I found another problem: you send `x_movement, y_movement` to `PlayerBullet`

```
player_bullets.append(PlayerBullet(x_movement, y_movement, mouse_x, mouse_y))

```

but `x_movement, y_movement` are functions, not values

```
def x_movement(keys_pressed, one):
        if keys_pressed[pygame.K_a] and one.x - VEL > -15: # left
            one.x -= VEL
        if keys_pressed[pygame.K_d] and one.x + VEL + one.width < 925: # right
            one.x += VEL

def y_movement(keys_pressed, one):
        if keys_pressed[pygame.K_w] and one.y - VEL > -15: # up
            one.y -= VEL
        if keys_pressed[pygame.K_s] and one.y + VEL + one.height < 500: # down
            one.y += VEL

```

You should send `one.x, one.y`

```
player_bullets.append(PlayerBullet(one.x, one.y, mouse_x, mouse_y))

```

---
Tags: mathematics, pygame, mouse, shooter
---


# Question
Title: Generating UVs for an annular sector/ wedge-shaped procedural mesh
I am using code to generate a mesh to show the firing arcs for a tabletop-style game I am working on. But when applying a material to it, I only get a solid color.

Here you can see the custom mesh and a Quad with the same test material applied.

Any help would be appreciated as I am more of a logic coder and am only just dipping my toes into this Custom Mesh coding. I suspect it has something to do with the UVs but not sure how to correct it if it is.

Here is the code I am using to generate this mesh:

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

public class FiringArcMeshGenerator : MonoBehaviour
{
    /// <summary>
    /// Credit to Knight666 (knight666.com) & Rickz0r
    /// https://gamedev.stackexchange.com/questions/31170/drawing-a-dynamic-indicator-for-a-field-of-view
    /// Code modified for modular use by ThomFoxx
    /// </summary>
    [SerializeField] private int _quality = 6;
    private Mesh _arcMesh;

    [SerializeField] private bool _isPrimary;
    [SerializeField] private float _primaryAngle = 45, _auxAngle = 180;

    private float _angleOfFire;

    private float _minDist;
    private float _maxDist;
    [SerializeField] private Vector3[] _verts;
    [SerializeField] private int[] _tris;
    private Vector2[] _uv;

    public void MeshSetup(ShipInfo ship)
    {
        WeaponInfo weapon;
        _arcMesh = new Mesh();
        if (_isPrimary)
        {
            _angleOfFire = _primaryAngle / 2;
            weapon = ship.Primary;
            _arcMesh.name = "Primary Arc";
        }
        else
        {
            _angleOfFire = _auxAngle / 2;
            _quality *= 2;
            weapon = ship.Auxiliary;
            _arcMesh.name = "Auxiliary Arc";
        }

        _minDist = weapon.MinRange;
        _maxDist = weapon.MaxRange;

        _arcMesh.vertices = new Vector3[4 * _quality];
        _arcMesh.triangles = new int[3 * 2 * _quality];

        Vector3[] normals = new Vector3[4 * _quality];

        for (int i = 0; i < normals.Length; i++)
            normals[i] = new Vector3(0, 1, 0);

        _arcMesh.normals = normals;

        GenerateMesh();

        GetComponent<MeshFilter>().mesh = _arcMesh;
    }

    void GenerateMesh()
    {
        float angle_lookat = 0;

        float angle_start = angle_lookat - _angleOfFire;
        float angle_end = angle_lookat + _angleOfFire;
        float angle_delta = (angle_end - angle_start) / _quality;

        float angle_curr = angle_start;
        float angle_next = angle_start + angle_delta;

        Vector3 pos_curr_min = Vector3.zero;
        Vector3 pos_curr_max = Vector3.zero;

        Vector3 pos_next_min = Vector3.zero;
        Vector3 pos_next_max = Vector3.zero;

        Vector3[] vertices = new Vector3[4 * _quality];
        int[] triangles = new int[3 * 2 * _quality];

        for (int i = 0; i < _quality; i++)
        {
            Vector3 sphere_curr = new Vector3(
                Mathf.Sin(Mathf.Deg2Rad * (angle_curr)),
                0f,
                Mathf.Cos(Mathf.Deg2Rad * (angle_curr)));

            Vector3 sphere_next = new Vector3(
                Mathf.Sin(Mathf.Deg2Rad * (angle_next)),
                0f,
                Mathf.Cos(Mathf.Deg2Rad * (angle_next)));

            pos_curr_min = transform.position + sphere_curr * _minDist;
            pos_curr_max = transform.position + sphere_curr * _maxDist;

            pos_next_min = transform.position + sphere_next * _minDist;
            pos_next_max = transform.position + sphere_next * _maxDist;

            int a = 4 * i;
            int b = 4 * i + 1;
            int c = 4 * i + 2;
            int d = 4 * i + 3;

            vertices[a] = pos_curr_min;
            vertices[b] = pos_curr_max;
            vertices[c] = pos_next_max;
            vertices[d] = pos_next_min;

            angle_curr += angle_delta;
            angle_next += angle_delta;

        }

        _verts = vertices.Distinct().ToArray();
        _tris = new int[3 * 2 * _quality];

        CalculateTrianlges();

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

        _arcMesh.Clear();
        _arcMesh.vertices = _verts;
        _arcMesh.triangles = _tris;
        _arcMesh.uv = _uv;
        _arcMesh.RecalculateNormals();
        _arcMesh.RecalculateUVDistributionMetrics();
        //_arcMesh.OptimizeReorderVertexBuffer();
    }

    private void CalculateTrianlges()
    {
        if (_minDist >0)
        {
            //takes the initial odd numbering due to Distinct Function
            _tris[0] = 0;
            _tris[1] = 1;
            _tris[2] = 3;

            _tris[3] = 1;
            _tris[4] = 2;
            _tris[5] = 3;

            _tris[6] = 2;
            _tris[7] = 5;
            _tris[8] = 3;

            _tris[9] = 4;
            _tris[10] = 5;
            _tris[11] = 2;

            for (int i = 4; i < _verts.Length - 3; i += 2)
            {
                _tris[i * 3] = i;
                _tris[i * 3 + 1] = i + 2;
                _tris[i * 3 + 2] = i + 3;
            }
            for (int i = 5; i < _verts.Length - 2; i += 2)
            {
                _tris[i * 3] = i;
                _tris[i * 3 + 1] = i - 1;
                _tris[i * 3 + 2] = i + 2;
            }
        }
        else
        {
            //still developing
        }
    }
}

```

Edit: With the fix of a missing command, Thanks @DMGregory, It's no longer a single color and shows the texture. But how do I get it to deform to the mesh? Right now it tiles, but I want it to stretch the one texture over the single-sided mesh.

Sorry for the bad paintbrush art, but this is what I am aiming for. 00 would be in the bottom left corner (Red) with 33 in the top right corner (Gold/Yellow).

# Answer
> 0 votes
Instead of generating all the middle vertices twice each, then having to filter down to only the distinct vertices, let's just not generate duplicates in the first place:

```
int vertexCount = 2 * (_quality + 1);
int indexCount = 3 * 2 * _quality;

var vertices = new Vector3[vertexCount];
var uv = new Vector2[vertexCount];

var indices = new int[indexCount];

for (int i = 0; i <= _quality; i++)
{
    float angle = Mathf.Deg2Rad(angle_start + i * angle_delta);

    var direction = new Vector3(Mathf.Sin(angle), 0f, Mathf.Cos(angle));

    int a = 2 * i;
    int b = 2 * i + 1;

    vertices[a] = transform.position + direction * _minDist;
    vertices[b] = transform.position + direction * _minDist;

    // Measure our position in the arc's sweep,
    // from 0 at the start angle to 1 at the other.
    float progress = i / (float)quality;

    // Assign the UVs as we go along.
    // "Inside" vertices get uv.y = 0, "outside" get uv.y = 1.
    uv[a] = new Vector2(progress, 0);
    uv[b] = new Vector2(progress, 1);
}

int p = 0;
for (int i = 0; i < _quality; i++) {
    int quad = 2 * i;
    _indices[p++] = quad + 0;
    _indices[p++] = quad + 1;
    _indices[p++] = quad + 3;
    _indices[p++] = quad + 0;
    _indices[p++] = quad + 3;
    _indices[p++] = quad + 2;
}

```

Bonus: shorter, simpler code!

One problem though: UV coordinates like this can only support affine texture mapping. That is, mappings that take parallel straight lines to parallel straight lines. But a texture that bends in a wedge or circle is not that. So you'll get visible zig-zag artifacts where lines drawn across your texture visibly crease where they cross the edges between triangles.

(Examples with a trapezoid mesh, and with a sphere)

Increasing your `_quality` parameter can reduce the artifacts by chopping the mesh into smaller pieces that better approximate the curve. But if you want to completely eliminate the artifacts, then you need to compute your UV coordinates in the pixel shader code - say by taking your vertex positions and converting them to polar coordinates.

---
Tags: unity, c#, mesh, materials, uv-mapping
---


# Question
Title: Why Can't I duck reverb on the mix bus in Unity?
i'm surprised there is so little documentation on this issue. But i'm trying to duck the audio on all the mix buses in Unity so that you can clearly hear the VO of the game.

Now it works great except that I have some reverb zones in the game and any sound that plays in these reverb zones, the actual reverb itself is NOT DUCKED.

So the VO is accompanied with a huge wall of wishy washy muddy noise.

Anyone deal with this before? How can we deal with this?

# Answer
> 1 votes
I don't think that's possible in Unity, at least as far as I know. The reverb zone is a component independent of the Audio Mixer, just as Audio Sources by default. You can set an Audio Mixer for Audio Sources, but not for Reverb Zones.

This forum post may help you. User ShapeFarm said this:

> We're using snapshots (that triggers when you go through different areas) in Unity 5 to change reverb settings etc. Works very nice! It's especially useful for the EQ and filter DPS's at disposal.

The previous post only helps us to corroborate the above, but it also helps us a bit to find a solution.

By using Audio Mixer's features, you could trigger certain Snapshots with certain audio filters (like reverb) instead of relying on Reverb Zones. This way, you could definitively play your VO without being affected by reverb zones.

---
Tags: unity, audio
---


# Question
Title: Unity: Adjusting the camera so that the scene view and the game view look same
when I make any object I'm able to see that by other side in the game view. And this troubles me in adjusting the objects.

So can anyone help me to adjust the main camera in such a way that views of both game and scene look the same?

Thanks in advance.

# Answer
> 5 votes
It simple, follow these steps

* Select the main camera
* Click on "GameObject" in the top panel
* Click on "Align View to Selected"

It seems you are a fan of Clash of Clans ;)

# Answer
> 0 votes
It may becasue your main camera has some specific rotation. You can reset the main camera and then adjust your Canvas.

# Answer
> 0 votes
**Hot Keys:**

* **Align with view:** Ctrl+Shift+F
* **Move To view**: Ctrl+Alt+F

**With Unity UI:**

* Select the main camera
* Click on "GameObject" in the top panel
* Click on "Align with view" or "Move To view".

# Answer
> 0 votes
Here is a way to do it with a script

```
using UnityEngine;
using UnityEditor;

[ExecuteInEditMode]
public class AlignCam : MonoBehaviour
{
    public Camera gameCam;
    public bool updateView = false;
    private void LateUpdate()
    {
        if (updateView)
        {
            SceneView sceneCam = SceneView.lastActiveSceneView;
            gameCam.transform.position = sceneCam.camera.transform.position;
            gameCam.transform.rotation = sceneCam.camera.transform.rotation;
        }
    }
}

```

---
Tags: camera, unity
---


# Question
Title: An issue that could be either serialization, or Unity's SceneManager
At this point, I don't have any idea of what could the issue be. So, I was trying to make a project wide loading screen. Through an editor window, I assigned the loading scene, which was picked up via script and assigned to the code base, from where it was loaded each time the loading screen was called.

First version I wrote worked almost perfectly. The problem was that for some strange reason it didn't work in the builds. I never got to the root of the problem so I decided to use another method. Now the problem got worse, because now it didn't work neither in the builds nor in the editor.

I knew working with scenes on editor was a very difficulty task, so I tried to use a custom serializable scene field class (This one, This one, and this one). None of them worked. Problem was that the scene I was trying to retrieve from editor (the *loading scene*) was always null. The only thing that could make sense in this case is that for some reason, these classes could not be serialized.

I thought maybe the Scriptableobject that had the fields referenced was the one that was null, but after some testing I was able to verify that this was not the case. So instead of using the custom class, I decided to just call the scene by its index. To my surprise, this didn't work either. While the scene was now not null (for obvious reasons), it was now invalid (as if the scene didn't exist).

The funny thing about all this is that actually, this scene is not the only field that I am referencing in the editor, in fact, I am referencing a scriptable object that for some reason has not given me any errors, unlike the scene (As far as I know, working with scriptable objects in the editor is even more tedious).

I'm here because I'm out of options, I have no idea what the problem is at this point.

These are my scripts: *What's the problem with them?*

```
// First script
public class SceneManagementProjectSettings : ScriptableObject
{
    private const string k_DefaultEventChannelPath = "Assets/Scripts/Project Wide/SceneManagement/CoroutineCallback.asset";

    [SerializeField] private int m_loadingSceneIndex;
    [SerializeField] private CoroutineChannel m_coroutineChannel;

    public int LoadingSceneIndex { get { return m_loadingSceneIndex; } }
    public CoroutineChannel CoroutineChannel { get { return m_coroutineChannel; } }

    public SceneManagementManager Manager => _manager;
    private SceneManagementManager _manager = new SceneManagementManager();

    internal static SceneManagementProjectSettings GetOrCreateSettings()
    {
        var settings = AssetDatabase.LoadAssetAtPath<SceneManagementProjectSettings>(SceneManagementSettingsProvider.k_SettingsPath);
        if (settings == null)
        {
            settings = CreateInstance<SceneManagementProjectSettings>();
            settings.m_loadingSceneIndex = 0;
            settings.m_coroutineChannel = AssetDatabase.LoadAssetAtPath<CoroutineChannel>(k_DefaultEventChannelPath);
            AssetDatabase.CreateAsset(settings, SceneManagementSettingsProvider.k_SettingsPath);
            AssetDatabase.SaveAssets();
        }
        return settings;
    }

    internal static SerializedObject GetSerializedSettings()
    {
        return new SerializedObject(GetOrCreateSettings());
    }
}

class SceneManagementSettingsProvider : SettingsProvider
{
    public const string k_SettingsPath = "Assets/Resources/SceneManagementSettings.asset";
    private SerializedObject m_SMSettings;

    class Styles {
        public static GUIContent LoadingScreenField = new GUIContent("Loading Scene Index");
        public static GUIContent CoroutineEventField = new GUIContent("Coroutine Channel");
    }

    public SceneManagementSettingsProvider(string path, SettingsScope scope = SettingsScope.Project) : base(path, scope) { }
    public static bool IsSettingsAvailable() {
        return File.Exists(k_SettingsPath);
    }

    public override void OnActivate(string searchContext, VisualElement rootElement)
    {
        m_SMSettings = SceneManagementProjectSettings.GetSerializedSettings();
    }

    public override void OnGUI(string searchContext)
    {
        m_SMSettings.Update();

        EditorGUILayout.PropertyField(m_SMSettings.FindProperty("m_loadingSceneIndex"), Styles.LoadingScreenField);
        EditorGUILayout.PropertyField(m_SMSettings.FindProperty("m_coroutineChannel"), Styles.CoroutineEventField);

        m_SMSettings.ApplyModifiedProperties();
    }

    [SettingsProvider]
    public static SettingsProvider CreateSceneManagementSettingsProvider()
    {
        if (IsSettingsAvailable())
        {
            var provider = new SceneManagementSettingsProvider("Project/Scene Management", SettingsScope.Project);

            // Automatically extract all keywords from the Styles.
            provider.keywords = GetSearchKeywordsFromGUIContentProperties<Styles>();
            return provider;
        }

        // Settings Asset doesn't exist yet; no need to display anything in the Settings window.
        return null;
    }
}

// Second script
public static class SceneManagement
{
    public const string k_SettingsPath = "Assets/Resources/SceneManagementSettings.asset";

    public static SceneManagementProjectSettings ProjectSettings =>
        _projectSettings;
    private static SceneManagementProjectSettings _projectSettings;

    public static SceneManagementManager Manager =>
        _manager ?? (_manager = ProjectSettings.Manager);
    private static SceneManagementManager _manager = new SceneManagementManager();

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
    static void Init()
    {
        if (ProjectSettings != null)
        {
            Manager.SetLoadingScene(ProjectSettings.LoadingSceneIndex);
            Manager.SetCoroutineChannel(ProjectSettings.CoroutineChannel);
        }
        else
        {
            _projectSettings = GetProjectSettings();
            if (ProjectSettings == null)
            {
                Debug.Log("<color=red>Project Settings Not Found</color>");
            }
        }

        Application.quitting += CleanUp;
    }

    static SceneManagementProjectSettings GetProjectSettings() {
        SceneManagementProjectSettings settings;

       #if UNITY_EDITOR
        var allSettings =
            AssetDatabase.FindAssets($"t:{nameof(SceneManagementProjectSettings)}").
                Select(AssetDatabase.GUIDToAssetPath).
                Select(AssetDatabase.LoadAssetAtPath<SceneManagementProjectSettings>).ToArray();
        if (allSettings.Length == 0)
        {
            Debug.Log("<color=red>Error</color>");
            return null;
        }
        else
        {
            settings = allSettings.First();
        }
        #else
        settings = Resources.FindObjectsOfTypeAll<SceneManagementProjectSettings>().FirstOrDefault();
        #endif
        if (settings == null)
        {
            Debug.Log("<color=red>Unable to retrieve or create Project Settings. Something went wrong during the process!</color>");
        }
        else
        {
            Debug.Log("<color=green>Project Settings retrieved succesfully!</color>");
        }

        return settings;
    }

    static void CleanUp()
    {
        _manager = null;
    }
}

```

# Answer
> 1 votes
I think this approach might be an anti-pattern to how Unity handles scenes. Scenes are introduced to Unity via `Build Settings` and are meant to be accessed via the `SceneManagement` API of Unity. Plus, the scene asset has nothing to do with the scene managed (loaded/unloaded...etc.) in Unity during gameplay. Direct access to scene files could be meant only for editor usage.

So, instead of a project-wide reference to scene assets, I suggest defining a project-wide reference to the identifier of the scene (i.e. `build index` or `name`) and using `SceneManager.LoadScene(sceneName)` to load the scene. You can also make use of the relevant API get the `Scene` object (i.e. `SceneManager.GetSceneByBuildIndex()` and `SceneManager.GetSceneByName()`).

Since scene indexes can change a lot during development, I achieve this by creating an `Enum` of scene names that matches the names of scene assets and using `SceneManager.LoadScene()` anywhere in code.

```
// Same as the names of scene assets.
public enum SceneName
{
    ...
    LoadingScreenScene,
    MainMenuScene,
    Level1Scene,
    Level2Scene,
    ...
}

public class MyBehaviour : MonoBehaviour
{
    ...

    private void LoadOtherScene()
    {
        // This line works anywhere in the project.
        SceneManager.LoadScene(
            SceneName.LoadingScreenScene.ToString(), LoadSceneMode.Single);
    }

    ...
}

```

Then, you can write your own scene manager that displays the loading screen and loads the next screen in the background.

Edit: Appending an alternative to prevent using `ToString()` every time you refer to a scene name. Still I prefer using enum so that it is possible to expose it to editor (e.g. an editor script that launches the scene you pick).

```
// Same as the names of scene assets.
public struct SceneName
{
    ...
    public static string LoadingScreenScene => nameof(LoadingScreenScene);
    public static string MainMenuScene => nameof(MainMenuScene);
    ...
}

public class MyBehaviour : MonoBehaviour
{
    ...

    private void LoadOtherScene()
    {
        // This line works anywhere in the project.
        SceneManager.LoadScene(
            SceneName.LoadingScreenScene, LoadSceneMode.Single);
    }

    ...
}

```

---
Tags: unity, c#, scene, editors, serialization
---


title: where is D3D11.h/lib for direcxt11.3

text:
# Question
Title: where is D3D11.h/lib for direcxt11.3
I'm starting to see how to do multiview rendering from different view in one pass. This needs D3D11\_FEATURE\_DATA\_D3D11\_OPTIONS3 to be checked but the D11 sdk 11\_0 don't know this flag and after a web search I can't get wher eto get d11.3 update (donwload .h and .lib I guess.

any link to help me for this?

thanks in advance

# Answer
## Where is the DirectX SDK?

> Starting with Windows 8, the DirectX SDK is included as part of the Windows SDK.

So download the latest Windows SDK from Microsoft and you'll get updated DirectX headers and libs.
> 2 votes

---
Tags: directx, version-control
---


# Question
Title: Box2D & Processing - Collision location randomly assigned to center point
I am working on a particle simulation using Box2D with Processing.

The setup: I generate 4 kinds of particles that exist in equal amounts (for instance 200 in total, 50 each). They are (for now) randomly moving inside a box, each edge of the box is made of a static boundary. The Particles should bounce off each other as well as all 4 boundaries. This works fine.

Now I am working with the `collisionListeners.beginContact()` function to make different things happen when different particles collide. My problem occurs in the following case: when two particles of the same kind collide, they should produce a particle of another kind at the location of their collision with an added velocity of their previous velocities. In most cases, this is working well! However, in about 15% of the cases, it does not: sometimes the new particle is not generated at the location of their collision, but at the world center point `(0,0)`, or rather at the center of the processing canvas if speaking in pixels `(width/2,height/2)`. This results in particles randomly shooting out of the center point of the canvas, which is not what I want. And even worse, they tend to stack up on top of each other causing errors.

I do not know why this is happening, I am suspecting it might have something to do with collisions that happen very close to the boundaries so that there is some kind of tunnelling effect that teleports them to the center? But I have no real clue...

I am getting the location of the collision inside `beginContact()` through this process:

```
// assign objects to colliding particles
  Fixture f1 = c.getFixtureA();
  Fixture f2 = c.getFixtureB();
  Body b1 = f1.getBody();
  Body b2 = f2.getBody();
  Object o1 = b1.getUserData();
  Object o2 = b2.getUserData();
// get velocity for new particle
  Vec2 velB1 = b1.getLinearVelocity();
  Vec2 velB2 = b2.getLinearVelocity();
  Vec2 addedVel = velB1.add(velB2);
// get collision coordinates in pixel values
  WorldManifold worldManifold = new WorldManifold ();
  c.getWorldManifold(worldManifold);
  Vec2 collPointPx = box2d.coordWorldToPixels(worldManifold.points[0]);

```

The last vector `collPointPx` is the one I am using when generating the new particle, and it is the vector that apparently every now and then shows `(0,0)` or rather `(width/2,height/2)` instead of the right location of the collision.

It would be great if anyone of you has an idea how to solve this. Maybe I am making a mistake in the code posted. Obviously, I am a beginner at this. Thank you very much!

# Answer
> 1 votes
The comments of DMGregory helped me out. I was using points from the collisions worldManifold, but they do not necessarily contain the exact location of the collision between two particles.

I solved it by subtracting the particle locations (bigger - smaller) and adding half of the result to the smaller one. This results in the center of a line drawn between them. As DMGregory pointed out, it makes sense to add some shift / weights to the point on this line, if the particles are not the same size.

```
// get collision coordinates in pixel values
    Vec2 posB1 = box2d.getBodyPixelCoord(b1);
    Vec2 posB2 = box2d.getBodyPixelCoord(b2);
    if ((posB1.x + posB1.y) > (posB2.x + posB2.y)) {
      collPointPx = new Vec2 ((posB2.x+((posB1.x-posB2.x)/2)), (posB2.y+((posB1.y-posB2.y)/2)));
    } else {
      collPointPx = new Vec2 ((posB1.x+((posB2.x-posB1.x)/2)), (posB1.y+((posB2.y-posB1.y)/2)));
    }

```

---
Tags: box2d, collision-resolution, particles, jbox2d, processing
---


# Question
Title: Is it possible to hide deprecated assets in Unity?
I'm specifically referring to the package manager.

Unity is aware, even in the editor, of which assets are declared deprecated, as it allows me to filter my results to only show the deprecated packages. However, I cannot figure out how to hide them.

How is that possible?

# Answer
> 2 votes
I suppose we're talking about deprecated assets that you've downloaded from the asset store. The Package Manager doesn't have an option to hide deprecated packages. The only way to do this (at the moment) is to directly hide it from the asset store.

On this post (Remove assets from "My Assets"?), user APSchmidt said:

> There is a "hide" button, just under the "Open in Unity" button. You must go on the assets store here, not within Unity to find it.

Go to AssetStore/Account/Assets and find the asset you want to hide. You'll see three options:

1. Add Label
2. Hide Asset
3. Open in Unity

Click on "Hide Asset". This should remove the asset from your asset list, thus hiding it on the Package Manager.

---
Tags: unity, assets, asset-management, filtering, user-interface
---


# Question
Title: How to enable more than 8 light sources in URP?
My location in the scene is the Bunker, there are many light sources in the form of wall lamps. There are more than 8 of them. Therefore, you need to be able to render more than 8 lights in the scene. How to achieve this?

# Answer
Have you tried adding more than 8 lights to the scene?

The 8 light limit is not about *only 8 lights allowed in scene*, it's *a mesh can only by affected by the nearest 8 lights*.

Take this as an example: let's suppose your bunker is one mesh, ok? So, you place 9 lights inside of it. The bunker, being one mesh, will only be affected by 8 of the 9 lights. The 9th light will only affect other meshes, since your bunker has already reached its limit.

One way to circumvent this would be to divide your bunker into several parts, as if it were a modular system. Each part can be affected by 8 different lights.

Another way would be to change the rendering path from Forward to Deferred. The latter is precisely for when you need more than 8 lights on scene.

You can read more about it here and here
> 3 votes

---
Tags: unity, rendering
---


# Question
Title: Get final position of Moving object along the collision surface using ProjectOnPlane
I have a problem to get the final position of moving object along the collision surface.. as you can see in picture \<1\> i want to get moveAmount.

so i get sameLengthWithDiffProjected on picture \<2\> but it's not the result what i expected.

what is my mistake? how can i get the final position? thanks in advance.

```
    horRayLength = horMoveAmount.magnitude/* + skinWidth*/;
    isHit = Physics.CapsuleCast(capsuleTop, capsuleBottom, capsuleCollider.radius, horMoveAmount.normalized, out raycastHit, horRayLength, horCollisionMask);
    if (isHit)
    {
        if (raycastHit.distance != 0)
        {
            var diff = horMoveAmount - raycastHit.point;
            var projected = Vector3.ProjectOnPlane(diff, raycastHit.normal);
            var sameLengthWithDiffProjected = projected.normalized * (diff.magnitude);
            var horMinusDiff = horMoveAmount - diff;
            moveAmount.x = horMinusDiff.x + sameLengthWithDiffProjected.x;
            moveAmount.z = horMinusDiff.z + sameLengthWithDiffProjected.z;
        }
    }

```

# Answer
Your calculation of the remaining move vector looks slightly wrong, you are using the absolute position of the collision, where you want to be using the amount moved so far. Instead you should include the current position of the object in your calculation:

```
var movedToFar = raycastHit.point - transform.position;
var diff = horMoveAmount - movedToFar;

```

Once you have this, you can get your final point by adding the projected diff to your collision point, e.g:

```
var finalPoint = raycastHit.point + sameLengthWithDiffProjected;

```

Additionally you may fine the Debug.DrawRay/DrawLine methods quite useful for visualising what is going on.
> 0 votes

---
Tags: unity
---


# Question
Title: What are the benifits to Unity's SRP vs Built-in render pipeline
I understand that unity claims the SRP is "more customisable" because you can program it with c# scripts, but is there anything the SRP can do that Built-in cannot, is it possible to achieve the same level of customisation by writing your own hlsl files in Built-in?

Nothing I've read seems to properly explain the difference and it just seems like URP is more restrictive than Built-in in terms of almost everything.

# Answer
> 4 votes
Well, eventually the built-in renderer *may* be deprecated and SRPs *may* become standard.

Something important to mention is that currently, the SRPs are much more complete and stable compared to other years.

The biggest advantages of SRPs are **ShaderGraph** and **VFX Graph**.

**ShaderGraph** is, as its name implies, a visual shader editor with nodes. Although with some limitations as of today, this package continues to expand and improve.

**VFX Graph** is basically an improved version of the particle system. Unlike shuriken particles, VFX Graph assets use the GPU to render, allowing for much more complex effects to be created.

Many of the new assets that are new to the Asset Store are now exclusive to either **URP** (Universal Render Pipeline) or **HDRP** (High Definition Render Pipeline), this because of what I mentioned earlier (that the built-in renderer *may* be deprecated).

The graphic quality is also something that improves a lot in both URP and HDRP. Unlike the built-in renderer, the default settings for each of these SRPs provide better quality right out of the box. You know the "*unity look*", right? Well, from experience I can say that it's much easier to escape this by using SRPs.

In short, SRPs have the advantage of being more friendly to **designers** (a goal that Unity has been pursuing in recent years). This does not mean that it is more restricted or limited. In fact, now it is easier to customize the graphic aspect of your project. Here's a very good example where someone created volumetric scattering as a renderer feature.

You can check the roadmap that Unity has on the different projects focused on graphics and rendering. There you can find the URP and HDRP section, where you can see the features that it currently has and those that are being worked on. Check here!

You can take a look a this discussion on the forums. According to the Unity team:

> We view the Universal render pipeline as the successor to the default rendering pipeline in Unity (aka the ‘built-in pipeline’). Universal RP is designed to be the default great place for authoring graphics and deploying everywhere, allowing you to achieve beautiful visuals, great performance with maximal platform reach.

---

On the other hand...

while the new SRPs are more designer-friendly, several important features for more technical users remain missing. Let's keep in mind that when I talk about more technical users, I mean those who used to do low-level things (compared to a large part of Unity users), like complicated shaders, or custom lighting systems.

To give you an idea, take a look at this comment regarding the workflow with shaders in SRPs:

> These three things combined (undocumented new shader syntax and shader graph limitations) makes for a massive barrier of entry for writing more technical shaders, and that's like, coming from me who's pretty hecking used to writing shaders in Unity at this point - for someone less used to writing shaders, then, to them, whatever shader graph doesn't natively support is effectively not a feature that exists in Unity

As a final note, every project has its needs. Choosing which render pipeline to use is something that should be done before creating the project in Unity. Although currently it is relatively easy to upgrade your project.

Choose what fits your needs.

---
Tags: unity, rendering, unity-urp
---


title: Using pygame with multiple threads

text:
# Question
Title: Using pygame with multiple threads
I have decided to try out pygame. I created a class that is supposed to handle all the GUI and game related stuff.

My idea is that I would have two seperate threads. One to handle the GUI and one to handle all the calculations the game does in the background.

```
import threading
import pygame
import pygame_gui

class Game ():

    engine_running = True
    gui_running = True
    clock = pygame.time.Clock()

    gui_framerate = 60.0
    engine_framerate = 120.0

    def __init__(self):

        pygame.init()
        pygame.display.set_caption('Explodotech')
        self.window_surface = pygame.display.set_mode((800, 600))
        self.background = pygame.Surface((800, 600))
        self.background.fill(pygame.Color('#000000'))

        self.manager = pygame_gui.UIManager((800, 600))

        ### Define GUI Elements here

        self.quit_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((650, 500),
                        (100, 50)), text='Quit', manager=self.manager,
                        tool_tip_text = "Quit the game")

        ### Create and start the threads
        self.gui_thread = threading.Thread(target = self.gui_loop)
        self.engine_thread = threading.Thread(target = self.engine_loop, args = [])

        self.gui_thread.start()
        self.engine_thread.start()

    def start_polling(self):
        """Starts the main loop"""
        self.engine_running = True

    def stop_polling(self):
        """Stops the main loop"""
        self.engine_running = False

    def gui_loop(self):
        """Managing all the GUI stuff"""

        print ("GUI-loop started!")

        while self.gui_running:
            print("Polling GUI")
            dT = self.clock.tick_busy_loop(60)/1000.0

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    self.gui_running = False

                if event.type == pygame.USEREVENT:
                    if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                        if event.ui_element == self.quit_button:
                            self.quit_button_event()

                self.manager.process_events(event)

            self.manager.update(dT)

            self.window_surface.blit(self.background, (0, 0))
            self.manager.draw_ui(self.window_surface)

            pygame.display.update()

    def engine_loop(self):
        """Doing all the game calculations in the background"""
        while self.engine_running:
            print(self.clock.tick_busy_loop(1))

    ### Define GUI events here

    def quit_button_event(self):
        """Shut down the GUI"""
        print("Quit-button pressed!")
        self.gui_running = False
        self.engine_running = False

```

Basically what's happening here is that I have two threads one should run the "gui\_loop" function the other should run the "engine\_loop". However when the gui thread starts and gets into its while-loop it get stuck. The windows goes unresponsive and I have to force windows to shut it down. However if I a create a Game-object and call the function directly it all works fine (obviously commenting out the party where I create the Thread-object):

```
g = Game()
g.gui_loop()

```

Any pointers what I am doing wrong would be greatly appreciated!

# Answer
Your program gets stuck after closing because you only stop the engine, not the Python program.

You need to exit the system as follows:

```
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()

```
> 2 votes

# Answer
Python is an interpreted language, and there's a thing called Global Interpreter Lock, which prevents multiple threads to run Python code simultaneously. (See details in Documentations of threading module.) If you run two full while loops in a single Python process, one of them is going to block another. You GUI freezes because your core loop blocked it. My computer, on the other hand, won't freeze the GUI, but the core thread won't run because the GUI thread blocked it.

You can have two ways around this:

1. Try combine two while loops into one, run the higher frequency one as main loop, and count how many time it has looped to occasionally run the lower frequency update.

```
 [Pseudo Code]
 update(self):
   dt = self.get_dt(self.core_freq)
   self.update_core()
   self.accumulated_dt += dt
   if self.accumulated_dt > 1/self.gui_freq:
     self.update_gui()
     self.accumulated_dt = 0

```
2. Use multiprocessing to create multiple processes, and communicate between to share data. Python multiprocessing gets around the GI Lock by create more processes, but communicating between them can be costly and dangerous (causing data races). So, I won't suggest you to make a game with it. Complex mechanisms like this should really be handled at engine level.
> 1 votes

# Answer
I am not sure why your code doesn't run correctly on your pc; it runs perfectly fine on mine.

Maybe your CPU doesn't support multithreading, or just doesn't have enough cores. My pc has 8 cores with 16 threads, not sure about your PC.
> 0 votes

---
Tags: python, pygame, thread
---


# Question
Title: Voxel terrain vs AABB collision detection
I am trying to implement collision detection in a voxel game. Currently I check the side of the collision by finding the closest side and checking whether there isn't a solid block next to that side. This doesn't work for the example shown below because the algorithm doesn't take the block in the bottom into account when checking collision with the block on the top. I could fix this for this example by checking if there are any blocks left of the top block that are solid and also collide with the player on the same side. Is there a better way to do this?

In the image the player is sliding right along the wall and gets stuck colliding with the left side of the top block.

A simpler example of the same problem is how to handle the collsion like in the image above. If the player is moving right and there is gravity then if the collision with the left side of the right block gets resolved first the player gets stuck.

# Answer
collision on voxel world is very simple. First you have to calculate the player position and size divide by the block size Example: **player.position.x + player.size / block.size** Then if you're using any sort of grid then check that position/grid if it has a solid block type in it.

Here is the sample code from my voxel game:

```
void Camera::collision(float dx, float dy, float dz)
{
    /* AABB collision checker */

    float x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, y5;
    x1 = floor((m_position.x - m_width) / m_block.getBlockSize());
    y1 = floor((m_position.y - m_bottom) / m_block.getBlockSize());
    z1 = floor((m_position.z - m_width) / m_block.getBlockSize());
    x2 = floor((m_position.x + m_width) / m_block.getBlockSize());
    y2 = floor((m_position.y + (m_top+2)) / m_block.getBlockSize());
    z2 = floor((m_position.z + m_depth) / m_block.getBlockSize());

    // stuck? go up
    if(floor(m_position.y / m_block.getBlockSize()) < m_worldSize.y) {
        while(Types::getSolidBlocks( m_map.getInPosition(floor(m_position.x / m_block.getBlockSize()), floor(m_position.y / m_block.getBlockSize()), floor(m_position.z / m_block.getBlockSize())) )) {
            m_position.y += m_block.getBlockSize();
            y1 = floor((m_position.y - m_bottom) / m_block.getBlockSize());
            y2 = floor((m_position.y + (m_top+2)) / m_block.getBlockSize());
            if(floor(m_position.y / m_block.getBlockSize()) > m_worldSize.y) break;
        }
    }

    // vertical collision

    if(Types::getSolidBlocks(m_map.getInPosition(x1, y1, z1)) || Types::getSolidBlocks(m_map.getInPosition(x2, y1, z1)) ||
        Types::getSolidBlocks(m_map.getInPosition(x2, y1, z2)) || Types::getSolidBlocks(m_map.getInPosition(x1, y1, z2))) {

        if(dy < 0) {
            m_position.y = y1 * m_block.getBlockSize() + m_block.getBlockSize() + m_bottom;
            m_direction.y = 0;
            m_onGround = true;
        }
        m_collision[1] = true;
    }

    if(Types::getSolidBlocks(m_map.getInPosition(x1, y2, z1)) || Types::getSolidBlocks(m_map.getInPosition(x2, y2, z1)) ||
        Types::getSolidBlocks(m_map.getInPosition(x2, y2, z2)) || Types::getSolidBlocks(m_map.getInPosition(x1, y2, z2))) {

        if(dy > 0) {
            m_position.y = y2 * m_block.getBlockSize() - (m_top+2) - .01;
            m_direction.y = 0;
        }
        m_collision[1] = true;
    }

    // horizontal collision

    x3 = floor((m_position.x - dx - m_width) / m_block.getBlockSize());
    y3 = floor((m_position.y - dy - m_bottom) / m_block.getBlockSize());
    z3 = floor((m_position.z - dz - m_width) / m_block.getBlockSize());
    x4 = floor((m_position.x - dx + m_width) / m_block.getBlockSize());
    y4 = floor((m_position.y - dy + (m_top+2)) / m_block.getBlockSize());
    z4 = floor((m_position.z - dz + m_depth) / m_block.getBlockSize());
    y5 = round(y3+(y4-y3)/2); // previous y position

    if(Types::getSolidBlocks(m_map.getInPosition(x1, y3, z3)) || Types::getSolidBlocks(m_map.getInPosition(x1, y3, z4)) ||
        Types::getSolidBlocks(m_map.getInPosition(x1, y4, z4)) || Types::getSolidBlocks(m_map.getInPosition(x1, y4, z3)) ||
        Types::getSolidBlocks(m_map.getInPosition(x1, y5, z3)) || Types::getSolidBlocks(m_map.getInPosition(x1, y5, z4))) {

        if(dx < 0) {
            m_position.x = (x3-1) * m_block.getBlockSize() + m_block.getBlockSize() + m_width;
            m_direction.x = 0;
        }
        m_collision[0] = true;
    }

    if(Types::getSolidBlocks(m_map.getInPosition(x2, y3, z3)) || Types::getSolidBlocks(m_map.getInPosition(x2, y3, z4)) ||
        Types::getSolidBlocks(m_map.getInPosition(x2, y4, z4)) || Types::getSolidBlocks(m_map.getInPosition(x2, y4, z3)) ||
        Types::getSolidBlocks(m_map.getInPosition(x2, y5, z3)) || Types::getSolidBlocks(m_map.getInPosition(x2, y5, z4))) {

        if(dx > 0) {
            m_position.x = (x4+1) * m_block.getBlockSize() - m_width - .01;
            m_direction.x = 0;
        }
        m_collision[0] = true;
    }

    if(Types::getSolidBlocks(m_map.getInPosition(x3, y3, z1)) || Types::getSolidBlocks(m_map.getInPosition(x4, y3, z1)) ||
        Types::getSolidBlocks(m_map.getInPosition(x4, y4, z1)) || Types::getSolidBlocks(m_map.getInPosition(x3, y4, z1)) ||
        Types::getSolidBlocks(m_map.getInPosition(x3, y5, z1)) || Types::getSolidBlocks(m_map.getInPosition(x4, y5, z1))) {

        if(dz < 0) {
            m_position.z = (z3-1) * m_block.getBlockSize() + m_block.getBlockSize() + m_depth;
            m_direction.z = 0;
        }
        m_collision[2] = true;
    }

    if(Types::getSolidBlocks(m_map.getInPosition(x3, y3, z2)) || Types::getSolidBlocks(m_map.getInPosition(x4, y3, z2)) ||
        Types::getSolidBlocks(m_map.getInPosition(x4, y4, z2)) || Types::getSolidBlocks(m_map.getInPosition(x3, y4, z2)) ||
        Types::getSolidBlocks(m_map.getInPosition(x3, y5, z2)) || Types::getSolidBlocks(m_map.getInPosition(x4, y5, z2))) {

        if(dz > 0) {
            m_position.z = (z4+1) * m_block.getBlockSize() - m_depth - .01;
            m_direction.z = 0;
        }
        m_collision[2] = true;
    }

}

```

Btw. The m\_map is a grid that checks the block type in the world and **dx, dy, dz** are the direction of the player

and here's how to use the collider:

```
// player movement
m_position.x += m_direction.x * dt;
collision(m_direction.x, 0, 0); // collision detector
m_position.y += m_direction.y * dt;
collision(0, m_direction.y, 0); // collision detector
m_position.z += m_direction.z * dt;
collision(0, 0, m_direction.z); // collision detector

```
> 1 votes

# Answer
I implemented this and it works.
> -1 votes

---
Tags: collision-detection, tilemap, collision-resolution, voxels
---


# Question
Title: Applying animation only to part of a text
Using the built-in text UI, is there a way to animate only a selected number of letters?

What I want to do is something like the word "you" in this video and "I'd" in this one

# Answer
As per DMGregory's suggestion in the comments, I propose a solution using the `<voffset>` tag for rich text. It's a little bit elaborate code-wise but doesn't require you to work with shaders at all.

### Setup

We begin by creating a *Text - TextMeshPro* UI element in the Hierarchy. Change the text, font, colour and alignment as you wish. By now, we have a simple, static text:

### Testing the `<voffset>` tag

The `<voffset>` tag changes the offset of the baseline. We can enclose the word 'world' between tags and add a value in pixels or ems. The enclosed text will be lifted

If we change the text content to `Hello, <voffset=10px>world</voffset>!` the result is the following:

### Changing the offset via Script

First of all, we must reference the *TextMeshPro* Component, so that we can access its `text` property. We do that with a class property and a function call at script startup:

```
TextMeshProUGUI meshText;
meshText = GetComponent<TextMeshProUGUI>();

```

We can animate the vertical movement via a sine function over time. We want control over the function's frequency and amplitude, thus limiting "how fast" and "how high" the text will float.

We define the following class properties:

```
public float frequency = 1f;    // frequency factor
public float amplitude = 10f;   // pixel factor

```

Now we can compute an offset value over time with parameters:

```
float offset = Mathf.Sin(Time.time * frequency) * amplitude;

```

We will feed this value to the text in each frame to update the animation.

To update the text and only change the `<voffset>` value, we can search for a substring of type `<voffset=*px>` where `*` is a number, but this would require using regular expressions, which is likely overkill.

A simpler approach exists. Substring replacement is easy if we know the substring to replace in advance. Then, we can do the following:

1. Save the original string populating the `text` property.

```
string sourceString;
sourceString = meshText.text;

```
2. Copy the above string with an updated offset value.

```
string newString = sourceString.Replace(
    "<voffset=0px>", "<voffset=" + offset.ToString() + "px>");

```
3. Update the text field with such string.

```
meshText.text = newString;

```

### Assembling the Script

Let's put everything together and in place. Our class should look like this:

```
using UnityEngine;
using TMPro;

public class Baseline : MonoBehaviour {
    public float frequency = 5f;
    public float amplitude = 10f;
    string sourceString;
    TextMeshProUGUI meshText;

    void Start() {
        meshText = GetComponent<TextMeshProUGUI>();
        sourceString = meshText.text;
    }

    void Update() {
        float offset = Mathf.Sin(Time.time * frequency) * amplitude;
        string newString = sourceString.Replace("<voffset=0px>", "<voffset=" + offset.ToString() + "px>");
        meshText.text = newString;
    }
}

```

### Testing

Now we can assign this script to the GameObject with a *Text Mesh Pro - Text (UI)* Component, tweak the parameters and test it:

This problem occurs because `<voffset>` adjusts the line height to accommodate the displaced text. We can fix that by selecting the *Capline* Alignment option from the Inspector:

And the result is what we expect:

Unfortunately, this simple solution isn't enough for multi-line text with animation:

In such a case, we simply need to force the overall text line-height to be constant for the whole text by adding the `<line-height>` tag at the beginning of our string:

```
<line-height=100%>Hello, <voffset=0px>world</voffset>!
How are you?

```

Now everything **does** work!

### Extending the script

This is a very simple approach to animating a single word in a text string. You can extend these functionalities to animate individual letters in a word, by enclosing each character between `<voffset>` tags and adding a phase offset to each letter so that they float at the same speed and height but different timing.
> 1 votes

---
Tags: unity, animation, text, unity-ui
---


title: Assimp Texture Coords problem

text:
# Question
Title: Assimp Texture Coords problem
I've got a problem when loading objects using assimp. I did succesfully load vertex data and I am able to draw static mesh (without bones and animations, I've got few bugs there but I'll go back to solving that problem after I solve this one). Back to the problem. I have loaded texture coords using this code

```
tmp.Tex.x = modelScene->mMeshes[i]->mTextureCoords[0][j].x;
tmp.Tex.y = modelScene->mMeshes[i]->mTextureCoords[0][j].y;

```

of course it is in cycle for all meshes and all vertices (i, j respectively).

Then I draw it using DirectX 11 and I get this result:

I tried almost all permutations of post loading flags that had something to do with UV coordinates and nothing helped (only the yellow spots changed it's color to green in some cases).

Textures should be loaded correctly (I checked file names in debugger and they were correct) then I loaded it using directX functions for that so no problems should not there.

The code for drawing is basically the same as in the book from Frank Luna, with minor changes (because I redesigned the whole framework to my needs). Shader is whole from the book.

I am hopeless already. I am looking for working way to load my models (fbx, dae) to my demo for almost 2 months now and nothing worked (this is the closest I've got), so if anyone have seen anything similar I would be really grateful for any pointers on where to look for problem.

Here is the source image

EDIT 1: So I tried to draw the texture on the quad using the same shader I use for drawing on model and somehow I used wrong TangentU and Normals what resulted in the picture on quad being black with occasional (when I moved camera) white stripes with shades of the actual texture so can't this problem have anything to do with tangents or normals? Or maybe something with TangentU being something different than actual Tangent? Code I use to load those is:

```
tmp.Normal.x = modelScene->mMeshes[i]->mNormals[j].x;
tmp.Normal.y = modelScene->mMeshes[i]->mNormals[j].y;
tmp.Normal.z = modelScene->mMeshes[i]->mNormals[j].z;

tmp.TangentU.x = modelScene->mMeshes[i]->mTangents[j].x;
tmp.TangentU.y = modelScene->mMeshes[i]->mTangents[j].y;
tmp.TangentU.z = modelScene->mMeshes[i]->mTangents[j].z;

```

# Answer
> 0 votes
So as many implied, it was problem with shader, or better said SSAO and/or shadow mapping.

I went back to the working demo that was attached to the book and used my Loader there and it worked. The problem was that in my framework I deleted the parts that were SSAO and ShadowMap related, and that somehow (I didn't study the shader code very much) caused the problem.

Hovewer I still had a problem with the texture being mirrored. I solved this by FlipWindingOrder flag and dissabling flipUVs flag.

Another additional problem with this model but not with another one I ran into was some weird 'shadow like' triangles all over my model. This was solved by going back to FBX model as the one I used was DAE converted from FBX using FBX View tool from Autodesk.

Thanks everyone for helping.

# Answer
> 0 votes
I encountered the same problem. Simply for my project, removing `aiProcess_JoinIdenticalVertices` from the flags of `Assimp::Importer::ReadFile` worked. For my project, this flag is OK for loading `.dae` files, but results in this problem when loading `.fbx` files.

---
Tags: directx11, assimp
---


title: Texture doesn't draw correct

text:
# Question
Title: Texture doesn't draw correct
I'm writing a game using SFLM and Opengl but when I create a terrain i got some OpenGl problems. I use heightmaps to generate a terrain but when I load the texture on it the texture is not correct mapped on the terrain. I use buffers to draw the terrain and the textures.

The code for loading the terrain:

```
void Terrain::loadTerrain(tstring filename) {

sf::Image* image = new sf::Image();

if (!image->loadFromFile(_T("GameData/Image/") + filename))
{
    Error::writeMessage("Terrain Class: Can't read file GameData/Image/" + filename);
}

size_ = sf::Vector2i(image->getSize().x, image->getSize().y);

hs_ = new float*[size_.y];
for (int i = 0; i < size_.y; i++) {
    hs_[i] = new float[size_.x];
}

normals_ = new sf::Vector3f*[size_.y];
for (int i = 0; i < size_.y; i++) {
    normals_[i] = new sf::Vector3f[size_.x];
}

//l was height
for (int y = 0; y < size_.y; y++) {
    for (int x = 0; x < size_.x; x++) {
        sf::Color color = image->getPixel(x, y);

        float h = float(color.r + color.g + color.b) / 3.0f / 15.0f;
        setHeight(x, y, h);
    }
}

delete image;
computeNormals();

```

}

The source for loading the image and convert it to Opengl textures:

```
   void Terrain::loadTexture(tstring filename, Layer layer)
{
    GLuint texture = 0;
    {
        sf::Image image;
        if (!image.loadFromFile(_T("GameData/Texture/") + filename))
        {
            Error::writeMessage("Terrain Class: Can't read file GameData/Texture/" + filename);
        }
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getSize().x, image.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
    }

    if (textures_.size() != 0)
    {
        map<Layer, GLuint>::iterator it = textures_.find(layer);

        if (it != textures_.end())
        {
            glDeleteTextures(1, &(it->second));
        }

        textures_.insert(pair < Layer, GLuint>(layer, texture));
    }
    else
    {
        textures_.insert(pair < Layer, GLuint>(layer, texture));
    }
}

```

I create the buffers with this method:

```
void Terrain::createBuffers()
{
    vhVertexCount = 2 * size_.x * (size_.y - 1);
    sf::Vector3f* vhVertices = new sf::Vector3f[vhVertexCount];
    sf::Vector3f* vhNormal = new sf::Vector3f[vhVertexCount];
    sf::Vector2i* vhTexCoords = new sf::Vector2i[vhVertexCount];

    bool texture = true;
    int nIndex = 0;

    for (int z = 0; z < size_.y - 1; z++)
    {
        for (int x = 0; x < size_.x; x++)
        {
            sf::Vector3f normal = getNormal(x, z);
            if (texture)
            {
                vhTexCoords[nIndex] = sf::Vector2i(0, 0);
            }
            else
            {
                vhTexCoords[nIndex] =  sf::Vector2i(1, 0);
            }

            vhVertices[nIndex] = sf::Vector3f((float) x, getHeight(x, z), (float) z);
            vhNormal[nIndex] = sf::Vector3f(normal.x, normal.y, normal.z);
            nIndex++;

            normal = getNormal(x, z + 1);

            if (texture)
            {
                vhTexCoords[nIndex] = sf::Vector2i(0, 1);
                texture = !texture;
            }
            else
            {
                vhTexCoords[nIndex] = sf::Vector2i(1, 1);
                texture = !texture;
            }

            vhVertices[nIndex] = sf::Vector3f((float) x, getHeight(x, z + 1), (float) z + 1);
            vhNormal[nIndex] = sf::Vector3f(normal.x, normal.y, normal.z);
            nIndex++;
        }
    }

    glGenBuffers(1, &vertexBuffer_);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer_);
    glBufferData(GL_ARRAY_BUFFER, vhVertexCount * sizeof(sf::Vector3f), vhVertices, GL_STATIC_DRAW);

    glGenBuffers(1, &normalBuffer_);
    glBindBuffer(GL_ARRAY_BUFFER, normalBuffer_);
    glBufferData(GL_ARRAY_BUFFER, vhVertexCount * sizeof(sf::Vector3f), vhNormal, GL_STATIC_DRAW);

    glGenBuffers(1, &textCoordBuffer_);
    glBindBuffer(GL_ARRAY_BUFFER, textCoordBuffer_);
    glBufferData(GL_ARRAY_BUFFER, vhVertexCount * sizeof(sf::Vector2i), vhTexCoords, GL_STATIC_DRAW);

    delete [] vhVertices;
    vhVertices = nullptr;

    delete [] vhNormal;
    vhNormal = nullptr;

    delete [] vhTexCoords;
    vhTexCoords = nullptr;
}

```

And finally the method to render everyting on the screen:

```
void Terrain::drawObject(sf::RenderWindow* window)
{
    if (!buffersCreated_)
    {
        createBuffers();
        buffersCreated_ = true;
    }

    glPushMatrix();

    float scale = 5.0f / max(size_.x - 1, size_.y - 1);
    glScalef(scale, scale, scale);
    glTranslatef(-(float) (size_.x - 1) / 2, 0.0f, -(float) (size_.y - 1) / 2);

    glActiveTexture(GL_TEXTURE0);

    glEnable(GL_TEXTURE_2D);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glBindTexture(GL_TEXTURE_2D, textures_.find(Layer::Mid)->second);

    glClientActiveTexture(GL_TEXTURE0);

    glBindBuffer(GL_ARRAY_BUFFER, textCoordBuffer_);
    glTexCoordPointer(2, GL_FLOAT, 0, (char *) NULL);

    glEnableClientState(GL_NORMAL_ARRAY);
    glBindBuffer(GL_ARRAY_BUFFER, normalBuffer_);
    glNormalPointer(GL_FLOAT, 0, (char *) NULL);

    glEnableClientState(GL_VERTEX_ARRAY);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer_);
    glVertexPointer(3, GL_FLOAT, 0, (char *) NULL);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, vhVertexCount);

    glPopMatrix();
}

```

Below there is an image from the scene. You can see that there is no texture on the terrain buth only one green color. How can I fix this issue?

# Answer
I might be mistaken, but in this line:

```
if (!image.loadFromFile(_T("GameData/Texture/") + filename))

```

if your `_T()` is the one from WinAPI, `filename` is implicitly cast to a `TCHAR*`, and this will end up adding two `TCHAR*`s, giving you a bad address. Try `tstring(_T("GameData/Texture/")) + filename`.
> 0 votes

# Answer
Try changing the `GL_REPEAT` into `GL_CLAMP_TO_EDGE` if this one couldn't solve the problem then check the texture coordinates properly.
> 0 votes

---
Tags: c++, opengl, textures, sfml
---


# Question
Title: Math function equivalence for deferred transparency blending
if one consider the following blending operation:

`color1*src_alpha` blended with `color2*(1-src_alpha)`

Where `color1` and `color2` are `RGB1*dot(L.N1)` and `RGB2*dot(L.N2)`

Is it possible to find any math function equivalent where `(RGB1 blend RGB2)` can be blended to `dot(L, function(N1,N2))`?

The idea is to store a correct value of N1 blended with N2 in a normal map for later lighting. And with more than 2 normals if needed.

# Answer
> 0 votes
No, this is obviously not possible.

A normal map has only 3 degrees of freedom in its RGB channels 4 if you extend into using alpha too. The shading problem you're describing has `(3 n) - 1` degrees of freedom, where `n` is the number of distinct normals you want to shade. (A single normal has two degrees of freedom, and every subsequent transparent layer adds two more degrees of freedom and a blend weight). You quickly end up with far more information than you have the bits to store.

And that's not even counting that the shading of each pixel depends not only on the normals of all the surfaces being lit, but also their locations. If the back surface is outside the range of the light, its normal should not contribute to the lighting and only the front one counts. And the reverse if the front surface is out of range. So now you either need to know the locations of all lights when doing your blend (in which case you might as well just do forward rendering), or also encode multiple depths per pixel and somehow be able to isolate the normal contribution at each depth.

This is why deferred shading is typically used only with opaque objects, and a follow-up forward pass to layer the transparency on top. Or tricks like alpha to coverage, dithering, and temporal anti-aliasing to render "transparent" blending as separate opaque samples and blur them together later.

You can also look into the technique of "depth peeling" for order-independent transparency, but it's quite heavyweight and not typically used in games.

---
Tags: mathematics, lighting, normals, alpha-blending
---