# Question
Title: Finding the position of a point based on a relative point inside a quad
I'm trying to get the relative point position on a quad using a \[0,1\] Vector2, like in the picture below:

The red dots are relative positions.

What I'm trying to make is a function that takes the A,B,C,D vertices, the relative position and return the local position of point.

Example using the first quad of the image:

```
// Returns Vector2(7, 7)
GetPositionOnQuad(Vector2(0.7f, 0.7f), Vector2(0,10), Vector2(10,10), Vector2(10,0), Vector2(0,0))

```

What are some ways of doing this?

# Answer
> 4 votes
Assuming that your quad is convex, you can solve for an interior point using a few linear interpolations (lerps) between the corner points of the quad.

To illustrate, consider finding a point (R for result) at (0.75, 0.5) within the interior of a quad with points A,B,C,D ordered as given in your description. Intuitively, we know that the result is going to be somewhat to the right of the middle. How can we find that?

First consider the simpler case of what would happen if we were looking for (0.75, 0.0). In that situation we would want the point (let's call it P) that sits 75% between A & B. We can find P by lerping between A & B. Similarly, if we simplified to the other extreme of (0.75, 1.0), we would find a point (let's call it Q) that's 75% between C & D. Much like before, we can find Q by lerping between C & D.

But we didn't actually want either extreme, we wanted something between them, something that accounts for the second parameter as given. Again, we can find that by lerping between the intermediate points P & R. In this case we wanted to be 50% between them.

Here's a general illustration:

In terms of code, you might have something like this:

```
static float Lerp(float a, float b, float t)
{
    return a + t * (b - a);
}

static PointF Lerp(PointF a, PointF b, float t)
{
    return new PointF(Lerp(a.X, b.X, t), Lerp(a.Y, b.Y, t));
}

static PointF PointInQuad(PointF t, PointF a, PointF b, PointF c, PointF d)
{
    PointF p = Lerp(a, b, t.X);
    PointF q = Lerp(c, d, t.X);
    return Lerp(p, q, t.Y);
}

```

# Answer
> 1 votes
Find the points on the four sides according to the proportion, and then find the intersection of the two segments.

Code:

```
class Vec2:
    def __init__(self, x, y) -> None:
        self.x = x
        self.y = y

    def __add__(self, v):
        return Vec2(self.x+v.x, self.y+v.y)

    def __sub__(self, v):
        return Vec2(self.x-v.x, self.y-v.y)

    def __mul__(self, n):
        return Vec2(self.x*n, self.y*n)

def GetPositionOnQuad(pos,A,B,C,D):
    p1 = A+(B-A)*pos.x
    p2 = D+(C-D)*pos.x
    p3 = A+(D-A)*pos.y
    p4 = B+(C-B)*pos.y
    return GetIntersection(p1,p2,p3,p4)

def det(a, b):
    return a.x * b.y - a.y * b.x

def GetIntersection(p1,p2,p3,p4):
    xdiff = Vec2(p1.x - p2.x, p3.x - p4.x)
    ydiff = Vec2(p1.y - p2.y, p3.y - p4.y)

    div = det(xdiff, ydiff)
    if div == 0:
        return -1,-1

    d = Vec2(det(p1,p2), det(p3,p4))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return x, y

result = GetPositionOnQuad(Vec2(0.7,0.7),Vec2(0,0),Vec2(0,10),Vec2(10,10),Vec2(10,0))
print(result)

```

---
Tags: mathematics, vector, geometry
---


# Question
Title: How should I share the states amongst all the executions of a Behaviour Tree triggered from all ticks?
I'm still learning about Behaviour Trees and my understanding of the "blackboard" is essentially a state object. When passing the state object through the ticks to the function calls (which are nodes and leaves), how should I share the states amongst all the executions of the trees triggered from all previous ticks?

I initially thought the states should be immutable so that the functions can be "pure". However, if the states are immutable, that would mean that whatever consequences triggered from a previous tick will have to be performed in its entirety even if a later tick that came in the middle of the execution has a different state value.

For example, if the behaviour tree was something like this:

When `Tick_1` first came in, the state was something like this:

```
{
  user: { cash: 10 }
}

```

So, at `Tick_1`, user has $10 and has enough cash to buy milk. The behaviour tree will go down the path of walking to the store and then buying milk.

However, the action of "Walking to Store" is asynchronous and takes some time before the "Buy Milk" action can take place. Now, when the "Walking to Store" action from `Tick_1` is still taking place, another tick `Tick_2` came in at this time with a state that the user now has $0 in his pocket:

```
{
  user: { cash: 0 }
}

```

Based on the latest state from `Tick_2` the user has no more money probably due to something that happened during `Tick_2`. But because the previous execution of the tree from `Tick_1` is still in progress and has no knowledge about the new state since its copy of the state is the old one and they don't shared a common mutable state, it will eventually go on and perform the "Buy Milk" action when it really shouldn't because by this time, the user has no more cash!

It seems to me that if the states passed to the ticks are immutable separate copy of states, the previous decision made has to be completed and we can't "cancel" the previous decision or execution.

If we use a shared state, however, this would mean the state is mutable and any of the functions or actions can change them through any side effects. It might turn out to be very messy and difficult to maintain with too many places changing a common state.

**My question is:**

* How should the blackboard or states of a behaviour tree be constructed? Should the states be mutable or immutable?
* Should every ticks share a common copy of states so that executions of the tree from the previous ticks are aware of the latest values in the states so that they either stop proceeding or react differently?
    + If so, how should this be done elegantly?

I'm using Typescript in my case but I'm assuming(?) the concept should be similar in any other context and languages.

*PS: I guess I could swap the positions of the condition and "walk to store" to reduce the problem in my example but I'm trying to use this to illustrate the dilemma I'm having.*

# Answer
> 1 votes
As far as I understand, the blackboard is not a *state* but more a *dumping ground for storing things that the AI should know*.

The blackboard is mutable: each behaviour can read from it and write to it, either for itself or for a future behaviour.

The tree per se has also it's own "state": in what node/leaf am I. It is mutable by the tree structure itself.

The behaviours are unaware of the tree state, and do not care.

The tree is not aware of the content of the blackboard, and does not care.

There can only be one tick active at a time, so in the example you provide, it would not be possible that the agent suddenly has no money to buy the milk when it gets to the store, because the behaviours are executed in sequence and the blackboard is not changed otherwise.

> How should the blackboard or states of a behaviour tree be constructed? Should the states be mutable or immutable?

The blackboard is mutable by the leaves, while another structure is required for the rest of your tree.

> Should every ticks share a common copy of states so that executions of the tree from the previous ticks are aware of the latest values in the states so that they either stop proceeding or react differently?

Yes.

> If so, how should this be done elegantly?

The blackboard can be either a reference to an instance that you pass to your tree when you tick it, or you can pass the reference to each behaviour when you create the tree.

---

I'm not a behaviour tree guru, but that is essentially the way I used it lately, based on BehaviorTree.CPP.

---
Tags: javascript, architecture, ai, behavior, behavior-tree
---


title: Unity asking to enter Safe Mode?

text:
# Question
Title: Unity asking to enter Safe Mode?
I installed 2021.3.2f1 with the documentation and WebGL module and created a new project from Unity Hub. When I try opening that though I get this:

Not sure why this is happening. I deleted the old installation from both Unity Hub and Finder on my Mac. I actually had installation issues with 2021.3.2f1 before it got installed successfully so I deleted and reinstalled both Unity and Unity Hub.

If I click ignore and open the project, I get a pretty long "DirectoryNotFoundException: Could not find a part of the path" error -- and apparently I can't add scripts to any object because of this error: "DirectoryNotFoundException: Could not find a part of the path '/Applications/2021.3.2f1/Unity.app/Contents/UnityReferenceAssemblies/unity-4.8-api/Facades'."

Plus, I noticed that in this project's folder, the "Assembly-CSharp.csproj" file is not there. I see the file in all my other projects which were done in the previous editor version (2020.3.30f1).

What does the safe mode and directory error mean though? Did I do anything that caused this? What should I do? I'm on Mac btw. Any help is appreciated, thanks.

# Answer
> 1 votes
Your best bet is to make a new project open it in unity. Close unity and copy the asset folder over to the new project and then reopen unity and let it process each asset again. Then resetup your project settings. It’s a pain but I’ve found it the cleanest way to move between major versions.

---
Tags: unity
---


title: bind mixamo bone to unity

text:
# Question
Title: bind mixamo bone to unity
I download the mixamo character bone and rig it in the blender. and then use it in unity. but it seen no match in unity?

I change the mesh in skinmeshrenderer and the mesh disappears?

But I use mixamo auto rigging, and replace the mesh in Skinmeshrenderer it's work find.(the mesh no disappears in skinmeshrenderer)

Any ideas?

# Answer
In order to implement a Mixamo animation in Unity, you can use the auto-rigging from Unity, if you don't know how to skin animation to the mesh. You'll have to follow the next steps.

**Mixamo Download**

1. Upload your character FBX:
2. Select an animation:
3. Click on Download, and do the next settings:

**Unity Procedure**

After importing your animation in Unity, you'll see a weird movement, on your character, that's because of the rig, so we'll have to change that.

1. That's how your rig panel on your animation should look like, Humanoid, and Copy the avatar from the mesh you just uploaded on Mixamo:
2. Weird animation movement ? Yea, that happens sometimes, in order to fix that you'll have to play with this values around ( I know it's a little vague, but there are no fixed standards, you turn them all on, put them on Original, and then turn off what's wrong):
> 1 votes

---
Tags: unity
---


title: Libgdx World point to screen point

text:
# Question
Title: Libgdx World point to screen point
It seems like converting a screen point to a world point is easy in libgdx but going from the world point to a screen point is quite tricky.

So How do I convert a world point into a screen point?

# Answer
> 0 votes
`Camera` has methods for both projecting (moving from world-coordinates to screen-coordinates) and un-projecting (moving from screen-coordinates to world-coordinates).

`Vector3 screenPosition = camera.project(worldPosition);`

`Vector3 worldPosition = camera.unproject(screenPosition);`

# Answer
> 0 votes
This is a versatile approach and works in many implementations

```
    public static Vector3 MultiplyPoint(Matrix4 m, Vector3 point)
{
    Vector3 result = new Vector3(0, 0, 0);
    result.x = m.val[Matrix4.M00] * point.x + m.val[Matrix4.M01] * point.y +  m.val[Matrix4.M02]* point.z +  m.val[Matrix4.M03];
    result.y = m.val[Matrix4.M10] * point.x + m.val[Matrix4.M11] * point.y + m.val[Matrix4.M12] * point.z + m.val[Matrix4.M13];
    result.z = m.val[Matrix4.M20] * point.x + m.val[Matrix4.M21] * point.y + m.val[Matrix4.M22] * point.z + m.val[Matrix4.M23];
    float num = m.val[Matrix4.M30] * point.x + m.val[Matrix4.M31] * point.y + m.val[Matrix4.M32] * point.z + m.val[Matrix4.M33];
    num = 1f / num;
    result.x *= num;
    result.y *= num;
    result.z *= num;
    return result;
}

public static Vector2 WorldToScreenPoint(float x, float y)
{
    Matrix4 V = Constants.Camera.view;
    Matrix4 P = Constants.Camera.projection;

    Matrix4 MVP = P.mul(V); // Skipping M, point in world coordinates
    Vector3 screenPos = MultiplyPoint(MVP, new Vector3(x, y, 0));

    Vector3 screenPoint = new Vector3(screenPos.x + 1f, screenPos.y + 1f, screenPos.z + 1f).scl(0.5f); // returns x, y in [0, 1] internal.

    return new Vector2(screenPoint.x * Constants.GlobalWidth, screenPoint.y * Constants.GlobalHeight); // multiply by viewport width and height to get the actual screen coordinates.
}

```

---
Tags: java, libgdx, mathematics
---


# Question
Title: Predicting Inclines and Declines for projectiles
For background, I am working on a top-down fighting game. I'm trying to create an archer class, in which the arrow sort of predicts the inclines/declines (moving it about the Y-axis \[or up/down\]). A great example of what I'm trying to accomplish is League of Legend's projectiles: https://gyazo.com/ba1e2e6ead871136bf4faad99287315e

In the gif, you can see the projectile scaling up the wall to match the floor on the incline. If you were at the top (where the projectile went originally) and shot the projectile down, it would do the opposite, sending the projectile down the decline to match the low ground.

I have thought up a couple of solutions, but they all seem extremely expensive (a ton of raycasting to predict the inclines/declines). If anybody has resources on how this could be done or could point me in the right direction, I'd appreciate it.

# Answer
Thanks to @DMGregory, they guided me in the right direction and I got it done. Briefly, what I did is this: Every time a new map is created, I also create a heightmap (a 2D array containing all heights of the map). This is done by taking the bounds of the map and firing rays to find the height of specific places around the map. In my case, I know my maps will never be larger than 400x400 (studs is the ROBLOX unit of measurement). Using that, I decide on a resolution-- I used the number '80'. What this means is that I will have 80 different heights across each row of the map. I feel like what I'm writing doesn't make sense, so I created some debugging visuals that might help with understanding.

```
function MapService.InitMap()
    local origin = SETTINGS.Origin + Vector3.new(0,150,0)

    for i = 0, SETTINGS.Resolution do
        HeightMap[i] = {

        }

        for j = 0, SETTINGS.Resolution do
            local curr = origin + Vector3.new(i, 0, j) * Inc
            local hit = workspace:Raycast(curr, Vector3.new(0,-250,0), params)

-- i will never have a height below -100, so I use that as the 'void' number in the matrix
            HeightMap[i][j] = (if hit ~= nil then hit.Position.Y else -100)
        end
    end
end

```

Now that I have that, I need to be able to figure out which cell each XZ position falls into and the Y position at that cell.

```
local Inc = MapSize/SETTINGS.Resolution

--@ret [y_position of cell], [coordinates of cell in Vector2]
function MapService.PointInHeightMap(position)
   local map_position = position * Vector3.new(1,0,1)

-- math.round is the equivalent of math.floor(n + .5)
   local x, z = math.round(map_position.X/Inc), math.round(map_position.Z/Inc)

   return HeightMap[x][z], Vector2.new(x, z)
end

```

Now that we have that, we need to do a problem that sort of reminds me of a coding interview question (LOL). If given an origin and end position, find all possible cells that line between both will cross.

My solution actually misses some cells, but it is accurate enough that I am pleased. The code snippet below includes the solution to make it more accurate if you were curious.

```
function MapService.PointsInDirection(origin, end_pos)
    local in_order_list = {

    }

    local magnitude = (end_pos - origin).Magnitude -- distance between both
    local u = (end_pos - origin).Unit -- direction vector
    local size_u = u.Magnitude

-- if you wanted to make this more accurate, divide 'u' by any number you'd like. do this at the cost of more operations

    local x = 0

    while magnitude > x do -- every 1 stud, check the cell we're in
        local _, coords = MapService.PointInHeightMap(origin)

        if table.find(in_order_list, coords) == nil then
            table.insert(in_order_list, coords) -- insert if not already in array
        end

        origin += u
        x += size_u
    end

    return in_order_list
end

```

Finally, I create the arrow and when I shoot, I calculate the end position. Using our handy function, I'll say MapService.PointsInDirection(origin, end\_pos) and in a nutshell, calculate for any 'y' changes about the arrow's path and adjust accordingly. Now, I'm sure you're all waiting for the end result... Here it is. :)

https://gyazo.com/dd303cf4c42014b2d01cccd48fae876f https://gyazo.com/3efc5b2cdd878f43dc9955e1de1015cb https://gyazo.com/38210d0aad290d05ef48c442767afb0f

**Some stats for nerds:**

The heightmap generates in about .005 seconds (at the creation of each map).

After about 1000 random runs of checking for potential paths of arrows, the average time to find each was .00021 seconds, which I am more than happy with.

Again, I appreciate DMGregory for guiding me in the right direction. If anybody has any questions, feel free to ask.
> 1 votes

---
Tags: physics, mathematics
---


# Question
Title: How can I deal with tilemap position in the editor?
Right now it is quite hard in Unity 2017.2 to track where is the `(0, 0)` coordinate in the tilemap editor, when painting. I tend to use a displayable dummy game object as a marker.

I'd like to also edit *two* different sets of tilemaps. One set\* of tilemaps is located at `(0, 0, 0)` absolute position, and another set of tilemaps in, say, `(32, 0, 0)` position. However it is quite confusing to me (perhaps there is an option, but I can't find it) when trying to guess where is the internal center of the currently focused tilemap, to start painting. If somehow I had to paint several different tilemaps (more than two sets, say), I'd get easily dazed by the tool.

(\* A set of tilemaps is not any kind of special objects, but just a concept embracing several tilemaps in the same position).

**Question**: Does Unity provide a way in the editor/UI to know the place of the `(0, 0)` coordinate inside the tilemap (when editing and focusing a specific tilemap)?

# Answer
> 7 votes
The select tool.
Clicking any tile with the select tool, the inspector will tell you the position relative to 0,0.

With a little bit of math (and/or additional clicks), you can hone in on whichever tile you are searching for

https://docs.unity3d.com/Manual/Tilemap-Painting.html

# Answer
> 3 votes
It is an old question - There doesn't still seem to be easy way to show clearly the origin and the bounds of a Tilemap, but it can be solved with a script that runs in the Editor like Philipp said.

I created this script. Red border shows the Tilemap current bounds, green cross shows the 0,0,0 position of Tilemap. Script does take into account position of Tilemap in World space, but if the Grid or Tilemap is scaled or rotated the rendering no longer will be aligned to Tilemap. It is also possible to see the unused space where user has erased the tiles, but hasn't compressed the bounds:

I might extend this and put it to my GitHub, but here is the current version.

Add the script to any Tilemap for which you want to show bounds + origin, and the code will run in Editor automatically.

```
using UnityEngine;
using UnityEngine.Tilemaps;

public class DrawTilemapBorder : MonoBehaviour
{
    Tilemap tilemap;

    void OnValidate()
    {
        if (tilemap == null)
            tilemap = GetComponent<Tilemap>();
    }

    void OnDrawGizmos()
    {
        Draw();
    }

    void Draw()
    {
        if (tilemap == null)
            return;

        // tilemap position
        var tp = tilemap.transform.position;

        // bounds + offset
        var tBounds = tilemap.cellBounds;

        // corner points
        var c0 = new Vector3(tBounds.min.x, tBounds.min.y) + tp;
        var c1 = new Vector3(tBounds.min.x, tBounds.max.y) + tp;
        var c2 = new Vector3(tBounds.max.x, tBounds.max.y) + tp;
        var c3 = new Vector3(tBounds.max.x, tBounds.min.y) + tp;

        // draw borders
        Debug.DrawLine(c0, c1, Color.red);
        Debug.DrawLine(c1, c2, Color.red);
        Debug.DrawLine(c2, c3, Color.red);
        Debug.DrawLine(c3, c0, Color.red);

        // draw origin cross
        Debug.DrawLine(new Vector3(tp.x, tBounds.min.y + tp.y), new Vector3(tp.x, tBounds.max.y + tp.y), Color.green);
        Debug.DrawLine(new Vector3(tBounds.min.x + tp.x, tp.y), new Vector3(tBounds.max.x + tp.x, tp.y), Color.green);
    }
}

```

# Answer
> 1 votes
This may be counterintuitive as one would expect the focused tilemap in the palette reveals its zero/origin. However that doesn't happen. Instead, to find the zero you will not only focus the tilemap in the palette, but also focus the tilemap in the game hierarchy.

The latter will reveal the little blue ring of its origin in terms of game space. You will notice the ring is in the corner of 4 squares (tiles), being the left-top one the square being `(0, 0)` and your coordinates system growing up-right. **However** as a guideline ensure you paint the (0, 0) tile at the end (or any of the four tiles in contact with the little *blue ring* marking the position), because the painted tiles will hide it. Unfortunately Unity does not have an additional way to marking the origin.

# Answer
> 1 votes
You can use this gizmo. It looks like this. More info in this tweet. Basically, what it does is draw the axes' cordinates of a selected Grid or Tilemap component. When zoomed in enough it draws the coordinates inside each tile, instead of axes, to ease visualization.

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

namespace Utils.Editor.Gizmos
{
    public static class GridCoordinatesGizmo
    {
        [DrawGizmo(GizmoType.Selected)]
        public static void DrawGizmo(Grid grid, GizmoType gizmoType)
        {
            Draw(SceneView.currentDrawingSceneView, grid);
        }

        [DrawGizmo(GizmoType.Selected)]
        public static void DrawGizmo(Tilemap tilemap, GizmoType gizmoType)
        {
            Draw(SceneView.currentDrawingSceneView, tilemap.layoutGrid);
        }

        private static void Draw(SceneView sceneView, Grid grid)
        {
            var camera = sceneView.camera;
            var bottomLeftWorld = camera.ViewportToWorldPoint(Vector3.zero);
            var topRightWorld = camera.ViewportToWorldPoint(Vector3.one);

            var labelStyle = new GUIStyle(GUI.skin.label)
            {
                fontStyle = FontStyle.Bold,
                alignment = TextAnchor.UpperLeft
            };
            var tmpTextSize = labelStyle.CalcSize(new GUIContent("0"));
            float textHeightWorld = GetVerticalScreenToWorldSize(camera, tmpTextSize.y);
            float textHalfHeightWorld = textHeightWorld * 0.5f;
            float offset = textHeightWorld * 2;

            // compute horizontal variables
            int minCellX = grid.WorldToCell(bottomLeftWorld).x;
            int maxCellX = grid.WorldToCell(topRightWorld).x;
            float minCellXTextSize = GetTextWidthWorld($"{minCellX}", labelStyle, camera);
            float maxCellXTextSize = GetTextWidthWorld($"{maxCellX}", labelStyle, camera);
            float maxWidthSize = Mathf.Max(minCellXTextSize, maxCellXTextSize);

            IEnumerable<int> xCells;
            if (maxWidthSize >= grid.cellSize.x * 0.8f)
                xCells = MathUtils.SplitNicely(minCellX, maxCellX).Select(x => (int) x);
            else
                xCells = Enumerable.Range(minCellX, maxCellX - minCellX + 1);

            // compute vertical variables
            int minCellY = grid.WorldToCell(bottomLeftWorld).y;
            int maxCellY = grid.WorldToCell(topRightWorld).y;
            IEnumerable<int> yCells;
            if (textHeightWorld >= grid.cellSize.y * 0.8f)
                yCells = MathUtils.SplitNicely(minCellY, maxCellY).Select(y => (int) y);
            else
                yCells = Enumerable.Range(minCellY, maxCellY - minCellY + 1);

            var xCellsList = xCells.ToList();
            var yCellsList = yCells.ToList();

            string cellText = "XXX ; XXX";
            if (GetTextWidthWorld(cellText, GUI.skin.label, camera) > grid.cellSize.x * 0.7f)
                DrawInAxis(grid, xCellsList, labelStyle, camera, bottomLeftWorld, offset, yCellsList, textHalfHeightWorld);
            else
                DrawInCells(grid, xCellsList, yCellsList, textHeightWorld);
        }

        private static void DrawInAxis(Grid grid, IEnumerable<int> xCells, GUIStyle labelStyle, Camera camera,
            Vector3 bottomLeftWorld, float offset, IEnumerable<int> yCells, float textHalfHeightWorld)
        {
            foreach (var x in xCells)
            {
                string text = $"{x}";
                float textHalfWidthWorld = GetTextWidthWorld(text, labelStyle, camera) * 0.5f;

                float xCenter = grid.GetCellCenterWorld(new Vector3Int(x, 0, 0)).x;
                float xText = xCenter - textHalfWidthWorld;
                float yText = bottomLeftWorld.y + offset;
                var handlePos = new Vector3(xText, yText, 0);
                Handles.Label(handlePos, text, labelStyle);
            }

            foreach (var y in yCells)
            {
                string text = $"{y}";
                float yCenter = grid.GetCellCenterWorld(new Vector3Int(0, y, 0)).y;
                float xText = bottomLeftWorld.x + offset;
                float yText = yCenter + textHalfHeightWorld;
                var handlePos = new Vector3(xText, yText, 0);
                Handles.Label(handlePos, text, labelStyle);
            }
        }

        private static void DrawInCells(Grid grid, IEnumerable<int> xCells, IEnumerable<int> yCells, float textHeight)
        {
            var xCellsList = xCells.ToList();
            var yCellsList = yCells.ToList();
            foreach (var x in xCellsList)
            {
                foreach (var y in yCellsList)
                {
                    string text = $"{x} ; {y}";
                    var handlePos = grid.CellToWorld(new Vector3Int(x, y, 0));
                    handlePos.y = handlePos.y + textHeight;
                    Handles.Label(handlePos, text, GUI.skin.label);
                }
            }
        }

        private static float GetTextWidthWorld(string text, GUIStyle style, Camera camera)
        {
            var textSize = style.CalcSize(new GUIContent(text));
            float textWidthWorld = GetHorizontalScreenToWorldSize(camera, textSize.x);
            return textWidthWorld;
        }

        private static float GetHorizontalScreenToWorldSize(Camera camera, float size)
        {
            float xZeroWorld = camera.ScreenToWorldPoint(Vector3.zero).x;
            float xRightWorld = camera.ScreenToWorldPoint(new Vector3(size, 0, 0)).x;
            return xRightWorld - xZeroWorld;
        }

        private static float GetVerticalScreenToWorldSize(Camera camera, float size)
        {
            float yZeroWorld = camera.ScreenToWorldPoint(Vector3.zero).y;
            float yRightWorld = camera.ScreenToWorldPoint(new Vector3(0, size, 0)).y;
            return yRightWorld - yZeroWorld;
        }
    }
}

```

# Answer
> -1 votes
```
using UnityEditor;
using UnityEngine;

[ExecuteInEditMode]
public class GetTilemapCoordinate : MonoBehaviour
{
    public Grid grid;

    public GetTilemapCoordinate()
    {
        SceneView.duringSceneGui += GetMousePosition;
    }

    public void GetMousePosition(SceneView scene)
    {
        Event e = Event.current;
        if (e != null)
        {
            if (Event.current.type == EventType.MouseDown)
            {

                Vector3Int position = Vector3Int.FloorToInt(HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).origin);
                Vector3Int cellPos = grid.WorldToCell(position);

                Debug.Log(cellPos);
            }
        }
    }
}

```

---
Tags: unity, tilemap, map-editor
---


# Question
Title: How do I fix missing anti-aliasing in the Unity scene view and game?
Both the editor and the game seem to lack anti-aliasing even though quality is set to Ultra.

I chose the "3D" project template when I created the project, so I am using the build-in render pipeline.

# Answer
The Unity editor doesn't perform anti-aliasing directly any more, unfortunately. You're expected to add it as a Post Processing effect via the Post Processing stack (see https://docs.unity3d.com/Packages/com.unity.postprocessing@3.2).
> 3 votes

---
Tags: unity, rendering, antialiasing
---


# Question
Title: Why do physic engines apply force fully linear, despite adding torque
I checked how the `applyForce` function on rigid bodies in 3 different physic engines work (cannon.js, matter.js, PhysicsJS) and it seems that this is the common way to do it:

```
function applyForce(position, force) {
    // linear
    this.force.x += force.x;
    this.force.y += force.y;

    // torque
    var relativeX = position.x - this.position.x;
    var relativeY = position.y - this.position.y;
    this.torque += relativeX * force.y - relativeY * force.x;
}

```

The force vector first gets added fully to the force vector of the body, and then additionally a torque is added, based on the where the force was applied relative to the center of mass.

How does the body receive the full linear force *additionally* to the torque? Doesn't that mean the body received more force than it was applied to?

If the body couldn't rotate, adding the full force lineary would make sense, but since it does, it seems unnatural to me. Where does the additional force come from?

# Answer
Your belief that angular acceleration should somehow diminish linear acceleration is simply false.

The linear and angular momentum of a system are each *separately* conserved.

Imagine a unit cube, axis aligned, and placed at the origin.

I fire a fast-moving BB pellet in the rightward / +x direction, striking the left side of the cube. The cube's normal here points exactly opposite the pellet's motion, so the collision forces act along the x axis: reflecting the pellet back leftward, and giving the cube a nudge to the right.

The pellet exits with a momentum pointing exactly left, so the cube must obtain a momentum pointing exactly right to preserve the linear momentum of the system as a whole.

Crucially, the pellet's resulting linear momentum is the same no matter where on the face it struck the cube. (From its perspective, the instantaneous interaction looks identical) That means the momentum the cube obtains must be the same to balance it, no matter whether it was struck in the center of the face and received no torque, or near the edge of the face which would also apply a torque.

So, torque does not subtract from the linear forces an object receives.

You can think of it as the same energy, just being non-uniformly distributed through the cube. When hit in the center of the face, all parts of the rigid cube are forced to move at the same velocity. But when hit off-center, one side of the cube moves faster while the other side moves slower, causing it to turn, but the average velocity across the whole cube, the velocity of the center of mass, remains the same in both cases.
> 2 votes

---
Tags: physics, rigidbody, physics-engine
---


# Question
Title: how to have player stay on a rotating platform?
Im making a top down game in unity. in my game there is a platform where the player can stand on. while this platform is moving the player moves with it. here is an example:

This almost works like i want it to. The player moves together with the platform and is still able to move while on it. (note that currently the player will always follow the platform. there is no check to see if the player is on the platform or not. but that's done for testing.). What i want know is that when the platform rotates the player will also follow the rotation. currently it looks like this when the platform is rotating:

here i move my character to show what i want to achieve:

This is the code for moving my player and also the code that keeps me on the platform:

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

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;

    public Rigidbody2D rb;
    public Rigidbody2D platform;
    public Camera cam;

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

        mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
    }
    Vector2 pos;
    private void FixedUpdate()
    {

        pos = pos + movement;
        rb.MovePosition(platform.position + pos  * moveSpeed * Time.fixedDeltaTime);

        Vector2 lookDir = mousePos - rb.position;
        float angle = Mathf.Atan2(lookDir.y,lookDir.x) * Mathf.Rad2Deg - 90f;

        rb.rotation = angle;
    }
}

```

this is the code for moving the platform:

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

public class Platform : MonoBehaviour
{
    public float moveSpeed = 5f;

    public Rigidbody2D rb;
    public Vector2 movement;

    private void Start()
    {
       rb = gameObject.GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + new Vector2(1f, 0) * Time.fixedDeltaTime);
        rb.MoveRotation(rb.rotation + 25f * Time.fixedDeltaTime);
    }
}

```

I know that is also possible to make the player a child of the platform and then move the platform by updating the transformation position. but i choose for a rigidbody for the platform movement because I want the player to be able to control the platform later on and then i will use things like addforce.

# Answer
> 0 votes
On contact with the platform's trigger collide, store a reference to the platform and your position relative to the platform's coordinate system.

The next time you move, transform that local position by the platform's updated position and orientation. That's the location where you would be if you were "stationary".

Apply any player-induced movement relative to this shifted point. Then transform your resulting position back into the platform's local coordinate system to use next frame.

When you exit the platform's collider, clear the reference to it so you default back to full control of your movement relative to the stationary world coordinate system after that.

---
Tags: unity, c#, rotation, rigidbody, top-down
---


# Question
Title: 1920x1080 Image don't fit to 1920x1080 screen
I'm making a game with pygame and I wanted to add a background for my game. I'm trying to add a 1920x1080 background to a 1920x1080 screen, but part of the background is not visible.

My code:

```
import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((1920, 1080))

bg_img = pygame.image.load("wp.jpg").convert()

clock = pygame.time.Clock()

while True:
    screen.blit(bg_img, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)
    pygame.display.update()
    clock.tick(60)

```

wp.jpg:

Result:

# Answer
I fixed the problem by changing my code to:

```
import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN|pygame.NOFRAME)

bg_img = pygame.image.load("wp.jpg").convert()

clock = pygame.time.Clock()

while True:
    screen.blit(bg_img, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)
    pygame.display.update()
    clock.tick(60)

```
> 0 votes

---
Tags: python, pygame, image
---


# Question
Title: Creating a Game in Three.js do i share camera, scene objects?
Im creating a game with React and Three.js and vanilla Javascript, i have several clases, representing objects in the game, do i need to create a camera, scene, renderer for each class or i simply share the canvas for every class?

# Answer
> 0 votes
So i found some code and implemented it to my own needs, i have also added Physics with cannon-es, but anything is posible.

```
import * as THREE from 'three';

import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import * as CANNON from 'cannon-es'

class Floor{
  constructor(game, world){
    this.assetsPath = game.assetsPath;
    //this.loadingBar = game.loadingBar;
    this.game = game;
    this.scene = game.scene;
    this.init(world);
    this.tmpPos = new THREE.Vector3();
  }

  /*
  get position(){
    if (this.plane!==undefined) this.plane.getWorldPosition(this.tmpPos);
    return this.tmpPos;
  }

  set visible(mode){
    this.plane.visible = mode;
  }
  */
  init(world){
    const textureLoader = new THREE.TextureLoader()
    const texturePlane = textureLoader.load(
        './AiCourse Models/Texturas/grass.jpg',
        () =>
        {
          console.log('loading finished')
        },
        () =>
        {
          console.log('loading progressing')
        },
        () =>
        {
          console.log('loading error')
        }
    )

    const geometry  = new THREE.PlaneGeometry(1000,1000,400)
    const material  = new THREE.MeshBasicMaterial({map: texturePlane})
    const floor = new THREE.Mesh( geometry, material )
    floor.receiveShadow = true
    floor.rotation.x = - Math.PI * 0.5
    this.scene.add(floor)

    const floorBody = new CANNON.Body()
    const floorShape = new CANNON.Plane()
    floorBody.mass = 0
    floorBody.addShape(floorShape)
    floorBody.quaternion.setFromAxisAngle(new CANNON.Vec3(- 1, 0, 0), Math.PI * 0.5)
    world.addBody(floorBody)

  }

  update(time){
    world.step(1 / 60, deltaTime, 3)
  }
}

export { Floor };

```

This way i pass game data to any class/component i wish, i was attempting to do it in a similar way. Hope this helps someone. In the class constructor i pass all game class data, a game class returning this data in the constructor will do (that is scene object, renderer, camera etc) simply pass this keyword in class. For the Physics with cannon, create a global world variable and set it up (establish gravity, etc) Well at least this is my solution but it works.

---
Tags: javascript, three.js
---


# Question
Title: How do i make my game object goes to that specific direction after it bounces off a collision and not behave erratically?
```
 public class Ball : MonoBehaviour
{
    public float speedBall = 200f;
    Rigidbody2D rbBall;

    private void Awake()
    {
        rbBall = GetComponent<Rigidbody2D>();
    }
    private void Start()
    {
        addStartingForce();
    }
    private void Update()
    {

    }

    void addStartingForce()
    {
        float x = Random.value < 0.5f ? -1f : 1f; //less than half, go negative. Greater than half, go positive
        float y = Random.value < 0.5f ? Random.Range(-1f, -0.5f) : Random.Range(0.5f, 1f);

        Vector2 direction = new Vector2(x, y);
        rbBall.AddForce(direction * speedBall);
    }

    public void addforce(Vector2 force)
    {
        rbBall.AddForce(force);
    }

    void HeadingTowards()
    {
        Vector2 Dir = new Vector2(-50f, 0f);
        rbBall.AddForce(Dir * speedBall);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.CompareTag("wall"))
        {
            HeadingTowards();
        }
    }
}

```

Now once it bounces off a wall, it sometimes head towards my ("HeadingTowards") direction which was intended but after each bounce it didn't and the speed goes crazy fast unless I put time.deltaTime which I was told to not put it on addforce.

# Answer
It sounds like you just want to bend the velocity to aim at a specific position, not add a force. So, don't add a force, just set the velocity.

```
void HeadingTowards(Vector2 targetPosition)
{
    Vector2 Dir = (targetPosition - rbBall.position).normalized;
    rbBall.velocity(Dir * speedBall);
}

```
> 1 votes

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


# Question
Title: Moving player inside of moving spaceship?
**INTRO:**

I am trying to achieve a spaceship that flies through space and the pilot can get out of their seat and walk around the ship and place physics objects in it while the ship is moving, rotating, accelerating, and decelerating

**EXAMPLES:**

1. Subnautica has achieved this to some degree, in their cyclops submarine, you can walk around it as it moves... However, this spaceship will be going quite fast, doing flips and rotating. I am not sure about other space games because I haven't played them.
2. Sea of thieve's pirate ship mechanic in those boats where you walk around on board

**MY PROGRESS**

The main issue I have is just making all the collisions work inside the ship, maybe there is an alternative... I was thinking of making a remote cockpit but that wouldn't be that flexible.

**CONCLUSION**

I would much appreciate any solutions or helpful resources, directions, or information to help achieve "using rigid bodies inside of rigid bodies, the children being a first-person player controller (preferably physics-based) and random physics objects."

Thanks in advance

# Answer
The ship stays in place and everything moves. Mostly. In this answer I present three ideas of how to go about it, and I'm referencing the games I'm basing them on.

*I could not find out what approach they use for Subnautica. However, considering some of the physics glitches I've seen (note: I have not played Subnautica), I'm guessing they don't do much special about it. Except that when you are moving inside the submarine, the submarine is either not moving or moving slow enough that it usually is not a problem.*

---

A situation where we see something similar is elevators. Traditionally games where there is a fight in an elevator will actually have the elevator static, and move the environment (for example using vertex shaders).

A relatively recent example is the game Prey (2017) that has an scripted ambush in an elevator, but it was too glitchy for combat. So for the ambush, they made an stationary replica of the elevator and teleport the player to there, hiding the teleport in the light flicker.

Quotes from "The Making of PREY - Documentary" by NoClip:

> Stevan Hird: There was definitively an elevator that was a challenge. It went from being an elevator to being an elevator with combat experience in it. And trying to combine that with a lot of complex physics and some insane player power made with it.
>
> (…)
>
> You have a moving player on top of another moving object. And what happens when it wants to move, you know, the platforms wants to move at a certain speed, and gravity wants to shove something through it. Or it moves it from underneath you too quickly, and you don't want the player to fall. So you end up in this weird situation of trying to glue things to elevators so that physics doesn't go crazy.
>
> (…)
>
> Anthony Huso: The ambush, specifically, where you have that fight is not in the elevator. It's a fake second elevator. So when we do the power flickers, we're teleporting you into a fake elevator. That's where your combat takes place. And then once that thing is dead (…) we send you back to the other elevator and start it back.

**Idea 1:** When the player enters the ship, you teleport it to an stationary ship. Looking outside would require a camera trick: position a camera to look from the appropriate position in the world and render that. *Similar to what some games do for mirrors or portals. which you could archive rendering to textures or using the stencil buffer, or clearing the depth buffer.*

---

Some space games would usually do that for other reasons (namely to avoid floating point errors that scale in magnitude as objects move away from the origin). An example of this is Outer Wilds.

Quotes from "The Making of Outer Wilds - Documentary" by NoClip:

> Logan Ver Hoef: Each planet is a rigid body, like a physically simulated object moving through space, affected by forces. And so is everything else, like everything in the game is.
>
> (…)
>
> Alex Beachum: The way with video games you got to keep the camera near the center of the world's coordinate space. Or you start running into floating point error and everything starts kind of jittering. And so we have to keep the player near the mathematical origin of the world. And the way we do that in this game (…) every time we apply a force to the player, we just apply an opposite force to every physics object in the world that's currently simulating. And it doesn't actually really do anything to performance because we're already doing that. We're already applying forces to every object, because everything is moving. It just another number on top of numbers. So when you jump in Outer Wilds, technically every planet's jumping out from under you, and you're more or less not moving.

**Idea 2**: everything moves, except whatever object the player is standing on. This means that when the player is on the ship, the ship is actually stationary, and thus moving around inside of it not a big deal.

---

For a more interesting example, take Portal 2. This games has an intro sequence where the room is moving. For this the player is actually moving a controller in a separate room, and then the game applies impulses to the player character to mimic what the character controller is doing, but inside the moving room.

Quote from Portal 2 in game developer commentary:

> We solved the problem of trying to compute the player within this highly dynamic environment by putting them in a virtual room that has all the base shapes of the rendered container, but is simply used to compute player navigation. (It's hidden somewhere else in the map). The viewpoint of the player is then parented to the coarse simulation transform, resulting in the final rendered frame. At the end of the ride the player is teleported into the actual game space.

---

And yes, Sea of Thieves had to deal with that too. I believe they do physics in a replica of the ship which is stationary somewhere beneath the sea, but you see the meshes on top of the ship. At least we know they do that for navigation…

Quote from "How Megalodon, Kraken and Skeleton Ships Haunt the Sea of Thieves | AI and Games":

> The big secret is the navigation mesh for the ships isn't actually moving. It's baked deep into the ocean. The navigation mesh for the entire ship is baked into the deep down on the ocean floor and each skeleton is plotting their movement on that nav mesh. This nav mesh doesn't move with the ship and stays at a fixed point. Meanwhile each coordinate on the navitation mesh is transposed from the ocean floor into the ships deck and hull respectively. This has to factor the current orientation of the ship with regards to the oceans surface. Meaning the navigation paths need to follow the actual rotation of the ship as it crashes through a wave.

**Idea 3**: Combining what they did for Portal 2 and Sea of Thieves we would have a physical environment that does not move where all the collisions and navigation is resolved. However, what we actually see are meshes transformed into the ship space imitating what is happening in the physical environment.

---

All the ideas presented here have the ship actually stationary so they don't cause trouble to the physics engine. However, I guess you want the motion of the ship to have some effect inside. In that case you might also want to change the gravity strength and direction in the physical environment, so they match the combination of the acceleration of the ship and the gravity it is under.
> 17 votes

# Answer
The main issues here are, roughly:

1. Floating-point imprecision and catastrophic cancellation. An ordinary (single-precision) float has 23 bits of mantissa. Say you're moving at 1.0 m/s, and you add 1mm/s. You end up moving at 1.00100004673 m/s after float rounding, which is close enough. But say you're in a ship moving at 1000 km/s (1 million m/s) and you do the same thing. You end up moving at... 1.0 m/s relative to the ship. The 1mm/s got dropped entirely! This can lead to movement jitter, physics instabilities, clipping, etc.
2. Figuring out what frames of reference you should use in the first place. Easy in relatively 'static' configurations (e.g. player in ship in world); far more difficult in e.g. a sandbox builder.
3. Figuring out which frame of reference to use when targeting objects to build / place / etc. This is more of a problem if you're on something like a rail car where you have multiple objects moving close to each other (like the ground and rail car). In some situations you can end up in quasi-ambiguous cases where it's non-trivial to figure out if the object you're putting down should be attached to the rail car or the ground. (Preferring the result that is closest to the player's speed or frame of reference can be a sane default here).
4. Many game engines aren't really designed for this sort of thing, and e.g. assume that the entire game world fits within a float.

There are a couple of ways of dealing with this:

1. 'Simply' ensure that you have enough bits of precision to deal with the loss of precision due to cancellation (e.g. by limiting relative speed scales, or by moving to `double`).
2. Use synthesized quad (or higher) precision (always, or just where necessary). Almost never a good idea, but still worth mentioning.
3. Use double-double arithmetic (or extensions thereof) (always, or just where necessary). This is similar, but not identical to, 2.
4. Use fixed-point, sized to accommodate the worst-case. This is a good idea *anyways* for lockstep multiplayer, but has a bunch of problems and caveats (a lot of processors (and GPUs!) pour a lot of die area into floating-point processing, fixed-point library and compiler support tends to be worse than floating-point support, etc). (I've been half-jokingly considering using 256-bit integers for everything, in Planck units. It's a terrible idea for many reasons, but it's still amusing to think about.)
5. Do calculations relative to a local frame of reference, essentially 'moving the world instead of the player'. This doesn't solve the issue in the general case, but can often mask the issue (errors tend to mainly occur far from the player) while being relatively straightforward. Beware that this can cause problems for multiplayer if players aren't close enough together to share said local frame of reference.
6. Design your physics engine to handle (and do calculations in) nested coordinate systems. This is powerful, but can be... complex.

Also be aware that many of these issues can also affect *rendering*, not just physics.
> 3 votes

---
Tags: physics, rigidbody, physics-engine, rigid-body-dynamics, meshcollider
---


# Question
Title: "There is no Camera attached to the Game Object" error
I moved my Visual Scripting from an embedded graph into a State Machine graph as a file.

Suddenly started getting this error...

MissingComponentException: there is no Camera attached to the gameobject but a script is trying to access it.

The offending node is a Camera Screen to World Point.

There wasn't a Camera component attached to this gameobject previously and it worked (thr gameobject is under the Main Camera).

Any advice on what went wrong, and how to fix it?

# Answer
I had moved my Visual Scripting code from Embedded (in the GameObject) to Graph. By making it a separate Graph file, I had hoped that multiple GameObjects could use the same code.

But when I moved the code, the Camera input for my "Screen to World Point" node changed. It used to be set to "Main Camera", but now that option had disappeared and it was set to "This".

I went to change it back to Main Camera, but there was no option to do so. In fact, when I clicked to "Select Camera "... the entire Scene tab had disappeared, and along with it the Main Camera option.

I moved the same Visual Scripting code to being Embedded and the Main Camera option reappeared. All code working again!

Not sure how to move this code to a Graph and have the Camera still work, but that is a separate issue. Thank you to all who answered and commented and helped steer me to the answer!!
> 1 votes

# Answer
I suspect that it is the Camera which got untagged: for automatic code (Camera camera = camera.main; OR here visual scripting), it needs to be tagged.

In the editor, select the camera, scroll down the drop-down menu in front of tag, and select "Main Camera".
> 1 votes

# Answer
Reason: Your script is trying to get the camera component from a Game object but is unable to find it.

Solution: Inspect that the correct game object is assigned from which you want to access the camera component. If the component is correct then, check whether the camera component is attached or not.?
> 0 votes

---
Tags: unity, camera
---


# Question
Title: Unity HDRP Emissions - When setting over 1 nit, blue becomes progressively more purple
I've been trying to use a HDRP Lit Shader material to create an intense lighting effect in a dark environment.

I'm using a texture as an emission mask which is simply a 16x16 black png split into quadrants by blue borders.

When the emission intensity is greater than 1, the emission becomes more purple than blue.

This is how I've configured the material

I'm brand new to HDRP so if anyone could shed some light into this then that would be appreciated. When I was using the unity default renderer with 2 overlapping materials it was looking fine but I was looking into doing this with shader graphs so thought it might be worth upgrading to HDRP while I was at it

# Answer
In the sky and fog volume object, add an exposure override if it doesn't already exist. In the exposure override, set sane min and max limits and mode to automatic histogram.

Hope this helps anyone else who comes across this.
> 0 votes

---
Tags: unity, shaders, materials, hdrp
---


title: Metaverse Game - Scam?

text:
# Question
Title: Metaverse Game - Scam?
I hope you can help me. I have invested in a metaverse game project which claims that 5 people are working full time on the project for 2 years already. Unfortunately in the last couple of days one team member got accused that he has stolen money from the investors. On the other side this team member accuses the rest of the team that they are lying and that a 14 year old boy is programming the game. The investors have seen not many progress of the game so far, only a couple of short videos how someone drives in a car through the city. Now I am wondering if the game exists and if so is the game done with some kits or the parts are just bought. I saw that it is possible to buy for 100$ a metaverse world. Would an expert see if its bought? Which (technical) question can I ask to find out if they use a bought world and if everything is made from scratch? Btw. they have collected around 3.3 Millionen $ for the game from investors :D

Thanks in advance!

# Answer
**Would an expert be able to see if the world was bought?**

Maybe, but unlikely. It's possible that someone familiar with Unreal Engine 5 development & the market for related engine assets would recognize material they've seen before. The problem is that there's a lot of content out there. At the time of writing this, there are 1823 pieces of UE5 content available under the Environments tab in the Unreal Engine Marketplace. That doesn't include things like subcontracting the work out cheaply on freelance marketplace such as Fiverr.

If they've blatantly ripped off a well known show case piece from Epic (or something equally popular) making few to no changes, an expert would probably be able to spot it as a clone. It seems unlikely that a *single* expert would notice all possible recycled content. If *many* people saw the video the chance that someone might catch it increases. For instance, the discovery of stolen art assets in Stellaris: Galaxy Command.

**Which technical question could be used to determine if they used purchased assets or made the world from scratch?**

I would ask that question directly in an on-the-record setting / scenario.
> 2 votes

---
Tags: unreal-5
---


# Question
Title: Why do my image sprites only change after closing the run, instead of when I start the game?
Why do my image sprites only change after closing the run, instead of when I start the game?

What I mean by this is that, upon starting the run, it does nothing. But once I hit the play button to end the run, it suddenly changes the images of `shirtSpace` and `pantsSpace` in both the game window and editor?

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

public class ClothesScript : MonoBehaviour
{
    // Variables
    Image shirtRenderer;
    Image pantsRenderer;
    Sprite[] shirtArray;
    Sprite[] pantsArray;
    public GameObject shirtSpace;
    public GameObject pantsSpace;
    int currentShirtIndex = 0;
    int currentPantsIndex = 0;

    // Start is called before the first frame update
    void Start()
    {
        shirtRenderer = shirtSpace.GetComponent<Image>();
        pantsRenderer = pantsSpace.GetComponent<Image>();
        shirtArray = new Sprite[4];
        pantsArray = new Sprite[4];
        LoadArrays();
        UpdateShirt();
        UpdatePants();
    }

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

    }

    // LoadArrays is called by Start to fill the arrays
    void LoadArrays()
    {
        shirtArray[0] = Resources.Load<Sprite>("Shirt0");
        shirtArray[1] = Resources.Load<Sprite>("Shirt1");
        shirtArray[2] = Resources.Load<Sprite>("Shirt2");
        shirtArray[3] = Resources.Load<Sprite>("Shirt3");
        pantsArray[0] = Resources.Load<Sprite>("Pants0");
        pantsArray[1] = Resources.Load<Sprite>("Pants1");
        pantsArray[2] = Resources.Load<Sprite>("Pants2");
        pantsArray[3] = Resources.Load<Sprite>("Pants3");
    }

    // UpdateShirt is called by Start and whenever the currentShirtIndex is changed
    void UpdateShirt()
    {
        shirtRenderer.sprite = shirtArray[2];
        Debug.Log("Cleared Shirt");
    }

    // UpdatePants is called by Start and whenever the currentPantsIndex is changed
    void UpdatePants()
    {
        pantsRenderer.sprite = pantsArray[currentPantsIndex];
        Debug.Log("Cleared Pants");
    }

    // ShirtDecrease is called when ShirtLeftButton is clicked
    public void ShirtDecrease()
    {
        if(currentShirtIndex <= 1)
        {
            currentShirtIndex = 3;
        }
        else
        {
            currentShirtIndex--;
        }
    }

    // ShirtIncrease is called when ShirtRightButton is clicked
    public void ShirtIncrease()
    {
        if(currentShirtIndex == 3)
        {
            currentShirtIndex = 1;
            UpdateShirt();
        }
        else
        {
            currentShirtIndex++;
        }

        UpdateShirt();
    }

    // PantsDecrease is called when PantsLeftButton is clicked
    public void PantsDecrease()
    {
        if(currentPantsIndex <= 1)
        {
            currentPantsIndex = 3;
        }
        else
        {
            currentPantsIndex--;
        }
    }

    // PantsChange is called when PantsRightButton is clicked
    public void PantsIncrease()
    {
        if(currentPantsIndex == 3)
        {
            currentPantsIndex = 1;
        }
        else
        {
            currentPantsIndex++;
        }
    }
}

```

# Answer
It looks to me like you want something more like this:

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

public class ClothesScript : MonoBehaviour
{
    // Let's not repeat ourselves.
    // Make a class for all the code used by both shirt & pants, so we type it once.
    [System.Serializable]
    public class SpriteSwapper {
        // Assign this in the inspector, like you do with shirtSpace already.
        [SerializeField] SpriteRenderer renderer;

        // Likewise, assign your sprites in the inspector.
        // Avoid using Resources.Load()
        [SerializeField] Sprite[] sprites;

        int currentIndex;

        public void SetSprite(int index) {
            // Wrap the index into the bounds of the array
            // (-1 will go to the last item in the array, -2 the second last...)
            // I assume index >= -sprites.Length, but you can check/assert if needed.
            currentIndex = (index + sprites.Length) % sprites.Length;
            renderer.sprite = sprites[currentIndex];
        }

        // No need for separate Increase/Decrease methods.
        // Call CycleSprite(1) to step forward, CycleSprite(-1) to step backward.
        public void CycleSprite(int step) {
            // Because of the wrapping in SetSprite, this handles any step forward,
            // or a step as large as the full array length backward.
            SetSprite(currentIndex + step);
        }
    }

    // Now each clothing item is just an instance of that class.
    [SerializeField] SpriteSwapper shirt;
    [SerializeField] SpriteSwapper pants;

    // No searching to do - you can just initialize each swapper.
    void Start() {
        shirt.SetSprite(0);
        pants.SetSprite(0);
    }

    // If you want to maintain the same API, it's just one-liners now:
    public void ShirtIncrease() { shirt.CycleSprite( 1); }
    public void ShirtDecrease() { shirt.CycleSprite(-1); }
    public void PantsIncrease() { pants.CycleSprite( 1); }
    public void PantsDecrease() { pants.CycleSprite(-1); }
}

```

That's much less code, even with all my comments, and will scale better as you add more clothing items to swap. If you encounter a bug, you can fix it in one place and it will work the same for all clothing items, unlike your current code where it's easy to introduce an inconsistency between shirts and pants, as shown in your question:

```
void UpdateShirt()
{
    shirtRenderer.sprite = shirtArray[2]; // Always picks 2.
    Debug.Log("Cleared Shirt");
}

void UpdatePants()
{
    pantsRenderer.sprite = pantsArray[currentPantsIndex]; // Variable index.
    Debug.Log("Cleared Pants");
}

```
> 0 votes

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


# Question
Title: Memory usage of simple SDL2 program grows linearly
I am a newbie in SDL2 and I was testing an example code of Lazy Foo SDL tutorial just out of curiosity. The program renders an image named x.bmp living in the same folder as the program. Here’s the example program testsdl2.cxx:

```
/*This source code copyrighted by Lazy Foo' Productions (2004-2022)
and may not be redistributed without written permission.*/

//Using SDL and standard IO
#include <SDL2/SDL.h>
#include <stdio.h>

//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

//Starts up SDL and creates window
bool init();

//Loads media
bool loadMedia();

//Frees media and shuts down SDL
void close();

//The window we'll be rendering to
SDL_Window* gWindow = NULL;

//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;

//The image we will load and show on the screen
SDL_Surface* gXOut = NULL;

bool init()
{
  //Initialization flag
  bool success = true;

  //Initialize SDL
  if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
  {
    printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
    success = false;
  }
  else
  {
    //Create window
    gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
    if( gWindow == NULL )
    {
      printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
      success = false;
    }
    else
    {
      //Get window surface
      gScreenSurface = SDL_GetWindowSurface( gWindow );
    }
  }

  return success;
}

bool loadMedia()
{
  //Loading success flag
  bool success = true;

  //Load splash image
  gXOut = SDL_LoadBMP( "x.bmp" );
  if( gXOut == NULL )
  {
    printf( "Unable to load image %s! SDL Error: %s\n", "03_event_driven_programming/x.bmp", SDL_GetError() );
    success = false;
  }

  return success;
}

void close()
{
  //Deallocate surface
  SDL_FreeSurface( gXOut );
  gXOut = NULL;

  //Destroy window
  SDL_DestroyWindow( gWindow );
  gWindow = NULL;

  //Quit SDL subsystems
  SDL_Quit();
}

int main()
{
  //Start up SDL and create window
  if( !init() )
  {
    printf( "Failed to initialize!\n" );
  }
  else
  {
    //Load media
    if( !loadMedia() )
    {
      printf( "Failed to load media!\n" );
    }
    else
    {
      //Main loop flag
      bool quit = false;

      //Event handler
      SDL_Event e;

      //While application is running
      while( !quit )
      {
        //Handle events on queue
        while( SDL_PollEvent( &e ) != 0 )
        {
          //User requests quit
          if( e.type == SDL_QUIT )
          {
            quit = true;
          }
        }

        //Apply the image
        SDL_BlitSurface( gXOut, NULL, gScreenSurface, NULL );

        //Update the surface
        SDL_UpdateWindowSurface( gWindow );
      }
    }
  }

  //Free resources and close SDL
  close();

  return 0;
}

```

I compiled this with: `clang++ -std=c++20 -g -fsanitize=address -Wall -Wextra -Wpedantic -Werror -I/usr/include/SDL2 -lSDL2main -lSDL2 testsdl2.cxx -o vimbin`

Running the binary shows some memory leaks. Heard that address sanitizer sometimes produces false leaks reports so I decided to profile the memory usage of the binary. Here I am attaching the graph of memory usage:

I am using Ubuntu 20.04 LTS and I installed SDL2 by this:

`sudo apt install libsdl2-dev`

So what’s wrong with the program? Or is my SDL2 setup wrong? Or is it something wrong with the library itself? How can I get rid of the leaks? Just tell me if any additional information is needed.

# Answer
Oh looks like all this happened just because I compiled this in address sanitizer mode. The program is keeping track of every block of memory ever allocated or freed for as long as the program is running so of course its total memory usage is increasing over time. Because it’s got more short-lived temporary allocations to track forever the longer the application runs. This also explains why it starts up using such an absurd amount of memory for a program which is doing so little.

So I just removed `-fsanitize=address` from the compilation flags and it returned to normal flat memory usage.
> 3 votes

---
Tags: sdl2, linux
---


title: Does mesh contain a color?

text:
# Question
Title: Does mesh contain a color?
I'm developing a simple 3D engine for education purposes. I'm wondering whether a mesh contains a color of each vertex? Because I saw somewhere that mesh does not contain a color at all. If so, then where the color of a 3D model is stored? For example, if I have the mesh of a cube, how do I know in what color to paint each face of the cube, if they have different colors?

# Answer
A mesh can contain colours, but it is not required to.

The most common way to apply colour information to a model is using an image called a texture map (or just a "texture" for short). This lets you include tons of fine surface detail - limited only by the number of pixels in the image - even if the model itself has very few vertices or polygons.

To support texture mapping, each vertex of the mesh will store not just its position in 3D space, but also its position in the texture image - what we call a texture coordinate. This is normally a 2D vector whose horizontal component is called "u" and vertical component is called "v" (to distinguish them from the xyz we use for world space coordinates), so you'll also hear these referred to as "UV coordinates". The pattern of how a 3D mesh is unfolded to lie flat in the 2D coordinate space of the image is called a "UV unwrap" for this reason.

Here's an example of a 3D modelled barrel, and its corresponding texture map. You can see the surface of the barrel has been unfolded, like a papercraft model, to sit flat in the square space of the texture. And the texture allows us to paint or render-in super fine detail like wood grain, even given a coarse low-poly model.

Example from Renderography

The texture map - or maps, if the model uses several textures for different aspects of its appearance - will usually be stored in a separate image file, alongside the model data, rather than being encoded into the same file as the mesh. It's up to the game code to know which texture(s) to load for each mesh, and render them together appropriately - engines will usually have a "materials" system to handle this.

When rendering a triangle onto the screen, the texture coordinates from each corner of the triangle are interpolated over all the screen pixels covered by the interior of the triangle, and the pixel or fragment shader uses those interpolated coordinates to look up the colour from the corresponding location in the texture map, and use that in its shading calculations. This is called texture sampling.

It is also possible however to encode colours inside a mesh directly. These are called vertex colours, and they're just an extra channel of data stored for each vertex, just like the texture coordinates, but representing an RGB triplet or RGBA quartet instead.

These can be used directly to colour the model, or as a tint to apply on top of a texture as above. Or they can be repurposed entirely for all kinds of exotic effects \- as varied as the shader programs that use them.

The problem with storing colours inside the mesh this way is you get only one colour data point per vertex. That means you can't make a point or line or other shape show up in the middle of a triangle this way, without subdividing the triangle to put more vertices in the middle. This makes vertex colours best-suited for information that changes in a slow / low-frequency way across the surface of a model, or where fine detail isn't needed. So you'll see it used to apply ambient occlusion shading or other global illumination effects, or doing things like tinting the bottom of grass quads to blend into the terrain underneath. For finer surface detail like the woodgrain above, you really need a texture - or several!

It is also possible to procedurally synthesize surface detail purely within the math of the shader program, but this is more complex to set up and can be more costly in performance for realistic-looking results, so this tends to be used more sparingly, in specialized applications.
> 0 votes

---
Tags: mesh, color
---


# Question
Title: The performance gains of tiled rendering on mobile
I'm making an OpenGL es app on android and I'm trying to improve the performance of it.

I found this technique called tiled rendering (not the same thing as tiled deffered rendering\*) wich divides the screen into tiles and renders them one at a time. The idea behind this is that non-dedicated GPUs (such as mobile phone GPUs) don't have a lot of memory, so dividing the screen into tiles reduces the amount of info to be sent to the GPU. This way, it's able to do all the calculations at once (like depth calculation) and it doesn't wait for the CPU to send additional info to continue each step of the rendering.

There's a bunch of other optimisation on top of this, but I'm only talking about the basics.

To implement this, I would need to make a draw call for each tile.

My question is: does the memory optimisation outweigh the draw call number performance hit?

Also, is there something in OpenGL es to do it automatically? Is it done by default in the background?

\*Tiled Deffered rendering is only applied to the postshading after rendering the geometry. I'm talking about rendering the actual geometry on tiles.

# Answer
> 0 votes
After some research, it turns out that tiled based rendering is built in the hardware. Here's an article from PowerVR, a mobile GPU manufacturer to coroborate : https://blog.imaginationtech.com/a-look-at-the-powervr-graphics-architecture-tile-based-rendering/

---
Tags: 3d, rendering, opengl-es, mobile
---


# Question
Title: Listening for a Custom Trigger in a Preset (that will be instantiated in the scene)
I have a Preset that is listening for a Custom Event sent from the GameObject known as Magnet.

I can't set the Preset to listen for Magnet since the Preset isn't in the scene yet (it gets instantiated at Runtime). So I have it find the GameObject with the tag Magnet (there is only one).

Problem is that I'm using Visual Scripting and the Find GameObject with Tag node has a Green arrow output... so I have to link it to something, I believe.

Any advice on how to properly set this up?

# Answer
> I have a Preset that is listening for a Custom Event sent **from** the GameObject known as Magnet.

You can find the parameter description when creating a new node. This GameObject parameter is the target object of the event rather than the source object.

> Problem is that I'm using Visual Scripting and the Find GameObject with Tag node has a Green arrow output... so I have to link it to something, I believe.

You don't have to worry about this. It's an output control port. See this.

In some cases they are useless. When a running node tries to get the output value of another node, it will give him a cache of the results if it has already run, and will run it on the spot if it has not.
> 1 votes

---
Tags: unity
---


# Question
Title: Scaling and offset problems with screen space reflexion in DX11
I've transposed from OpenGL to DX11 a SSR ray marching shader (code found here : https://community.khronos.org/t/screen-space-reflections/69987). It seems to work well but I have had an initial problem of final scale for the mirrored stuff (see picture left). The first shader used is below.

(NOTE: i'm reconstructing at the moment the position from the depthmap (txPosition) which is slowing down a lot and I calculate on the fly the view normal as being camera position - pixel world position (InvLightProj.xyz - dPL.xyz in PS\_PostDeferredReflex) . Also the mirrored stuff is just the albedo (txDiffuse) for now):

```
 static const float rayStep = 0.25f;
 static const float minRayStep = 0.1f;
 static const int maxSteps = 5;
 static const float searchDist = 5.0f;
 static const float searchDistInv = 0.2f;
 static const int numBinarySearchSteps = 5;
 static const float maxDDepth = 1.0f;
 static const float maxDDepthInv = 1.0f;

 float3 BinarySearch(float3 dir, inout float3 hitCoord, out float dDepth)
 {
    float depth;
     float4 projectedCoord;
     for(int i = 0; i < 3; i++)
     {
         projectedCoord = mul(float4(hitCoord, 1.0), ViewProj);//use the projection matrix
         projectedCoord.xy /= projectedCoord.w;
         projectedCoord.xy = projectedCoord.xy * 0.5 + 0.5;
        float D = txPosition.Sample(samPoint, projectedCoord.xy).r; if ( D == 1 ) return float3(0,0,0);
        float4 dPL = float4(projectedCoord.x*2-1, (1-projectedCoord.y)*2-1, D, 1);
        dPL.xyz = float3(InvProj.x*dPL.x,InvProj.y*dPL.y, 1)/(InvProj.z*dPL.z+1);
        dPL = mul(dPL, InvView);depth = dPL.z;
        dDepth = hitCoord.z - depth;
         hitCoord += (dDepth > 0.0)?dir:0;
         dir *= 0.5;
         hitCoord -= dir;
     }
     projectedCoord = mul(float4(hitCoord, 1.0),ViewProj);
     projectedCoord.xy /= projectedCoord.w;
     projectedCoord.xy = projectedCoord.xy * 0.5 + 0.5;
     return float3(projectedCoord.xy, depth);
 }

 static const float reflectionSpecularFalloffExponent = 3.0;

 float4 RayCast(float3 dir, inout float3 hitCoord, out float dDepth)
 {
     dir *= rayStep;
     float depth;float4 projectedCoord;
     float4 Ray = float4(0.0f, 0.0f, 0.0f, 0.0f);
     for(int i = 0; i < maxSteps; i++)
     {
         hitCoord += dir;
         projectedCoord = mul(float4(hitCoord, 1.0),ViewProj);
         projectedCoord.xy /= projectedCoord.w;
         projectedCoord.xy = projectedCoord.xy * 0.5 + 0.5;
        float D = txPosition.Sample(samPoint, projectedCoord.xy).r; if ( D == 1 ) return float4(0,0,0,0);;
        float4 dPL = float4(projectedCoord.x*2-1, (1-projectedCoord.y)*2-1, D, 1);
        dPL.xyz = float3(InvProj.x*dPL.x,InvProj.y*dPL.y, 1)/(InvProj.z*dPL.z+1);
        dPL = mul(dPL, InvView);depth = dPL.z;
         dDepth = hitCoord.z - depth;
        Ray = float4(BinarySearch(dir, hitCoord, dDepth), 1.0);
        if(dDepth < 0.0) return Ray;
     }
     return Ray;
 }

 float4 PS_PostDeferredReflex(PS_INPUTQUAD Input) : SV_TARGET
 {
     float3 specular = txDiffuse.Sample(samPoint, Input.Tex).rgb;
     if(specular.r+specular.g+specular.b == 0.0) return float4(0.0, 0.0, 0.0, 0.0);
     float D = txPosition.Sample(samPoint, Input.Tex).r;    if ( D == 1 ) return float4(0,0,0,0);
     float4 dPL = float4(Input.Tex.x*2-1, (1-Input.Tex.y)*2-1, D, 1);
     dPL.xyz = float3(InvProj.x*dPL.x,InvProj.y*dPL.y, 1)/(InvProj.z*dPL.z+1);
     dPL = mul(dPL, InvView);
     if ( dPL.y > 1 ) return float4(0,0,0,0);
      float3 viewPos = InvLightProj.xyz;
      float3 viewNormal = (InvLightProj.xyz-dPL.xyz);
     // Reflection vector
     float3 reflected = normalize(reflect(normalize(viewPos), normalize(viewNormal)));
     // Ray cast
     float3 hitPos = viewPos;
     float dDepth;
     float4 coords = RayCast(reflected * max(minRayStep, -viewPos.z), hitPos, dDepth);
     float2 dCoords = abs(float2(0.5, 0.5) - coords.xy);
     float screenEdgefactor = clamp(1.0 - (dCoords.x + dCoords.y), 0.0, 1.0);
     // Get color
     float3 Color = txDiffuse.Sample(samPoint, coords.xy).rgb;
     float Spec = 1;//pow(specular, reflectionSpecularFalloffExponent);
     float EFactor = screenEdgefactor * clamp(-reflected.z, 0.0, 1.0);
     float Search = clamp((searchDist - length(viewPos - hitPos)) * searchDistInv, 0.0, 1.0) * coords.w;
     return float4(Color, Spec*EFactor*Search);
 }

```

new code for my mirror shader

```
static const float UVInc = 0.015f;
static const float UVIncL = UVInc*0.45f;

float4 PS_PostDeferredReflex(PS_INPUTQUAD Input) : SV_TARGET
{
     float D = txPosition.Load(int3(int(Input.Tex.x*ScreenX), int(Input.Tex.y*ScreenY),0)).r;
     if ( D == 1 ) return float4(0,0,0,0);
      float2 TexProj = float2(Input.Tex.x*2-1,1-2*Input.Tex.y);
      float4 PosVRef = float4(TexProj, D, 1);
      PosVRef.xyz = float3(InvProj.x*PosVRef.x,InvProj.y*PosVRef.y, 1)/(InvProj.z*PosVRef.z+1);
      float4 PosWRef = mul(PosVRef, InvView);
      if ( PosWRef.y > 1 ) return float4(0,0,0,0);
      float2 TexHit = Input.Tex;
      float2 Tex;
      float hit = 0;
      float2 TexProjCur = TexProj;
      TexProj = Input.Tex;
      float A = 0.5f;
      for (int i = 0; i < 150; i++)
      {
         TexProjCur.y+=UVInc;
         if ((TexProjCur.y < -1) || (TexProjCur.y > 1)) break;
         Tex = mad(TexProjCur, float2(0.5f, -0.5f), 0.5f);
         float D = txPosition.Load(int3(int(Tex.x*ScreenX), int(Tex.y*ScreenY),0)).r;
         if ( D < 1 )
         {
            float4 PosV = float4(TexProjCur, D, 1);
            PosV.xyz = float3(InvProj.x*PosV.x,InvProj.y*PosV.y, 1)/(InvProj.z*PosV.z+1);
            float4 PosWorldPix = mul(PosV, InvView);
            if ( PosWorldPix.y > 0 )
            {
                float4 MirrorPix = mul(PosWorldPix, Reflex_View_World);
                {
                     MirrorPix/=MirrorPix.w;
                     MirrorPix.xy = mad(MirrorPix.xy, float2(0.5f, -0.5f), 0.5f);
                     MirrorPix.y-=0.011f;//correction for PosWorldPix.y = 0 alignment default
                     if (abs(MirrorPix.y - TexProj.y) <= UVIncL)
                     {
                        hit = 1;
                        TexHit = Tex;
  //                    A = 0.5f-clamp(PosWorldPix.y/100, 0, 1);//activate to fade with height
                        break;
                     }
                 }
             }
          }
    }
    if ( hit < 1 ) return float4(0,0,0,0);
    float3 Color = txDiffuse.Load(int3(int(TexHit.x*ScreenX), int(TexHit.y*ScreenY),0)).rgb;
     return float4(Color,A);
 }

```

# Answer
After some time spent to work around this I have some results shown in the picture below. What I learnt was

1 : don’t forget GL uses projUV\*(0.5, 0.5) + 0.5 when DX uses projUV\*(0.5, -0.5) + 0.5

2 : how to produce a normalmap in view space (see lighting in camera space https://docs.microsoft.com/en-us/windows/win32/direct3d9/camera-space-transformations)

3 : the most important. Use texture.load instead of texture.sample to be able to iterate inside loop with dynamic branch as required for the ray marching algorithm (discussion on this here : https://gamedev.net/forums/topic/636473-load-vs-samplegrad/5015249/). As a collateral result it’s also much faster allowing longer loop sampling.

A first solution I found with ray marching (https://community.khronos.org/t/screen-space-reflections/69987) was difficult to set and at the end produced these “tubular” artifacts I cant’ remove (picture A). I found the code from McGuire better looking (picture C) but with some holes for overlapping objects when z does not match.

While working on that I had this simple idea to write a shader to reconstruct the mirrored position (panel B). The idea is that the mirrored uv coordinates of the mirrored pixel must match the uv coordinates of the current pixel that receive this mirrored pixel. Interestingly this code produces a result similar to the McGuire’ one but with some artifacts like the distorded orange plane and an approximate results when positionworld y=0 that I compensated. The code above was change to this mirror shader to show how I proceed. I’m interested if someone can help me improve it as for the binarysearch of ray marching. My attemps for this were moderately succesfull.

Finally the code from GitHub (https://github.com/RoundedGlint585/ScreenSpaceReflection/blob/master/shaders/SSRFragment.glsl) was identical to McGuire’ except it produces “vertical holes” (panel D). It's advantage is that it is the faster one.
> 0 votes

---
Tags: shaders, directx11, ssr
---


# Question
Title: How to set the UVs of a procedurally generated road mesh?
I want to create a road through a c# script in Unity. I created a mesh like this.

The "vertetices" first adds the left and then the right points. Then set the UV the same order and value as "vertetices". Then I got the following result. Figure 1 is the effect I generated, and Figure 2 is the effect I want.

The road may be less regular, such as a turning situation, but my texture is square, how do I need to display the texture properly?

```
using UnityEngine;
using System.Collections;
public class MeshHelper
{
    // Use this for initialization
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
    }
    /*
     *
     */
    private Vector3[] CreateVertices(Vector2[] leftBoundary, Vector2[] rightBoundary)
    {
        int index = 0;
        Vector3[] vertices = new Vector3[leftBoundary.Length + rightBoundary.Length];
        foreach (Vector2 coor in leftBoundary)
        {
            vertices[index] = new Vector3(coor.x, coor.y, 0.0f);
            index++;
        }
        foreach (Vector2 coor in rightBoundary)
        {
            vertices[index] = new Vector3(coor.x, coor.y, 0.0f);
            index++;
        }
        return vertices;
    }
    private Vector2[] CreateUV(Vector2[] leftBoundary, Vector2[] rightBoundary)
    {
        int index = 0;
        Vector2[] vertices = new Vector2[leftBoundary.Length + rightBoundary.Length];
        foreach (Vector2 coor in leftBoundary)
        {
            vertices[index] = new Vector2(coor.x, coor.y);
            index++;
        }
        foreach (Vector2 coor in rightBoundary)
        {
            vertices[index] = new Vector2(coor.x, coor.y);
            index++;
        }
        return vertices;
    }
    private int[] CreateTriangles(Vector2[] leftBoundary, Vector2[] rightBoundary)
    {
        if (leftBoundary.Length == 0 || rightBoundary.Length == 0)
        {
            return null;
        }
        int minLength = leftBoundary.Length > rightBoundary.Length ? rightBoundary.Length : leftBoundary.Length;
        int index = 0;
        int[] triangles = new int[3 * (leftBoundary.Length + rightBoundary.Length)];
        /*
         * Add the tran
         */
        for (int i = 0; i < minLength - 1; i++)
        {
            triangles[index] = i;
            triangles[index + 1] = i + 1;
            triangles[index + 2] = leftBoundary.Length + i;
            triangles[index + 3] = i + 1;
            triangles[index + 4] = leftBoundary.Length + i + 1;
            triangles[index + 5] = leftBoundary.Length + i;
            index += 6;
        }
        /*
         * Add the res tran
         *
         */
        if (leftBoundary.Length > rightBoundary.Length)
        {
            for (int i = 0; i < leftBoundary.Length - rightBoundary.Length; i++)
            {
                triangles[index] = rightBoundary.Length - 1 + i;
                triangles[index + 1] = rightBoundary.Length + i;
                triangles[index + 2] = leftBoundary.Length + rightBoundary.Length - 1;
                index += 3;
            }
        }
        else
        {
            for (int i = 0; i < rightBoundary.Length - leftBoundary.Length; i++)
            {
                triangles[index] = leftBoundary.Length - 1;
                triangles[index + 1] = 2 * leftBoundary.Length + i;
                triangles[index + 2] = 2 * leftBoundary.Length + i - 1;
                index += 3;
            }
        }
        return triangles;
    }

    /*
     * All road is quadrilateral
     *
     */
    public Mesh GetMesh()
    {
        HDMap.Boundary boundary = HDMap._instance.GetHDMap();
        // TODO: How to get uv ?
        Mesh mesh = new Mesh
        {
            vertices = CreateVertices(boundary.left, boundary.right),
            uv = CreateUV(boundary.left, boundary.right),
            triangles = CreateTriangles(boundary.left, boundary.right)
        };
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        return mesh;
    }
}

```

The coordinates are as follows

```
public class HDMap : MonoBehaviour
{
    public static HDMap _instance;
    public void Awake()
    {
        _instance = this;
    }
    public class Boundary
    {
        public Vector2[] left;
        public Vector2[] right;
    }
    public Boundary GetHDMap()
    {
        Vector2[] left ={
            new Vector2(0.0f,0.0f),
            new Vector2(0.1937856264412403f,0.049468484707176685f),
            new Vector2(0.3875712528824806f,0.09893696941435337f),
            new Vector2(0.5813568793237209f,0.14840545412153006f),
        }

        Vector2[] right={
            new Vector2(-0.8656984844710678f,3.391248462256044f),
            new Vector2(-0.6718908273614943f,3.4407225707545877f),
            new Vector2(-0.47808317036833614f,3.4901966797187924f),
            new Vector2(-0.28427551325876266f,3.539670788217336f),
        }
        Boundary boundary = new Boundary();
        boundary.left = left;
        boundary.right = right;
}

```

# Answer
You are setting the UV coordinates to exactly the same coordinates as the vertices. That means when you move a vertex, the texture doesn't move. It always stays perfectly aligned with the world grid. What you actually want is for the texture to stretch and skew so that it always fills the whole road polygon.

So what you need to do is set the UV coordinates of every road square to a full texture ranging from `(0, 0)` to `(1, 1)`. Looking at the first sketch you posted in the question, the UV coordinates of the first road segment should be:

```
1: (0, 1)
2: (0, 0)
7: (1, 0)
6: (1, 1)

```

Then the texture should repeat in the second segment of the road:

```
2: (0, 1)
3: (0, 0)
8: (1, 0)
7: (1, 1)

```
> 3 votes

# Answer
For the u coordinate - set it to be 0 for every vertex on the left boundary and 1 for every vertex on the right boundary.

For the v coordinate - measure the distance along the boundary. So start with v=0 at vertex 1, then at vertex 2 set v = d(1,2) the distance from vertex 1 to vertex 2. Then at vertex 3 set v = d(1,2) + d(2,3). And so on for each vertex. This method works for curved roads as well as straight ones, and your texture will always look correctly proportioned.
> 0 votes

---
Tags: unity, textures, procedural-generation, uv-mapping
---


# Question
Title: Rotating an object in a circular path (using time)
I want to move an object in a circular path but I want it to complete its movement in that circle when the time ends.

I tried doing this:

```
p.tmy = p.tmy + p.duration/p.radius
p.x0 = p.radius * math.cos(p.tmy + 0.025)
p.x1 = p.x0 * math.cos(p.tmy) -  0 * math.sin(p.tmy)
p.y1 = p.x0 * math.sin(p.tmy) +  0 * math.cos(p.tmy)

```

The issue is that it's too slow or too fast & doesn't complete the circle on time.

# Answer
> 0 votes
First, you need to calculate how much progress you should have made as a function of time.

Let's say your total amount of time you have to complete the rotation is \\$T\\$ & the amount of time travelled so far is \\$t\\$.

Then \\$\frac{t}{T}\\$ gives you a number between 0.0 & 1.0 indicating how much progress you should have made. For instance, if your time limit is 10 second & you have been moving for 8 seconds, then you know you need to have covered 80% of the rotation.

Next, you need use the relative progress to determine how far you've rotated. There are \\$360^\circ\\$ in a circle which is is equivalent to \\$2\pi\\$ radians. Since the math functions use radians, we'll use that for our math as well.

\\$\frac{2\pi t}{T}\\$ is the relative amount of the rotation. This is literally just multiplying your progress % by the total possible radians required for rotating. For instance, using the 8 of 10 seconds example from before, you would have travelled about 5.0265 radians or \\$288^\circ\\$.

Plugging that math into your cos & sin functions will give you the X & Y coords on the unit circle. From there you can scale & translate as needed.

For instance, if your circle is centered on `cx,cy` and has a radius of `r`, you would have something like the following:

```
x = math.cos(2*math.pi*t/T) * r + cx
y = math.sin(2*math.pi*t/T) * r + cy

```

---
Tags: lua
---


title: How to center a tilemap in Phaser?

text:
# Question
Title: How to center a tilemap in Phaser?
In Phaser, I am loading a Tilemap from JSON.

I would like my Tilemap to display in a particular position (for simplicity here I say the middle of the screen).

```
var map = this.game.add.tilemap('level');
map.addTilesetImage('tiles2', 'tiles2');
var layer = map.createLayer('Ground', map.widthInPixels, map.heightInPixels);
layer.anchor.set(0.5);

//this does not work...
layer.position.set(this.world.centerX, this.world.centerY);

//or even
layer.x = this.world.centerX;
layer.y = this.world.centerY;

```

The `anchor.set` works as it should however setting the position does not seem to work.

What am I doing wrong?

# Answer
> 5 votes
I found out why it was not working... I needed to do this:

```
layer.fixedToCamera = false;
```

# Answer
> 0 votes
If you create rectangles for the tiles, the origin is not from the left upper corner, they start from the middle. if you create a tile in Phaser and set his position to x:0,y:0 with 32\*32 size it is only 16\*16 large, because you need to set it at x:width/2, y:height/2

# Answer
> 0 votes
I'm using Phaser 3.55, and I'm using a newly introduced isometric tilemap. The trick is to move the camera, rather than the tilemap itself:

```
this.cameras.main.scrollX = -this.map.widthInPixels / 2;
this.cameras.main.scrollY = -this.map.heightInPixels / 2;

```

# Answer
> -2 votes
```
layer.position.set(this.game.world.centerX, this.game.world.centerY);

```

---
Tags: javascript, tilemap, phaser
---


# Question
Title: Unity tilemap WorldToCell returns floored world position
I have a tilemap that is filled with tiles by script. That works well so far. Now my aim is to make the tiles interactable by making them clickable.

I achieved this by adding an EventSystem object under the tilemap, adding a Physics 2D Raycaster component to the camera and then impementing IPointerDownHandler.OnPointerDown(..) in my script.

But here is the problem: I need to get the tile at the position that is clicked. As far as I read, this should easily be possible by calling the tilemaps WorldToCell function and then using the cell position to get the tile from the tilemap. However WorldToCell does only return me the floored world position instead of the cell position inside the tilemap.

My OnPointerDown function looks like this:

```
void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
{
    Debug.Log("Clicked at " + eventData.position.x + ", " + eventData.position.y);

    Tilemap tilemap = gameObject.GetComponent<Tilemap>();
    Vector3Int cellPos = tilemap.WorldToCell(new Vector3(eventData.position.x, eventData.position.y, 0));
    Debug.Log("Clicked at " + cellPos.x + ", " + cellPos.y);
}

```

If I click on a tile then then output on console looks like this:

```
Clicked at 1379,554, 275,0186
Clicked at 1379, 275

```

Can someone tell me what I got wrong or how WorldToCell actually works? I searched far and wide but none seems to have the same problem.

# Answer
> 2 votes
`PointerEcentData.position` is a screen position rather than a world position. See EventSystems.PointerEventData-position :

> The position value is window-based. This is zero-zero bottom left.

So you can convert it to world postiion first, using Camera.ScreenToWorldPoint :

```
var worldPos = Camera.main.ScreenToWorldPoint(eventData.position);
Vector3Int cellPos = tilemap.WorldToCell(worldPos);

```

---
Tags: unity, 2d, tilemap, grid
---


# Question
Title: If I have a number of nested GameObjects tagged with a particular phrase, how can I select the tagged GameObject one level above the bottommost child?
For my Unity project, I have a standard GameObject: it's an animal with 3 GameObjects nested under it (called Neem, Feem and PrintState). There are 6 Animals in my Hierarchy at the moment.

* Snake
* Tiger
* Goat
* Zebra
* Narwhal
* Fox

These Animal GameObjects are all tagged "ANIMAL".

In the attached screenshot, there are 3 Animal GameObjects nested under each other: the Snake is in the top level, and then Tiger nested below it, and Goat below that. The other 3 Animal GameObjects are all in the root.

In my data model, Animals are either in the root level or nested as only children. No Animal can ever have more than one child nested below it. (In practical terms, there would only usually be up to 5 or so Animals nested under another Animal - but that probably doesn't matter here.)

Here's the situation: If I ask Unity to look under the Snake GameObject... I'd like to get the bottommost animal GameObject nested under it. In this case of Snake, the bottommost animal GameObject would be Goat. (I wouldn't want any of the GameObjects under Goat - I want to ignore those for the purpose of this search.)

If I told Unity to look under Zebra... I'd like to get the Zebra. (Again, I'd want to ignore the 3 non-Animal GameObjects.)

Is there a way I can count the GameObjects tagged ANIMAL under a given other GameObject? Or another way to address this more directly, and get returned the bottommost GameObject tagged Animal?

Thanks!

# Answer
> 1 votes
Instead of a tag, I'd use a marker component, something like this:

```
public class Animal : MonoBehaviour {

    static Animal GetDeepestAnimal(GameObject initial) {
        if (!initial.TryGetComponent(out Animal child))
            return null;

        Animal parent;
        do {
            parent = child;
            child = parent.GetComponentInChildren<Animal>();
        } while (child != null);

        return parent;
    }
}

```

Place an `Animal` component on each animal game object.

Now you can call `Animal.GetDeepestAnimal(someGameObject)` to find the most deeply nested animal component in its child hierarchy, which in turn gives you access to its game object.

---
Tags: unity
---


# Question
Title: How do I detect if a player is touching the empty screen in Unity?
I'm making a simple puzzle game.

I can very easily detect if a player touches my GameObjects, by turning on colliders and using OnMouseDown.

In my game, when a player touches a GameObject... that GameObject starts a particular action.

The most intuitive way for a player to stop that action is to just touch anywhere on the screen other than that particular GameObject (like say, the empty screen). That way the game will know that the GameObject has no longer been selected.

How can I detect if someone has touched an empty screen?

# Answer
The quick way for rapid prototyping would be to simply have an object that can react on clicks as well on your background. Just because the user thinks the background is empty does not mean you can't have an object there that reacts on clicks.

This could of course cause some other problems as well if it ever gets rendered on top of all your other objects. But for a start it is good enough to get it running and focus on the other parts.
> 2 votes

# Answer
Just set a boolean `clickedMe` in `OnMouseDown` if this object was the one clicked on. If you get to `Update` and `Input.GetMouseButtonDown(0)` says there was a pointer click this frame, but `clickedMe` is false, then that click must have been on another object or no object at all.

```
bool clickedMe;
bool amSelected;

void OnMouseDown() {
    clickedMe = true;
    amSelected = true;
}

void Update() {
    if (Input.GetMouseButtonDown(0)) {
        if (clickedMe) {
            // Reset to false to use in future frames.
            clickedMe = false;
        } else {
            // Clicked elsewhere - deselect me.
            amSelected = false;
        }
    }
}

```

A more robust and efficient solution is to make your own pointer interaction script with just a single instance in the scene. When the mouse is clicked, fire a ray to see what it hit. You can then store that object as the last touched target, and let it know that it's been deselected if a later click ray hits nothing / another object. This way you have just one script polling input every frame, not multiple, and you can centralize management of selected objects, different selection modes, etc.
> 0 votes

---
Tags: unity
---