title: Weird Lines in my Unity Android Build

text:
# Question
Title: Weird Lines in my Unity Android Build
So I've been getting this weird bug in the Android build of this game I'm working on. There are these weird lines that all over the place. As far as I can tell, this is a visual bug. Like something wrong with a shader or the camera settings or something but I can't quite figure it out completely. Please help out if you can.

TIA.

I've attached pictures. The ones with the lines are from my phone and the one without is from the Unity Editor.

# Answer
> 2 votes
Z-fighting is a visual artifact that occurs when two or more objects in a 3D scene occupy the same space and compete to be rendered on the screen. This competition results in flickering, shimmering, or distorted textures, making it difficult to distinguish between the objects.

Z-fighting is primarily caused by limited precision in representing depth values in computer graphics. In a 3D rendering pipeline, each pixel on the screen is associated with a depth value, also known as a Z-value, which represents the distance from the camera. When multiple objects have similar or overlapping Z-values, the renderer struggles to determine which object should be displayed in front, leading to the visual glitch.

To address Z-fighting, there are several solutions you can try. One common approach is to increase the distance between the objects that are experiencing the issue. By doing so, you provide more space for the depth buffer to differentiate between the objects, reducing the likelihood of Z-fighting. However, this solution may not always be feasible or practical.

For a more comprehensive understanding of Z-fighting and its solutions in Unity, you can refer to the following link: Unity Z-Fighting Solutions. This resource provides additional insights and techniques to mitigate Z-fighting issues in your Unity projects.

Remember, it's always recommended to analyze your specific scenario and experiment with different approaches to find the most suitable solution for your particular case.

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


# Question
Title: How to set GameObject on tilemap through script
In the built in Tile Palette tilemap editor, you can choose a GameObject brush to set custom tile GameObjects. How would I be able to set a gameObject onto a tile through a script?. There is no function for this in the tilemap class, or at least the documentation does not mention anything, so how would this work?

**Details:**

I have a few prefabs that I would like to use the "gameObject brush" on; I also have a tilemap ready to place the tiles.

# Answer
> -1 votes
You can utilize the Prefab Brush tool for your purpose. There are various tutorials available on YouTube that can guide you through its usage.

By default, selecting the prefab brush from the menu can be challenging. Therefore, I developed a tool to simplify the visualization process. Since I couldn't use the TileMap Palette, I created a custom palette to achieve the desired results.

You can find the Prefab Painter tool on GitHub at the following link: https://github.com/smkplus/prefab-painter. It provides a more intuitive approach to working with prefabs in your Unity projects.

In the provided link, you'll also find an image demonstrating the tool's interface:

Additionally, there is a GIF showcasing the tool in action:

Feel free to explore the Prefab Painter tool and experiment with its features to enhance your prefab workflow.

---
Tags: unity, c#, tilemap, tiles, gameobject
---


title: Blending in 3D graphics

text:
# Question
Title: Blending in 3D graphics
I studying DirectX blending. Please explain what is Src and Dest. For example I have drawn scene - it's Src as I suppose. And on this scene I now puting box - it's Dest in blending, as I guess. And I process blending my previous scene Src with my box Dest. Or what?

# Answer
The buffer starts with the color/skybox/whatever you've cleared it with.

After that, for each render pass

* sourceValue is the value output by the fragment shader.
* destinationValue is the value already in the buffer.

So you're choosing how to blend the thing you're rendering (src) with what's already been put in the buffer (dst) by any previous passes.
> 2 votes

---
Tags: directx
---


# Question
Title: Is there some psychological reason for why most game's UI is always the same colors?
Shooter games : Either Blue/teal/azure or other shades of blue and transparent or gray and transparent

MMO games : Either blue and transparent or shades of Brown+Gold or a very dark red, so dark it's almost brown

Mobile and Browser RPGs : Cutsie icons and everything is green, brown and shiny with a little bit of blue

Source: Search image... google "MMO UI" or "RPG UI" and everything is either transparent or brown for example

just search any genra of game by UI and your google page will almost look like an array of identical images.

Is this there only because players are used to certain types of UI? Like how back in the day, talking decades ago.... some RPGs used Blue for health and green for energy or red for your teams health bars and blue for the enemy health bars simply because no one was used to the colors we consider normal today so any color scheme was ''normal" at the time?

or is there simply a psychological reason for these color schemes dedicated to certain game genras?

I'm asking because I'm making an rpg game, I'm making the UI now , and I just noticed that I never played a single rpg game that deviated from the standard rpg ui colors...

# Answer
When picking a color palette for your game UI, there are several considerations:

* Fitting with the theme of the game. If you have a medieval fantasy game, then the UI color scheme should communicate "old". So you often see colors creating associations with wood, leather, old paper and rough stone. If you have a science fiction game, the UI color scheme should communicate "modern". So you often have grays and blues.
* Fitting with the overall aesthetics of your game. If the diegetic visuals of your game are oriented at a specific color palette, then you want your UI to have the same palette to ensure an overall consistent aesthetic. How to pick a color palette for a game, why it is so important and how to apply it is a whole other topic one could write several paragraphs about. But needless to say that the one place where it is the easiest to apply is the UI.
* Readability. On the other hand, you don't want the UI to look too similar to the background it is displayed on, because then it might no longer look visually distinct enough to get the players attention. Finding the right balance between standing out enough to be visible but not so much as to feel out of place is a delicate matter. This is where good art direction comes into play.
* Following conventions of the platform and genre. Most new players will have experience with other games on the same platform and/or in the same genre. Building on established design language and patterns greatly accelerates the onboarding process for these players. There are several reason why mobile UIs look so different from PC UIs. One of them is that the player does not have a mouse cursor. The UI can't communicate what's interactive through mouse hover, so anything that can be pressed must look explicitly pressable. Which is why buttons in mobile games tend to look very "buttony", while PC game menus can get away with a simple piece of clickable text with no decoration whatsoever.
* Accessibility for people with color blindness. Perhaps the most important here is red/green color blindness. Especially when you target a predominantly male demographic, because about 9% of genetically male people have trouble differentiating red and green. Other color visibility conditions are rarer, but not to be neglected either.
* Good artists copy, great artists steal! When there is already a game on the market you aspire to live up to, then why not ~~blatantly rip off~~ take some inspiration from their design?

All these considerations (with the exception perhaps of picking a distinct color palette) result in UI artist gravitating towards the same color choices.
> 8 votes

# Answer
> I'm making an rpg game, I'm making the UI now , and I just noticed that I never played a single rpg game that deviated from the standard rpg ui color

This is intended to ease knowledge transfer. When using the a symbol (or a color in this case) to represent something, it poses less friction to the players if they are consistent with other games, as that means less time learning your game.
> 4 votes

# Answer
My thoughts would be that people like familiarity, and it's easier to get into a game (or other medium) if you can quickly recognise them.

This extends a bit further than just colors and color shemes, as it also applies for icons, terms, atmosphere, game mechanics and more. Color is just a part of that grander scheme.

Changing the colors usually applies to the game's overall style. For example: Overwatch, who displays health in many colors, like white, orange and blue, but not Red. This is fitting because the whole game's color code is more like white, orange and blue.
If a game looks more like a traditional RPG, but the health looks blue instead of red, then I would wonder if such change was necessary, and if there was a reason behind it. (though, you could take that opportunity to add a bit of lore to the game).

I don't think it's a rule to hold on to these color patterns. But striving away from it to make it less familiar/more unique is a risk on the game's appeal.
> 2 votes

---
Tags: game-design, gui, rpg, design-patterns, ui-design
---


# Question
Title: Can I just convert everything in godot to C#
Does godot 3.5.1 support C# fully ? Like does C# for godot have all the same methods that GDscript has?

I'm asking because I remember trying to learn gamedev a long time ago with C++, I was overwelmed with having to define every single basic thing from the graphics to normalizing fps, diagonal movement and don't get me on 3D stuff... I've never used it again since then.

The creators of Godot said through their own tests C# is 4 times faster than GDscript.... So I'm asking now, once I finish my game in GDscript is it possible to just take all the scripts and change them to C#? will all the methods used be the same?

I don't care if it is tedious and slow work, Ain't got the biggest brain, all I care is that it is easy work.

My game as it is consumes only 3% to 10% of my cpu and 5% to 20% of my gpu even on havier scenes and I have a really bad laptop... so for now performance is not a problem... but you never know... I mean.... 4 times faster! it could probably run on a toaster.

# Answer
The Godot C# documentation provides an incomplete list of the API differences between C# and GDScript. There are some difference in the methods & properties names. Additionally, some things in C# work differently than they do in GDScript. For example,

GDScript uses `onready` to defer the initialization of a member variable until the ready function is called. However C# does not have this ability and to work around the issue you need to override the `_Ready()` in the item of interest to perform the necessary initialization. So where you might do the following in GDScript:

```
onready var my_label = get_node("MyLabel")

```

The C# version would look like this:

```
private Label _myLabel;

public override void _Ready()
{
    _myLabel = GetNode<Label>("MyLabel");
}

```

Similarly, `preload` isn't available in C# and some work arounds are required to get the same functionality.

However, it's probably worth fact checking some of the differences. For instance, the documentation mentions in several places that C# doesn't support parameterless constructors for structs. As mentioned in the comments, this was recently added in C# 10. Since Godot already has an official alternative you may want to stick with that, but it may be the case that embracing changes to C# make more sense depending on your situation and context.

> Can you take all the scripts and change them to C#?

Generally yes, though the work will vary depending on the nature and complexity of the scripts.

> Will all the methods used be the same?

No.

As alluded to in the comments, translation isn't a silver bullet solution for optimization. If you want to improve your performance, profile your code.
> 12 votes

# Answer
Pikalek answer is correct. I'll expand a bit about the performance and the translation process.

---

I want to point out that C# will give you more optimization avenues than GDScript, because C# has typed dictionaries, supports passing by reference,defining custom structs, etc.

*C# has other perks not available in GDScript, for example interfaces.*

Be aware that C# - as GDScript - run on the CPU, so the GPU should remain the same.

---

Furthermore, I want to point out that this is not an all or nothing conversion, as Godot support having both GDScript and C# on the same project.

My recommendation is to have GDScript call into C#, this is because the integration of GDScript with Godot is better (having syntax for easy node access, and for exporting variables to the inspector).

One gotcha you will stumble upon the interaction between C# and GDScript is that they can't consume each other async methods. However, GDScript `yield` can work with a method that returns objects that emit signals, and you can `await` signals on C# with `ToSignal`. Thus, you might want to refactor any asynchronous operations in the boundary between C# and GDScript to use signals for communication.

Because of this, you can translate your project from GDScript to C# by parts. However you need to choose carefully the boundary for your translation.

---

Another thing to keep in mind is that C# is an static typed language.

Even if you decide to use `dynamic` in C#, GDScript duck typing is more convenient for dynamically typed code (usually if you rely on duck typing in GDScript, you would want to define interfaces in C#).

Thus you might find helpful to specify the types of as much of the GDScript code as possible before attempting to translate to C#. At least when C# and GDScript interact, you need the methods to have their return and parameters types specified.

The Godot editor will help you identify which lines are not fully typed... Pay attention to the color of the line numbers. If the color is pale, the line is not fully typed.

*By the way, you don't have to specify all types explicitly. As in GDScript you can use implicit typing, by initializing variables with `:=` instead of `=` (this is similar to using `var` in C# or `auto` in C++).*

Anyway, as you would know, you cannot have everything fully typed in GDScript (e.g. GDScript does not have typed dictionaries, as mentioned earlier), but as long as you can tell the types even when the code is not fully typed, you should be able to translate to C#.

---

I'll close by saying that even though C# is fully supported in Godot, since C# integration with the Godot editor is inferior, you will want to move to an external editor for C#, which might give you proper IntelliSense, refactoring options, and so on.
> 11 votes

---
Tags: c#, 3d, performance, opengl-es2, godot-3
---


# Question
Title: Why when creating a grid for example 10x10 and drawing a random path the path is sometimes diagonal sometimes crossover the path and sometimes curved?
```
using UnityEngine;

public class RandomPathGenerator : MonoBehaviour
{
    public int gridSize = 10;
    public int minPathLength = 5;
    public int maxPathLength = 10;
    public float squareSize = 1f;
    public Color pathColor = Color.red;
    public Color startColor = Color.green;
    public Color endColor = Color.blue;
    public float startEndRadius = 0.4f;

    private Vector2Int[] directions = { Vector2Int.up, Vector2Int.down, Vector2Int.left, Vector2Int.right };

    private Vector2Int startPoint;
    private Vector2Int endPoint;
    private Vector2Int[] path;

    private void OnGUI()
    {
        if (GUI.Button(new Rect(10, 10, 100, 30), "Generate Path"))
        {
            GenerateRandomPath();
        }
    }

    private void GenerateRandomPath()
    {
        ClearGrid();

        startPoint = GetRandomPointOnEdge();
        endPoint = GetRandomPointOnDifferentSide(startPoint);

        int pathLength = Random.Range(minPathLength, maxPathLength);
        path = new Vector2Int[pathLength];
        path[0] = startPoint;
        path[pathLength - 1] = endPoint;

        for (int i = 1; i < pathLength - 1; i++)
        {
            path[i] = GetRandomValidNeighbor(path[i - 1]);
        }
    }

    private Vector2Int GetRandomPointOnEdge()
    {
        int side = Random.Range(0, 4); // 0: Top, 1: Right, 2: Bottom, 3: Left

        int x, y;

        switch (side)
        {
            case 0: // Top edge
                x = Random.Range(0, gridSize);
                y = gridSize - 1;
                break;
            case 1: // Right edge
                x = gridSize - 1;
                y = Random.Range(0, gridSize);
                break;
            case 2: // Bottom edge
                x = Random.Range(0, gridSize);
                y = 0;
                break;
            case 3: // Left edge
                x = 0;
                y = Random.Range(0, gridSize);
                break;
            default:
                x = 0;
                y = 0;
                break;
        }

        return new Vector2Int(x, y);
    }

    private Vector2Int GetRandomPointOnDifferentSide(Vector2Int point)
    {
        int side = Random.Range(0, 3); // 0: Top, 1: Right, 2: Bottom

        int x, y;

        switch (side)
        {
            case 0: // Top edge
                x = Random.Range(0, gridSize);
                y = gridSize - 1;
                break;
            case 1: // Right edge
                x = gridSize - 1;
                y = Random.Range(0, gridSize);
                break;
            case 2: // Bottom edge
                x = Random.Range(0, gridSize);
                y = 0;
                break;
            default:
                x = 0;
                y = 0;
                break;
        }

        if (side % 2 == 0) // Top or Bottom side
        {
            if (point.x == x)
            {
                x = (x + 1) % gridSize;
            }
        }
        else // Right side
        {
            if (point.y == y)
            {
                y = (y + 1) % gridSize;
            }
        }

        return new Vector2Int(x, y);
    }

    private Vector2Int GetRandomValidNeighbor(Vector2Int point)
    {
        Vector2Int neighbor;

        do
        {
            neighbor = point + directions[Random.Range(0, 4)];
        }
        while (!IsValidPoint(neighbor) || IsPointOnPath(neighbor));

        return neighbor;
    }

    private bool IsValidPoint(Vector2Int point)
    {
        return point.x >= 0 && point.x < gridSize && point.y >= 0 && point.y < gridSize;
    }

    private bool IsPointOnPath(Vector2Int point)
    {
        for (int i = 0; i < path.Length; i++)
        {
            if (path[i] == point)
            {
                return true;
            }
        }
        return false;
    }

    private void OnDrawGizmos()
    {
        DrawGrid();
        DrawPath();
        DrawStartAndEndPoints();
    }

    private void DrawGrid()
    {
        Gizmos.color = Color.white;

        for (int x = 0; x < gridSize; x++)
        {
            for (int y = 0; y < gridSize; y++)
            {
                Vector3 squarePos = new Vector3(x * squareSize, y * squareSize, 0f);
                Gizmos.DrawLine(squarePos, squarePos + new Vector3(squareSize, 0f, 0f));
                Gizmos.DrawLine(squarePos, squarePos + new Vector3(0f, squareSize, 0f));
            }
        }

        Gizmos.DrawLine(new Vector3(gridSize * squareSize, 0f, 0f), new Vector3(gridSize * squareSize, gridSize * squareSize, 0f));
        Gizmos.DrawLine(new Vector3(0f, gridSize * squareSize, 0f), new Vector3(gridSize * squareSize, gridSize * squareSize, 0f));
    }

    private void DrawPath()
    {
        if (path == null)
            return;

        Gizmos.color = pathColor;

        for (int i = 0; i < path.Length - 1; i++)
        {
            Vector3 center1 = new Vector3(path[i].x * squareSize + squareSize * 0.5f, path[i].y * squareSize + squareSize * 0.5f, 0f);
            Vector3 center2 = new Vector3(path[i + 1].x * squareSize + squareSize * 0.5f, path[i + 1].y * squareSize + squareSize * 0.5f, 0f);

            Gizmos.DrawLine(center1, center2);
        }
    }

    private void DrawStartAndEndPoints()
    {
        if (startPoint == null || endPoint == null)
            return;

        Vector3 startPointPos = new Vector3(startPoint.x * squareSize + squareSize * 0.5f, startPoint.y * squareSize + squareSize * 0.5f, 0f);
        Vector3 endPointPos = new Vector3(endPoint.x * squareSize + squareSize * 0.5f, endPoint.y * squareSize + squareSize * 0.5f, 0f);

        Gizmos.color = startColor;
        Gizmos.DrawWireSphere(startPointPos, startEndRadius);

        Gizmos.color = endColor;
        Gizmos.DrawWireSphere(endPointPos, startEndRadius);
    }

    private void ClearGrid()
    {
        startPoint = Vector2Int.zero;
        endPoint = Vector2Int.zero;
        path = null;
    }
}

```

The result when clicking the button:

the red drawn path is diagonal on the left image. in the middle image the path is diagonal and also cross over the path itself and also the start and end points on the same side of the grid. on the right another example.

what I want to make is that the start/end point will never be the same on the same side of the grid. the random path must be up,down,left,right directions not diagonal and never cross over itself.

# Answer
Those funny paths are because your idea is \[what's a nice word for doesn't work work and can't be made to work -- need to start over?\] Your middle picture is a good example: it rolled a "5" for length. From the green-square starting space it goes 5 steps then stops in the middle of the grid. It appears to move diagonally through 3 squares after that, but it doesn't. It actually jumps to the final square because you added it to the end. The actual path is something like (0,0) (0,1) (1,1) (2,1) (2,2) (1,2) (0,4). Print it out to check.

The code is unfixably broken since nowhere in the code does it try to end at the blue sphere. It just wanders randomly. In fact, it could curve in on itself and get stuck in getRandomValidNeighbor since all 4 neighbors could be on the path. Making it try to reach the target in X moves involves figuring out how far it is away and how many extra spaces it need to use up. For example, if the end is 8 spaces away and it has 20 more path to use up it should prefer moving in a direction "away" from the end; but if it has 8 spaces left it needs to move in either direction towards the target. And then you'd still need to account for getting stuck.
> 0 votes

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


title: Rendering Infinite 2D chunks?

text:
# Question
Title: Rendering Infinite 2D chunks?
I'm working on a top-down 2D RTS with C++ and SDL2, and have implemented the biome/terrain generation, tile rendering and a rudimentary camera system. I already have the skeleton code in place that can create 64x64 Chunks but what I've been struggling to realize is how to render them on an infinite grid plane, where they will dynamically generate/load and deactivate/unload based on the cameras scrolling position. What design patterns and SDL functions should I use to achieve "infinite terrain rendering?"

# Answer
I'm not going to go into much detail, but conceptually, in broad strokes... what we're talking about here is display, not game logic, and not the vagaries of SDL. So I won't go into chunk generation, but rather, chunk & chunk-slot management (assumes you have chunk data already).

Forget 2D. Think 1D, a straight line running left to right. Imagine you have the data of 4 elements (chunks) A, B, C, D. Imagine that the infinite world this 1D line represents consists of a never-ending sequence of ...ABCDABCDABCD... in both directions along the line. And imagine that you can always see for 2 chunks in either direction (to each side of you, left & right). 2+2 = 4 slots.

So let's say you're sitting between AB & CD. Great, you have two chunk slots to either side of you. Right now they're filled with AB & CD. But what if you move right? Well then you need to take A and put it next to D, don't you? If you move more right, then you need to shift B over next to A as well... and then C... and then D... and then A again... ad infinitum.

The opposite applies if you're moving left... ad infinitum.

I like to think of it as the "area of interest slots" problem. You have 2 slots to one side, and 2 slots to another. What is in each of those slots (A, B, C, or D) varies as the player moves. But they should always be able to see for 2 slots in each direction in my example; your viewing distance may vary.

Then step it up into 2 dimensions. I would use the first 16 letters of the alphabet to create a 4x4 space where you always remain in the middle, but the chunk slots shift around you.

**Then** to dispay your 2D world, rather than just flipping a finite number of chunks data (ABCD) between slots as above, you'll instead use generated data to put into the slots, and move those slots in x and y, rather than in just one dimension.
> 1 votes

---
Tags: procedural-generation, sdl2, grid, terrain-rendering
---


# Question
Title: Why is mission planner not reading my Lua script?
Whenever I try to run my Lua script, right after the first function, be it defining a parameter, mission planner (ground control station of ardupilot), display an error message saying unexpected token.

```
function pr()
local altitude = vehicle:get_altitude()
  if altitude > 1
  then
    abc:set_value(1)
    gcs:send_text("Above 1m")
  else
    abc:set_value(0)
    gcs:send_text("Below 1m")
  end

  return update, 500
end

local abc = param:define_class("abc")
 abc:set_name("test")
 abc:set_description("This is a test parameter.")
 abc:set_value(1)

 param:add_parameter(abc)
pr()

```

Here, right after the function, it displays an error message:

> `("SyntaxError: unexpected token 'abc'")`

# Answer
> 0 votes
`abc` is shown in the `pr()` function before it is defined. This is likely because you're defining `abc` as a local variable.

Some suggestions to fix it:

* make `abc` a global variable by removing the `local` part. (I recall pico-8 auto defines variables that way)
* add the `abc` as parameter to the `pr()` function , like `pr(abc)` at both locations

---
Tags: lua
---


# Question
Title: How do i know when the objectsList have all the objects after the nested method loop finished?
For example let's say the depthLevel value is 2 and then in objectsList there is 76 items.

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

public class ObjectList : MonoBehaviour
{
    [Range(0, 10)]
    public int depthLevel = 0;
    public GameObject targetObject;
    public List<Transform> objectsList = new List<Transform>();

    private Transform targetTransform;

    private void Start()
    {
        targetTransform = targetObject != null ? targetObject.transform : transform;
        GetNestedChildren(targetTransform, depthLevel);
    }

    private void Update()
    {
        if (depthLevel != objectsList.Count - 1)
        {
            objectsList.Clear();
            GetNestedChildren(targetTransform, depthLevel);
        }
    }

    private void GetNestedChildren(Transform parent, int depth)
    {
        if (depth <= 0)
        {
            objectsList.Add(parent);
            return;
        }

        for (int i = 0; i < parent.childCount; i++)
        {
            Transform child = parent.GetChild(i);
            objectsList.Add(child);
            GetNestedChildren(child, depth - 1);
        }
    }
}

```

Now I want to get the objectsList variable and use it in this script as waypoints:

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

public class FlyCamera : MonoBehaviour
{
    public Transform[] waypoints;
    public float movementSpeed = 2f;
    public float minDistance = 1f;
    public float maxDistance = 10f;
    public float minHeight = 0f;
    public float maxHeight = 10f;
    public bool randomizeVisitOrder = false;
    public ObjectList objectList;

    private int currentWaypointIndex = 0;
    private bool isMoving = false;

    private void Start()
    {

        waypoints = GameObject.FindGameObjectWithTag("Waypoint").GetComponentsInChildren<Transform>();

        if (waypoints.Length > 0)
        {
            transform.position = waypoints[0].position;
        }

        StartMovement();
    }

    private void Update()
    {
        if (isMoving)
        {
            MoveToWaypoint();
        }
    }

    private void MoveToWaypoint()
    {
        if (currentWaypointIndex >= waypoints.Length)
        {
            // Reached the last waypoint, stop moving
            isMoving = false;
            return;
        }

        Vector3 targetPosition = waypoints[currentWaypointIndex].position;
        targetPosition += RandomOffset();

        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * movementSpeed);

        // Check if we are close enough to the current waypoint
        if (Vector3.Distance(transform.position, targetPosition) < minDistance)
        {
            currentWaypointIndex++;

            if (randomizeVisitOrder && currentWaypointIndex < waypoints.Length)
            {
                // Randomize the next waypoint index
                int randomIndex = Random.Range(currentWaypointIndex, waypoints.Length);
                Transform temp = waypoints[currentWaypointIndex];
                waypoints[currentWaypointIndex] = waypoints[randomIndex];
                waypoints[randomIndex] = temp;
            }
        }
    }

    public void StartMovement()
    {
        if (waypoints.Length > 0)
        {
            currentWaypointIndex = 0;
            isMoving = true;
        }
    }

    private Vector3 RandomOffset()
    {
        float distance = Random.Range(minDistance, maxDistance);
        float angle = Random.Range(0f, 360f);
        float height = Random.Range(minHeight, maxHeight);

        Vector3 offset = new Vector3(distance * Mathf.Cos(angle * Mathf.Deg2Rad), height, distance * Mathf.Sin(angle * Mathf.Deg2Rad));
        return offset;
    }
}

```

The problem is in the Start of the FlyCamera script:

```
 waypoints = objectList.objectsList;

```

objectsList is still null. how can I wait first the objectsList to be get all objects first and then using it in the FlyCamera script?

# Answer
> 0 votes
Here is a version that uses UnityEvents. You might want to add a second one to trigger something else in case you play around with `depthLevel`. You probably can as well remove the Update method in ObjectList and replace the code in a setter for depthLevel. That way you don't need to check every Update for it.

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

public class ObjectList: MonoBehaviour {

    [Range(0, 10)]
    public int depthLevel = 0;
    public GameObject targetObject;
    public List<Transform> objectsList = new List<Transform>();

    private Transform targetTransform;
    public UnityEvent onCalculationDone;

    private void Start() {
        targetTransform = targetObject != null ? targetObject.transform : transform;
        CalculateObjectList();
    }

    private void Update() {
        if (depthLevel != objectsList.Count - 1) {
            CalculateObjectList();
        }
    }

    private void GetNestedChildren(Transform parent, int depth) {
        //...
    }

    private void CalculateObjectList() {
        objectsList.Clear();
        GetNestedChildren(targetTransform, depthLevel);
        onCalculationDone?.Invoke();
    }
}

```

Im not sure why you would acces the ChildrenTransforms in ObjectList when you have done the calculation on the objectList. But since the question is about how to react when the calculation is done, the code focused on that.

```
using UnityEngine;

public class FlyCamera: MonoBehaviour {

    private ObjectList _objectList;
    private void Start() {
        _objectList = GameObject.FindGameObjectWithTag("Waypoint").GetComponent<ObjectList>();
        _objectList.onCalculationDone.AddListener(StartMovement);
    }

    private void StartMovement() {
        if (_objectList.objectsList.Count > 0) {
            //you can use the positions as well directly from objectList here
            //or you can copy them over to the old waypoints
            transform.position = _objectList.objectsList[0].position;
            currentWaypointIndex = 0;
            isMoving = true;
        }
    }
}

```

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


title: SurfaceView shows black screen

text:
# Question
Title: SurfaceView shows black screen
My code does not work correctly. SurfaceView shows a black screen instead of Bitmaps. I make a game loop that doesn't depend on CPU, like Fix Your Timestep!, but I can't get it to work.

```
public class DrawView extends SurfaceView implements SurfaceHolder.Callback {
private DrawThreat drawThread;
public  Background background;
private int height;
private int width;

public DrawView(Context context) {
    super(context);
    getHolder().addCallback(this);
    drawThread = new DrawThreat(getHolder(), this);
    setFocusable(true);
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    Rect surface = getHolder().getSurfaceFrame();
    this.width = surface.width();
    this.height = surface.height();
    Bitmap back= BitmapFactory.decodeResource(App.getContext().getResources(), R.drawable.fon);
    back = Bitmap.createScaledBitmap(back, width, height, false);
    background = new Background(back, back, 0, 0, 0, -height);
    drawThread = new DrawThreat(getHolder(), this);
    drawThread.start();
}

public class DrawThreat extends Thread {

private final DrawView drawView;
private SurfaceHolder surfaceHolder;
private boolean running=true;
private static final int UPDATES_PER_SECOND = 25;
private static final int UPDATE_INTERVAL = 1000 / UPDATES_PER_SECOND * 1000000;
private static final int MAX_FRAMESKIP = 5;
private long nextUpdate = System.nanoTime();

public DrawThreat(SurfaceHolder surfaceHolder, DrawView drawView){
    super();
    this.surfaceHolder = surfaceHolder;
    this.drawView = drawView;

}

```

Tried to implement a game loop, but only a black screen is displayed

<pre><code>@Override
public void run(){
    while (running){
        Canvas canvas = surfaceHolder.lockCanvas();
        int skippedFrames = 0;

        while (System.nanoTime() > this.nextUpdate && skippedFrames < MAX_FRAMESKIP) {
            long delta = UPDATE_INTERVAL;
            this.drawView.update(delta);

            this.nextUpdate += UPDATE_INTERVAL;
            skippedFrames++;
        }

        double interpolation = (System.nanoTime() + UPDATE_INTERVAL - this.nextUpdate) / (double) UPDATE_INTERVAL;
        this.drawView.draw(canvas);
        surfaceHolder.unlockCanvasAndPost(canvas);
    }
    }
    }
```
</code></pre>

# Answer
> 1 votes
I have also run into this issue. When my game view would start, I would see the SurfaceView area flash black, then my background graphics would render. I believe this due to the surface view initializing late, after the onSizeChanged() method being called by the system, then the surface view's canvas would be valid and able to be drawn too.

I addressed this issue in my layout file that held my SurfaceView. I put in a View with the same measurements as my surface view, so that it would show behind the SurfaceView. I also set the background color of the stand-in View widget to the most predominate color the surface view would initially show. So now upon game startup, the black flash is not shown, only the green color, followed shortly after by the background graphics that was mostly using the color in the View.

```
<View
    android:id="@+id/canvasStandin"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:visibility="visible"
    android:background="#FF005500"
    app:layout_constraintTop_toBottomOf="@id/dividerBottom"
    app:layout_constraintBottom_toTopOf="@id/controllerEdge"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    />
<com.mygames.gameview.MySurfaceView
    android:id="@+id/gameView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:visibility="visible"
    app:layout_constraintTop_toBottomOf="@id/dividerBottom"
    app:layout_constraintBottom_toTopOf="@id/controllerEdge"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    />

```

Once the game starts, you can always reference the standin component and remove it or make the visibility invisible.

# Answer
> 0 votes
Hey so this is my loop it might need a few changes but it works for my game.

```
public class GameLoop extends Thread{
    public static final double MAX_UPS = %1$s;
    private static final double UPS_PERIOD = 1E+3/MAX_UPS;
    public Game game;
    public final SurfaceHolder surfaceHolder;

    private boolean isRunning = false;
    public double averageFPS;
    public long startTime;

    public GameLoop(Game game, SurfaceHolder surfaceHolder) {
        this.game = game;
        this.surfaceHolder = surfaceHolder;
    }
    public double getAverageFPS() {
        return averageFPS;
    }

    public void startLoop() {
        isRunning = true;
        start();
    }
    @Override
    public void run() {
        super.run();
        // Declare time and cycle count variables
        int updateCount = 0;
        int frameCount = 0;
        long elapsedTime;
        long sleepTime;
        // Game loop
        Canvas canvas = null;
        startTime = System.currentTimeMillis();
        while(isRunning) {
            // Try to update and render game
            try {
                //canvas = surfaceHolder.lockCanvas();
                canvas = surfaceHolder.lockHardwareCanvas();
                synchronized (surfaceHolder) {
                    game.update();
                    updateCount++;
                    game.draw(canvas);

                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } finally {
                if(canvas != null) {
                    try {
                        surfaceHolder.unlockCanvasAndPost(canvas);
                        frameCount++;
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            // Pause game loop to not exceed target UPS
            elapsedTime = System.currentTimeMillis() - startTime;
            sleepTime = (long) (updateCount*UPS_PERIOD - elapsedTime);
            if(sleepTime > 0) {
                try {
                    sleep(sleepTime);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // Skip frames to keep up with target UPS
            while(sleepTime < 0 && updateCount < MAX_UPS-1) {
                game.update();
                updateCount++;
                elapsedTime = System.currentTimeMillis() - startTime;
                sleepTime = (long) (updateCount*UPS_PERIOD - elapsedTime);
            }
            // Calculates and shows the FPS (slows down gameplay when active)
            //if (game.showFPS == false) {
            elapsedTime = System.currentTimeMillis() - startTime;
            if (elapsedTime >= 1000) {

                averageFPS = frameCount / (1E-3 * elapsedTime);
                updateCount = 0;
                frameCount = 0;
                startTime = System.currentTimeMillis();
            }
            // }
        }
    }

    public void stopLoop() {
        isRunning = false;
        try {
            join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

```

---
Tags: java, android, game-loop, android-studio
---


# Question
Title: How to fix Gradle errors about API level, androd.enableR8, and resource linking failed?
I encountered several errors when building on Unity 2021 for Android Platform. They're all part of the same "error group" so I'll list all of them down here since they're all part of a single problem which is exporting a game for Android. I can't find a single solution since everything I'm listing is part of my solution.

Here are some of the errors I've encountered:

1. In Google Play Console, "You cannot use API level 30 and below. For security reasons, your app should use API level 31+"
2. In Unity, "android.enableR8 is deprecated"
3. In Unity, unityLibrary:compileDebugJavaWithJavac
4. In Unity, "Gradle Build Failed. Android resource linking failed... AAPT: error: attribute android:export not found"
5. In Unity, "Gradle Build Failed. Android resource linking failed..."

# Answer
> 4 votes
## "You cannot use API level 30 and below"

You just need to set the API level to 31+ in `Edit/Project Settings/Player/Other Settings/Identification/Target API Level`

## android.enableR8

Google made breaking changes with how Unity builds the Android projects. The solution is to download a gradle that is v6.1.1+ and below v7 in https://gradle.org/releases/. This YouTube video explains it clearly. I'll list down the things he did to get his project working. Note: His steps didn't work for me; hence, the succeeding solutions may help you.

1. Download gradle from link whose version is greater than or equal to 6.1.1 and less than 7.0.0. (why not below 6.1.1, because Unity said so.)(why not 7+, see section below). Extract it to a folder. Copy the folder path. The folder path should contain the `lib` folder which Unity will be needing.
2. In `Edit/Preferences/External Tools`, untick the gradle checkbox and paste the folder path to your gradle you've extracted.
3. In `Edit/Project Settings/Player/Publishing Tools`, check these 5 items.
4. Add `android:export="true"` in the first Activity tag in `Assets\Plugins\Android\AndroidManifest.xml`. (In my case, this didn't work but, for some, it worked for them. Just try doing it first)
5. In `Assets\Plugins\Android\baseProjectTemplate.gradle`, make sure the version in this line is `4.0.1`.

```
    classpath 'com.android.tools.build:gradle:4.0.1'

```
6. In `Assets\Plugins\Android\gradleTemplate.properties`, comment out the `android.enableR8` by placing a `#` at the start of the line.
7. Attempt to build.

If not working, proceed to next section.

## unityLibrary:compileDebugJavaWithJavac

1. Make sure you downloaded a gradle between 6.1.1 and the last version before it becomes 7. Here's a reference
2. Attempt to build. If not working, proceed to next step.

## AAPT: error: attribute android:export not found

1. Remove `android:export=true` in the first Activity tag in `Assets\Plugins\Android\AndroidManifest.xml`
2. Attempt to build. For me, the Unity project was already able to export the game.

## Gradle Build Failed. Android resource linking failed...

1. If still not working, see below content which is from here

```
android.useAndroidX=true
android.enableJetifier=true

```
2. Another solution is to go to the Editor folder in your project, create a file called `AndroidManifestPostGenerateGradleProject.cs`, and then paste the following script into it:

```
{
    public void OnPostGenerateGradleAndroidProject(string path)
    {
        Debug.Log("Build path : " + path);
        string gradlePropertiesFile = path + "/../gradle.properties";
        if (File.Exists(gradlePropertiesFile)) File.Delete(gradlePropertiesFile);

        StreamWriter writer = File.CreateText(gradlePropertiesFile);
        writer.WriteLine("android.useAndroidX=true");
        writer.WriteLine("android.enableJetifier=true");
        writer.Flush();
        writer.Close();
    }
}

```
3. If there's still a problem, see conversation regarding unicode characters

These are pretty much my research over the past week. Hopefully, this helps some devs.

# Answer
> 1 votes
In my case the issue was in Target Level API.

By default API 34 was set.

After changing it to API 33 gradle built my project.

Probably the root cause is API 34 in beta at this moment.

Hope this will help if you are strugging a whole day like I am.

---
Tags: unity, build-process, export, build
---


title: Bending at edges of screen

text:
# Question
Title: Bending at edges of screen
This is a weird effect where objects bend at the edges of the screen (shearing?). It doesn't happen everywhere. I know it happens in Minecraft and Godot, but not Blender or Bevy. What is it and is there a way to remove it?

**Here's an example (Godot):**

Cube at the center of the screen :

Same cube, just rotated the camera:

And here's the cube in a similar position in Blender:

In Blender the cube isn't distorted in any way. What's going on?

# Answer
This is not "bending" (notice that straight lines remain straight, they don't become curved), but a distortion due to linear perspective.

As I explain in some previous answers, from a specific viewpoint (determined by the camera's field of view angle and the physical dimensions of the display viewport), this effect exactly cancels out the foreshortening you get in your visual field from looking at a flat screen obliquely. So even though the object gets stretched to cover more screen pixels, those pixels occupy a smaller angular span across the viewer's retina, and the illusion of a window into a virtual 3D world is preserved.

The trouble is, the "correct" field of view for a typical viewport size and viewing position is often narrower than we'd like. Imagine drawing straight lines from the bridge of your nose through the center of the top and bottom edges of your window. The angle between those lines is probably only 60 degrees or maybe less - so we'd only see a fairly narrow slice of our 3D world through that viewport if we used the optimal distortion-cancelling field of view angle in our rendering.

Instead, games and 3D apps often use vertical field of view angles of 90+ degrees, which would correspond to a viewing position much closer to the screen. From farther back, there's not enough foreshortening to compensate, and we end up seeing some of this stretching - most noticeably at the far left and right sides of the window for landscape-oriented displays. Players (especially in FPS games) and developers usually accept a certain amount of this distortion as a compromise in trade for being able to see more of the world at a time / having more peripheral vision.

In the Blender screenshot, this effect is less apparent only because the field of view angle is relatively small for the width/aspect ratio of the viewport. If you stretched the viewport wider with the same FoV setting, you'd see the distortion become more pronounced.

You can change your editor camera's field of view settings in Godot to reduce the apparent distortion, in exchange for seeing less of your world at a time.

In games designed to be played on widescreen monitors, especially FPS games, we'll sometimes use alternative camera projections or post-process shaders to minimize the apparent distortion at the edges of the screen. This results in a compromise projection that might not be strictly correct from any point of view, but is aesthetically preferable to seeing elongated/skewed objects at the far edges.
> 3 votes

---
Tags: graphics
---


# Question
Title: How can I map a texture around a sphere without a seam?
I am attempting to wrap a texture around a sphere without any warping using Unity's Shader Graph. I have been following this StackExchange answer, and have semi-successfully converted their shader code into this graph:

Unfortunately, however, I end up with a seam from pole to pole of the sphere. It is very noticeable in-game, but a little hard to see in a screenshot:

After some research, it is my understanding that it is rather difficult to wrap a sphere without generating a seam. But, if I use the texture on one of Unity's default shaders, no seam is generated. So I thought I would ask anyway. Of course I can not use a default shader because then I would have a warped texture again.

# Answer
> 2 votes
First, the reason this happens:

When rendering a triangle, your GPU evaluates 2x2 blocks of pixels at a time. That means when you sample a texture in a fragment shader, the GPU has 4 sets of texture coordinates to work with. It looks at the differences between these 4 texture coordinates (screenspace partial derivatives) to estimate how much the texture is being stretched in this neighbourhood - either due to the camera being close/far, looking at the surface at an angle, or due to intrinsic stretching in the model's UV unwrap. With this information, it can automatically select the right mipmap to read from, or apply the right amount of anisotropic filtering, so that the texture comes out looking the best it can: not sparkly and aliased from undersampling, and not unnecessarily blurry.

The trouble is that when we calculate texture coordinates for an equirectangular projection / spherical coordinates, one of these 2x2 screenspace pixel blocks can straddle the wrap-around point from just-shy-of-one to just-past-zero in the longitude direction. As far as the GPU is concerned, that means the entire texture has been compressed down, so that 100% of its width fits across a 1-pixel stride, and it auto-selects the smallest mip to sample from. You end up with the average colour of the whole texture, instead of the appropriately-filtered colour for the part of the sphere you were actually trying to render.

Here is a graph that fixes this seam in Unity URP:

The idea here is that we calculate two texture coordinates: one with the wrap-around point in the normal place, and one where we've moved the wrap-around point to the other side of the sphere. We calculate what level of detail should be used for each attempt, and when they disagree (when one says the block straddles the wrap-around and the other doesn't), we pick the smallest one. Then finally we sample the texture with that "least-of-two" LoD estimates.

One downside with this approach is that we lose anisotropic filtering, so you may find the glancing edges of the sphere appear more blurry than you'd like.

In shader code, we can use the `tex2Dgrad` function or equivalents to do a similar trick while supporting anisotropy, but as you've found, this function isn't currently exposed to the Unity shader graph - we'd have to use a Custom Function node to inject raw shader code to access it.

A simpler solution though, and one that may scale better for your needs, is to store your spherical textures not as 2D equirectangular rectangles, but as cubemaps. This gives a more even texel density over the surface of the sphere, so you can get away with smaller textures for the same worst-case detail, or better detail with the same texture memory. Filtering for these is already supported out-of-the-box, so your shader stays simpler too.

---
Tags: unity, 3d, shaders, textures, unity-shader-graph
---


# Question
Title: now how do I go about making a skill bar and a tool bar?
**TLDR** **QUESTION** the main thing I don't understand how do i make it so that when i press a keybind i activate not a skill but a slot in the skillbar and the slot in the skillbar activates the skill

extra details :

The system im trying to achieve is basically Minecraft + Classic mmos.

tool bar with 3 tools on the side of an array of 3x24 so 75 slots in total, mouse wheel to scroll through the tools, left click to use the main function of the tool and right click to use the secondary function of the wheel, in the image there is a crossair even tho it is kind of transparent and hard to see in this screenshot. I plan to eventually have at least 7 classes, 10 skills per class which means 70 total skills and other skill tress that are classes and by classless i mean they don't have any classic mmorpg archetype of theme attached to it like being an archer/warrior/mage and so on..

each skill can be used while holding any tool whatsover, and the characters have 4 ways of hold things.... Iron guard like in the image, where you hold any long object behind you be it a sword spear or axe whatever, an universal holding system that applies to anything and looks natural with any tool, dual wielding, and shield+ sword

kind of like in guild wars 2 .

so each skill has 4 variations for the animation which can seem crazy "omg this guy wants to make 280 different animations! it's impossible" .... not really all I have to do is take one animation that already exists, adjust the arms by doing a bunch of copy and paste and each animation can be adapted in a few minutes even seconds.

so it's more a question of each skill having 4 possible states which isn't that crazy at all, it's just if elif elif elif else.

and for now my third person controller script looks like that : https://github.com/Ceisri/Velsia-Action-combat-/blob/main/scripts/Action%20combat.gd

i had another script with another character model and more animations but i realized something like "wait it is useless that i spend all this time with all those attacks and such things, i first need to understand how to make a skill"

so now that i fixed a bunch of problems with movement mechanics, like dodging, sliding, teleporting and climbing....all i need to do is to add a crouching system and swimming system and then i can work on adding a skill bar and a skill tree.

# Answer
In general you need these:

1. HUD elements, which ideally would be `Control`s. So the bar is a `Control` and each slot is a `Control` (and you probably use `Container`s to arrange them).
2. Scripts attached to those `Control`s, so they can take input (not disimilar to how the player controller takes input). So they can react to the actions the player presses to activate the skills.
3. Custom `Resource`s to represent the skills, then you can have an `export var` on the `Control` scripts to associate them to each slot.
4. A way to communicate with the player. I suggest you an autoload (sigleton) for that. You might, for example define a signal in the autoload, the `Control` emits the signal passing the skill `Resource`... And the player controller (or another `Node` in the same scene) can subscribe the signal in the autoload and acutally execute the skill. *Yes, the autoload would be a signal bus (event bus).*

The execution of each skill might differ, of course. Some aspects you might configure with properties on the `Resource`. But presumably skills not only have difference of degree but also differences of kind... So you want to associate behavior to them... To do that, give them `PackedScene` properties of the things they would instantiate (e.g. which projectile it shoots, or particles, or whatever you need), which can each have a custom script attached, so they all have unique behavior.

Assuming the instantiated scenes need access to the data on the `Resource` that represents the skill, you can have a method in the `Resource` class that handles the instantiation and also injects itself in the instance.

*See How to implement a composable character/skill system in the Godot 4.0 Game Engine? for a more elaborated version of this (I'm aware you are on Godot 3, but the idea is the same).*

And, of course, you would further develop the UI, to allow the player to customize which skill goes where (e.g. drag and drop).
> 1 votes

---
Tags: 3d, gui, rpg, combat, godot-3
---


# Question
Title: How can I utilise world generation through chunks (to reduce lag)
I've been working on a 2D pixel-styled survival game(with the Godot Game Engine), from the birds-eye view(not a side scroller like Terraria) - where the world would look like a map if zoomed out.

So far, I've used OpenSimplexNoise() to generate each map tile. This works fine, however if I wanted a large map, such as 500x500 tiles, the game would very quickly drop frames as it tries to process each tile(especially when enabling Y-sort and processing for each interactive item to be found)

Although that is no surprise, I haven't been able to find an appropriate fix or solution for this on YouTube, most tutorials only show how to generate tile-by-tile.

Could *you* please show me how to generate(and process) the world through chunks(such as Minecraft), so that when a chunk reaches a certain distance from the player, it is no longer processed?

I have also been asking ChatGPT **lol**, but it has been vague in this area when asking to expand its ideas.

I would ideally like to be able to load and offload terrain as the player explores areas.

Although I am new-ish to Godot, I have been creating simple games and learning coding theory for a while on Khan Academy(@apex.ka) and I'm eager to expand my growth and skills by your help.

Also, even if you are unfamiliar with Godot Game Engine, I could still potentially implement your logic into the engine.

Thanks in advance, -Apex

Oh! I almost forgot -- Another simpler solution would be to ignore chunks, and just draw/process tiles that are within a certain radius of the player. The only problem there is that the Godot Game Engine(note: I'm using Godot 3 and not 4, as most of the tutorials are in 3, so whilst I'm learning I haven't upgraded) -- there is no way to hide a tile. I think Godot 4 fixes this :|

Therefore, I was thinking about separating the world into chunks of individual TileMap nodes, which then could be toggled to invisible when off the screen.

Thanks again,

# Answer
> 1 votes
I agree with DMGregory's comment that you should use `TileMap` as chunks.

You may also use a `VisibilityNotifier2D` per chunk if you need to run some code when they are out of view. By the way, note what the documentation says about `VisibilityNotifier2D`:

> **Note**: For performance reasons, VisibilityNotifier2D uses an approximate heuristic with precision determined by `ProjectSettings.world/2d/cell_size`

You can make that precise by sizing the chunks according to the project setting `world/2d/cell_size`... Or rather I should say you should tweak them together. There should be a sweet spot for the chunk size (too small and the logic that hide/disable them is running too often, too big and they require too much processing). So use experimentation and profiling.

You can use a secondary `Thread` to create the `TileMap`s and use `call_deferred` to add them to the scene tree (`call_deferred("add_child", tile_map)`).

About the generation of the tiles, yes it is tile by tile, but there are other opportunities for optimization. Look for anything you can cache/memoize in your code. In fact, if you plan to remove chunks that are away from the player, I remind you that removing them from the scene tree (`remove_child`) is not the same as deleting them (`queue_free`) so you can have a cache of recently removed chunks ready to be added back... And going down that rabbit hole, you might implement an object pool for chunks, so instead of creating a new chunk from scratch you might reuse one that was removed.

---
Tags: gdscript, godot-3
---


# Question
Title: AI for global decision-making in 4X games
I understand how things work in combat, but not quite in terms of global decision making.

For example, in Civ, at the global level AI has to juggle multiple objectives, e.g. whether to invest money in constructing Building A in City B, or choosing which tech to research, whether to declare war or offer peace to an opponent, etc.

So my question is, what sort of algorithms are used for this? My guess would be something like Gantt chart or numerical solution for an assignment problem that prioritizes jobs.

EDIT: more specifically,

1. How do I formulate an optimization problem
2. What kind of solution can be used?

For example, a 1) bipartite graph solved by 2) Hungarian method.

# Answer
> 3 votes
There is a reason why the AI in most 4X games is so bad that it can only challenge a moderately experienced player through blatant cheating: AI for 4X games is a really complex issue. It has to handle multiple conflicting priorities. The importance of these priorities depends on a ton of variables, a lot of them with uncertain or unknown values. And the actions to solve those priorities often also have a complexity level that makes it hard to estimate how feasible they actually are.

There is no one algorithm to solve the problem of long-term planning. And those which exist require a lot of game-specific tweaking to enable them to make vaguely plausible decisions within the context of the game they are used in.

But a couple algorithms which can help here are:

* Rule engines. Rule engines are basically long lists of conditions. "IF \[I don't have a barrack\] AND \[I have the resources to build a barrack\] THEN \[build a barrack\]". The simplest way to build a rule engine is basically a function with a ton of `if` statements. But many games outsource this to a domain-specific language to make it easier for the designers to experiment with the rulesets.
* Goal-oriented action planning. This algorithm picks a goal and then tracks backwards to check what needs to be done to pursue that goal. Example: "I want to capture that enemy city -\> I need a unit capable of capturing -\> I need a barrack to build such a unit -\> I need 250 wood to build a barrack -\> I should send a unit to collect wood". This algorithm allows to determine the cost of what it takes to fulfill each goal by adding up the costs of all the steps. This cost calculation can be used to decide which goal to pursue.
* Utility AI. The AI rates its situation based on certain metrics, and then uses a scoring system to decide what to do next. Example: "I am at war: +50 military importance. I have the strongest army: -27 military importance. I am far behind in technology: +43 tech importance. I am slightly ahead in economic development: -3 economy importance. Result: I should invest in technology".
* Machine learning. I don't believe I have actually seen a 4X game yet that does this. But with machine learning being all the rage right now, it might be worth trying to train a neural network to play your game.

---
Tags: ai, optimization
---


title: Unity and Blender integration .blend

text:
# Question
Title: Unity and Blender integration .blend
How can I manually set that Unity can read .blend file inside Unity?

I have portable Blender.

When I add blend file in Unity it says: *Blender is not found.* How to make Unity understand .blend file?

# Answer
According to documentation, Unity imports .blend files through FBX. You're going to export your scene to FBX if you want to use your assets in your Unity project.
> 2 votes

# Answer
I encountered this issue with Unity 2021.3.26f1 and Blender 3.60. With this, saving .blend files directly in my Unity project's asset folder should have worked to import them automatically, but I was still getting the "Blender is not found" message.

Turns out Unity doesn't understand Blender Collections. I had to place my asset into the default "scene collection" collection in Blender for the model to be automatically recognized.
> 0 votes

# Answer
Take these steps to manually configure Unity to recognize .blend files. Firstly, confirm that Blender is installed and its path is added to the system's environment variables. After this, open Unity and go to Edit \> Preferences \> External Tools. Look for "Blender Executable" in the "External Tools" window and click "Browse". Locate the installation location of Blender on your computer and choose the "blender.exe" executable. Finally, click "Open". To save your changes, click "Apply" after adding ".blend" to the "External Tools" window's "File Extensions" section by clicking "Add".

Make sure you have a Blender version that works with Unity. Also, ensure both programs are running in 64-bit mode. After that, you should have no issues importing .blend files into Unity.
> 0 votes

---
Tags: unity, blender
---


# Question
Title: where should i start if i want to make an enemy from robots forever 2 (or if you are unfamiliar a physics based enemy that uses procedural generation)
this is probably a long shot, but I didn't really know where to ask this question. I just wanted to ask if anyone knows any resources that can help explain how to make something like this. Thanks, and sorry for the trouble

I've seen videos on procedural animation, but all the ones I've found have been a floating body with legs that connect to the ground as its moves which makes a walking animation, though these are not affected by physics, so I'm not that interested.

# Answer
It is very difficult to simulate the movement of a robot completely using physics. You need to make the robot stand, move, and turn in balance, and all this can only be done through the control of a limited number of joints. But good thing the bots are in the game world, we can easily cheat.

Here is an example from The Legend of Zelda:

The robot in the picture uses several single-function components to realize the stable walking of the biped robot.

First it uses a component that provides torque to keep the robot in balance:

It then makes the robot's two feet cycle out of phase. If the robot has more legs, you can refer to the movement patterns of animals or insects:

In conclusion, the solution is:

1. Artificially providing torque to the robot's torso to give it a tendency to maintain balance.
2. Similarly, add a y-torque to the robot's torso to make it rotate toward the target.
3. Use the animation system or timeline to control all the legs so they have an animation sequence that moves forward.
4. Adjust the gravity of the torso, when the number of remaining legs of the robot reaches a threshold, the robot falls.
> 0 votes

---
Tags: unity, physics, animation, ai
---


# Question
Title: Should I model with quads or with n-gons?
Model 1 — all 4-sided polygons  Wireframe Gun Model 1

Model 2 — polygons have arbitrary number of sides/vertices  Wireframe Gun Model 2

# Answer
It doesn't really matter. 3d models with faces that have more than 3 vertices don't really exist in 3d graphics\*. They are a usability-convention of the modeling program. 3d rendering engines can only render triangles. So when the model is exported from the modeling program and into a game engine, all non-triangular faces get broken up into triangles anyway.

Too many superfluous edges on a surface can of course result in more triangles being generated than necessary, which can negatively affect performance. But that doesn't seem to be the case here. The edges all seem to be in places where the triangulation phase would generate edges anyway.

<sub>\*Excluding some really exotic rendering techniques you usually don't see in mainstream 3d games</sub>
> 6 votes

# Answer
If you are using proper topology, then the number of faces and vertices will always be roughly the same. Eventually, if your model has 0 triangles and only quads, the vertices and the quads will be almost the same amount. In the image the quads are roughly 2200 and the vertices 2100. This is only because the model is sliced into pieces. Otherwise the numbers would be more even.

Your computer is only calculating where each vertex is located and how it moves. And then it fills up the space between. You really only have to think to always work with quads and never with any shape that has more than 4 vertices.

Triangles are fine, but only to save geometry so use them sparingly.

If your geometry has too many vertices, just press `M`, select "merge by distance" and set the distance to 1 millimeter.

If your geometry has shapes with more than 4 vertices - pentagons and such things - press `space` and search in the bar for "triangulate faces". Then press again `Alt`+`J` to transform the triangles into quads.
> 2 votes

---
Tags: optimization, models, 3d-meshes
---


# Question
Title: How do you have the clothing mesh hide the body mesh underneath?
How do you have the clothing mesh hide the body mesh underneath, to prevent odd patches of body from sticking out in tighter modular clothing?

Is there some sort of shader trick that can have the clothing always render "in front of" the mesh?

# Answer
This is a pretty common problem many people run into and the solution depends largely on what you are trying to do in your game.

If your character is unable to change clothes in game, or has a very limited selection of clothing, what many people will do is flatten the character mesh and clothing meshes to a single character model. After doing so you can delete any geometry that would be inside the clothing that might risk clipping through. This should also give some small performance increases as there is less geometry to render overall. Since most games only offer 1-3 clothing options per character exporting one character model per clothing option usually isn't too bad.

If your character needs to be able to change clothes constantly (such as equipping armor in an MMO), what I would do is create a shader for your main character that, in addition to your usual textures, takes in a special clothing mask texture that controls the alpha channel of your character based on what they are wearing. For example if you want to equip a T-shirt to your character you masking texture would show all of the bodies UVs except the torso and shoulders as white and the rest as black. If you want to equip a three piece suit, show everything as black except the hands, neck and face. You may need to allocate more than one texture slot of clothes can be mixed and matched, but this should basically set everything that should be covered up as visible so you don't have to worry about clipping except in areas where the body should be visible (neck line and wrists).

Shadergraph Sample Shader

HLSL Surface Sample Shader

```
Shader "Ina's Cool Shaders/Lit/Character Shader"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _ClothingMask("Clothing Mask", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader
    {
        Tags
        {
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "Queue" = "Transparent"
        }
        LOD 200
        Blend SrcAlpha OneMinusSrcAlpha

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows alpha

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _ClothingMask;

        struct Input
        {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
        // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
        // #pragma instancing_options assumeuniformscaling
        UNITY_INSTANCING_BUFFER_START(Props)
        // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            fixed4 mainColor = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = mainColor.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;

            // Masking
            fixed4 maskingData = tex2D(_ClothingMask, IN.uv_MainTex);
            o.Alpha = maskingData.r; // any channel is fine, if your mask is black and white rgb should all be the same values
        }

        ENDCG
    }
    FallBack "Diffuse"
}

```

HLSL Unlit Shader Sample (base code taken from https://answers.unity.com/questions/1098744/unlit-texture-transparent-shader.html)

```
 Shader "Ina's Cool Shaders/Unlit/Character Shader"
 {
     Properties
     {
         _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
         _ClothingMask("Clothing Mask", 2D) = "white" {}
     }

     SubShader
     {
         Tags
         {
             "Queue"="Transparent"
             "IgnoreProjector"="True"
             "RenderType"="Transparent"
         }

         LOD 100

         ZWrite Off
         Blend SrcAlpha OneMinusSrcAlpha

         Pass
         {
             CGPROGRAM

             #pragma vertex vert
             #pragma fragment frag
             #pragma multi_compile_fog

             #include "UnityCG.cginc"

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

             struct v2f
             {
                 float4 vertex : SV_POSITION;
                 half2 texcoord : TEXCOORD0;
                 UNITY_FOG_COORDS(1)
             };

             sampler2D _MainTex;
             sampler2D _ClothingMask;
             float4 _MainTex_ST;

             v2f vert (appdata_t v)
             {
                 v2f o;
                 o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                 o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
                 UNITY_TRANSFER_FOG(o,o.vertex);
                 return o;
             }

             fixed4 frag (v2f i) : SV_Target
             {
                 fixed4 col = tex2D(_MainTex, i.texcoord);
                 UNITY_APPLY_FOG(i.fogCoord, col);

                 fixed4 clothingMask = tex2D(_ClothingMask, i.texcoord);
                 col.a = clothingMask.r;
                 return col;
             }

             ENDCG
         }
     }
 }

```
> 4 votes

# Answer
The game I'm working on now uses a similar approach as described by Benjamin Danger Johnson, but we bake the information into the mesh to save a texture.

Ahead of time, we charted out the different parts of the body we might want to hide (eg. forearms to the wrist for long-sleeve shirts, to the elbow for baseball shirts, upper arms just past the shoulder for T-shirts, no arm hidden for sleeveless tops...)

Each different region gets an integer code. We save that code in a vertex attribute on the mesh (like a vertex colour or texture coordinate channel).

Based on the combination of clothing worn at a time, we compute which of these numbered regions should still be visible (each clothing item stores which region IDs it covers), and we express that as a bitmask — where the nth bit is 1 if region n should show skin, or 0 otherwise. We send this bitmask to the GPU as just one uniform variable.

In the vertex shader, we compare the region ID for the current vertex against the bitmask. If it lines up with a 1 somewhere, the shader pipeline keeps running as normal. If it doesn't, we abort the vertex (if you output NAN for the vertex position, the GPU won't draw triangles using that vertex).

That lets us clip out the invisible geometry as early as possible in the pipeline, before rasterization or the expensive skin shader, and without extra overdraw, blending costs, or texture memory/sampling.
> 2 votes

# Answer
"you can avoid the problem althogether by slicing the character into pieces instead of using shaders"

thi's how I arrange the textures: here's naked

here's clothed

This way you only need to apply skin color to one single texture or either to only one part of the texture without ever coloring by mistake the clothing if you are using masks.

and most importantly, if your game as transmog or the ability to color your clothing, you can do so without coloring your skin by mistake.

The end result looks like that, it also allows you to combine any piece of clothing with any other clothing or body part whilist having the least ammount of textures, the least ammount of vertices and if you are using some node logic 1 single material call for a character with multiple separated meshes... I don't personally do it, but I've seen a dude doing it unity, basically every single armor or clothing piece in his game was sharing one single material which is great for performance.

and if you are worried about having to animate a thousand pieces of bodies and clothing so they all work well together...

just use mixamo...it automatically weight paints your characters, I've never had a single problem with clipping while using mixamo.
> 0 votes

---
Tags: unity, shaders, rendering, mesh
---


# Question
Title: How to create custom UI element from Hierarchy Menu in Unity?
I have a custom UI element and I would like to instantiate it from Hierarchy like you do with any other UI element (button, text etc.). I know how to do this so it is instantiated in the scene but how to make it instantiate exactly like UI elements so it gets instantiated onto a canvas?

# Answer
> 1 votes
Ok so I figure it out here is the creation code:

```
  public static void CreateUIObject(string path)
{
    GameObject selectedObject = Selection.activeGameObject;

    if(selectedObject != null)
    {
        //If selected object contains canvas
        if(selectedObject.GetComponentInParent<Canvas>())
        {
            GameObject newObject = GameObject.Instantiate(Resources.Load(path),
            Selection.activeGameObject.transform) as GameObject;
            newObject.name = path;
            Place(newObject);

        }
        else
        {
            GameObject newCanvas = GameObject.Instantiate(Resources.Load("Canvas"),
                Selection.activeGameObject.transform) as GameObject;
            newCanvas.name = "Canvas";
            Place(newCanvas);
            GameObject newObject = GameObject.Instantiate(Resources.Load(path),
            newCanvas.transform) as GameObject;
            newObject.name = path;
            Place(newObject);
        }
    }
    else
    {
        GameObject newCanvas = GameObject.Instantiate(Resources.Load("Canvas")) as GameObject;
        Place(newCanvas);
        newCanvas.name = "Canvas";
        GameObject newObject = GameObject.Instantiate(Resources.Load(path),
        newCanvas.transform) as GameObject;
        newObject.name = path;
        Place(newObject);
    }
}

public static void Place(GameObject gameObject)
{
    // Find location
    SceneView lastView = SceneView.lastActiveSceneView;
    gameObject.transform.position = lastView ? lastView.pivot : Vector3.zero;

    // Make sure we place the object in the proper scene, with a relevant name
    StageUtility.PlaceGameObjectInCurrentStage(gameObject);
    GameObjectUtility.EnsureUniqueNameForSibling(gameObject);

    // Record undo, and select
    Undo.RegisterCreatedObjectUndo(gameObject, $"Create Object: {gameObject.name}");
    Selection.activeGameObject = gameObject;

    // For prefabs, let's mark the scene as dirty for saving
    EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}

```

And here is the part that calls this methode in the asset menue:

```
  [MenuItem("GameObject/UI/ArrowSelector(TMP)", priority = -50)]
private static void CreateArrowSelector()
{
    CreateUtility.CreateUIObject("ArrowSelector");
}

```

So first I get the selected object from the hierarchy. If it isn't null I check if that object or any of his parents contains canvas GameObject, if it does I instantiate my object Under it. If not I create new canvas (note that I put a canvas prefab into a resource folder because I don't know how to use Unitys default one) and use it as a parent for my UI object.

If selected object is null I just do the same thing as if there is no canvas on selected gameobject but without assigning a parent to the canvas.

I copied place function from a tutorial it handles some Unity tooling stuff like undo redo and not sure what else.

**These are editor scripts so make sure to place them in Editor folder.**

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


# Question
Title: How to add a slot to processing queue using a ring buffer with three pointers?
I am working on a farm game made in C. I am currently working on adding item processing, such as milling wheat into flour. Under the hood, I am using a ring buffer to handle the queues for processing. I keep 3 pointers for the ring buffer. A collect pointer for the rear, a new task pointer for the front, and an active pointer to point to the currently active event.

Right now I am working on adding a mini upgrade, a new slot for a queue of the processing building. I am having problems with deciding how to handle this in a way that is good for me the programmer and the eventual user.

When I add a new slot to a queue, it changes how my 3 pointers should be positioned. For example, if the queue was full, the new task pointer should now be at the new empty slot. There is also the active pointer. If you have 3 slots in the queue, events in slots 1 and 2, and you add another event such that it gets added to slot 0. Then you add a new slot to the queue such that it is slot 3. The active pointer would get stuck in slot 3, resulting in behavior that is not wanted.

I currently see 3 options:

1. Do not allow the addition of new slots
    * This is likely the simplest solution, however, it is not quite what I want.
2. Only allow the addition of new slots when the entire queue is empty.
    * This would work well and is what I am currently leaning toward. This is good for the programmer, but I don't think it is convenient for the user. Would this be a good trade-off in convenience for the programmer vs convenience for the user? Would this be considered a sane game mechanic?
3. Manually place the pointers into the correct places.
    * This would be the best in convenience for the user, however, it would be a lot of work for the programmer.

Which would be the best approach? Is there another solution that I am missing?

# Answer
> 1 votes
I don't think you should sacrifice usability for programming convenience. A queue that can enlarge is not the halting problem, so we can just bite the bullet and solve it.

Presumably you have a maximum number of queue slot upgrades? If so, you can make the queue the largest size it could ever be right from the start, and store the current capacity in a byte nearby. When something wants to add something to the queue, check the current capacity and deny the option if the queue is full. Then upgrading is just incrementing this value, and no pointers need to move because they're still valid in the new state as well.

---
Tags: game-mechanics, data-structure, c
---


# Question
Title: Unit Testing start method of a MonoBehaviour
In Unity how can I unit test the start method?

I am not trying to test interaction between objects but the private methods are called by the Start method, so I figured I should call the start method and check the values of the object. But it seems the Start method is not called at all.

To make sure it is not some bug in my actual code that is being tested I added this line to the Start method of the building class: `numberOfXTiles+=23432`

I have a Scene called "TestScene" that I add an empty GameObject called "TestObject"

This is the play mode testing script:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using UnityEngine.SceneManagement;
using System;

public class TestBuilding
{

// A reference to the game object that has the script with the Start method
private GameObject gameObject;
private Building building;

// A method that runs before each test and instantiates the game object
[UnitySetUp]
public IEnumerator SetUp()
{
    // Load the scene asynchronously
    SceneManager.LoadScene("TestScene");

    // Wait until the scene is loaded
    yield return new WaitUntil(() => SceneManager.GetSceneByName("TestScene").isLoaded);

    gameObject = GameObject.Find("TestObject");

    gameObject.AddComponent<Building>();
    building = gameObject.GetComponent<Building>();
    yield return null;
}

[UnityTest]
public IEnumerator TestTileNumberAutoCalculation()
{
    //setting up
    building.numberOfXTiles = 2;
    building.numberOfZTiles = 3;
    building.occupiedTilesRelativeGridVectors.Add(new Vector3(12, 0, 9));

    //expecteds
    int expectedX = 12, expectedZ = 9;

    yield return null;//wait one turn so that start method is run

    bool xPassed, zPassed;

    //checks
    xPassed = (expectedX == building.numberOfXTiles);
    zPassed = (expectedZ == building.numberOfZTiles);

    //handle message
    string message = "";
    if (!xPassed)
    {
        message += "X failed to pass: expected =  " + expectedX + "  found = " + building.numberOfXTiles + "\n";
    }
    if (!zPassed)
    {
        message += "Z failed to pass: expected = " + expectedZ + "  found = " + building.numberOfZTiles;
    }

    Assert.IsTrue(xPassed && zPassed, message);
}
}

```

Console output says x is 2. That is how I am sure Start method is not run. However if I add the same line to the update I see that x has changed to `23432`.

# Answer
> 1 votes
I figured it out. `gameObject.setActive(bool)` is the solution.

I believe the start method is being called when the MonoBehaviour object is added as the component in this line `gameObject.AddComponent<Building>();` So what is happening is the start method is triggering and doing its thing in the \[UnitySetUp\] method then I am setting the values I need in the actual test method. And since the start method is already fired the new values are not being processed.

To solve this issue, I set the gameObject as inactive before adding the component in the setup and I turn it active after I set the values.

```
[UnitySetUp]
public IEnumerator SetUp()
{
    SceneManager.LoadScene("TestScene");

    // Wait until the scene is loaded
    yield return new WaitUntil(() => SceneManager.GetSceneByName("TestScene").isLoaded);

    gameObject = GameObject.Find("TestObject");
   gameObject.SetActive(false);
    gameObject.AddComponent<Building>();
    building = gameObject.GetComponent<Building>();

}

[UnityTest]
public IEnumerator TestTileNumberAutoCalculation()
{

    //setting up
    building.numberOfXTiles = 2;
    building.numberOfZTiles = 3;

    building.occupiedTilesRelativeGridVectors.Add(new Vector3(12, 0, 9));

    gameObject.SetActive(true);
   ...

```

I am setting it as a community wiki so that people can correct any bad practice and write the perfect unit test method.

---
Tags: unity, c#, unit-testing
---


title: How to outline animated mesh in Godot?

text:
# Question
Title: How to outline animated mesh in Godot?
this little freak, is roughly 1.3 meters tall so around 4.2 feet. In first person he is decently easy to spot but in third person he blends too easily with ground so even if he is only 4-5 meters away from you so 16-20 feet... it get's very hard keep eyes on him. and since it's "AI" is set to follow the player's back, it is very easy to not notice a goblin that is about to bonk your head from behind.

even when looking at him while he is wacking, slamming and swinging his stick around, his body is almost invisible and you see moslty just the stick.

so to prevent that, I came up with a simple idea , give the players an ability "concentrate" when players activate concentrate they walk slowly but all enemies within a certain distance are outlined.

so in godot.... how do you outline things?

# Answer
> 2 votes
## Outline Mesh

The closest to a build-in solution is to create an outline mesh. That is a mesh that is slightly larger but inverted (normals are the opposite way, so inside is outside and vice versa).

The main drawback of this approach is that the size of the outline is defined in 3D space (so the outline is also affected by perspective, and will look smaller the further away from the camera).

---

You can create an outline mesh from code by calling `create_outline` on the `Mesh`. Which will create a new `Mesh`, which then you would have to give to a `MeshInstance`.

---

Or you can do it from the editor:

1. Select the `MeshInstance`
2. Click the "Mesh" option in the toolbar
3. Click "Create Outline Mesh..."
4. Specify the margin (how much larger you want it to be).
5. Click create.

It will create a new `MeshInstance` as a child of the original.

---

Either way, do not forget to set a material. And also, for the effect to work, you need the new `MeshInstance` to move the same way as the original.

---

## Outline Shader

The other option is create a post-process shader... With the approach you can define your outline in pixels, so you don't have the perspective problem.

*If you are going to target mobile, I'll advice you to not use this method, as the performance is much worse.*

You can use the approach described in Custom post-processing, which have you render the scene to a secondary `Viewport` so you can use the resulting image as a `Texture` which is the input for your shader. This approach only gives you color... *Getting other information might require rendering to other secondary `Viewport`s while also overriding materials to get what you want*.

Or you can use method described in Advanced post-processing that has you create a simple mesh (often a quad) to cover the screen. This approach gives you color in the `SCREEN_TEXTURE`, and depth in `DEPTH_TEXTURE`. *Also it avoids secondary `Viewport`s.*

Either way you want to implement an Edge detection algorithm (e.g. filter/convolution/kernel).

In fact, you can find an example in the "Custom post-processing" article linked above... Which does this:

```
    vec3 col = -8.0 * texture(TEXTURE, UV).xyz;
    col += texture(TEXTURE, UV + vec2(0.0, SCREEN_PIXEL_SIZE.y)).xyz;
    col += texture(TEXTURE, UV + vec2(0.0, -SCREEN_PIXEL_SIZE.y)).xyz;
    col += texture(TEXTURE, UV + vec2(SCREEN_PIXEL_SIZE.x, 0.0)).xyz;
    col += texture(TEXTURE, UV + vec2(-SCREEN_PIXEL_SIZE.x, 0.0)).xyz;
    col += texture(TEXTURE, UV + SCREEN_PIXEL_SIZE.xy).xyz;
    col += texture(TEXTURE, UV - SCREEN_PIXEL_SIZE.xy).xyz;
    col += texture(TEXTURE, UV + vec2(-SCREEN_PIXEL_SIZE.x, SCREEN_PIXEL_SIZE.y)).xyz;
    col += texture(TEXTURE, UV + vec2(SCREEN_PIXEL_SIZE.x, -SCREEN_PIXEL_SIZE.y)).xyz;
    COLOR.xyz = col;

```

---

You might find more examples searching online. Be aware that they all require their specific setup to work (either extra `Viewport`s or the quad that covers the screen, or something else). *Also double check for which version of Godot they are for, as Godot 4 results are taking more and more prevalence.*

---
Tags: shaders, graphic-effects, godot-3, outline
---


# Question
Title: Is it possible to detect if the cursor is over a GameObject with a specific tag?
I've tried quite a few things, but none of them have worked reliably. Here is what I'm currently using:

```
    float scrollInput = Input.GetAxis("Mouse ScrollWheel");

    // Check if the mouse is over a UI GameObject with the tag "BlockZoom"
    if (EventSystem.current.IsPointerOverGameObject()) {
        GameObject go = EventSystem.current.currentSelectedGameObject;
        if (go != null && go.tag == "BlockZoom") {
            // If the mouse is over a UI GameObject with the "BlockZoom" tag, then don't zoom the camera.
            scrollInput = 0f;
        }
    }

```

It works *sometimes*. But obviously, I'm not "selecting" an object.

So is there a way to do this? Keep in mind these are UI elements in screenspace.

# Answer
I think the error in your mental model here is that the "currently selected object" is not necessarily the same as the same object as the one the mouse cursor is currently on. A game object becomes the "selected game object" when the user interacts with it. For example, a text input becomes the "currently selected object" while the text cursor is in it.

If you want to find out what UI widgets are at a certain screen position, then you have to use the GraphicRaycaster component on your EventSystem. The example code for the GraphicsRaycaster.Raycast method does *almost* what you want: find out which UI objects are under the cursor (keep in mind that objects can overlap, so you might get more than one result for a single screen position). Now you just need to add a check for the tag.
> 1 votes

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


# Question
Title: Cannot find game library when trying to port game to android
I've been working on a project of mine(a game with SDL3 + OpenGL ES 3.2), and as of right now I want to port it to android with android NDK, I compile my game as a library(compiles and links correctly, inside and outside of android studio), but when I launch my application on an emulator it prints:

```
SDL Error:

dlopen failed:library "libimage-engine.so" is not found

```

I specify my libraries in the getLibaries method:

```
protected String[] getLibraries() {
        return new String[] {
                "c++_shared",
            "SDL3",
            "image-engine",
                "image"
        };
    }

```

**Update** the library is located in `android-project/app/build/intermediates/cmake/debug/obj/x86_64`

I think the issue is with the fact that its a debug version and not a release one

**Update 2** I noticed I forgot to add a library which loads the images(stb\_image), one oddity that I have noticed is that the libloader(a separate shared library) is found. I also analyzed it with apk analyzer and all the libraries are in the apk.

# Answer
The mistake was in a typo, the method getLibraries() takes in image-engine, while the library is built as image\_engine. If you have a better way of parsing libraries, please provide it in the comments or answers.
> 0 votes

---
Tags: android, porting, ndk
---


# Question
Title: How do I smoothly connect isometric tiles at different height levels?
I am trying to figure out how to smoothly connect isometric tiles at levels. For example, below are tiles at different levels.  I want to smoothly connect the tiles at the two levels based on the surface texture (the green grass on top). I can do a shear with the left and right halves of the top texture to connect a "corner", but I can't figure out what the transformation is to smoothly connect an entire face. For example, I want the 2nd level height to smoothly connect to the top texture of the bottom layer along the west facing side.

I looked at this old question here: How to create tilted (height) isometric tiles. but I can't understand the solution of "shearing to the right, then rotate by 45 and scale in height".

# Answer
> I looked at this old question here: How to create tilted (height) isometric tiles. but I can't understand the solution of "shearing to the right, then rotate by 45 and scale in height".

The person who asked that question had started with a square tile, then rotated and scaled it to get an isometric one:

The top answer there was to add a skew step to the process: skew, then rotate, then scale:

Doing the skew first makes the tile end up skewed relative to the isometric grid, so it still lines up with other tiles.

You do need to find the correct skew angle for your isometric grid. There's probably an equation for this, but I got to 27 degrees for my grid by trial and error.
> 3 votes

---
Tags: tilemap, tiles, isometric, pixel-art
---


# Question
Title: How to implement user friendly screen panning on 3D HTML canvas for RTS game
How can I get RTS map panning like how it was done in C&C red alert (with the mouse at the edge of the screen moves the screen in that direction) with a Babylon.js RTS game in the html canvas? This would be simple should I force the game to be full screen, but I don't think this would be practical.

I was thinking of checking that the mouse is near the edge of the canvas to pan but this could be annoying for the user. Perhaps I could force the mouse to be in the bounds of the canvas (in non fullscreen mode) until the user presses some shortcut key, but again I could be breaking the browser experiance.

Your advice?

# Answer
VirtualBox has a fantastic solution to this problem -- they lock your cursor inside the window, if you press the control key, in my case that's cmd. You have proposed this and I would deffinetly advise for it.

An example implementation of this would be, the user clicks on the game window and everything else darkens, to create the illusion of them being in the letterbox. When the user hits esc for menus or maybe even the lock-in key, turn the lights back on, to express the change.

There really isn't any other way of making an engaging RTS game, without screen panning. And since that is the usual case, players would be used to it already.

If you absolutely want to cater to everyone, I would also add a lock-less edge pan, but I, as a user, would be against that as it feels incredibly clunky.
> 1 votes

# Answer
I think your best approach would be to build a very basic prototype and see if it fits the game play style you want. That mechanic is called "edge panning", maybe you will find something under that name.

To implement it in a browser you may need the Pointer Lock API. Maybe you also want to add an alternative for using your game without a mouse but on a touch screen.
> 0 votes

---
Tags: html5, html-canvas, webgl, rts, screen-management
---


# Question
Title: How to prevent accidental double-tap dodge when changing directions?
```
    if Input.is_action_just_pressed("forward") or Input.is_action_just_pressed("backward") or Input.is_action_just_pressed("left") or Input.is_action_just_pressed("right"):
      dash_count += 1
    if dash_count == 2 and dash_timer < double_press_time:
      horizontal_velocity = direction * dash_power * 2.5

```

This checks if the the movement inputs are being pressed, if yes... gain one 1 point in dash count... dash count returns to zero after 0.3 seconds

if dash count is 0, you can't dash... if dash count is 2, your character will dodge/dash in the direction of movement.

The system exists to allow dodging by simply double pressing the movement keys... but I also realized that is quite easy to dodge by mistake by simply switching directions....

How do I fix this without creating a different timer for every single input? Also I tried reducing the dodge timer, but after testing it with my brother, I realized around 0.25 and 0.3 seconds is the safest as even a child can manage to dodge correctly with this timer.

# Answer
As Theraot explaind in a comment, you only need one additional variable, to store the previously tapped direction. Only activate the dodge if the latest tap is in the same direction as the previous.

```
if Input.is_action_just_pressed("forward") or Input.is_action_just_pressed("backward") or Input.is_action_just_pressed("left") or Input.is_action_just_pressed("right"):
    if tap_count == 0 or dash_timer > double_press_time:
        tap_count = 1
    else if tap_count == 1 and direction.dot(previous_direction) > 0.0:
        tap_count = 2
        horizontal_velocity = direction * dash_power * 2.5

previous_direction = direction

```
> 1 votes

---
Tags: movement, game-mechanics, input, gdscript, godot-3
---