# Question
Title: What are some ways to prevent a user from cheating by playing for a friend with a lower game skill level?
In a game with leagues for players with different skill levels, what are some ways to ensure a player can't get a higher-skill level friend to play for them? Want to maintain a good gaming experience for beginners.

# Answer
> 2 votes
There are none.

If a beginning player wants to ruin their experience by having a friend play for them, too bad (or good) for them.

If an experienced player wants to waste their time helping their beginning friend, they'll likely get bored at some point.

Keep in my mind that if a bad player gets boosted by a good player, they'll be clueless when they'll be left on their own with players really too good for them.

You *could* prevent this by having a closed environment where the players play, like an on-site tournament, but I suppose you don't have access to such infrastructure.

# Answer
> 0 votes
If this is a tournament-like situation (not an ordinary day by day ladder), you can put in some anti-impersonation rules, e.g. **ask players to stream their play** via Twitch with keyboard and display in view. Of course this is going to work only if there are enough players who agree to over-complicate their plays to such extent to avoid the fear of impersonators.

We had similar case in our game, where high-level players would enter the tournament twice or more (under real and fake identities). If they would have to stream their play, that would have made such behavior much more of a hassle or impossible.

---
Tags: multiplayer, anti-cheat
---


# Question
Title: MeshDataTool corrupting normals. What could be wrong?
When opening a mesh with MeshDataTool, even if I don't do any changes, committing the mesh turns it darker.

# Answer
> 0 votes
The problem was, that the obj file was indexed

---
Tags: godot
---


# Question
Title: How to snap a point to the height of the navmesh surface?
I'm making generator for EQS and need to put points on navmeshes located on different heights, one above other. So, my idea is to make raycast vertically and find intersection points with navmeshes. But how to do it?

I tried to set CollisionResponseChannel to NavMeshBoundsVolume but all raycast hits happened on the edge of volume's box, not on navmesh.

# Answer
> 3 votes
I found the function what does exactly what I need:

```
bool ARecastNavMesh::ProjectPointMulti(const FVector& Point, TArray<FNavLocation>& OutLocations, const FVector& Extent,
    float MinZ, float MaxZ, FSharedConstNavQueryFilter Filter, const UObject* QueryOwner) const

```

There is the example of usage:

```
void UEnvQueryGenerator_VolumetricGrid::NavigationRaycast(TArray<FNavLocation>& Points, const FVector& Position, FEnvQueryInstance& QueryInstance) const
{
    const UObject* Querier = QueryInstance.Owner.Get();

    const ANavigationData* NavData = nullptr;
    NavData = FEQSHelpers::FindNavigationDataForQuery(QueryInstance);

    const ARecastNavMesh* NavMeshData = Cast<const ARecastNavMesh>(NavData);
    if (NavMeshData == nullptr || Querier == nullptr)
    {
        return;
    }

    FSharedConstNavQueryFilter NavigationFilter = UNavigationQueryFilter::GetQueryFilter(*NavData, Querier, ProjectionData.NavigationFilter);

    TArray<FNavLocation> HitLocations;
    const FVector ProjectionExtent(ProjectionData.ExtentX, ProjectionData.ExtentX, (ProjectionData.ProjectDown + ProjectionData.ProjectUp) / 2);

    NavMeshData->ProjectPointMulti(Position, HitLocations, ProjectionExtent, Position.Z - ProjectionData.ProjectDown, Position.Z + ProjectionData.ProjectUp, NavigationFilter, Querier);

    for (int32 HitIdx = 0; HitIdx < HitLocations.Num(); HitIdx++)
    {
        Points.Add(HitLocations[HitIdx]);
    }
}

```

---
Tags: physics, unreal-4, raycasting, navmesh, intersection
---


# Question
Title: C# Jobs + Burst executing slowly (bottleneck?)
I'm trying to make a system where the player can do a RTS-like drag-to-select of tiles in a box to mark trees to be chopped or ores to be mined.

I'm testing this system on a large scale, possibly selecting 300x300 or up to 500x500 tiles per frame. For this, I thought jobs + burst would be a good idea. Every time the cursor moves, I check this if this large array of tiles is inside the bounds of the map (a 100x100 rectangle), but it's worth noting this system might be doing other checks as well.

However, using Unity's profiler (deep profile) I don't even use the returned array for anything and I'm getting pretty awful results:

It seems like the actual jobs themselves are taking up a tiny fraction of the time (tiny green columns inside the marked red area) but something else on the main thread is bottlenecking it. Here's some of the popups that occur when I click on some of the huge blue bars in the main thread:

Am I bottlenecking the main thread by initially filling out the NativeArray on the mainthread before even starting the jobs?

Here's the code for the main thread method:

```
private void UpdateBoxSelection()
{
    Vector3Int newEndNode = Map.GridPosFromMousePos();

    if (newEndNode == EndNode) { return; }

    SelectedNodes.Clear();
    EndNode = newEndNode;

    var lowerLeftTile = new Vector3(Mathf.Min(StartNode.x, EndNode.x), Mathf.Min(StartNode.y, EndNode.y));
    var upperRightTile = new Vector3(Mathf.Max(StartNode.x, EndNode.x), Mathf.Max(StartNode.y, EndNode.y));

    int howManyToCheck = (Mathf.Abs(EndNode.x - StartNode.x) + 1) * (Mathf.Abs(EndNode.y - StartNode.y) + 1);

    var uncheckedNodes = new NativeArray<float3>(howManyToCheck, Allocator.TempJob);

    int index = 0;

    for (int x = (int) lowerLeftTile.x; x <= upperRightTile.x; x++)
    {
        for (int y = (int) lowerLeftTile.y; y <= upperRightTile.y; y++)
        {
            uncheckedNodes[index] = new float3(x, y, 0);
            index++;
        }
    }

    var job = new ReallyToughParallelJob
    {
        UncheckedNodes = uncheckedNodes,
        xMin = Map.Instance.Rect.xMin,
        xMax = Map.Instance.Rect.xMax,
        yMin = Map.Instance.Rect.yMin,
        yMax = Map.Instance.Rect.yMax
    };

    JobHandle handle = job.Schedule(howManyToCheck, 1000);
    handle.Complete();

    uncheckedNodes.Dispose();
}

```

And the code for the Job:

```
[BurstCompile]
public struct ReallyToughParallelJob : IJobParallelFor
{
    public NativeArray<float3> UncheckedNodes;

    [ReadOnly] public float xMin;
    [ReadOnly] public float xMax;
    [ReadOnly] public float yMin;
    [ReadOnly] public float yMax;

    public void Execute(int index)
    {
        float3 newNode = UncheckedNodes[index];

        if (Contains(newNode)) { UncheckedNodes[index] = newNode; }
        else { UncheckedNodes[index] = float3.zero; }
    }

    public bool Contains(float3 point)
    {
        return point.x >= (double) xMin && point.x < (double) xMax && point.y >= (double) yMin && point.y < (double) yMax;
    }
}

```

# Answer
> 1 votes
Yes, it indeed appears as if the majority of the execution time goes into building the NativeArray with all the tile coordinates, while the job operating on said array only takes a tiny fraction of the computational time.

But that array does not even contain very useful data. It's really just a consecutive list of all the coordinates within a large rectangle. Some things you could try are:

* Don't parallelize per-tile, parallelize per-row. Create a `NativeArray<int>` of the row numbers you want to check, and then have the Execute-function perform a for-loop over the tiles from start to end of the row. This still gives you 100 units of work for a 100x100 selection. Still more than enough granularity for letting the engine distribute the load on multiple cores in an efficient manner.
* Create a permanent NativeArray for all tiles on the map which you create once (`Allocator.Persistent`). Then use `NativeSlice`s to tell the job system which tiles you want checked.
* Use another (non-parallel) job to build the `UncheckedNodes` NativeArray. A burst-compiled job might be able to do that more efficiently than regular C# code. Then schedule the `ReallyToughParallelJob` with the array-building job as a dependency.
* (probably the best solution) Don't use the array at all. Replace it with these fields to the job which tell the job the area it's supposed to iterate:

```
[ReadOnly] public float xStart;
[ReadOnly] public float width;
[ReadOnly] public float yStart;
// height is implied by the iteration count you pass when you schedule the job

```

And then calculate the tile coordinates of the current tile in the Execute method:

```
x = index % width + xStart;
y = index / width + yStart;

```

---
Tags: unity, c#, performance, unity-job-system, burst
---


# Question
Title: Puzzle idea wanted: Locate a point from n/x known locations
Am working on an open 2D world, random-generated game where the player will over time find certain, (apparently)randomly placed locations. The player is guided through other means to those locations to make them reasonably easy to find. There is an arbitrary number of those locations and the player can view them on a 2D map.

Now for gameplay sake, I'd like that every further location they find, makes it more clear where a certain, special location is on the map (finding it could be the goal of the game for example).

When they have, for example 5 of them, it should be "relatively exact". I'm happy to provide the player some sort of geometric tools on the map etc. but the theme of the game is more or less realistic, so the map should not just magically show them the target locations directly triggered by finding the 5th location. It should be a challenge...

All the locations including the goal one shall be predetermined when the game starts and it's unknown in what order the player will find them.

Does somebody happen to have an idea for such an approach?

My first idea was to use the centroid, aka gravity center of a polygon formed by the locations, but that can be somewhere entirely different when having 5 location compared to when having 8 locations. Thus since I don't know the order in which the player will find the locations, this does not work.

Am happy for any input :)

# Answer
Here are a couple of potential approaches.

One is to place your secret location first, then draw a small number of (hidden) lines through it. Place your other locations along those lines. (They don't have to sit *exactly* on the line - clustering them *near* the line is enough) You could think of these as "ley lines" connecting important sites.

With just a small number of locations found, it's hard to tell where the lines are, since *any* two points make a line. But as you fill in more and more, you can start to identify the pattern. Once you can spot two clear lines, head to the place where they meet to find the secret location.

---

Another method is to place some indicator feature at each of your locations that hints the *direction* to the secret location. Something like a standing stone facing a particular compass bearing. You can control the difficulty of the puzzle by varying how exactly you indicate the direction. In the example below, I snap the indicator to the closest cardinal/semi-cardinal direction, so you need more than just a few locations to triangulate the secret location's position.

You could show these directional cues on the player's map as I've done here, or give them the tools to annotate the map with their directional discoveries once they notice/uncover this feature.

(Minor spoiler for The Witness follows)

> These obelisks in The Witness use this strategy. Each of the 8 faces of the obelisk lists the discoverable patterns that can be found somewhere in the 45-degree arc of the map in the direction it faces. This isn't a super precise guide, but enough of a clue to get the player looking in the right direction. In their case, the patterns are always close to the obelisk, so you could also consider using different cues for "this direction, nearby" versus "this direction, far"
> 2 votes

---
Tags: puzzle
---


# Question
Title: Placing player hand on wall, only works with right-angled walls
```
RaycastHit hit = Interactor.hit;
Transform hitCollider = hit.transform;

Vector3 xPoint = Vector3.Scale(hit.point - hitCollider.position, hitCollider.right);
LeftHand.position = hitCollider.position + Vector3.Scale(xPoint, hitCollider.right);

```

This script runs whenever the camera is pointed at a `Wall` object and `LeftMouseButton` is pressed. The hand (sphere) should be placed within the wall, sticking to the location of the `RaycastHit`. For brevity, I've cached the position of the `RaycastHit.point` and the transform of the wall from the ray collision. I've also omitted the offsets which move the hand to the corner, since they work fine on their own. For now I'm only concerned with matching the wall's X axis.

As you can see, this works fine on walls rotated to 90° angles, but at any other rotation there's some funny business going on. The hand is placed too close to the player, and its position on the wall's X axis is reluctant to stray from the wall transform.

I imagine the issue is either with `Vector3.Scale` or `hitCollider.right`. In either case, I'm at a loss for alternatives.

Also, the walls are all rotated so that their forward axis faces away from the player. If this is ever an issue I'll just make one hitbox for each side.

I should also say I can't use the normal of the `raycastHit`, as sometimes I'll want an oversized hitbox which can be hit from below or above.

# Answer
> 2 votes
**SOLUTION:**

Thanks to DMGregory showing how to use `Vector3.Dot()`, I was able to fix the solution *and* easily change the `zOffset` depending on which side of the wall the player is on. Also thank you to Pikalek for fixing my post formatting.

```
hit = Interactor.hit;
anchor = hit.transform;

float playerSide = Mathf.Sign(Vector3.Dot(transform.forward, anchor.forward));

Vector3 yOffset = new Vector3(0, anchor.localScale.y / 2, 0);
Vector3 xOffset = Vector3.Dot(hit.point - anchor.position, anchor.right) * anchor.right;
Vector3 zOffset = (anchor.localScale.z / 2) * (anchor.forward * playerSide);

hand.position = anchor.position + (xOffset + yOffset - zOffset);

```

# Answer
> 1 votes
Your vector projection expression is incorrect for the general case. It's basically coincidence that it works when all axes but one are zero and the remaining is ±1. What you want is this:

```
// Project displacement from collider to hit point onto local x-axis.
Vector3 xOffset = Vector3.Dot(hit.point - hitCollider.position, hitCollider.right)
                * hitCollider.right;

// (Note that by construction, this vector must point parallel to hitCollider.right)

// Add projected offset back to collider position to get a point along its local x-axis.
LeftHand.position = hitCollider.position + xOffset;

```

(I've renamed your variable because it's not a point in space, but a displacement / offset *between* points - this distinction is important during transformation)

Another way to express this is:

```
// Convert the position to the collider's local coordinate system.
Vector3 local = hitCollider.transform.InverseTransformPoint(hit.point);

// Zero out the axes we don't want.
local.y = 0;
local.z = 0;

// Convert back to world coordinates.
LeftHand.position = hitCollider.transform.TransformPoint(local);

```

---
Tags: unity, c#, transformation, raycasting
---


# Question
Title: Scene lightning is wrong when scene is loaded from a different scene
I have a problem with the light in my scene. If I start the scene directly, it looks like I want it to be. If I load the scene from another, the light is too dim. Lighting is still applied, but everything is darker than it is supposed to be.

Used version is 2021.1.15f1, there is no lighting selected under Rendering/ Lighting/ Scene.

There is no code that is manipulating the lighting, a single directional light is used. If I deactivate the spot light, it gets even darker.

Loading the scene directly:

Loading the scene from a different scene:

Directional light settings:

# Answer
> 4 votes
It appears that my Lighting Settings went corrupt and Unity went back on default settings, similar to when none are added. Unlike when they are missing fully, the error did not throw the usual "Lighting has been disabled" or similar errors. Deleting them from Lighting Settings in all scenes, generating new settings and assigning them again fixed the problem.

If someone else is stumbling to something similar, it can be found under Window/ Rendering/ Lighting.

---
Tags: unity, lighting
---


# Question
Title: How to calculate SDF intersection for union and primitive?
First I union A1 and A2 (with min). A2 distance is closest. Then I do intersect (max) between the union A (min of a1 and a2) and B rectangle. Distance to A2 is result. But that doesn't help me to to render only the intersection.

# Answer
> 2 votes
The result you are getting should help you if you are going to do ray marching.

The result you get `d = max(min(a1, a2), b)` is a minimum safe distance you can advance the ray, in any direction, and be sure you won't collide with anything. This does not mean you will collide at that distance, it means you need to sample again at that distance.

The issue is that these operations done with `min` and `max` are not an exact SDF. They are only lower bound (it is equal or smaller than the exact SDF) with the correct contour at zero. This is good enough to render with ray marching, even though it means extra iterations. *Be aware the ray marching may require a lot of iterations anyway, in particular when a ray is passing nearby the geometry.*

Sadly, **there is no general solution to compute the exact SDF of an union, subtraction or intersection of SDFs**. If you need an exact SDF of the result you will need a function capable of generating the SDF directly from the description of the shape, instead of manipulating SDFs with union, subtraction or intersection.

*As mental exercise, consider that the intersection of `a2` and `b` is void. What SDF would you expect to get? With `max` you get an "SDF" that is zero nowhere - which is correct - but it still has local minima that correlates to the contour of the shapes.*

I'll refer you to Inigo Quilez article on Interior SDFs for further reading.

---
Tags: signed-distance-field
---


# Question
Title: How to make the object to move to the target smooth ease in out from the player hand and back?
The problem is that I'm using Lerp and if I'm making the transform to move from the originPosition to the target(destinationTransform) it's not moving from the player hand but from another position near the player.

This screenshot is the transform object in the player hand as the original position it's should be the original position :

Then when the transform start moving to the target he start moving not from the hand but from a position near the hand :

This line is making the transform moving :

```
transform.position = Vector3.Lerp(originPosition, destinationTransform.position, curve.Evaluate(s));

```

If I'm changing in this line from originPosition to transform.position then it will move from the hand but the duration will not be 10 seconds or the time I'm setting.

```
transform.position = Vector3.Lerp(transform.position, destinationTransform.position, curve.Evaluate(s));

```

What I'm trying to do is to move the transform to the target stay at the target hang there X seconds and the start moving back.

and only when it's moving back top make the transform in the end to be Transferring as child of the target(the player hand) when reaching to the target that is not the player hand don't make it child only on the way back.

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

public class MoveToTarget : MonoBehaviour
{
    public enum TransitionState
    {
        None,
        MovingTowards,
        Transferring
    }

    public Transform destinationTransform;
    public bool isChild = false;
    public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
    public float duration = 10.0f;
    public bool go = false;

    private float t;
    private Transform originTransform;
    private float timer;
    private TransitionState state = TransitionState.MovingTowards;
    private Vector3 originPosition;
    private SphereCollider col;
    private bool enableCollider = true;

    void Start()
    {
        t = 0.0f;

        curve.postWrapMode = WrapMode.Once;
        originPosition = transform.position;
        col = GetComponent<SphereCollider>();
    }

    void Update()
    {
        if (go)
        {
            if (col != null && enableCollider)
            {
                //col.enabled = false;
                //transform.GetComponent<Rigidbody>().isKinematic = true;

                Destroy(col);
                Destroy(transform.GetComponent<Rigidbody>());
                transform.GetComponent<InteractableItem>().enabledInteraction = false;

                enableCollider = false;
            }

            switch (state)
            {
                case TransitionState.MovingTowards:
                    var v = destinationTransform.position - transform.position;
                    if (v.magnitude < 0.001f)
                    {
                        state = TransitionState.Transferring;
                        originTransform = destinationTransform;
                        timer = 0;
                        return;
                    }

                    t += Time.deltaTime;
                    float s = t / duration;

                    transform.position = Vector3.Lerp(originPosition, destinationTransform.position, curve.Evaluate(s));
                    break;

                case TransitionState.Transferring:
                    timer += Time.deltaTime;
                    this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);

                    if (timer >= 1.0f)
                    {
                        this.transform.parent = destinationTransform;
                        transform.localPosition = new Vector3(0, 0, 0);
                        isChild = true;

                        go = false;

                        state = TransitionState.None;
                        this.enabled = false;
                        return;
                    }
                    break;

                default:
                    this.enabled = false;
                    return;
            }
        }
    }
}

```

# Answer
Okay. Depending on what you're doing with this, a coroutine might be more appropriate. It allows you to "fire and forget", with the added bonus that local variables are kept alive as long as the coroutine is, so you don't need long-lived state cluttering your classes up.

I think you're overcomplicating things, unless there's more logic not shown that explains the structure you've adopted.

How about something like this:

```
    IEnumerator GoAndReturn(Vector3 target, float duration = 10) {
        var parent = this.transform.parent;
        this.transform.parent = null;

        var originPosition = this.transform.position;

        var startTime = Time.timeAsDouble;

        var t = 0f;
        while (t <= 1) {
            // t varies from 0 to 1 over duration
            t = (float)((Time.timeAsDouble - startTime) / duration);
            // Assuming a curve that returns from 0 to 1 as s varies 0->1
            if (t < 0.5) {
                // Outward journey
                transform.position = Vector3.Lerp(originPosition, target, curve.Evaluate(t * 2));
            } else {
                //return journey
                transform.position = Vector3.Lerp(parent.transform.position, target, curve.Evaluate((1 - t) * 2));
            }
            yield return null;
        }
        this.transform.parent = parent;
        this.transform.localPosition = Vector3.zero;
    }

```

Then you can invoke it with:

```
    StartCoroutine(GoAndReturn(destinationTransform));

```

or

```
    StartCoroutine(GoAndReturn(destinationTransform, duration: 5));

```
> 0 votes

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


# Question
Title: Visual Studio Code Unity AutoComplete still not working
I am having an issue with Visual Studio Code AutoComplete for Unity.

Some of the autocomplete is working, such as: `void Start()`, `void Update()`, but most of the rest of Unity Autocomplete is not working such as: `GameObject`, `Rigidbody`, `Input.GetKey`, etc..)

I know VScode and Unity are not connected like how Unity and Visual Studio are, but it seems that a lot of people make it work somehow, so I thought it is possible to make it work without much trouble.

* I have the extensions needed to make it work (C#, Unity Tools, Unity Snippets Code etc...)
* I have set vscode as my script editor (Unity -\> Edit -\> Preferences -\> External Tools)
* I installed .NET Core SDK and .NET Framework 4.6 Targeting Pack
* I tried uninstalling Unity and vscode but that didn't work either...

How can I solve this?

# Answer
> 1 votes
I used to have the same problem, please check which version of omnisharph you have installed, the newest version have a problem with the intellisense, try to install an older version of the omnisharph and it will work ! Also try to check if you have the required plugins for Unity.

# Answer
> 1 votes
I used the following method and it worked:

1. Change in External Tools: Edit -\> Preferences :choose " Visual Studio Code"
2. Open file : Assembly-CSharp-Editor in your project folder and Download the Framework Version that is the same as the version in this file EX: v4.7.1
3. Open VScode tool - Settings - \>code lens and tick.

# Answer
> 0 votes
Try right clicking in the folder view, and click open c# project, that fixes it for me

# Answer
> 0 votes
* See if visual studio code is installed in Unity package manager.
* In Visual Studio Code, install the following extensions : Debugger for Unity, Unity tools, Unity Code Snippets

# Answer
> 0 votes
In my case, I didn't installed any .Net, I just installed an older version (1.16.21) of c# extension, I hope this helps

---
Tags: unity, c#, ide, visual-studio-code, code-hinting
---


# Question
Title: How can I move the object constantly downward in pygame?
I want the object to move continuously downward even while I'm pressing the upward key in keyboard. Eventually causing the object to drop completely after some moment.

```
character = pygame.image.load('pngfile')
character_size = character.get_rect().size

to_x = 0
to_y = 0

clock = pygame.time.Clock()

character_speed = 0.05

velocity_y = 0.1

#eventloop
running = True
while running:
        dt = clock.tick(60)
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        running = False
                character.move_ip(0, velocity_y * dt)

```

so on and so on. I skipped the unnecessary parts to keep it short. Whenever I type the last line, `move_ip` doesn't become a method. It works find when I changed the object to `pygame.Rect()` but I don't know why this one isn't working. I got the keyboard control right but I just couldn't make the object to move constantly. Any help will be greatly appreciated.

# Answer
> 1 votes
because `character` is a `pygame.Surface`, not a `pygame.Rect`, so it can't be moved: `AttributeError: 'pygame.Surface' object has no attribute 'move_ip'`

the `Rect` and `Surface` are two are different but related objects: the `Rect` describes the position and size of the thing we want to draw, and the `Surface` describes the image that we want to draw.

In your example code, `character_size` isn't a `Rect` either, just a two-tuple containing `(width, height)`. That is the size we want, but it needs to be applied to a `Rect` first.

Once you have a `Rect` of the proper size, then you can update its position with `Rect.move_ip`.

Finally, you can draw `character` using this rect.

```
screen = pygame.display.set_mode((240,180))
character = pygame.image.load('test.png')

# note - I am copying the entire rect rather than just
# its size so that I have something to move.
character_rect = character.get_rect().copy()

clock = pygame.time.Clock()
velocity_y = 0.1

running = True
while running:
        dt = clock.tick(60)
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        running = False
        character_rect.move_ip(0, velocity_y * dt)
        screen.fill(pygame.Color(0, 0, 0, 255))
        screen.blit(character, character_rect)
        pygame.display.flip()

```

When I run this altered script, I do indeed see the image moving down the screen.

---
Tags: pygame
---


# Question
Title: Blueprint can't pull a function from a Widget
I am working on a project and I am stumped on something and it is taking me to long to fix this issue.  As seen above I am this is where I am, what I need to do is set up a widget text that changes by what the player does. The problem is I have been following this tutorial, which is found here -\> https://www.youtube.com/watch?v=ILtVovyqrmY&t=1097s It starts at 16:09 for the starting point of my problem and ends at 19:42, and I have somehow got stuck.  As seen above he can easily pull the function out of the widget but when I try it won't allow me too. Can someone help me please?

(Note: I have the name for the character changed for my version of the game compared to the tutorial and the text is different because of the video maker changing the name and moving it somewhere.)

Below here is a number of screenshots that show the game and the main concern.

# Answer
> 1 votes
Why is Your WBP\_BarkText a widget of type "Editor Utility Widget" (Light Blue widget blueprint color)? It should be of type "User Widget" (Dark Blue widget blueprint color), you can find it by right clicking in the Content Browser and hovering over "User Interface" and then clicking "Widget Blueprint". Go back to the vid and redo the steps after the widget blueprint was created and use the correct type of widget blueprint, it should work afterwards, good luck! :)

Here's a screenshot for clarification.

---
Tags: unreal-4, blueprints
---


# Question
Title: Worker threads are not being utilized in Time rewind system, is this job system really multi-threaded?
I am trying to make a simple time rewind mechanic. It's working but it becomes slower as number of game objects increases. I decided to give Job System a shot. My idea is to interpolate between positions and rotations for N game objects in parallel. It is certainly running faster than single thread execution.

However, when I see the profiler, the worker threads are sitting idle.

Here's the screenshot:

And here's the IJob code:

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

[BurstCompile]
struct RewindJob : IJob
{
    public int RewindableIndex;
    [ReadOnly]
    public NativeArray<Vector3> positions;

    public NativeArray<Vector3> finalPositions;
    public float currentTime;

    public void Execute()
    {
       //rewind code for interpolating b/w positions
    }
}

```

and this is how I schedule RewindJob for each entity like this in main thread:

```
NativeArray<Vector3> finalPositions = new NativeArray<Vector3>(m_Objects.Count, Allocator.TempJob);

for (int i = 0; i < m_Objects.Count; i++)
{
    NativeArray<Vector3> positions = new NativeArray<Vector3>(count, Allocator.TempJob); ;

    TimeRewindable rewindable = m_Objects[i];

    for(int yo = 0; yo < count; yo++)
    {
        positions[yo] = rewindable.m_Transforms[yo].position;
    }

    RewindJob rewindJob = new RewindJob();
    rewindJob.finalPositions = finalPositions;
    rewindJob.positions = positions;
    rewindJob.RewindableIndex = i;

    JobHandle handle = rewindJob.Schedule() ;
    handle.Complete();
    positions.Dispose();
}

for(int i = 0; i < m_Objects.Count; i++)
{
    m_Objects[i].transform.position = finalPositions[i];
    m_Objects[i].transform.rotation = finalRotations[i];
}

finalPositions.Dispose();
finalRotations.Dispose();

```

What I can understand is it's not real multi-threading but context switching. Can anyone just explain a little bit what's happening? Thanks.

# Answer
> 1 votes
When you want Unity to run multiple jobs in parallel, then you have to let it. You are scheduling multiple jobs in a loop, but each time you call

```
JobHandle handle = rewindJob.Schedule() ;

```

you immediately call

```
handle.Complete();

```

The Complete-method will wait until the job is finished. That means that your code ensures that no job will be scheduled until the previous job has completed. So what would Unity need a second worker-thread for?

If you want to give Unity a chance to run all those jobs in parallel, then

1. Create a `new NativeArray<JobHandle> handles(m_Objects.Count, Allocator.TempJob);`
2. Collect the return value of Schedule in that array
3. After you scheduled all the jobs, call `JobHandle.CompleteAll(handles);`

Unity will then be obligated to finish all the jobs in `handles` as quickly as possible, which will probably mean that it is going to use multiple worker-threads.

---
Tags: unity, multithreading, unity-job-system
---


title: Why is Area2D not detecting collisions?

text:
# Question
Title: Why is Area2D not detecting collisions?
I am making a sidescrolling shooter and I am working on the shooting mechanism. I have two scenes, one contains a KinematicBody2D with a Sprite, position2D and a collisionshape2D and a second KinematicBody2D with a CollisionShape for testing bullet collision. The scene also has a Tilemap called Level. In the second scene I have an Area2D with sprite and collisionshape as my bullet.

Code for the bullet (Only important parts):

```
extends Area2D

onready var sprite = get_node("/root/Game/Player/Sprite")

func _on_VisibilityNotifier2D_screen_exited():
    print("Freed")
    queue_free()

func _on_Bullet_body_entered(body):
    print("Entered: ", body.name)

```

Player shoot() function:

```
func shoot():
    var bullet = Bullet.instance()
    get_node("/root/Game").add_child(bullet)
    bullet.global_position = $Position2D.global_position

```

Upon starting the game this is printed out, without the player having shot:

```
Entered: Player
Entered: Level
Freed

```

When shooting into the second KinematicBody2D, nothing happens at all, the bullet only gets freed after exiting the screen.

What am I doing wrong?

# Answer
You say that:

> Upon starting the game this is printed out, without the player having shot:
>
> ```
> Entered: Player
> Entered: Level
> Freed
>
> ```

This suggest that you have a an instance of the `Area2D` in the scene tree before hand. What you want is to have the bullet and whatever it needs as a separate scene that you instance.

Which is what I expect the line `Bullet.instance()` does. To be clear, here `Bullet` must refer to a `PackedScene` loaded from a separate scene file.

---

And you say that:

> When shooting into the second KinematicBody2D, nothing happens at all, the bullet only gets freed after exiting the screen.

This suggest that the `"body_entered"` signal is not connected on the `Bullet` scene (on the separate file, that you loaded into `Bullet` the signal is not connected, probably). I'm guessing you only connected it on the instance you have on your scene tree before hand, which explains why that one prints `Entered: Player` and `Entered: Level`.

---

I might be guessing wrong. But, in general terms: You want a separate scene file for the bullet, that you can load and instance on demand (I'm guessing you already have it). Make sure that separate scene file has all that it needs to work, so that they work regardless or where or when you instance it. *You may take advantage of Autoloads \- which are available everywhere all the time, unless you remove them explicitly - if you need to get something from outside*. Also make sure you don't have a bullet instanced in the scene before hand.
> 1 votes

---
Tags: collision-detection, godot, gdscript
---


# Question
Title: How to use AddComponent to add an instance of the derived class, not the base class that defines the method?
This is my base class

```
using UnityEngine;

public class Weapon : MonoBehaviour, IInteractable
{
    public void Interact(Player player)
    {
        player.gameObject.AddComponent<Weapon>();
    }
}

```

It's extended by different children such as Pistol and M16. How can I make it so that the Interact function of the base class adds the child script instead of the base script?

# Answer
> 3 votes
You can accomplish this using the Curiously Recurring Template Pattern:

```
public class Weapon<T> : MonoBehaviour, IInteractable where T: Weapon<T> {

    public void Interact(Player player) {
        player.gameObject.AddComponent<T>();
    }
}

public class RangedWeapon : Weapon<RangedWeapon>
{
    // Put anything the derived weapon class needs here.
}

```

When the compiler generates the code for `RangedWeapon.Interact`, the `T` placeholder type becomes `RangedWeapon`, and so the component that gets added is this weapon's own type.

---

However, I'd recommend that you separate the concepts of "Weapon Pickup the player can interact with to pick up / equip the weapon" from "Weapon Behaviour running on the player object that the player can shoot".

These might conceptually be the same thing in terms of the game's fiction (the AK47 sitting on the ground is the same AK47 I pick up and fire), but in terms of the game's implementation they often have very little in common. One needs to shoot and one doesn't. One needs to listen for pick-ups and the other doesn't. They might not even use the same model and texture, if you have high-detail versions to show in the player's hands.

So instead you could do something like this:

```
public class WeaponPickup : MonoBehaviour, IInteractable {

   public Weapon weaponToEquip;

   public void Interact(Player player) {
       var weaponInstance = Instantiate(weaponToEquip, player);
   }
}

```

You can then create a prefab for each weapon (possibly many different variants using the same scripts) and use a single script to represent interactable versions of *any* of them.

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


# Question
Title: Assign biomes to areas with a Voronoi noise function
I've created this terrain based on a Voronoi noise function:

This is how it looks without the elevation:

I want to assign biomes to the polygons following certain rules and use the slope on the polygons to create the smooth transition between biomes. So in conclusion I need to identify the areas and its neighbors. For the moment I am only able to iterate through every vertex in the plane and get his position. Do you have any idea on how to store the areas with its neighbors to create the biomes map for my world?

# Answer
The dual graph of a Voronoi diagram is a Delaunay Triangulation:

(The corners of the Voronoi polygons are the circumcenters of Delaunay triangles, and the seed points of the Voronoi diagram are the vertices of Delaunay triangles. Corresponding edges of the two diagrams are perpendicular)

This relationship is so key that many libraries/algorithms for generating Voronoi diagrams will also provide you with corresponding Delaunay triangles if you ask, making this a convenient starting point.

One simple way to assign weights to your biomes is to use these triangles, because they have consistent topology: every triangle connects exactly three biomes.

For each point you want to generate, determine which Delaunay triangle it sits within. That determines which three neighbouring Voronoi cells you need to blend.

Generate your biome-specific data using the rules for each of these three Voronoi cells respectively.

Next, find the barycentric coordinates of the point you're generating within the triangle. This is a set of three numbers - one for each vertex. When your point is exactly at one of the vertices, that vertex's weight is 1.0. When your point is on the opposite edge from a vertex, that vertex's weight is 0.0.

So you can use these directly as blend weights for the three biome outputs, and get C0 continuity along the edges of the triangles.

You can still have first derivative discontinuity, however - if that's noticeable for your particular biomes and terrain resolution/rendering, then you may need to use a more complicated blending function.
> 2 votes

---
Tags: javascript, procedural-generation, tilemap, three.js, noise
---


# Question
Title: CustomEditor GUI button hides all public fields in inspector?
I am new to Unity. I have a simple game object with one script attached to it and then another script to add a button which will call the function within the script attached to the game object. My problem is I want to have two editable fields `height` and `width` but if the custom editor is added to the game object then those public fields no longer display in the inspector window...Not sure why?

WorldGenerator.cs:

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

public class WorldGenerator : MonoBehaviour {

public int height;
public int width;

public void RunWorldGeneration()
{
    Generate worldGenerator = new Generate();
    float[,] world = worldGenerator.GenerateWorld(width, height);

}
}

```

WorldGeneratorEditor.cs:

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

[CustomEditor(typeof(WorldGenerator))] // If I comment this out the public variablbes show
// If it is uncommented, then just the button with "Generate" text shows
public class MapGeneratorEditor : Editor
{

public override void OnInspectorGUI()
{
    WorldGenerator worldGen = (WorldGenerator)target;

    if (GUILayout.Button("Generate"))
    {
        worldGen.RunWorldGeneration();
    };
}
}

```

# Answer
> 2 votes
From the docs on Editor.DrawDefaultInspector():

> Description
>
> Draw the built-in inspector.
>
> Call this function from inside OnInspectorGUI method to draw the automatic inspector. It is useful you don't want to redo the entire inspector, but you want to add a few buttons to it.

If you don't include a call to this method, Unity will assume your custom inspector is drawing everything it wants drawn — that way you can draw fields in customised ways without them showing up twice, or hide serialised fields you don't want to edit directly.

# Answer
> 1 votes
It's usually best practise to add `base.OnInspectorGUI();` at the top of the `OnInspectorGUI()` method.

public override void OnInspectorGUI()
{
    base.OnInspectorGUI();

    WorldGenerator worldGen = (WorldGenerator)target;

    if (GUILayout.Button("Generate"))
        worldGen.RunWorldGeneration();
}
```

---
Tags: unity
---


title: Create buttons in the editor

text:
# Question
Title: Create buttons in the editor
So I've seen people do stuff like

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

public class [ScriptName] : Editor
{
   // A bunch of code that I can't understand.
}

```

but what exactly do they do to make buttons on their script?

# Answer
> 1 votes
Unity provides an ability to override the `OnInspectorGUI` function which is called when drawing an inspector window for a specific script.

The way it works is you can just create a new class derived from Editor class and tell the unity to create our custom inspector windows for your specific script.

And then in your `OnInspectorGUI` you can ask unity to draw all sorts of controls including buttons, color dialogs, sliders, etc!

**Now to make a simple button with the traditional "Hello World" text, follow this code:**

```
using UnityEngine;
using UnityEditor;

public class MyScript : MonoBehaviour
{
    public bool doesntMatter;
}

[CustomEditor(typeof(MyScript))]
public class MyScriptEditor : Editor
{
    void OnInspectorGUI()
    {
        var myScript = target as MyScript;
        myScript.doesntMatter= EditorGUILayout.Toggle("Hello World"); //Returns true when user clicks
    }
}

```

---

---

**Now if you've got a good grasp, here's something that you might actually need when creating custom inspector windows:**

*When the user toggles a checkmark, more variables wqill be shown to the user.*

```
using UnityEngine;
using UnityEditor;

public class MyScript2 : MonoBehaviour
{
    public bool show = false;
    public int num1;
    public float num2;
    public bool anotherToggle = false;
    public GameObject go;
}

[CustomEditor(typeof(MyScript2))]
public class MyScript2Editor : Editor
{
    void OnInspectorGUI()
    {
        var myScript2 = target as MyScript2;

        myScript2.show = EditorGUILayout.Toggle("Show Hidden Values");
        myScript2.anotherToggle = EditorGUILayout.Toggle("Show Another Hidden Value");

        if(myScript2.show)
            myScript2.num1 = EditorGUILayout.IntField("Enter a number:", myScript2.num1);
            myScript2.num2 = EditorGUILayout.Slider("Choose float between 1 to 10:", myScript2.num2, 0, 10f);
            if(myScript2.anotherToggle)
                myScript2.go = EditorGUILayout.ObjectField("Very hidden gameObject:", go, typeof(GameObject));
    }
}

```

---

---

---

Hope this helped you create your first inspector windows :)

# Answer
> 1 votes
A solution I often use is creating "pseudo-buttons" using bools and Unity's OnValidate() method

```
    void ExampleMethod()
    {
        Debug.Log("Hello World!");
    }

    public bool pseudoButton = false;
    void OnValidate()
    {
        if (pseudoButton)
        {
            ExampleMethod();

            pseudoButton = false;
        }
    }

```

It's a bit of a hacky, but its useful for quick debugging, and to not waste time with creating a new custom

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


# Question
Title: Techniques to make 3D models to look like oil paintings
I intend to develop a fantasy 3D game focused on warships, with a look similar to oil paintings.

The reasoning behind this decision is that the art style would allow for a sense of wonder and curiosity.

Currently, the most viable technique I could think of was to make the 3D models into "onions" with multiple layers one after another with multiple types of strokes. But this seems very labor intensive to me, and would probably make the models too heavy to run efficiently (I haven't tested it yet, I'm looking for references before trying).

The main problem is that I couldn't find anything concrete and free to use that could match an oil painting.

The most pertinent example I come across is Arcane, where they use Digital Painting to texture (I think it's texturing and not a machine learning program that paints frame by frame) the characters.

I also found a PS4 game which is a game creation tool called "Dreams", however I don't own a PS4 and I wouldn't be able to extract the models created there for Blender either.

I also found some programs that use machine learning to turn videos into animated oil paintings, but it only works with videos and I don't have the knowledge to try to turn this into an engine (assuming it would be possible).

(This one program in specific is called "EbSynth")

Or, at the end of the day, **am I just having too unrealistic expectations, just like anyone excited with a new project**?

# Answer
> 2 votes
A kuwahara shader would be a good start, with bright colors as an input. First hit resulted in this:

```
Shader "Unlit/Oil Painting"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
        _Radius ("Radius", Range(0, 10)) = 0
    }
    SubShader
    {
        Blend SrcAlpha OneMinusSrcAlpha
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0
            #include "UnityCG.cginc"

            struct v2f {
                float4 pos : SV_POSITION;
                half2 uv : TEXCOORD0;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert(appdata_base v) {
                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                return o;
            }

            int _Radius;
            float4 _MainTex_TexelSize;

            float4 frag (v2f i) : SV_Target
            {
                half2 uv = i.uv;

                float3 mean[4] = {
                    {0, 0, 0},
                    {0, 0, 0},
                    {0, 0, 0},
                    {0, 0, 0}
                };

                float3 sigma[4] = {
                    {0, 0, 0},
                    {0, 0, 0},
                    {0, 0, 0},
                    {0, 0, 0}
                };

                float2 start[4] = {{-_Radius, -_Radius}, {-_Radius, 0}, {0, -_Radius}, {0, 0}};

                float2 pos;
                float3 col;
                for (int k = 0; k < 4; k++) {
                    for(int i = 0; i <= _Radius; i++) {
                        for(int j = 0; j <= _Radius; j++) {
                            pos = float2(i, j) + start[k];
                            col = tex2Dlod(_MainTex, float4(uv + float2(pos.x * _MainTex_TexelSize.x, pos.y * _MainTex_TexelSize.y), 0., 0.)).rgb;
                            mean[k] += col;
                            sigma[k] += col * col;
                        }
                    }
                }

                float sigma2;

                float n = pow(_Radius + 1, 2);
                float4 color = tex2D(_MainTex, uv);
                float min = 1;

                for (int l = 0; l < 4; l++) {
                    mean[l] /= n;
                    sigma[l] = abs(sigma[l] / n - mean[l] * mean[l]);
                    sigma2 = sigma[l].r + sigma[l].g + sigma[l].b;

                    if (sigma2 < min) {
                        min = sigma2;
                        color.rgb = mean[l].rgb;
                    }
                }
                return color;
            }
            ENDCG
        }
    }
}

```

(Accoding to his youtube channel, `My shaders are free-to-use. No need any credit.` Source here: Oil Shader)

A fast way would be to apply it to the camera and render everything with it.

* Create a new material
* Assign the shader to the material
* Create a mini script for using it

\[ExecuteInEditMode\] public class CameraWithShader: MonoBehaviour {

```
 public Material material;
 void OnRenderImage (RenderTexture source, RenderTexture destination) {
     Graphics.Blit(source, destination, material);
 }

```

}
* Place the script on your camera
* Assign the material to the script

---
Tags: 3d, textures, graphic-effects, art, non-photorealistic
---


# Question
Title: Can a BoxCollider 2D be a child object of a Rigidbody 2D ? (as it's not working)
I tried to find a solution before and asked elsewhere but couldn't find the exact same issue. I have a parent game object that is a Rigidbody 2D, and this object has children that are BoxColliders 2D. (The parent object needs to be dragged, and the child blocks need to move along with it and to be colliders). It used to work in the past -- so i'm not sure if an Unity update broke this. But now my other Rigidbody 2D doesn't collide with these child BoxColliders any more.

**Is there a (new ?) rule I don't know about using BoxColliders as child of a Rigidbody ? (or sometimes in the very same object)**

By the way : I haven't assigned any material to the BoxCollider 2D and Rigidbody 2D, as I don't think they need it. The Rigidbody is Dynamic and I'd like to keep it that way.

Thanks for your help

# Answer
Thank you DMGregory for your reply.

I \[FIXED\] it, the problem was really something else, so here it is, if that can be useful to anyone :

* I tried with a backup of the project, and Unity 2018, no issues
* I exchanged the scripts, gameobjects attributes etc. not working in Unity 2021
* IN THE END, I tried **unticking the checkbox Constraints \> Freeze Position \> Y** (in the parent rigidbody of the child 2DCollider) which didn't cause any issues in the past
* **And it worked**, the collider rigidbody coming from the top (Y) now collides as expected !

Have a nice day
> 0 votes

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


# Question
Title: How are GraphNode String IDs supposed to be used
Once you add several `GraphNode` instances to `GraphEdit` they get some unusual ID strings surrounded with `@` signs and with an attached ID. E.g. Running `get_connection_list()` returns following array:

```
[
  {
    from: "StartNode",
    from_port: 0,
    to: "TransformNode",
    to_port: 0
  },
  {
    from: "TransformNode",
    from_port: 0,
    to: "@TransformNode@119",
    to_port: 0
  },
  {
    from: "@TransformNode@119",
    from_port: 0,
    to: "@TransformNode@120",
    to_port: 0
  },
  {
    from: "@TransformNode@120",
    from_port: 0,
    to: "OutputNode",
    to_port: 0
  }
]

```

How can I reference / work with those IDs and e.g. retrieve the corresponding node?

# Answer
Those are `Node` names. You should be able to retrieve the `Node`s with `get_node` (or `get_node_or_null` or `get_node_and_resource`), just like any other `Node`.

---

Godot will not allow two `Node`s with the same `NodePath`. So, when you add a `Node` with the same `name` as a sibling `Node`, Godot will generate a new `name` for it. **This is NOT particular of `GraphEdit` or `GraphNode`.** *Godot will check for collisions and generate names for any kind of `Node`.*

---

In this case, you seem to have been adding `Node`s with the `name` set to `"TransformNode"`. The first one you added has no problem, since the `name` was not used before by any sibling `Node`. However, when adding the second sibling `Node` with the `name` set to `"TransformNode"` it conflicts with the one you already added. So Godot generates a new `name` of the format `@name@number` (for example `"@TransformNode@119"`). And it continues doing that for any other sibling `Node` with the same `name` added.

---

I should also mention that Godot does the same thing if you add anonymous `Node`s. I mean `Node`s with empty string for `name`. So you get nodes with names like `"@@20"` (notice this follows the same rule as above, the name part just happens to be an empty string). *Adding anonymous `Node`s also avoids checking for name collision. Which can be a performance improvement if you are adding a lot of `Node`s in a short period of time (there are other better optimizations for bullet hell games, by the way, but that is a different topic).*

---

The numbers are just counting up, among `name` collisions and anonymous `Node`s. However, a `GraphEdit` creates a lot of anonymous `Control`s for its visual representation, which make the count go up relatively fast. As a result the numbers can be hard to predict, but should be consistent.
> 2 votes

---
Tags: godot, graph
---


# Question
Title: Choosing Number of Points and PPI Resolution To Future-Proof Game Images
I'm working on an iOS SpriteKit game and I'm currently designing some images to be used as character animations in Photoshop. There are many different iPhones with various screen sizes and resolutions, because of this designers generally have to create assets in 1,2,3x multiples.

I've read a few design articles that suggest to use design your assets/images at 1x points with a small resolution like 72 and then scale it up by a multiple like 2x or 3x for higher resolution devices (like those with a Retina display).

Why would this be the suggested route, won't this cause blurring every time we scale up? Would it not instead make sense to work with a very high resolution PPI? Or maybe even use something like vector graphics - although I don't see options for Vector graphics in Photoshop, not sure if this is properly supported?

Thanks for any help in clearing up my confusion.

# Answer
There is no way I will cover every possible style out there.

I will mention pixel art, because it is probably the one that requires more care, but I'm not going into much detail here. DMGregory has done a better job than I could over other answers already linked in comments: here, here, and here.

I will suggest a general style independence approach. And then I will talk about cartoon styles. With the caveat that I'm looking at this from the perspective of a developer who may *sometimes* draw.

But, before any of that…

---

**Future proof for what?**

You might want one of these, I'm not entirely sure which:

* An application that will continue to look good on larger resolutions, without any updates.
* A no effort solution to support new resolutions.
* A guaranteed that your images are usable for a team that wants to make a high resolution remake of your game.

These aren't the same thing. Keep that in mind.

And you may also future proof in the sense of using an artistic style that will not look dated. *Or that is designed to look dated? Like Pixel Art? "Everything that was ever popular is still fun for some people, it's just not fashionable anymore" -- Matthew Colville.* In my opinion cartoon styles age better.

---

**Pixel Art**

For pixel art, I would suggest working from the small resolution - where every pixel matters - to make sure all the detail is visible. And then scale it up with your graphics software (avoiding any algorithms would make the image blurry, and sticking to integer factors), tweak and iterate. You would be providing custom images for different resolutions. *This yields the BEST results, but it is not future proof in the sense that supporting more resolution might mean scaling and tweaking again.*

For future proof, you could also have logic to pick at runtime an integer factor of the image scales available, and use that one up scaled. To make sure the pixel art looks OK. Perhaps introducing borders if sensible, or let it reveal more of scenario (if that does not introduce a form of cheating or unfair advantage, as would be the case in a multiplayer game). *Example by Kenney.*

*You may also be interested in Pixel-art scaling algorithms. You could implement some via shaders. For what I read, SpriteKit supports this: Understanding Shaders in SpriteKit.*

---

**General approach**

For other - not pixel art - styles that do not suffer so much from runtime scaling. I would suggest to work at a scale you are confortable at, on a tool you are confortable with. Test scaling up and down with your graphics software from there, tweak and iterate. *This would allow you to make future proof graphics in the sense that they look OK under scaling.*

Starting from a large image size and scaling down might make some sense. *And for that hypothetical team that will make the remake decades for now, it would be fantastic.* Ideally you would want to choose a scale that is an integer factor of the ones you want to support, that would allow you to have grid lines that matches the pixels for smaller resolutions. *\[Insert meme about days without using least common mumtiple\].* So, you want to support 3X and 2X scaling? Work at 6X scaling. Future proof for 4X scaling? Work at 12X scaling. Future proof for 5X scaling? Work at 20X scaling. Future proof for 6X... Still 60X scaling. Future proof for 7X... Work at 420X scaling, ha! *You still need to test, tweak and iterate. And make sure no important detail is lost at the smaller resolutions. This is not a get away without iterating free card.*

---

**Cartoon styles**

If you have a cartoon - not pixel art - style, then vector graphics are probably a good fit. You can use a software with vector graphics support, and - if sensible for your style - configure it to keep a constant pixel thickness for the lines. And, of course, make sure to test on the smaller resolutions, tweak and iterate.

For what I read SpriteKit will allow you to import vector graphics and will handle exporting them to PNGs for you. See SpriteKit Vector graphics performance. This is future proof in the sense that it would require no additional effort to support more resolutions in an update.

*Since you are suing SpriteKit, the decision I mention in the next paragraph might have already been taken for you.*

You - and your team - have to decide between having vector graphics rendered at runtime (getting better results at the cost of performance), or exporting at different resolution. *If there is a developer that will handle this for you in your team, give them a vector graphic file in some format they can work with (if in doubt, SVG※).* There is - of course - the option of using exported images for small resolutions and using runtime vector graphics for the larger ones, which would cover any future ones.

※: I will advocate SVG because being an open standard it is likely to stick around long term and have wide software support, including free tools: inkscape \- We don't want another Macromedia/Adobe Flash situation, do we? *That hypothetical future team will have a hard time getting a legal copy of that one privative software that supports the other format you are using.*

---

Beyond that, using shaders opens a lot of possibilities.

Aside from doing custom up scaling as I mentioned about pixel art… You can use signed distance fields (implement their rendering with shaders). They give you very efficient, resolution independent, not blurry, 2D monochrome images. See Improved Alpha-Tested Magnification for Vector Textures and Special Effects. That could be your solution for outlines in a cartoon style. And you can let the coloring be blurry, which is OK if your style uses gradients or flat colors… Such as a cartoon style.

*I will also mention that some styles will tile textures instead of scaling them. Have you seen Chowder? Something like that.*

---

**AI?**

I want to close mentioning that neural networks trained for up scaling images are a thing. *\[Insert enhance meme\]*. And while that might or might not match human authored quality, and while it won't work or perform well on every device, that might be the future option. And there is nothing special you need to do to today… Well, except keeping a copy of your assets at the highest resolution and on a standard format free from licensing issues. There will be new technology, and there is only so much future proofing you could do on that regard.
> 1 votes

---
Tags: animation, sprites, graphics, ios, spritekit
---


# Question
Title: How do you exactly implement a Semi-Implicit Euler type of movement in a 2D platformer?
So I've been following along *Sebastian Lague's 2D platformer* tutorial, and to understand exactly how the physics of how a jump is done, I dug into the subject and noticed a lot of people, from GafferonGames and Kyle Pittman, all mention using Semi-Implicit Euler in making an accurate jump.

Now my problem is: How do you exactly implement this type of integration scheme in a game?

Specifically a platformer. A comment on the tutorial I was following said that the code below uses the Explicit Euler type of integration. Though I'm not exactly sure myself on whether or not this is true; another tutorial I found on the topic, specifically *Jorge Rodriguez's Math for Game Developers* uses the Semi-Implicit Euler integration to make a spaceship simulator, but the code used was C++ and I only have some limited C# and I was not able to fully understand parts of the code that went into implementing the integration.

> Specifically:
>
> ```
>           auto v = [vn, gravity](Vector x, float h) -> Vector
>             {
>                 return vn + gravity(x) * h;
>             };
>
> ```

```
            auto a = [xn, gravity](Vector v, float h) -> Vector
            {
                return gravity(xn) + gravity(xn + v*h) * h;
            };

```

from what I understand, this function returns a Vector2, but I don't know if the auto = a \[xn, gravity\] is supposed to be about declaring a variable or what, or how the -\> vector bit fits in the whole code.

All in all, I need help, I'm still pretty new to programming and general and these small nuances confuse me. Any help is greatly appreciated, Thank you.

This is the code for the Platformer Character controller I followed from Sebastian Lague.

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

[RequireComponent (typeof(EntityController2D))]
public class PlayerController : MonoBehaviour
{
    EntityController2D playerController;

    #region Y-Velocity Fields
    public float jumpDisplacementDeltaTime = 0.75f;
    public float jumpHeight = 6.0f;

    float gravity;
    float jumpVelocity;

    #endregion

    float moveSpeed = 6.0f;

    Vector2 velocity;

    public void Start()
    {
        playerController = GetComponent<EntityController2D>();

        gravity = -(2 * jumpHeight) / Mathf.Pow(jumpDisplacementDeltaTime, 2);
        jumpVelocity = Mathf.Abs(gravity) * jumpDisplacementDeltaTime;

        print ($"Gravity: {gravity}");
    }

    // Update is called once per frame

    public void Update()
    {
        Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

        if (playerController.collisions.below || playerController.collisions.above)
            {
            velocity.y = 0;
            }

        if (Input.GetKeyDown(KeyCode.Space) && playerController.collisions.below)
            {
            velocity.y = jumpVelocity;
            }

        velocity.x = input.x * moveSpeed;
        velocity.y += gravity * Time.deltaTime;
        playerController.Move(velocity * Time.deltaTime);
    }
}

```

# Answer
> 1 votes
You probably figured it out by now, but I'll answer since no-one else has. Basically, it's a lambda function declaration called like:

```
 v(aVec, aFloat);

```

The `->` arrow part is a late return type, (just pretend what comes after gets put where the auto is).
The `[]` brackets say what variables the function needs to know about, so it can use them. yea...should be right.

---
Tags: unity, 2d, physics, integration
---


# Question
Title: How to change size of a SINGLE tile on a tilemap at runtime?
I'm having trouble figuring out how to change the scale (size) of a single sprite (tile) on a Unity Tilemap.

In the game, I place trees as tiles on a tilemap, and when they grow over time, I want to increase the scale of those trees on specific tile. (different trees can be in different growth states)

Every option I tried or looked up so far only seems to work for rescaling the entire tilemap, not only a single, specific sprite (tile) on the tilemap.

Is there any way to achieve this functionality?

EDIT: I notice the Tile class documentation mentions a `transform` property which is a `Matrix4x4`. I'm not sure if this can be used to change the size or how.

# Answer
After further research, I figured it out.

If you wanted to increase the size of a specific tile by two times, all you need to do is unlock the tile flags and set the new scale matrix like so:

```
Matrix4x4 newMatrix = Matrix4x4.Scale(new Vector3(2, 2, 2));

Tilemap.SetTileFlags(position, TileFlags.None);
Tilemap.SetTransformMatrix(position, newMatrix);

```

There is also `Tilemap.SetColor` and works in a similar way.
> 1 votes

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


title: Smoothing Heightmap Data

text:
# Question
Title: Smoothing Heightmap Data
I've made a Heightmap Generator that creates island heightmaps like in this picture:

I am dividing the grayscale ( 0 - 255 ) into 4 diferent parts ( water, sand, gras and forrest ) and after coloring those layers the heightmap looks like this:

As you can see, the "coast" is pretty noisy ( there are some sand-pixels on the edges, that are not connected to the island itself )

So my question is, **How to smooth that noisy coast / beach ?**

Is there any quick method that detects those "lonly" pixels and turns them into water ?

can i use the smoothing function below to smooth the final output ?

( I'm working with either a float\[\]\[\] or a Color\[\]\[\] array )

---

**UPDATE**

here is my smoothing function that i've implemented in my heightmap generation core.

i don't know if i can use this function for this purpose.

```
    public static float[][] GenerateSmoothNoise( float[][] baseNoise, int octave ) {
        int width = baseNoise.Length;
        int height = baseNoise[ 0 ].Length;

        float[][] smoothNoise = GetEmptyArray<float>( width, height );

        int samplePeriod = 1 << octave; // calculates 2 ^ k
        float sampleFrequency = 1.0f / samplePeriod;

        for( int i = 0; i < width; i++ ) {
            //calculate the horizontal sampling indices
            int sample_i0 = ( i / samplePeriod ) * samplePeriod;
            int sample_i1 = ( sample_i0 + samplePeriod ) % width; //wrap around
            float horizontal_blend = ( i - sample_i0 ) * sampleFrequency;

            for( int j = 0; j < height; j++ ) {
                //calculate the vertical sampling indices
                int sample_j0 = ( j / samplePeriod ) * samplePeriod;
                int sample_j1 = ( sample_j0 + samplePeriod ) % height; //wrap around
                float vertical_blend = ( j - sample_j0 ) * sampleFrequency;

                //blend the top two corners
                float top = Interpolate( baseNoise[ sample_i0 ][ sample_j0 ],
                    baseNoise[ sample_i1 ][ sample_j0 ], horizontal_blend );

                //blend the bottom two corners
                float bottom = Interpolate( baseNoise[ sample_i0 ][ sample_j1 ],
                    baseNoise[ sample_i1 ][ sample_j1 ], horizontal_blend );

                //final blend
                smoothNoise[ i ][ j ] = Interpolate( top, bottom, vertical_blend );
            }
        }

        return smoothNoise;
    }

```

and for those who are interested, i'm calling `GenerateSmoothNoise()` in this way -\>

```
    public static float[][] GeneratePerlinNoise( float[][] baseNoise, int octaveCount ) {
        int width = baseNoise.Length;
        int height = baseNoise[ 0 ].Length;

        float[][][] smoothNoise = new float[ octaveCount ][][]; //an array of 2D arrays containing

        float persistance = 0.7f;

        //generate smooth noise
        for( int i = 0; i < octaveCount; i++ ) {
            smoothNoise[ i ] = GenerateSmoothNoise( baseNoise, i );
        }

        float[][] perlinNoise = GetEmptyArray<float>( width, height ); //an array of floats initialised to 0

        float amplitude = 1.0f;
        float totalAmplitude = 0.0f;

        //blend noise together
        for( int octave = octaveCount - 1; octave >= 0; octave-- ) {
            amplitude *= persistance;
            totalAmplitude += amplitude;

            for( int i = 0; i < width; i++ ) {
                for( int j = 0; j < height; j++ ) {
                    perlinNoise[ i ][ j ] += smoothNoise[ octave ][ i ][ j ] * amplitude;
                }
            }
        }

        //normalisation
        for( int i = 0; i < width; i++ ) {
            for( int j = 0; j < height; j++ ) {
                perlinNoise[ i ][ j ] /= totalAmplitude;
            }
        }

        return perlinNoise;
    }

```

# Answer
> 3 votes
Note: I'm gonna use the term "pixel" here to refer to a unit of land in your height map.

I'll assume your definition of noise are groups of land pixel are that smaller than certain size and you want these removed (turned into water).

In that case, a simple method may be just counting the total number of connected pixels (size) for each group of land pixels(islands) and removing ones with pixel count below a certain threshold. You can do this in O(n) time using flood fill (http://en.wikipedia.org/wiki/Flood\_fill) as follows:

1. For each pixel, start a flood-fill to count number connected land pixels (don't replace any pixels yet). Store this starting pixel in a list if number pixels \< threshold. You flag each pixel that you've encountered in the algorithm so that you never look at the same pixel twice.
2. For each pixel you stored in that list, flood-fill and replace land pixel with water pixel.

Pesudocode:

> ```
> for each pixel at point p in map
>     count = floodFillCount(p, map)
>     if(count < threshold)
>         remove_list.add(p)
> for each point p in remove_list
>     floodFillReplace(p, water_height, map)
>
> ```

Note that this method will not remove things like a very long thin lines of land.

# Answer
> 0 votes
If someone wants to use the function `GenerateSmoothNoise()` in Unity for example here is a small adaptation (with the function `Interpolate()`) :

```
public static float[,] GenerateSmoothNoise(float[,] baseNoise, int octave, float frequency) {
    int width = baseNoise.GetLength(0);
    int height = width;

    float[,] smoothNoise = new float[width, height];

    int samplePeriod = 1 << octave; // calculates 2 ^ k

    for (int i = 0; i < width; i++) {
        //calculate the horizontal sampling indices
        int sample_i0 = (i / samplePeriod) * samplePeriod;
        int sample_i1 = (sample_i0 + samplePeriod) % width; //wrap around
        float horizontal_blend = (i - sample_i0) * frequency;

        for (int j = 0; j < height; j++) {
            //calculate the vertical sampling indices
            int sample_j0 = (j / samplePeriod) * samplePeriod;
            int sample_j1 = (sample_j0 + samplePeriod) % height; //wrap around
            float vertical_blend = (j - sample_j0) * frequency;

            //blend the top two corners
            float top = Interpolate(baseNoise[sample_i0, sample_j0],
                baseNoise[sample_i1, sample_j0], horizontal_blend);

            //blend the bottom two corners
            float bottom = Interpolate(baseNoise[sample_i0, sample_j1],
                baseNoise[sample_i1, sample_j1], horizontal_blend);

            //final blend
            smoothNoise[i, j] = Interpolate(top, bottom, vertical_blend);
        }
    }
    return smoothNoise;
}

public static float Interpolate(float a, float b, float x) {
    float ft = x * 3.1415927f;
    float f = (float)(1 - Math.Cos(ft)) * 0.5f;
    return a * (1 - f) + b * f;
}

```

And it's possible to create a very cool effect like in Minecraft by using, for example, `octaves = 4` and `frequency = 10f`.

---
Tags: c#, .net, heightmap, perlin-noise
---


title: Why can't I stop Coroutine?

text:
# Question
Title: Why can't I stop Coroutine?
```
private IEnumerator FlickerEffectInTime()
{
    while(true)
    {
        startTime += Time.deltaTime;
        if (startTime < 2)
        {
            GetComponent<SpriteRenderer>().enabled = !GetComponent<SpriteRenderer>().enabled;
            Debug.Log(startTime);
            yield return new WaitForSeconds(0.1f);
        }
        else
        {
            startTime = 0;
            GetComponent<SpriteRenderer>().enabled = true;
            Debug.Log("stoped flick");
            StopCoroutine("FlickerEffectInTime");

        }
    }
}

```

The while loop is infinite I have use `StopCourotine()` How can I resolve it ?

# Answer
The routine won't stop on its own because, as you said, the while loop is infinite. Instead, replace the `true` in `while(true)` with a `bool` variable that you can set either inside or outside of the coroutine.

```
bool allowFlicker =true
while(allowFlicker)
{
    // do stuff here

    //time to stop? Then set allowFlicker false
    allowFlicker = false
}

```

This looks like it could also be simply placed in the `Update` or `FixedUpdate` functions.
> 1 votes

# Answer
The recommended way to make a coroutine end itself is to exit all the loops and have it run to the end. For example, if you want the coroutine to stop when `startTime` gets larger than 2f, you can do this:

```
private IEnumerator FlickerEffectInTime()
{
    while(startTime < 2.0f)
    {
        startTime += Time.deltaTime;
        GetComponent<SpriteRenderer>().enabled = !GetComponent<SpriteRenderer>().enabled;
        yield return new WaitForSeconds(0.1f);
    }

    startTime = 0;
    GetComponent<SpriteRenderer>().enabled = true;
}

```

However, sometimes that's not feasible. In that case there is a better alternative to self-terminating the coroutine with StopCoroutine. Just use the statement `yield break;`. It signals to the code which processes an IEnumerator that the enumeration has ended and the enumerator can be disposed. Which in the context of Unity Coroutine means that the coroutine should be stopped.
> 1 votes

---
Tags: unity, coroutines
---


# Question
Title: How to stop Sprites from stretching on Mobile with different aspect ratio
On Unity 2020.3.24f1:

* I created a 2D Core Project and changed to build on any Android device.
* Added a simple 2D Circle Sprite to my Scene.

**The Problem:**

I want my Game to run in 9:16 aspect ratio all the time. If the device screen has another aspect ratio letterboxing will do fine. But running the game on my Redmi Note 10 with screen dimensions of 1080x2400 stretches the circle vertically.

I tried this script which is basically the same as the script on this site. When I use 9:16 aspect ratio (in the script) no letterboxes are appearing. But when I change to 16:9 (in the script) with my device being in portrait mode there are letterboxes but the circle is still stretched.

I searched the web for around 4 hours tried everything I found and checked every option in the project settings but can't get this to work.

# Answer
I had a wrong understanding of how Unity Remote 5 works. When running the game in the editor Unity will use (as usual) the resolution/aspect ratio set in the Game panel of the editor then just mirror it to the connected device. So adding a custom resolutio/aspect ratio with the same dimensions as the device will fix this problem.
> 1 votes

---
Tags: unity, mobile, aspect-ratio
---


title: High CPU usage with Godot tilemap

text:
# Question
Title: High CPU usage with Godot tilemap
I am using Godot as my game engine and I am making a basic 2D game, I have a small map with 1 Player and 5 Enemies walking around in it. The game includes some basic code for walking and shooting at enemies, so nothing too crazy. However, the game uses up to 18% of my cpu (I have an Intel Core i7 920) which it usually only does when playing big 3D games. So, what am doing wrong? I think I might be keeping track of to many enemies? I already tried the Low CPU usage option in the Godot settings, but it didnt really change anything.

Here's what I found in the profiler:

I was running for 1264 frames and it gave me this:

Script Functions - 22.79 ms

\_physics\_process - 80.89 ms

\_physics\_process - 32.96 ms

\_on\_Area2D\_body\_entered - 16.00 ms

check\_input (A function checking key input) - 14.37 ms

shoot (Instancing a bullet scene and moving it) - 10.11 ms

# Answer
> 1 votes
I used a Tilemap as my Level and it was put in front of the player in the node tree, so the Level outside the player camera was rendering as well. It now works just fine

---
Tags: 2d, performance, tilemap, godot
---


# Question
Title: Best Practice for Procedural Generation and Code Updates
I am using an initial seed to generate data. The question I have though is what is the best way to mantain the information with code updates. For example if I have something similar to:

```
initial_seed = 1;
mount_seed( initial_seed );
var weather = ['snow','sun',rain','fog'];
shuffle(weather);
current weather = weather[0]; // sun
// a bunch of code and variables
abc = rand(1,100); // 20

```

The problem is if I do updates to the 'weather' variable, it will break all the code after.

```
initial_seed = 1;
mount_seed( initial_seed );
var weather = ['snow','sun',rain','fog','windy'];
shuffle(weather);
current weather = weather[0]; // fog
// a bunch of code and variables
abc = rand(1,100); // 76

```

My initial thought was to save the variables 'current weather', etc and load those up instead of the seeds. It would make version control easier since the variables are saved and loaded. The problem is when I have thousands of variables with different lengths, the save files get bloated. The other option would be to save the initial seed and a version of the code and load up the seed and version every time. I'm curious what the most scaleable option would be as well as how other bigger companies have come at this issue.

# Answer
> 1 votes
> The problem is if I do updates to the 'weather' variable, it will break all the code after.

The less you do, the better. If you are only picking a weather at random, you probably don't need to shuffle the array. Just get a random number up to the number of elements. It would always be a single call regardless of how many options are there.

---

> My initial thought was to save the variables 'current weather', etc and load those up instead of the seeds. It would make version control easier since the variables are saved and loaded. The problem is when I have thousands of variables with different lengths, the save files get bloated.

That is probably not a problem. In particular if the variables don't change often. At least not for one or a few worlds generated per server. *I suppose you don't go from rain, to snow, to fog, to windy, by walking a few steps. So these variables don't need be stored with high resolution.*

However, if you want to have a single server for many large worlds, at some point it would become an issue. *You would face some other issues before you get there.*

I'll be assuming that many large worlds in the same server is the situation from here on.

---

> The other option would be to save the initial seed and a version of the code and load up the seed and version every time.

Let me tell you a "secret": code is data. Do not think about storing a version of the code that generates the world. Think about storing a description of how to generate the world. It could be as simple as a file with a list of variable names and what are their possible values, plus the seed and any other metadata needed. Then - in code - for any variable that needs a value, you can see if it is in the file, and generate it according to it.

Thus, no, it would be keeping the old code. Instead it is generating as faithful as possible in the newer version of the code. And thus, you would not be maintaining (i.e. providing technical support for) multiple versions of the code.

"But wait" - I imagine you say - "the order in which they are generated matters. Also, what about variables that are not in the file?".

---

I have a solution for you. *Which - by the way - I think deserves to gain popularity.* We are going to use noise. "Pff." - I imagine you say - "that is nothing new". And you are right. However, we will not use noise how it first comes to mind. *You can - of course - use some noise function for generation - e.g. terrain elevation and such. That is not what I'm suggesting, in fact, I'll assume you are already doing something like that.*

I want you to have some other noise you can use for extra variables (it might also be extra dimension on some noise you have). Then to pick your random values by reading a position from that noise. *You can store as metadata on the descriptor file, what are the coordinates in noise space for each variable (it can be the coordinates from the world, plus some coordinates form the file).*

If you need a variable number of random values (e.g. for shuffle requiring a number of random values depending on the number of elements), you define a ray (some initial position and a step vector) in noise space to read from. *And - of course - store that as the metadata for the shuffle in the descriptor file.*

This removes the problem of ordering. *Inserting more calls to get a random value will no longer affect other calls done afterwards.* That way, adding a new option to `weather`, which means more calls to generate random numbers, only affects `weather`. It does not mess with the generation of anything else.

---

And about the extra variables... If you have variables that are not in the descriptor file, it means it is from an old version. But that is no problem: you can add any missing variables to the descriptor file, knowing they will not affect the others thanks to using noise as I explained above.

Removed variables? That just means some parts of the descriptor file are ignored. You could remove them.

---

OK, let us say you want to keep the world up to where the players explored generated with the old version, but continue with the new version. What then? Then you would have two descriptor files, or more. You would need to know for what parts of the world use what file. *Which is much less data than storing the value of every variable for each part of the world.*

In this case, you probably don't want extra variables to be randomized in old files. For that you can give them a constant default value.

By the way, storing what file to use where compresses very well, because a lot of contiguous areas would be using the same file. In fact, you might want to store this with even less resolution than the variables it generates. *Since it compresses well, you may want to gzip the files. Or you could even use an image format - which each color referring to a file - and stored them a lossless compression format.*

Knowing what parts are generated with a version and which with another may also allow you to interpolate in the edge to hide any transition artifacts.

---

*You would still need to store any persistent changes to the world that player make. There is no way around that.*

*See also: Noise-Based RNG - GDC 2017.*

---
Tags: java, procedural-generation, php
---


# Question
Title: How can I update the Navmesh path in 2D games?
There are destructible and indestructible objects on the map I created with Tilemap, and I create a walkable area (bake) for my enemy object using the information I found on the internet and the Navmesh packages for 2D games. However, the problem is that after my player destroys breakable objects (Tilemap grid cell), the enemy object still perceives those areas as unwalkable. I'm wondering how I can update the navmesh for the enemy again while the game is running.

I found videos and information on how to do this in 3D games, it looks pretty simple. But I couldn't find anything for 2D games.

Note: I'm using Unity.

# Answer
> 0 votes
I found a solution. First of all, download the package in the link and put it in unity. (required for 2D games)

https://github.com/h8man/NavMeshPlus

Then you can follow how to do it from the link below: (Do what is explained up to the GEOMETRY OPTIONS heading.)

https://github.com/h8man/NavMeshPlus/wiki/HOW-TO

Finally, create a script for your object named "NavMesh" and write the following code. Thus, if your map objects disappear or move during the game, that free space will be recalculated and become a walkable area.

```
 using UnityEngine;
 using UnityEngine.AI;

 public class Runtime : MonoBehaviour
 {
public NavMeshSurface2d Surface2D;

void LateUpdate()
{
    Surface2D.BuildNavMesh();
}
}

```

Note: Don't forget to assign the NavMeshSurface2d component to the Runtime script.

---
Tags: unity, 2d, ai, navmesh
---


# Question
Title: How do you get the texture coordinate hit by the mouse on a UI Raw Image in Unity?
It seems raycast hit does not work for UI... is it possible to get the .textureCoord of a point hit by the mouse on a UI raw image? (raw image provided by a render camera elsewhere far far away)

# Answer
> 1 votes
The `RectTransformUtility` has a helper method for finding the position of a screen point inside any`RectTransform`'s bounding rectangle:

```
var rt = (RectTransform)rawImage.transform;

bool inside = RectTransformUtility.ScreenPointToLocalPointInRectangle(
    (RectTransform)rawImage.trasnform,
    Input.mousePosition,
    camera,
    out Vector2 pointInRect
);

```

Then you can just remap these coordinates from the local rectangle of the `RawImage` object into the UV space of the texture it's displaying:

```
if (inside) {
    Vector2 textureCoord = pointInRect - rt.rect.min;
    textureCoord.x *= rawImage.uvRect.width / rt.rect.width;
    textureCoord.y *= rawImage.uvRect.height / rt.rect.height;
    textureCoord += rawImage.uvRect.min;
}

```

Note that if your UI is in "Screen Space - Overlay mode", then the `camera` argument should be `null`.

If your texture coordinates are upside-down, you may need to set

```
trextureCoord.y = rt.rect.height - textureCoord.y;

```

before the scaling step.

---
Tags: unity, gui
---


# Question
Title: Alternative to using the user's camera for strength-training minigame
I want to make an action RPG with combat similar to that of monster hunter, simply because I really dislike tab target or turn-based combat.

I want the playable characters to have stats like strength, intelligence, precision and so on. And I want the player to do activities related to each stat to improve them.

For things like precision, I will just use accuracy challenges, no scope crossbow with no crosshair, with harder challenges to get your precision stat higher and higher, and each stat has different bonuses obviously. For intelligence, I'd use game puzzles based on math, memory and logic.

But what about strength? Other than telling the user to lift weights in front of the camera, which could sound weird for a lot of people, what other options are there?

# Answer
> 1 votes
Here's a frame-challenge - do you need a strength stat at all? Game controllers are designed to be require as little physical effort as possible to read inputs accurately and satisfyingly, so there aren't going to be a lot of obvious ways to map real-life strength to in-game strength. That said, I do have some ideas below, with caveats.

But rather than struggle against the limitations of your idea, why not embrace them? If there isn't a compelling reason to include strength in your game beside "other RPG games use strength" you can absolutely go without it. If the idea of minigames that test skills that correspond to in-game stats is core to your game, that should take precedence over other considerations that aren't as core.

So maybe your world outlawed big beefy swordsman, and instead everyone is a wizard or a ranger. Or maybe there are gigantic anime-style swords, but they're magically enchanted to not require any particular strength, and instead are all about hand-eye coordination and reaction speed. There are endless other reasons a world might lack strength-based fighters, but whichever one you come up with, you have some interesting opportunities to differentiate your world from those in other RPGs.

---

All that said, if strength is a core part of your game idea, what I've seen work in other games for similar purposes is button mashing (or some extension thereof). It works thematically since it's brute-force-y and can be a bit of a workout for your wrist muscles. It also doesn't have to be limited to literally mashing a button - for example, you could spin a joystick really quickly, or rapidly alternate between pressing the left trigger and the right trigger.

It has some disadvantages, though: it's hard to generalize cross-platform, since things that work well on console like spinning the joystick don't work on PC or mobile, and vice versa. It can also run the risk of players damaging their controllers or even themselves, but you should be fine as long as you don't go overboard on how fast people need to go.

---
Tags: game-mechanics, rpg
---


title: Steam Controller thinks it has 2 hats?

text:
# Question
Title: Steam Controller thinks it has 2 hats?
Is there any reason why a Steam Controller would think it has two hats?

The pad on the left is HAT 0, as expected. Note that the pad on the right is not a HAT/DPAD, it is two **axes** (Axis2 and Axis3) also, as expected.

```
03000000de2800000211000011010000 "Steam Controller" axes:4 buttons:21 hats:2 balls:0

```

Still, SDL\_JoystickNumHats() returns 2. And bottom hat values on change if a trigger is pressed?

Tested with latest SDL 2.0.14 version.

I think ultimately, this info comes from the kernel via ioctl **JSIOCGAXMAP** that identifies the triggers as HAT, not as triggers?

# Answer
For reference, `hid-steam` maps Steam Controller inputs to these input events:

```
ABS_HAT2Y: left trigger
ABS_HAT2X: right trigger
ABS_X/ABS_HAT0X: X value
ABS_Y/ABS_HAT0Y: Y value
ABS_RX: right-pad X value
ABS_RY: right-pad Y value
BTN_TR2: right trigger fully pressed
BTN_TL2: left trigger fully pressed
BTN_TR: right shoulder
BTN_TL: left shoulder
BTN_Y: button Y
BTN_B: button B
BTN_X: button X
BTN_A: button A
BTN_DPAD_UP: left-pad up
BTN_DPAD_RIGHT: left-pad right
BTN_DPAD_LEFT: left-pad left
BTN_DPAD_DOWN: left-pad down
BTN_SELECT: menu left
BTN_MODE: steam logo
BTN_START: menu right
BTN_GEAR_DOWN: left back lever
BTN_GEAR_UP: right back lever
BTN_THUMBR: right-pad clicked
BTN_THUMB: left-pad touched
BTN_THUMB2: right-pad touched
BTN_THUMBL: joystick clicked

```

This mapping follows the Linux Gamepad Specification which specifies how gamepad trigger buttons (named ZL and ZR in the spec) should be mapped to input event codes.

> Triggers:
>
> Trigger buttons can be available as digital or analog buttons or both. User- space must correctly deal with any situation and choose the most appropriate mode. Upper trigger buttons are reported as BTN\_TR or ABS\_HAT1X (right) and BTN\_TL or ABS\_HAT1Y (left). Lower trigger buttons are reported as BTN\_TR2 or ABS\_HAT2X (right/ZR) and BTN\_TL2 or ABS\_HAT2Y (left/ZL). If only one trigger-button combination is present (upper+lower), they are reported as “right” triggers (BTN\_TR/ABS\_HAT1X). (ABS trigger values start at 0, pressure is reported as positive values)

`hid-steam` maps the triggers to both `BTN_TR2`/`BTN_TL2` and `ABS_HAT2X`/`ABS_HAT2Y`, which causes SDL2 to detect another Hat Switch.
> 2 votes

# Answer
The problem, of course, is that the Steam Controller's D-Pad isn't actually a D-Pad (with 9 possible input states), it's a touchpad (with two continuous axes). The hid-steam driver implies this by indicating that ABS\_HAT0X/Y have a range of -32767 .. 32767, but SDL seems to ignore that and treat it like a regular hat, where `Y < 0 => UP`, `X > 0 => RIGHT`, etc.

This in turn makes the D-Pad all but unusable via SDL: it is impossible to touch the pad perfectly centered on either axis, so in practice SDL will only ever report the hat to be in the corners; trying to touch "UP" will waver between UP-LEFT and UP-RIGHT depending whether your finger is just barely left or right of center on the touchpad.

I'm in the midst of trying to find a solution to this problem (which arose for me in the context of RetroPie's version of EmulationStation) but haven't found the right place to address it yet. There may be an environment variable or some other way to make SDL handle this input correctly, or it may require a patch to notice that (for example) the "hat" input range is far wider than -1 / 0 / 1 and to just expose it as an axis instead.

(I've raised this issue with SDL, so hopefully this will be fixed in a future release.)
> 2 votes

---
Tags: sdl2, joystick, gamepad
---


title: Best way to save game in story game

text:
# Question
Title: Best way to save game in story game
In a while I plan to create a story game that would have different routes and endings and I was wondering what would be the best way to save a game of a game like this, if it would be a folder, individual file. Etc.

# Answer
The information you need to save is:

1. Which step of the story is the player currently on?
2. What's the state of the game? (variable values, story flags etc.)

This should not be a lot of data, so saving those to a file should be sufficient.
> 1 votes

---
Tags: algorithm, optimization, data-structure, savegame
---