# Question
Title: Unity InputSystem will Send but not Broadcast
I'm trying to organise my project so that each MonoBehaviour receives relevant impulses/actions and handles them.

I have the following:

`InputManager`: Empty game object with a PlayerInput component. Used to configure/switch mappings, handle input-related functionality.

`MapController`: GameObject with lots of functionality and children that sits alongside the InputManager. Needs to be aware when the `ToggleView` action is fired.

I have an appropriate action (tied to the spacebar):

The PlayerInput is set to Broadcast:

If I create a `public void OnToggleView() { ... }` in `MapController`, it never fires.

However, if I attach the following to the same GameObject as the PlayerInput...

```
public class TestShim : MonoBehaviour {
    public void OnToggleView() {
        Debug.Log("Test shim toggled");
    }
}

```

It fires just fine.

Same if I switch the mode from Broadcast to Send.

I was under the impression that Broadcasting should check for relevant methods on all enabled GameObjects?

What am I missing / how can I raise the event in `MapController`?

# Answer
see the docs: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.4/manual/Components.html#notification-behaviors

Broadcast messages uses GameObject.BroadcastMessage which sends the message to the gameobject and any of its children, not any object in the scene.

There are a bunch of ways you can work around this, either have a custom component on the InputManager to receive the event and forward it to your MapController, or get a reference to the input action in code (either from the PlayerInput component, or from an InputActionReference set on the MapController).
> 2 votes

---
Tags: unity, input, messaging
---


# Question
Title: Change Mesh face colors / materials at runtime
I'm trying to change the color/material of the faces on my object at runtime. My object has a default SpatialMappingWireframe to begin with:

And I'm trying to assign new colors on start like so:

```
void Start()
{
    Mesh mesh = GetComponent<MeshFilter>().mesh;

    Color[] colours = new Color[mesh.vertices.Length];

    for (int i = 0; i < mesh.vertices.Length; i++)
    {
        colours[i] = Color.red;
    }

    mesh.colors = colours;

    Debug.Log($"Colour Count: {colours.Length}");
}

```

I can see the debug line being output, but no changes to my scene:

Apologies if I'm missing something obvious

# Answer
> 1 votes
The default shader on a material does not support assigning new colours. Assigning a new shader to the material asset resolves the issue:

Quoting the a StackOverflow answer:

1. in the `Project` view (Assets) do `right click``Create``Material`
2. Give that material a name
3. For the `Shader` from the Dropdown menu find and select e.g. `Particles``Standard Unlit` (or if you want to receive lightning `Standard Surface`)
4. Finally use this material for your object either by dragging it into the `MeshRenderer``material` or by simply dragging it onto the according object in the `Scene` view (the latter might not work if there is no mesh for that object yet)

---

Result:

---
Tags: unity, mesh, materials, color, vertex
---


# Question
Title: Reliable RPC frequency limits in Unreal Engine
I am implementing a fighting game in Unreal Engine and I want to implement "rollback". The way I envision it so far is that in every frame, the client will send the inputs it received in that frame (30 fps max for now) to the client. Dropping any inputs is unacceptable. To me, it looks like the best way to do this is with RPCs, and if there are inputs in one frame, I will send an RPC to the other client with those inputs. Since inputs can't be dropped, it looks like a good idea to use reliable RPCs. However the documentation explicitly warns against making a reliable RPC every frame.

> Warning: Overuse of Reliable functions can result in overflowing the queue for them. This will result in forced disconnections. If you call a replicated function on a frame-by-frame basis, you should make it Unreliable. If you have a Reliable function that is bound to player input, you should limit how often the player can call that function.

Should I really be concerned about hitting this limit if I am making only one RPC per client every frame, and at 30fps max? 60 fps? During a match, theoretically these RPCs will be the only network traffic, as everything gameplay essential will be computed client side from the inputs, and nothing else needs replication. It would be the simplest method by far.

A second question is, even if I don't hit this limit, would reliable RPC introduce noticable latency over, say, using TCP, or some other method I am unaware of? Is sending packets every frame simply too much traffic?

# Answer
> 0 votes
You should try to avoid sending Reliable RPCs whenever you can. Unreliable RPCs however you may send as much as you want. The engine will send them, but they may get dropped due to the nature of underlying network implementation (UDP)

The downside of using Reliable RPCs is that they need to be re-transmitted and they won't go thru the network and arrive the server faster than they can. If it's physically impossible to send a packet over they won't go thru regardless of reliable or unreliable. They simply get re-transmitted.

Reliability basically incurs a cost of having to resend your RPCs, having to order them and also waiting, to make sure they all arrive in order. This can eventually increase latency and may not be what you want for a fast paced game.

What you could do is queue up your input commands and re-send them manually, and order them on your end. Most of the time you only care about the latest input anyways.

I'm want to refer you to the old UDK docs which provides a pattern you could use.

Pleas see Semi-reliable function calls

https://docs.unrealengine.com/udk/Three/FunctionReplication.html

---
Tags: networking, unreal
---


# Question
Title: Unity Netcode how to resolve responsiveness issues on the client?
I have been reading the Unity Netcode manual and other related articles, which explains very clearly why it is essential to care about latency. Still, I haven't seen good examples of implementing a solution. Below is a quick video of a bare-bones project simply reproducing the issue. I am using a local host/client model, with a simulated 70ms of delay, and you can see on the client side the bullets always spawn outside the player, which I understand why, but how do I go about fixing it. I just can't find good examples dealing with the issue.

**Video here: https://youtu.be/ZuX2f2s3w3o**

**Screenshot:**

Here is the code that spawns the bullets:

```
using Unity.Netcode;
using UnityEngine;

public class PlayerAttacks : NetworkBehaviour
{
    public GameObject projectile;
    public float FireRate;

    float _nextShot;

    void Update()
    {
        if (!IsOwner) return;

        if (Input.GetKey(KeyCode.Space))
        {
            if (_nextShot <= Time.time)
            {
                if (IsServer)
                {
                    SpawnProjectile();
                }
                else
                {
                    SpawnServerRpc();
                }

                _nextShot = 1 / FireRate + Time.time;
            }

        }
    }

    [ServerRpc]
    void SpawnServerRpc()
    {
        SpawnProjectile();
    }

    void SpawnProjectile()
    {
        var p = Instantiate(projectile, transform.position, transform.rotation);
        p.GetComponent<NetworkObject>().Spawn();
        Destroy(p, 4f);
    }

}

```

# Answer
> 1 votes
I found a solution that works for me. This is a client-side solution. In the script above I was making an RPC call and waiting for the server to respond with the object instance and location. Fully server managed.

In order to get the visuals and performance I wanted, instead of spawning the projectile on the server, my approach is to instantiate the projectile on all the clients.

So basically, on mouse click, make a RPC call AND create the projectile locally. The RPC call will ask the server to call on all clients to spawn a projectile locally.

```
  void Update()
{
    if (!IsOwner) return;

    if (Input.GetMouseButton(0) && nextFire <= Time.time)
    {
        nextFire = 1 / fireRate + Time.time;
        FireBulletsServerRpc();
        ExecuteRayCast();

    }
}

[ServerRpc]
public void FireBulletsServerRpc()
{
    FireBulletsClientRpc();
}

[ClientRpc]
public void FireBulletsClientRpc()
{
    if (!IsOwner)
        ExecuteRayCast();
}

void ExecuteRayCast()
{
    Vector3 direction = GetDirection();

    TrailRenderer trail = Instantiate(bulletTrail, LeftGun.transform.position, LeftGun.transform.rotation);
    TrailRenderer trail2 = Instantiate(bulletTrail, RightGun.transform.position, RightGun.transform.rotation);

    StartCoroutine(SpawnTrail(trail));
    StartCoroutine(SpawnTrail(trail2));

    if (Physics.Raycast(LeftGun.transform.position, direction, out RaycastHit hit, float.MaxValue))
    {
        //Now that we hit something calculate the distance
        var distance = Vector3.Distance(transform.position, hit.point);
        print($"Distance: {distance}");
        //Calculate time for the bullet to get there
        var time = distance / (trailSpeed * 2);
        print($"Time to get there: {time}");
        //When time is up, do a physics overlay to see if something still there
        //if so apply damage
        StartCoroutine(CheckForAppliedDamage(time, hit.point));

    }
}

```

An important detail to keep in mind is in the ClientRpc call. Since the user creating the projectile already created it locally, it should ignore the server call to make it. That's why I checked if I am not the owner of that call. I hope this will help other people out there.

```
[ClientRpc]
public void FireBulletsClientRpc()
{
    if (!IsOwner)
        ExecuteRayCast();
}

```

---
Tags: unity, multiplayer, unity-networking
---


# Question
Title: How to measure section of environment in unity editor using mouse cursor?
I know in some graphical apps, user can measure object size by dragging the mouse. and the editor draws a line and shows the size. It's a really helpful feature.

is it a feature implemented in unity as a built-in feature or do I have to write an extension for it?

# Answer
> 1 votes
I just made a simple Editor overriding `EditorTool`.

If enabled, when user holds the left shift button, the editor draws a line and shows the size:

```
[EditorTool("Ruler Tool")]
public class RulerTool : EditorTool
{
    VisualElement _toolRootElement;
    bool _downEvent;
    bool _upEvent;

    private Vector3 _startPosition;

    public override void OnActivated()
    {
        _toolRootElement = new VisualElement();
        _toolRootElement.style.width = 200;
        var backgroundColor = EditorGUIUtility.isProSkin ? new Color(0.21f, 0.21f, 0.21f, 0.8f) : new Color(0.8f, 0.8f, 0.8f, 0.8f);
        _toolRootElement.style.backgroundColor = backgroundColor;
        _toolRootElement.style.marginLeft = 10f;
        _toolRootElement.style.marginBottom = 10f;
        _toolRootElement.style.paddingTop = 5f;
        _toolRootElement.style.paddingRight = 5f;
        _toolRootElement.style.paddingLeft = 5f;
        _toolRootElement.style.paddingBottom = 5f;
        var titleLabel = new Label("Ruler Tool");
        titleLabel.style.unityTextAlign = TextAnchor.UpperCenter;

        _toolRootElement.Add(titleLabel);
        var sv = SceneView.lastActiveSceneView;
        sv.rootVisualElement.Add(_toolRootElement);
        sv.rootVisualElement.style.flexDirection = FlexDirection.ColumnReverse;

        SceneView.beforeSceneGui += BeforeSceneGUI;
    }

    public override void OnWillBeDeactivated()
    {
        _toolRootElement?.RemoveFromHierarchy();
        SceneView.beforeSceneGui -= BeforeSceneGUI;
    }

    void BeforeSceneGUI(SceneView sceneView)
    {
        if (!ToolManager.IsActiveTool(this))
            return;

        if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.LeftShift)
        {
            if (!_downEvent)
                _startPosition = GetCurrentMousePositionInScene();

            _downEvent = true;
            Event.current.Use();
        }
        else if (Event.current.type == EventType.KeyUp && Event.current.keyCode == KeyCode.LeftShift)
        {
            _downEvent = false;
            Event.current.Use();
        }
    }

    public override void OnToolGUI(EditorWindow window)
    {
        if (!(window is SceneView))
            return;

        if (!ToolManager.IsActiveTool(this))
            return;

        if (_downEvent)
        {
            float distance = Vector3.Distance(_startPosition, GetCurrentMousePositionInScene());
            Handles.Label(GetCurrentMousePositionInScene() + new Vector3(0, 0, 0.7f), distance.ToString());
            Handles.DrawLine(_startPosition, GetCurrentMousePositionInScene());
            Handles.DrawWireDisc(GetCurrentMousePositionInScene(), Vector3.up, 0.5f);
        }

        window.Repaint();
    }

    Vector3 GetCurrentMousePositionInScene()
    {
        Vector3 mousePosition = Event.current.mousePosition;
        var placeObject = HandleUtility.PlaceObject(mousePosition, out var newPosition, out var normal);
        return placeObject ? newPosition : HandleUtility.GUIPointToWorldRay(mousePosition).GetPoint(10);
    }
}

```

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


# Question
Title: What is the equivalent of Unity's Transform.Forward in Stride
To get the forward direction in Unity, I use `Transform.Forward`. How do I do this in Stride?

# Answer
As stated in the official documentation, Stride3D's equivalent to Unity's `mygameobject.transform.forward` is:

`myentity.Transform.WorldMatrix.Forward`
> 0 votes

---
Tags: transformation, stride
---


title: Find look at rotation with offset

text:
# Question
Title: Find look at rotation with offset
I've been trying to make a function similar to "Find look at rotation" but with an offset. Imagine I have a pivot and an object attached to that pivot with some location and rotation offset. I want to rotate the pivot so that the child object is facing a target.

The blue box is the pivot, the gray is the child object and the red is the target. I've found a method that should work, but I'm having trouble implementing it.

This is the function that I've made.

I've asked this question on math stack exchange and this function is based on this answer that I got...

The points that are being referred to in this are:

* B - The child object location
* C - A point on the line that goes from the child object along its forward vector
* D - The target location
* O - Origin and also the pivot location

> ...rotate point \\$D\\$ about an axis passing through the origin, so that \\$D\\$'s image lies on the line \\$BC\\$. After we find this rotation, we'll just invert the rotation and apply it to line \\$BC\\$, to make it contain point \\$D\\$.
>
> Since the rotation of point \\$D\\$ about any axis passing through the origin, will be another point that lies on the sphere centered at the origin, and with a radius equal to \\$OD\\$, then all we have to do to find the image of point \\$D\\$, is intersect the sphere with line \\$BC\\$. There can be no intersections, one intersection, or two intersections at most. If there are no intersections, then it is not possible to perform this rotation to satisfy the given condition. Otherwise, pick an intersection, call it \\$D′\\$ as the image of \\$D\\$. Now we want to rotate \\$OD\\$ into \\$OD′\\$, and this can be done in an infinite number of ways, as the axis of rotation is not unique, but instead lies in the plane whose normal vector is \\$DD′\\$ and passing through the midpoint of \\$DD′\\$.
>
> However, there is a rotation that uses the minimum possible rotation angle, and that rotation has an axis given by \\$OD\times OD'\\$, and the rotation angle \\$\theta\\$ is given by:
>
> $$\theta = \text{atan2}\bigg( \dfrac{OD \cdot OD'}{ \\| OD \\|^2 } ,\dfrac{ \\| OD \times OD' \\| } { \\| OD \\|^2 } \bigg) = \text{atan2} ( OD \cdot OD' , \\| OD \times OD' \\| )$$

Plugging the equations above into Geogebra I did indeed get the desired result, but I'm having trouble replicating the same in Unreal.

The result that I get:

# Answer
> 1 votes
For anyone wondering, the math is good and the problem was in the way I applied the rotation. Here's the "correct" way to apply it:

---
Tags: mathematics, rotation, vector, unreal-4, unreal
---


title: How to pixelate scene including bloom?

text:
# Question
Title: How to pixelate scene including bloom?
I am currently using URP to add bloom to my particle systems. The problem I'm facing is that I can't pixelate the game. I have tried to implement several methods to post pixelate (via shaders and render texture) but none conserve the bloom on the particle system.

This is the effect I'm after (using pixel perfect camera and zooming the editor window) but I can't achieve this in build mode.

Any help on how I should pixelate the game so you can still see the character?

This is without 4x zoom:

This is my current settings:

# Answer
> 1 votes
When you increase the zoom of the game view like this:

what you're doing is cropping out a smaller section of the render target it's been drawn into.

So you can simply draw to a smaller render target in the first place.

Create a `RenderTexture` asset in your Assets folder, and set it to a resolution about 4x smaller than your target screen resolution. (If you want to support multiple resolutions, you can use a C# script to create and assign this `RenderTexture` dynamically to match the current screen/window resolution)

Set your camera's "Output Texture" field to render into this `RenderTexture`. That forces it to render only the number of pixels in that texture - including all post effects like bloom. You may also need to adjust the "Reference Resolution" in your pixel perfect camera script to work with your cropped-in resolution - otherwise it may try to scale everything down further to fit into the smaller space.

Lastly, create a new UI `Canvas` set to "Screenspace - Overlay" mode. Add a `RawImage` component that stretches to fill the whole canvas, and assign your `RenderTexture` as the image for it to display. That handles scaling up the few pixels of the render target up to the full window/screen size and displaying them to be seen.

# Answer
> 0 votes
Not sure that I understand your question exactly, but ensure you are importing your sprites with Filter Mode set to Point(no filter):

---
Tags: unity, shaders, camera, graphic-effects, bloom
---


# Question
Title: Sprite with hard transition from opaque to transparent shows translucent pixels in Sprite Editor
I have no idea why I have blurry/transparent borders on sprites when I cut them in the Sprite Editor, whereas I get everything fine in a graphic editor.

Picture from Sprite Editor with a problem:

Picture from the graphic editor (everything looks fine):

My Unity settings:

# Answer
> 1 votes
You've set the "Max Size" for this texture in the import settings to 2048, and asked Unity to automatically resize the image using the Mitchell algorithm if it's larger than this:

But your sprite editor shows that you have a sprite at a position some 500 pixels past this maximum cutoff, out around 2560 pixels from the far edge:

So it looks like your image is larger than the max size you've asked for. That means Unity will do exactly what you told it you wanted: downsample the image to 2048x2048 using the Mitchell algorithm, which includes blending adjacent pixels, creating partial translucency.

To fix this, author your sprites within your max size budget so that Unity does not have to scale them down, or increase the max size setting you're using on import so that it accommodates the image's authored size.

---
Tags: unity, sprites
---


# Question
Title: Pattern for scripts that should only update when in trigger range
I have a script that triggers when the enemies are in range of my objective, but it also contains an Update method for its the damage.

I noticed that Update is being called even when the enemies are not in range of the objective.

I am wondering if it's worth it to have the triggers and Update code in separate scripts, then turn off/on the scripts when entering or leaving the triggers. Or is there a better pattern to use for this kind of setup?

# Answer
You don't need the trigger and update code to be written in separate scripts. Collision messages like `OnTriggerEnter/Exit` will be called even on disabled MonoBehaviours, to give you the option to wake them up in response.

So this for example:

```
public class TriggerWatcher : MonoBehaviour {

    int _collidersOverlapped = 0;

    void Start() {
        enabled = false;
    }

    void OnTriggerEnter(Collider other) {
        _collidersOverlapped++;
        enabled = true;
    }

    void OnTriggerExit(Collider other) {
        _collidersOverlapped--;
        enabled = _collidersOverlapped > 0;
    }

    void Update() {
        Debug.Log("tick");
    }
}

```

...will only "tick" on frames where there's at least one collider overlapping it.

If you have just one object overlapping this trigger at a time, you can also use `OnTriggerStay(Collider other)`, which will be called once each physics step for each collider that previously called `OnTriggerEnter` and has not yet called `OnTriggerExit`. But note this can be more than once per display frame.

You can even call `OnTriggerEnter` as a coroutine by writing `IEnumerator OnTriggerEnter`, to start some continuous action each time a trigger crosses in - but this will have some allocation cost compared to using the built-in methods.

As for "is it worth it", as pointed out in the comments, only profiling your game will tell you whether you are paying a significant cost with your current setup, and whether you gain any significant savings from alternatives.

While it's tempting to think that one way must just be faster or slower, this can actually depend a lot on the specifics of your game. Even an ostensibly "slower" way to do things as judged on paper can be just as fast or even faster in some circumstances, if it's making use of resources that were otherwise sitting idle due to another bottleneck.

Always measure before you burn time on "optimizations" that might not have a discernible impact on your game / on your target hardware.
> 2 votes

---
Tags: unity, c#, performance, monobehaviour
---


# Question
Title: Gameobject not spawning in desired position after InvokeRepeating and Instantiate
# Context

Hello, currently creating a clone of "Crossy Road" and what I'm trying to do is to spawn my moving object called "Vehicle" at a random speed and rate of spawn. This is also applicable to "Plank", but I will start first with the vehicle. So far, everything is working fine as *intended* for the game mechanics, but I would like to finalize with this issue so it is fully functional in terms of playability.

# Problem

My issue now is I 3 different spawns objects: grass, river, and road. Each object holds other objects (let's call it spawners) depending of what field is being spawn. For example, if grass field object is spawned, it will spawn trees depending in a random varied selection. Another example is with road field. When the road is spawned, a vehicle will be spawned from either left or right in its current initial position. This vehicle will moves as intended with a random speed, but not with the original spawn position and rate (as shown in the GIF. The vehicle spawns in the middle of the road and not in the beginning of the left/right road).

As far I'm aware, my rate is currently unused because it is not the main issue I want to solve. However, the issue now is with the **transform position** not working as I have pictured in my head. So what is happening is that when the road is spawned again, the vehicle is spawned in the middle of the trajectory instead of resetting to the beginning.

Also, I have noticed that when I print the vehicle object, the Z-axis has a weird number compared to the original position.

# Attempts done

I have been thinking that maybe it is the way I have set everything up. I have 4 vehicle objects with a child object called "Tank". However, in each vehicle object, I'm using `SetActive(...)` only and not really reusing the object itself to the beginning. Later on, I want to organize this spaghetti code and optimize it (e.g ObjectPool to spawn my roads and other GameObjects after hitting a certain range, adding a player range detection to spawn a field to name a few).

To be honest, my whole code feels bloated for something simple. This will be fixed once everything is working accordingly.

# Code

## `SpawnManager.cs` (some links provided too from learning to make this)

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

/*
** Weighted randomness: https://forum.unity.com/threads/random-numbers-with-a-weighted-chance.442190/
** Scriptable Object Weight spawn example: https://www.youtube.com/watch?v=FCksj9ofUgI&ab_channel=LlamAcademy
** From scratch loot tables with Scriptable Objects to make a loot table: https://www.youtube.com/watch?v=tX3RWsVLnzM&ab_channel=GregDevStuff
** Creating a random with an animation curve: https://www.youtube.com/watch?v=zw1OERK5xvU&ab_channel=HamzaHerbou
** Random Vehicle position spawn (maybe this can help me): https://stackoverflow.com/questions/51312481/move-spawn-object-to-random-position
*/

public class SpawnManager : MonoBehaviour
{
    public GameObject Player;
    public Spawn[] Field;
    public GameObject[] SpawnObjectTrees;
    public GameObject[] SpawnObjectVehicles; //different vehicles
    public GameObject[] SpawnObjectPlanks; //3 sizes (small, medium, large)
    private PlayerControl2 playerControlScript;
    private int distancePlayer;
    private int toggle;
    private bool keepSpawning;
    bool vehicleFlag = false;
    bool plankFlag = false;
    public float randomNumSpawn;

    void Awake()
    {
        keepSpawning = true;
        playerControlScript = GameObject.Find("PlayerObject").GetComponent<PlayerControl2>();
        InvokeRepeating("Spawner", 3f, randomNumSpawn);
    }

    void Update()
    {
        if (Input.GetButtonDown("up") && !playerControlScript.gameOver)
            SpawnField();
    }

    void Spawner()
    {
        bool activeLeft = false;
        bool activeRight = false;

        if (vehicleFlag)
        {
            print(initialObjectSpawn);
            for (int i = 0; i < SpawnObjectVehicles.Length; i++)
            {
                print($"{SpawnObjectVehicles[i]}: {SpawnObjectVehicles[i].transform.position}"); //Here I get the weird position.z values pretty wonky
                toggle = Random.Range(0, 2);
                if (toggle == 1 && !activeLeft)
                {
                    activeLeft = true;
                    SpawnObjectVehicles[i].SetActive(true);
                }
                if (toggle == 0 && !activeRight)
                {
                    activeRight = true;
                    SpawnObjectVehicles[i].SetActive(true);
                }
                else
                    SpawnObjectVehicles[i].SetActive(false);
            }
        }
    }

    void SpawnField()
    {
        //I want to spawn the vehicles, planks, and trees in sets accordingly to the field (grass, river, road)
        //For vehicles and planks, they can move horizontally from either -z or z boundaries
        //NOTE: keepSpawning may be useless if i have a playerControlScript.gameOver already in here
        if (keepSpawning)
        {
            distancePlayer += 3;
            Vector3 intPos = new Vector3(0, 0, 0);
            int i = Random.Range(0, 1000);
            for (int j = 0; j < Field.Length; j++)
            {
                if (i >= Field[j].minProbabilityRange && i <= Field[j].maxProbabilityRange)
                {
                    intPos = new Vector3(distancePlayer, -1f, 0);
                    GameObject Surface = Instantiate(Field[j].spawnField);
                    if (Surface.CompareTag("Grass"))
                        TreeToggle();
                    if (Surface.CompareTag("Road"))
                    {
                        vehicleFlag = true;
                        VehicleToggle();
                    }
                    // if (Surface.CompareTag("River")) this will be the same as vehicle
                    // {
                    //     plankFlag = true;
                    //     PlankToggle();
                    // }
                    //Add spawn for vehicles and planks with given spawnrate/spawn intervals
                    Surface.transform.position = intPos;
                    vehicleFlag = false;
                    plankFlag = false;
                }
            }
        }
    }
    void TreeToggle()
    {
        int counter = 0;
        for (int i = 0; i < SpawnObjectTrees.Length; i++)
        {
            int toggle = Random.Range(0, 2); //[0, 2)
            if (toggle == 1 && counter < 5) //True and when there are already 5-4 trees to toggle
            {
                counter++;
                SpawnObjectTrees[i].SetActive(true);
            }
            else //fills the rest to inactive Trees
                SpawnObjectTrees[i].SetActive(false);
        }
    }
    void VehicleToggle()
    {
        // I have Left and Right with 2 vehicles in each. My goal is to setActive one of them each side at a time with a different interval spawnrate and speed
        Spawner();
    }

    void PlankToggle()
    {
        Spawner();
    }
}

[System.Serializable]
public class Spawn
{
    public GameObject spawnField;
    public float minProbabilityRange = 0.0f;
    public float maxProbabilityRange = 0.0f;
}

```

# Hierarchy/Inspector

If there is any information you want to know, feel free to ask and I will make a quick edit to fulfill these goals. Again, thank you for your time and appreciate it :D I hope you are having a good day!

# Answer
It looks like your `Field` array is storing references to the "Grass", "Road", and "River" child objects of your `SpawnManager` *in this scene*.

That means these objects and their children like vehicles are part of the active game scene, ticking and updating every frame. So the original car(s) start at their respective waypoints and begin driving along the road. Then sometime later you spawn a new road, which copies the whole Road object and its children in their current state - partway along the road.

This code needs some major refactoring to fix this, because it's relying on these objects being in the scene to vary their setups.

Right now the only things you do *to* the copy are instantiate it and position it:

```
GameObject Surface = Instantiate(Field[j].spawnField);
// ...
Surface.transform.position = intPos;
// These two could be one line, by the way:
// var Surface = Instantiate(Field[j].spawnField, intPos, Quaternion.identity);

```

Everything else - `VehicleToggle` / `TreeToggle` / `PlankToggle` \- never gets a reference to this `Surface` variable, so they can't alter the newly-spawned slice of the world in any way.

But how are you seeing differences?

Because they keep modifying *the originals* \- watch them carefully in the Scene view while your game is running and you'll see the original world slices have their trees, vehicles, and planks blinking in and out of existence. Whatever state was left after the last world slice spawned is the one that's cloned to make the next world slice.

To fix this, I'd recommend moving most of this logic from the manager spawning the world slices, and into the world slice prefabs themselves:

```
public class SpawnPoint : MonoBehaviour {
    [SerializeField] Transform _prefab;

    public void Spawn() {
        Instantiate(_prefab, transform.position, _prefab.rotation);
    }
}

public class MapChunk : MonoBehaviour {
    [System.Serializable]
    public struct SpawnCollection {
        [Range(0, 1)]
        [SerializeField] float _chancePerSpawner;
        [SerializeField] int _maxSpawns;
        [SerializeField] SpawnPoint[] _spawnPoints;

        public void Spawn() {
            int spawned = 0;
            foreach (var spawner in _spawnPoints) {
                if (spawned == _maxSpawns) break;
                if (Random.value < _chancePerSpawner) {
                    spawner.Spawn();
                    spawned++;
                }
            }
        }
    }

    [SerializeField] int _width = 1;

    [SerializeField] SpawnCollection[] _collections;

    public Vector3 SpawnAt(Vector3 position) {
        var instance = Instantiate(this, position, transform.rotation);

        foreach (var collection in instance._collections) {
            collection.Spawn();
        }

        position.x += _width;
        return position;
    }
}

```

Then your `SpawnManager` does not need to know about grass/road/river - it can just have an array of `MapChunk` prefabs *from the Assets folder, not the scene*.

It can randomly select one, call its `Spawn` method with the current spawn position, and get back the position for the next spawn, taking into account the width of the selected chunk. This lets you mix and match wider and narrower prefabs for more complex setups.

All the logic of how to set up the contents of a given slice is delegated to that slice - simplifying your manager, and ensuring you don't accidentally repeat the mistake of modifying the global state / original prefab instead of the spawned instance.

Each map slice exposes a collection of related spawners you can use to group the left vs right lanes of traffic, and enforce limits on the number of cars per direction or number of trees. Just note that - matching the code you provided - spawn points earlier in the array have a higher probability of being selected, while spawn points later in the list are only used if the earlier ones fail their random roll.
> 0 votes

---
Tags: unity, gameobject
---


title: OpenGL 4 tracers

text:
# Question
Title: OpenGL 4 tracers
We have implemented a glow map into our renderer. It basically uses a blur filter on the glow map pass. But, I cannot figure out how to do tracers in OpenGL. Someone suggested using a couple of textures that are saved between frames, ping-ponging them so to speak. However, I am stuck at the part where I need to implement it. My C++ code is:

```
glowmap_copier.use_program();

// create output temp texture, with texstorage
GLuint temp_tex;

glGenTextures(1, &temp_tex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, temp_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, win_x, win_y, 0, GL_RGBA, GL_FLOAT, NULL);
glBindImageTexture(0, temp_tex, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, temp_tex);
glUniform1i(glGetUniformLocation(glowmap_copier.get_program(), "output_image"), 0);

// activate glow and last frame glow input textures
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, glowmap_tex);
glUniform1i(glGetUniformLocation(glowmap_copier.get_program(), "inputa_image"), 1);

glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, last_frame_glowmap_tex);
glUniform1i(glGetUniformLocation(glowmap_copier.get_program(), "inputb_image"), 2);

// call compute shader
glDispatchCompute((GLuint)win_x, (GLuint)win_y, 1);

// Wait for compute shader to finish
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

// copy from temp to last frame using glCopyImageSubData
glCopyImageSubData(temp_tex, GL_TEXTURE_2D, 0, 0, 0, 0,
    last_frame_glowmap_tex, GL_TEXTURE_2D, 0, 0, 0, 0,
    win_x, win_y, 1);

glDeleteTextures(1, &temp_tex);

```

and:

```
// OpenGL 4.3 introduces compute shaders
#version 430

layout(local_size_x = 1, local_size_y = 1) in;

layout(binding = 0, rgba32f) writeonly uniform image2D output_image;
layout(binding = 1, rgba32f) readonly uniform image2D inputa_image;
layout(binding = 2, rgba32f) readonly uniform image2D inputb_image;

void main()
{
    // Get global coordinates
    const ivec2 pixel_coords = ivec2(gl_GlobalInvocationID.xy);
    const vec4 output_pixel = imageLoad(inputa_image, pixel_coords) + imageLoad(inputb_image, pixel_coords);

    imageStore(output_image, pixel_coords, output_pixel);
}

```

An image of the glow effect is:

What I would like is to be able to accumulate the effect, and have it fade over time. Tracers, basically. Any ideas on how to do something like this in OpenGL 4? P.S. it seems that this problem is analogous to motion blur.

An example of the glow map is below. The glow map contains non-black data for the reaper's small eyes, as well as the 4 lights, and a small border around the game board. There is also an orange glowing thing, which represents the mouse location.

# Answer
@user253751

We used a compute shader to combine the glow map and last frame's glow map. Works good.

```
glUseProgram(glowmap_copier.get_program());

// create output temp texture
GLuint temp_tex;

glGenTextures(1, &temp_tex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, temp_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, win_x, win_y, 0, GL_RGBA, GL_FLOAT, NULL);
glBindImageTexture(0, temp_tex, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);
glUniform1i(glGetUniformLocation(glowmap_copier.get_program(), "output_image"), 0);

// activate glow and last frame glow input textures
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, glowmap_tex);
glBindImageTexture(1, glowmap_tex, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA32F);
glUniform1i(glGetUniformLocation(glowmap_copier.get_program(), "inputa_image"), 1);

glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, last_frame_glowmap_tex);
glBindImageTexture(2, last_frame_glowmap_tex, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA32F);
glUniform1i(glGetUniformLocation(glowmap_copier.get_program(), "inputb_image"), 2);

// call compute shader
glDispatchCompute(win_x, win_y, 1);

// Wait for compute shader to finish
glMemoryBarrier(GL_ALL_BARRIER_BITS);

// debug -- shows that it works
vector<float> output_pixels(win_x* win_y * 4);
glActiveTexture(GL_TEXTURE0);
glBindImageTexture(0, temp_tex, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);

glCopyImageSubData(temp_tex, GL_TEXTURE_2D, 0, 0, 0, 0,
    last_frame_glowmap_tex, GL_TEXTURE_2D, 0, 0, 0, 0,
    win_x, win_y, 1);

// debug -- shows that it works
glActiveTexture(GL_TEXTURE0);
glBindImageTexture(0, last_frame_glowmap_tex, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);

glDeleteTextures(1, &temp_tex);

```

and:

```
// OpenGL 4.3 introduces compute shaders
#version 430

layout(local_size_x = 1, local_size_y = 1) in;

layout(binding = 0, rgba32f) writeonly uniform image2D output_image;
layout(binding = 1, rgba32f) readonly uniform image2D inputa_image;
layout(binding = 2, rgba32f) readonly uniform image2D inputb_image;

void main()
{
    // Get global coordinates
    const ivec2 pixel_coords = ivec2(gl_GlobalInvocationID.xy);
    const vec3 output_pixel = imageLoad(inputa_image, pixel_coords).rgb + 0.5*imageLoad(inputb_image, pixel_coords).rgb;

    imageStore(output_image, pixel_coords, vec4(output_pixel, 1.0));
}

```

The result:
> 0 votes

---
Tags: opengl, c++, shaders
---


# Question
Title: How to prevent players from brute forcing puzzles?
I'm making a classic Resident Evil / Silent Hill type game, so am currently in progress of writing a few puzzles.

Currently, I have a combination lock - 4 digits 0-9. Each digit of the combination is marked with a symbol, so that each position can be linked to a puzzle in which the correct number can be found.

Obviously, I'd like the player to solve all 4 puzzles, but there is nothing that stops them solving 3 puzzles then just brute force guessing the last one.

Is this something I should care about? Is it almost like a built in contingency / loophole if the player gets stuck? I've thought about having some sort of 'lives' system, where if you try too many times it locks you out - but that's far too extreme for just a puzzle.

Or the lazy way out I've considered, is maybe to just have 3 puzzles and the 4th one has some in-universe explanation that the correct answer has been lost to time, and the only way *is* to brute force it, but it just doesn't seem like the "right" solution.

This is my first game, so the first time I'm properly thinking about this kind of stuff, so just wanted to get some thoughts and opinions on how people have handled this in the past. Thanks!

# Answer
> 24 votes
A couple of thoughts:

1. You can keep digit inputs blocked (in various ways) until player achieves the source of the digit. In other words, design your 4-combination lock as a 4-keys lock.
2. You can make the "digits" more complex, e.g. require 4 pairs of 2 letters (26^2 combinations per input) rather than 4 digits (10 combinations per input).
3. You can redesign the lock to require 4 independent but mutually required actions - e.g.: WD40 (to grease the mechanism) + Key (to unlock) + PIN-code (to unlock) + UV-lamp (to see markings in PIN input).
4. If the game is more interesting than boring - players will always choose to play it more rather than bruteforce/cheat - just give them that possibility even if they unlock by mistake/misclick/whim.
5. Try breaking the "lockpicking flow" if it starts. It can be as simple as a progressive delay after each try, or as complex as adding a cutscene and teleporting player out into the mobs swarm and resetting the whole combination (cruel but effective).

# Answer
> 9 votes
In general I won't worry about it.

First of all, don't think of brute forcing as cheating. Think of it as taking the fun out of the game (in particular if you make the combination longer). In general, you want to make finding/interpreting/following clues the fun part. You want players to enjoy doing that, so they want to do that instead of brute forcing※.

※: Zibelas has very good point in comments: if people can look it up online (or ask somebody who already completed the game), that is easier than brute forcing the combination lock, and thus more likely that people will do it. Some games will randomize the combinations to get around this.

To encourage people to find clues, give the player a clue early on. Preferably something that they can try right away, even if it is a misdirection. The point is to get them to interact with the mechanic, and to tell them that there is stuff they can find. *It can also be an opportunity for some lore exposition (e.g. that was the old combination, but they changed it because reason).*

About some penalty, in general I would be against. But if you really want to have a penalty, consider if this can prevent players to experience the game to the end. Permanently locking a part of the game is OK as long as it is optional. Otherwise, you might as well give them a game over. What happens on a game over? They have to start from a save/check point or the beginning? - Well, that is a set back. You can come up with a better set back... Just waiting some time is probably boring. But you could have the player do some task so they can get more attempts (e.g. get some consumible item).

As I said, I'm against a penalty. Instead, I suggest to change the puzzle more interesting. A combination lock is very similar to a key lock, except that you can either find the combination or guess it. If you want to remove the possibility of guessing, then make it a key lock. Otherwise, add a wrinkle to combination lock puzzle, for example that when you input some digit it changes others. So that it is not only figuring out what combination to input, but also how to input it. And you can always combine it with some other kind of puzzle.

# Answer
> 9 votes
This is something I accidentally play-tested and it works surprisingly well -- give a medium-length delay after an incorrect answer. Don't make them click past anything and watch something interesting ... just give a delay. It doesn't have to be that long before people naturally take that time to think about the next try. Maybe they add up the delays in their head and decide to take a little longer solving the puzzle. Or maybe they were going to zip through 0,1,2,3... but decide to go with their gut and try 7 after 0. They can still brute force it, but the delays are telling them "come-on, you're waiting anyway -- you may as well think about it some more".

Mine was educational so I didn't want to be too cutsie (and I also secretly graded them on missed guesses). But for a game you could make the delays a little longer each time -- maybe guessing as soon as possible makes the delay even longer. One time a wrong guess could reset the previous answer (which isn't all that bad -- they remember the old puzzle and feel good about solving it faster this time). Even if they brute force it, they at least feel as if they've earned it.

Then, if you can, repeat that sort of puzzle. Game puzzles are easy to not take seriously -- many are boring afterthoughts. But after a few of the same type they realize you're serious about the puzzle, maybe it is fun, so they may as well work on a strategy.

# Answer
> 9 votes
Don't. As a game developer, it is not your job to "force" players to do anything. There are several reasons a player might want to "solve" your puzzle in a non-traditional way:

1. The player is playing the entire game in a non-traditional way, such as a speedrun or other player-defined challenge run. You should not impose barriers to prevent people from enjoying the game in the way they want to enjoy it. These players tend to be among your game's most devoted fans, and spiting them is not going to make them like you as a developer.
2. The player is not in your target audience and will not enjoy the game no matter what you do. No matter what your target audience is, it will never include everybody, and worrying about people outside that audience will lead to no good outcome.
3. The puzzle is not fun or interesting to your target audience. If you have a bad puzzle, the last thing you want to do is force people to solve it. Would you rather have a player skip a bad puzzle or give up on the game entirely? That said, this is a real problem that you should worry about. You should be able to tell from playtesting if this is going to be a problem with your puzzle, and if it is, you should redesign the puzzle to be more suitable or remove it entirely.

There are, of course, exceptions, for example:

* You are making an educational game, and the puzzle is important to show mastery of the subject matter.
* You are making a multiplayer game, AND a player could receive some unfair advantage by brute-forcing the solution.
* You're making a gatcha game or similar and you're charging people to attempt the puzzle or some such nonsense.

In this case, you could just make it a ten-digit code and have the puzzles each give two digits.

# Answer
> 2 votes
I've been thinking for a bit and I came with a possible solution. Have a combination lock of 5 digits and give two digits when completing the last puzzle. Having to brute force ~50 combinations on average is enough to discourage most reasonable players from doing this. This solution is less satisfying perhaps because the last digit is different from the other 3. You could also have a combination lock with 8 digits to make each puzzle the same again (so you would get 2 digits each puzzle).

Another solution would be to have the positions of the digits be unknown and to give the positions with the last puzzle. You could also give the position of the first digit and the last digit, after which the player would have to guess the positions of the middle two digits. In the game the positions of the middle two digits could be displayed as damaged/unreadable because of wear. I show an example of this last solution below to make it more clear. On average this solution would take `3*2*10/2 = 30` tries to guess before the last digit is known. This is on the low side but might just be enough to discourage brute forcing, especially when it takes some time to enter each digit.

```
_ _ _ _  ()      digit: 6, position: 2
_ 6 _ _  ()      digit: 7, position: ?
_ 6 _ _  (7)     digit: 8, position: ?
_ 6 _ _  (7,8)   digit: 9, position: 4
_ 6 _ 9  (7,8)
7 6 8 9  ()      INCORRECT
8 6 7 9  ()      CORRECT

```

# Answer
> 1 votes
Other answers have covered an idea that I'll paraphrase here as:

> Instead of having a puzzle which requires the player to find pieces of information from the world, have them find items. If the thing the player needs is some information then they can guess it, but if it's some items then it makes sense for the player not to be allowed to proceed until they have acquired those items within the game.

However, sometimes you might still want the puzzle to be information-based rather than item-based, for narrative or aesthetic reasons. In that case, the problem is that you want the puzzle to require the player to acquire information *within the game*, but you don't want the puzzle to be solvable by a player who has the exact same information acquired from *outside the game*, e.g. by guessing or looking it up on a wiki.

Here's a possible solution: make the player's character need a justification for why the information is correct. For example, suppose the player's character has been hired by a wealthy family to find where their deceased matriarch has hidden a particularly rare and valuable coin. In this case, the player needs to solve the puzzle by acquiring information, i.e. the location of the coin. In fact, the coin is hidden inside a porcelain ornament in the family's home, and the only way to get it out is to break the ornament into pieces.

Now suppose the player knows the required information (i.e. the coin's location) because they looked it up online, or they guessed. They can just go and break the ornament and get the coin, right? Not so fast, because the ornament itself is somewhat valuable and the family won't just let the player character break the ornament for no reason. So, the player actually needs to play the game and find the information about the coin's location in the intended way, because the player's character needs to be able to convince the family that that's where the coin is.

So, the goal is for there to be a narrative reason that the player's *character* must know the information, in order for the *player* to be mechanically allowed to have the character act on that information. Here's a few more shorter examples:

* You are disarming a bomb and if you enter the wrong code, it will explode; you can't just enter a code they looked up outside of the game, because the other characters aren't willing to risk the bomb blowing up without having some reason to believe you know the correct code.
* You are solving a mystery to find out who should be arrested for a crime that has been committed. You cannot have that person arrested without some evidence that they are indeed the culprit.
* There is treasure buried somewhere on this island, but it's going to take a lot of work to dig for it even once you know where it is. Your crewmates aren't going to dig in some random location that the player guessed, you need to find the treasure map so you can be sure that's where it's really buried.

The easiest way to have the player's character justify the information to other characters is to have them find an item which proves it. That may be fine for your purposes since the narrative of the puzzle is still about acquiring information rather than acquiring the item. But you can also have it work without an item; just have the dialogue play out differently (or, give different dialogue choices) depending on if the player's character has acquired the information.

# Answer
> 0 votes
**Four locks.**

Each lock requires 4 characters.

1st is digits. Second is a 4 letter word. Third puzzle is a riddle and tells how to combine first and second solutions to get the third.

4th lock is old. It does not look right. It might be rusty.

4th puzzle solution is not a number, but a boltcutter.

https://en.wikipedia.org/wiki/Gordian\_Knot.

# Answer
> 0 votes
Consider what is the purpose of finding the numbers - couldn't the player just pick up items, or press switches to unlock the puzzle? Take a good look at Andrew Ray's answer, he has a good point.

If you really really want it, the truly impenetrable way of doing it is multiplication. Consider a puzzle like this:

In this version, the player needs to multiply the numbers, on a calculator, and then enter the result.

I was too lazy to draw more than 3 digits, but you can have 5. Good luck figuring the factors. The order does not matter in this puzzle. With two digit factors, this is frustrating to brute force. You can still do it the same way, but it's way to annoying since you'd have to calculate all the possible factors for the last number. It's also something I haven't quite seen in a game.

That said, these number "puzzles" don't really entertain me. Just give me 4 keys I need to collect and be done with it.

# Answer
> 0 votes
The core issue is that you are, at the same time:

* Giving the players the freedom to work with (and unlock) the lock without any prior requirements
* Have some requirements in mind that you want players to engage with before handling the lock.

One of these has to give. Either you remove the ability to unlock the lock, or you accept that your players are able to circumvent your puzzle content.

It might seem railroady to disallow using the lock until the entire code is known, but railroading players is precisely what you are intending to do here.

If instead it is important to you to not railroad your players in any way, then that renders the question itself moot.

---
Tags: game-design, game-mechanics, puzzle
---


# Question
Title: How to check which Area2D's are overlapping with KinematicBody2D?
My player is a KinematicBody2D with a CollisionShape2D as a child.

When the player presses a button I want to check if he stands on certain (static) areas.

This areas are Area2D with a CollisionShape2D as a child.

so I thought, i could do something like this in my player-class:

```
public override void _Process(float delta)
{

    if (Input.IsActionPressed("interact"))
    {
        //Check which areas are overlapping
    }

    //Do other stuff like moving
}

```

But unfortunately I did not find a way to do this with KinematicBody2D.

So is there a way to query which Area2D's are overlapping with my KinematicBody2D?

# Answer
This is much easier starting with the `Area2D`s. You can query each `Area2D` with `overlaps_body`. Something like this:

```
var areas := [$Area, $Area2] # perhaps get the list from somewhere else
for area in areas:
    if area.overlaps_body(self):
        print("Overlapping " + area.name)

```

On the other hand, if you don't have references to the areas, you will have to do a physics query, which I believe would be like this:

```
var space := get_world_2d().direct_space_state
var query := Physics2DShapeQueryParameters.new()
query.collide_with_areas = true
query.collide_with_bodies = false
query.set_shape($CollisionShape2D.shape)
query.transform = $CollisionShape2D.global_transform
var result := space.intersect_shape(query)
for area_collision in result:
    var area := area_collision.collider as Area2D
    if is_instance_valid(area): #perhaps some other checks here
        print("Overlapping " + area.name)

```

This is the physic query in C#:

```
        var space = GetWorld2d().DirectSpaceState;
        var query = new Physics2DShapeQueryParameters();
        query.CollideWithAreas = true;
        query.CollideWithBodies = false;
        var collision = GetNode<CollisionShape2D>("CollisionShape2D");
        query.SetShape(collision.Shape);
        query.Transform = collision.GlobalTransform;
        var result = space.IntersectShape(query);
        foreach (Godot.Collections.Dictionary item in result)
        {
            GD.Print("All Dictionary: " + item.ToString());
            var collider = item["collider"];
            GD.Print("Found: " + collider.ToString());
            GD.Print("Type: " + collider.GetType().ToString());
            var area = collider as Area2D;
            if (area!= null)
            {
                GD.Print("Some Random Area");
            }

            var treasure = collider as Treasure;
            if (treasure != null)
            {
                GD.Print("Found some treasure");
            }
        }

```
> 2 votes

---
Tags: c#, godot
---


# Question
Title: Why is the Hiero font not coordinated to fit neatly in the display window?
I imported a font with Hiero and I draw the font like:

```
font.draw(batch, "1", 0, 48);

```

This is the resultant image:

So the font it moved up to hit the bottom perfectly, but it doesn't touch the left side perfectly. Why does this happen? Is there a way I can fix this? It seems like if I set the x coordinate to -3 it works, but this seems somewhat arbitrary. Any ideas?

# Answer
That spacing is called font kerning. And that is exactly why there is padding in front. The purpose of kerning is so that letters fit nicely next to each other, and that they aren't too close or too far away from each other.
> 3 votes

# Answer
I think you want full control of the text box, right?

Here is some code for you, soured from another Q&A thread:

```
GlyphLayout layout = new GlyphLayout(); //dont do this every frame! Store it as member
layout.setText("meow");
float width = layout.width;// contains the width of the current set text
float height = layout.height; // contains the height of the current set text

```
> 0 votes

---
Tags: java, 2d, libgdx
---


# Question
Title: How to apply shadows on an animated model
I have followed the learnopengl.com tutorial on skeletal animation, but it does not apply shadow on the animated model.

Here is the vertex shader that is used to display the character. I suspect that `FragPosLightSpace` is not calculated properly, as it's the only variable that is used only to calculate the shadow in the fragment shader (if other variables were wrong, I suspect the model wouldn't display properly).

```
#version 330 core

layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;
layout(location = 2) in vec2 aTexCoords;
layout(location = 3) in ivec4 boneIds;
layout(location = 4) in vec4 weights;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

const int MAX_BONES = 100;
const int MAX_BONE_INFLUENCE = 4;
uniform mat4 finalBonesMatrices[MAX_BONES];

uniform mat4 lightSpaceMatrix;

// Output
out vec3 FragPos;
out vec3 Normal;
out vec2 TexCoords;
out vec4 FragPosLightSpace;

void main()
{
  mat4 boneTransform = finalBonesMatrices[boneIds[0]] * weights[0];
  boneTransform += finalBonesMatrices[boneIds[1]] * weights[1];
  boneTransform += finalBonesMatrices[boneIds[2]] * weights[2];
  boneTransform += finalBonesMatrices[boneIds[3]] * weights[3];

  vec4 totalPosition = boneTransform * vec4(aPos, 1.0);

  gl_Position =  projection * view * model * totalPosition;

  TexCoords = aTexCoords;

  vec4 NormalL = boneTransform * vec4(aNormal, 0.0);

  Normal = (model * NormalL).xyz;

  FragPos = (model * totalPosition).xyz;

  FragPosLightSpace = lightSpaceMatrix * vec4(FragPos, 1.0);
}

```

# Answer
> 0 votes
The solution:

```
FragPosLightSpace = lightSpaceMatrix * model * totalPosition;

```

---
Tags: opengl, skeletal-animation, shadow-mapping
---


# Question
Title: Registering recipe for Minecraft with Forge on IntelliJ
I'm using Forge on IntelliJ IDEA to make a mod for Minecraft, and I think I am stuck on where I need to register a recipe for an item.

**How I got to that idea:** I tested it out and everything worked. No bugs/errors: The item that would be made with the recipe (a rubber band) was available right away in creative mode. However, when I was trying to do the recipe part for creating the rubber band, which would include getting a dandelion that leads to an achievement(?) that shows the player they would then be able to make a rubber band with dandelions, the achievement only showed the regular recipe that's in the original game.

I know the setup of the files that import other methods works because I tried it out with this example. It also shows that the rubber\_band.json was made in the resources, so my guess is that the part that went wrong is most likely how I did not include the registration of the recipe for the rubber band. I'm just unsure how to get that settled.

Here is what I have so far:

```
public class Recipes  extends RecipeProvider {

    public Recipes(DataGenerator generatorIn) {
        super(generatorIn);
    }

    @Override
    protected void buildCraftingRecipes(Consumer<FinishedRecipe> consumer) {
        ShapelessRecipeBuilder.shapeless(Registration.RUBBER_BAND.get())
                .requires(Items.DANDELION, 9)
                .unlockedBy("has_dandelion", has(Items.DANDELION))
                .save(consumer);
    }
}

```

^ with imports, this is the recipes (the only one I have so far)

```
    public static final RegistryObject<Item> RUBBER_BAND = ITEMS.register("rubber_band", () -> new Item(ITEM_PROPERTIES));
    // public static final TagKey<Item> DANDELION_ITEM = TagKey.create(Registry.ITEM_REGISTRY, new ResourceLocation(glow.MODID, "dandelion_item"));

        public static final DeferredRegister<RecipeType<?>> RECIPES = DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS.getRegistryName(), glow.MODID);
    public static final RegistryObject<RecipeType<CraftingRecipe>> RUBBER_BAND_RECIPE = RECIPES.register("rubber_band_recipe", () -> new Recipe<ITEM_RECIPE>);

```

^ this is towards registration

```
singleTexture(Registration.RUBBER_BAND.getId().getPath(), mcLoc("item/generated"), "layer0", modLoc("item/rubber_band"));

```

^ this is towards ItemModelProvider

```
tag(Registration.DANDELION_ITEM)
                .add(Registration.RUBBER_BAND.get());

```

^ these are the tags

```
add(Registration.RUBBER_BAND.get(), "Rubber band");

```

^ this is the name

I am following this tutorial and this tutorial to get the format organized (and understand things better). I am also using this doc to see what I'm looking for, though I'm still not getting a good grasp on reading it.

Once more, my goal is to be able to craft the rubber band.

This is what it should look like at the crafting table:

The player should also unlock the recipe when picking up the dandelion:

Also, this is for game 1.18.2. Thank you in advance!

I have not yet used the `Recipes` class. I have been trying to follow along with this, which is the most recent version of the tutorial author's, but this also does not mention `Recipes` while it includes the class.

# Answer
I realized I missed adding `new Recipes()` in the class `DataGenerators`

@Mod.EventBusSubscriber(modid = glow.MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class DataGenerators {

    @SubscribeEvent
    public static void gatherData(GatherDataEvent event) {
        DataGenerator generator = event.getGenerator();
        if (event.includeServer()) {
            generator.addProvider(new Recipes(generator)); // this was previously commented out
            // generator.addProvider(new LootTables(generator));
            BlockTags blockTags = new BlockTags(generator, event.getExistingFileHelper());
            generator.addProvider(blockTags);
            generator.addProvider(new ItemTags(generator, blockTags, event.getExistingFileHelper()));
        }
        if (event.includeClient()) {
            generator.addProvider(new BlockStates(generator, event.getExistingFileHelper()));
            generator.addProvider(new ItemModels(generator, event.getExistingFileHelper()));
            generator.addProvider(new LanguageProvider(generator, "en_us"));
        }
    }
}
```

> 0 votes

---
Tags: java, minecraft-modding, modding
---


# Question
Title: Calculating train animation speed based on distance
I have an **animation clip** of a train which is covering about a 16707-meter distance in 56.66667 seconds. So that's:

* distance covered (from start to end position by animation ) = 16707
* Animation length (in seconds) = 56.66667

Now I want it to complete the animation in 9 minutes. How should I calculate the ideal speed so that the train reaches its destination in 9 minutes from the starting point of the animation?

# Answer
You can compute a playback speed as:

```
float desiredLengthInSeconds = 9f * 60f; // 9 Minutes * 60 seconds per minute

float playbackSpeedRatio = animationClip.length / desiredLengthInSeconds;

```

Then if you're using an `Animation` component, apply that speed as:

```
foreach (var state in animationComponent) {
    state.speed = playbackSpeedRatio;
}

```

Or for an `Animator` component:

```
animatorComponent.speed = playbackSpeedRatio;

```

Since the total distance travelled is 16707 m, covered in 540 s (9 minutes), that means the train is travelling at an average speed of 16707/540 = 31.93888... m/s.
> 0 votes

---
Tags: unity, mathematics, animation
---


# Question
Title: How do I make square tiles with numbers on them?
I would like to make a game called 15 puzzle. But I'm not a designer. I'm interested more in programming side of the process. So for this project I need some really simple squares with numbers. I've made a png image using Paint but all I could get is to add the image to the Assets folder. I couldn't add it to a gameobject. I think I'm missing something. Probably smth about textures. In short, some guidance would be apreciated.

# Answer
Create a child of the tile and add "TextMeshPro - Text" Component to it. It needs some adjustments, because the text frame is way bigger than the tile, but then it works fine.
> 1 votes

---
Tags: unity, image
---


# Question
Title: Trying to package an Unreal project for Windows but it builds the default demo fps map?
This is really frustrating but I made a complicated Unreal Engine level and it built the default FPS project. It didn't build a single asset in my scene.

I would build the project by clicking `Package Project`. (Btw the app isn't blank, I have the view turned away from the assets for IP protection purposes):

Also I have my project settings following the tutorials that I found online:

So why is it not building my game?

# Answer
I incorrectly put “Stage” as the "Editor Startup Map" instead of as the "Game Default Map."

So I switched the "Game Default Map" from "FirstPersonMap" to “Stage” and it built the correct scene.
> 1 votes

---
Tags: unreal, build-process, unreal-5, platform
---


title: How to handle overlapping meshes?

text:
# Question
Title: How to handle overlapping meshes?
So I want to note that I am a beginner at game dev but an okay coder. I wish to make a game in which the character changes clothes.

I have a character and a few clothing meshes that all have the exact same rig with the same bone names.

So I equip the clothes to the character using a script to attach them to the avatar's rig and it works very well. However, meshes of clothes that are being worn on top of each other like coats and t-shirt overlap and create a bad appearance

How do I fix this? As I am new to gamedev I might not completely understand how to execute your suggestions so any youtube videos or tutorials on this issue would be really really welcome. Thank you so much!

# Answer
The preferred solution is that each layer is designed to fit on top of the the smaller layer when designed.

If that is not possible, scale the outer clothing by a small amount, just enough to cover the inner layer.

Blender is free and mostly on par with the "big guys". There are many tutorials available.
> 1 votes

---
Tags: shaders, 3d-meshes, mesh
---


# Question
Title: Interactable actors should be implemented via components or inheritances?
I am new to game development and I am learning Unreal Engine right now.

When a player character `APlayer` wants to interact with other actors (such as `ALight`, etc), generally the process is as follows:

* `APlayer` gets a reference to `ALight` via line tracing or collision.
* `APlayer` checks whether the reference is of type `ALight`, if yes then invoke the public `Interact` method exposed by `ALight`.

It is clear enough to me that I need to provide an interface (abstract class) first.

```
class UInteractableInterface : public UInterface{};
class IInteractableInterface
{
public:
    virtual void Interact(AActor* Instigator) = 0;
};

```

Now for the `ALight` part I got confused in determining whether

* option A: `ALight` implements `IInteractableInterface`
* option B: `ALight` does not implement `IInteractableInterface` but it depends on `USwitch` which implements `IInteractableInterface`.

## Option A (`ALight` implementing `IInteractableInterface`)

```
class ALight: public AStaticMeshActor, public IInteractableInterface
{
public:
    virtual void Interact(AActor* Instigator) override;
};

void ALight::Interact(AActor* Instigator)
{
    UE_LOG(LogTemp, Warning, TEXT("%hs"), __FUNCTION__);
}

```

```
void APlayer::InteractWithOther()
{
    // Other code pertaining to line tracing or collision
    // is removed for the sake of simplicity!

    AActor* OtherActor = Result.GetActor();
    if(OtherActor && OtherActor->Implements<UInteractableInterface>())
    {
        auto InteractableActor = Cast<IInteractableInterface>(OtherActor);
        InteractableActor->Interact(this);
    }
}

```

## Option B (`USwitch` implementing `IInteractableInterface`)

```
class USwitch : public UActorComponent, public IInteractableInterface
{
public:
    virtual void Interact(AActor* Instigator) override;
};

void USwitch::Interact(AActor* Instigator)
{
    UE_LOG(LogTemp, Warning, TEXT("%hs"), __FUNCTION__);
}

```

```
class ALight: public AStaticMeshActor
{
public:
    ALight();

protected:
    UPROPERTY(VisibleAnywhere)
    class USwitch* Switch;
};

void ALight::ALight()
{
    Switch = CreateDefaultSubobject<USwitch>("Switch");
}

```

```
void APlayer::InteractWithOther()
{
    // Other code pertaining to line tracing or collision
    // is removed for the sake of simplicity!

    if(AActor* OtherActor = Result.GetActor())
    {
        for (auto Comp : OtherActor->GetComponents())
        {
            if (Comp && Comp->Implements<IInteractableInterface>())
            {
                auto InteractableComp = Cast<IInteractableInterface>(Comp);
                InteractableComp->Interact(this);

                break; // for single retrieval
            }
        }
    }
}

```

# Question

When developing with Unreal Engine, which approach is recommended and what are the prons and cons between them?

# Answer
> 2 votes
Inheritance is typically faster than component based interactions.

The difference is one less run-time dereference.

The general rule is to use components for run-time and level-design time flexibility, otherwise use fixed(compiled) structures/objects.

Option A seems to provide the much more direct route.

By utilizing unique collision channels the `OtherActor->Implements<UInteractableInterface>()` check could be eliminated all together.

# Answer
> 1 votes
There is another option, make all Actors implement the IInteractableInterface interface by default (and remove that interface from the hierarchy) and use a `CanBeInteractedWith` query to check whether it's something that can be interacted with (or setting the proper collision channel).

This will simplify your code because you can assume all entity classes can be interacted with so no casts are needed and attempting to interact with something that doesn't have an interaction will result in a noop.

void APlayer::InteractWithOther()
{
    // Other code pertaining to line tracing or collision
    // is removed for the sake of simplicity!

    AActor* OtherActor = Result.GetActor();
    if(OtherActor && OtherActor->CanBeInteractedWith())
    {
        OtherActor->Interact(this);//Other actor will handle the specific interaction, perhaps through checking all its components
    }
}
```

---
Tags: c++, software-engineering, unreal, component-based, inheritance
---


# Question
Title: Implementing a bot to find the player in a grid
I have a 2d array with ground represented by 0s and the walls represented by 1s.

Player can use a LOOK command or a MOVE command. Look command returns a 5x5 array centered around the player and the player can move in any of the 4 directions. Each actions takes up a round.

I want to implement a bot that is trying to find and catch the player that can also use these commands once per round.

What is the best way to balance the use of LOOK and MOVE commands for the bot and what is an algorithm to find the best route to patrol the map in.

# Answer
# Don't let perfect be the enemy of good

"Best" is very likely unattainable. You don't know what strategy the player might use to escape. Some chasing algorithms will be good at catching some avoidance algorithms, and worse at catching others.

## Tips for producing adversarial game-playing AIs in general

I'll start with my procedure (from my own college days) writing AIs to play various combinatorial games. I'm going to stop short of suggesting any specific algorithms, but that's not because I don't want to help. I don't know what your technical level is, or how long you have to write the bot. This game seems fairly complex and any useful AI for it is likely fairly involved, so the sky's the limit with how complex you want to go.

The advice I'm giving assumes that you're at least an upper-level college student with at least two weeks to work on this.

### Get the simplest possible AI working

In this case, the simplest AI I can think of would be one that randomly decides to MOVE or LOOK each round, and if it MOVEs, randomly chooses the direction.

### Get the simplest possible adversary working

In the question as you posed it, the adversary is the player - but it doesn't have to be! Humans are inconsistent and slow when it comes to playing games. If you want to be able to figure out what algorithms are good, you'll need a way to score them that is fast and consistent - this means writing an AI to replace the human opponent.

In this case, the simplest possible escaper is the same as the simplest possible chaser: randomly move/look every round.

### Get the simplest possible gym environment working

If your professor didn't already give you one, create a program that simulates the game itself, which your two bots can play Move/Look against.

If the assignment doesn't give any description as to how the boards might be laid out, then you'll want to go with the simplest possible boards for now (in this case, I'd go with a finite rectangle of open space surrounded by walls).

Then create a gym, which scores each chaser and escaper.

* For each chaser, (of which you only have 1 right now)
* For each escaper/adversary, (of which you only have 1 right now)
* For each board, (of which you only have 1 right now)
* Play a bunch of games with random start positions for each player and score them.
    + You'll need to enforce a turn limit, as most of the time two random-walks will not intersect in any reasonable time.
* Output the total scores in a readable format. In order, you'll likely want:
    + A total score for each chaser
    + A total score for each escaper
    + Chaser score broken down by escaper (which cats are good at catching which mice)
    + Chaser and escaper score broken down by board.
    + The full breakdown of the results of each chaser/escaper/board.

### Iterate on all three

If you have an idea for a chaser that might be good, implement it, throw it in the gym, and score it against the rest. Similarly for a new escaper. Add new boards when you think of them, too (unless you know what boards your prof. will be evaluating you against). An algorithm will perform differently on an empty field, as it would for a sparsely occluded field, single-tile wide maze, multiple-tile wide maze, etc.

Try to have as many simple ideas as possible at first to seed the competition.

Whenever you make a new (working) version, leave the old version in the gym. If you make a new escaper optimization that evades your latest chaser, you might find that a version three attempts ago isn't vulnerable to the new tricks.

## Specific advice for this game

For this particular game, I can think of a few things I'd probably put in, for both chasers and escapers.

### Build a map of the walls

Every non-simple AI (both chaser and escaper) for this game will want to build a map as they go, and most of the time, they'll want to LOOK whenever they're about to move into unexplored space in order to avoid moving into walls.

### Build a "position cloud" of where the opponent might be

If the opponent was at a certain position the last time you LOOK'd, then in the next move, they cannot be more than one space away from that position. If you'd make the same move regardless of where they are in that cloud, there's no need to LOOK again. Every time you MOVE without LOOKing, the cloud grows by one space in all directions.

In a tight maze, for example, the chaser might only need to LOOK when you're standing in an intersection - unless the rules allow the escaper to jump over the chaser if they're adjacent and both move toward each other, in which case they might need to LOOK any time when they're at the edge of the cloud, too.

An escaper is likely trying to maximize the distance between itself and the nearest edge of the chaser's cloud, while the chaser is probably trying to minimize the size of the escaper's cloud first, and then minimize the distance between itself and the farthest edge of the cloud second.

### Break the game down into phases

I see this game breaking down into three phases, and a good AI for this game will want to change its behavior depending on what phase the game is in.

First, if the two players do not start close together, then the game has two phases. In the first phase, neither player has any information about where the other player is. During this phase, the Chaser wants to find the Escaper, but without any knowledge, all they can do is explore as much ground as possible. The Escaper wants to not be found, but they can also use this time to explore and plan their escape.

Second, both sides make contact. Escapers will probably try to flee toward areas they know, because they have the advantage if they know the terrain and the chaser doesn't (a simple escaper might try just backtracking their last 10 steps whenever they see the chaser). This advantage goes away as the game goes on and the chaser maps more territory.

During this phase, the chaser should prioritize mapping the territory. They have very little chance of actually catching the escaper on their home ground, but there might still be some advantage in minimizing the size of the escaper's cloud during this time (or in other words "have some rough idea of where they are"). The escaper at this point should try to cautiously map more territory, but avoid being cornered.

Finally, once the chaser has enough of a map to confidently attack, they push the game to its third phase, by aggressively trying to minimize the size of the escaper's position cloud ("cut them off and drive them into corners"). This would mean thinking multiple moves ahead. If the escaper flees into unexplored territory, they can move back to phase 2.

### Sometimes it's better to guess than to LOOK

I can think of a few different escaper algorithms which will beat chasers 100% of the time if they stop to LOOK whenever they need to make a decision. Consider having an "aggression" variable that will determine how likely a chaser is to simply guess instead of LOOKing. My intuition tells me that aggression should increase with the length of the game: the longer the escaper has managed to succeed, the more likely it is that you're up against a "perfect" escaper and can't win without making guesses.
> 0 votes

---
Tags: 2d, algorithm, ai, path-finding
---


# Question
Title: My Player is not attached to the wall when climbing
I am trying to create a climbing system from my 3d game, player will be able to climb anything like terrain tree rocks, or whatever. I managed to get the player to climb but unfortunately when he climbs he is not attached to the wall, his hands are in the air close to the wall it's like he is grabbing in the air, and his knees go inside the wall. I tried using IK, and it worked to get the player's hands attached to the wall, but it overrides the animation so the hand is always attached to the wall and doesn't animate
this is the code for the climbing part what am I doing wrong?

```
        var vi = Input.GetAxis("Vertical");
        var h = Input.GetAxis("Horizontal");
        var move = transform.up * vi + transform.right * h;
        m_Animator.SetBool("Climb", true);
        m_Animator.SetFloat("H", move.y, 0.1f, Time.deltaTime);
        m_Animator.SetFloat("V", move.x, 0.1f, Time.deltaTime);
        m_Animator.applyRootMotion = true;
         rb.velocity = transform.up * vi*0.5f + this.transform.right * h*0.5f ;
        Vector3 v = (m_Animator.deltaPosition) / Time.deltaTime;
        rb.angularVelocity = Vector3.zero;
        transform.rotation = Quaternion.LookRotation(frontWallHit.normal * -10f);
        rb.useGravity = false;
        pm.m_GroundNormal = Vector3.up;

```

# Answer
> 1 votes
You've picked a hard nut to crack. Climbing on arbitrary surfaces can be quite tricky. Especially considering all the (sometimes literal) corner cases you have to be aware of. So I can't give you a copy&paste code solution which is just going to work for anyone. I can only provide some advise how to figure one out of your own.

Using IK is certainly the right way to do it. But keeping the IK weight at 100% with a static IK position isn't going to work because, as you noticed, it permanently glues the hand/foot to the target. You want that through *some* phases of the climbing animation, but not all of them. The solution can be to change the IKWeight of each limb during the animation.

* 1.0 weight during the phase where the character is grabbing the hold
* gradually reduce it to 0.0 during the let-go phase
* Set the new IK target to the next grab position while the weight is 0.0
* gradually increase it to 1.0 while the character starts grabbing again

Another strategy is to keep the hands and feet under 100% IK at all times but move their IK targets. That requires a script that determines the position of each new hold on the climbing surface and then, when changing from one hold to another, interpolates the positions between them. Yes, that means that you basically do most of the climbing animation via code instead of in your animation program.

A good way to do either is to create a new MonoBehaviour which exposes the IK targets and IK weights (and probably also IK hints) of the animator for all 4 limbs as inspector properties. You can then create animation actions within Unity for those properties and put them on a separate layer of your animation controller. That way you can tweak the IK weights during the animation using curves.

You might also want to take a look at the new animation rigging system. It is an alternative IK system that provides a lot more flexibility. It allows you to implement IK for *any* bone, not just hands and feet. It also has some interesting specialized IK controllers. For example, the Multi-Position Constraint could be useful to gradually shift between different climbing holds.

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


# Question
Title: Little problem with offsetting transformed vertex in a vertex shader
I’m working on some home-made menu stuff under DX11. I’m creating the rect menus at start all located at position 0,0. Each menu contains some lines of options. Everything is created as transformed vertex (e.g. -1..1 coordinates). Now I want the menu to appear where I click the mouse. So I need to offset the mesh vertices and I’m trying to do it within the vertex shader.

Here the code

```
The shader constant to store the offset in Rectshow
cbuffer cbMesh : register(b8)
{
 float4 FactorColor;
 float4 RectShow;
}

The offsetting at the vertex level
PS_INPUT_FONT VS_FONT(VS_INPUT_FONT input)
{
  PS_INPUT_FONT output = (PS_INPUT_FONT)0;
  output.Pos = float4(input.Pos.xy + RectShow.xy, input.Pos.z, 1);
  output.Tex = input.Tex;
  return output;
}

```

Within my app the letters positions are calculated this way with Rect.xy being in coordinate \[0..Screensize\]:

```
FLOAT tX = Rect->x * 2 / gViewPort.width -1;
FLOAT tY = 1 - Rect->y * 2/ gViewPort.Height;

```

For each letter and lines I use some tX/tY offsetting during mesh creation.

Now logically I’m calculating the offset from mouse position Pt in coordinate \[0..Screensize\]:

```
gCBFont.RectShow.x = Pt.x * 2 / gViewPort.Width - 1;
gCBFont.RectShow.y = (1 - Pt.y * 2 / gViewPort.Height);
gpDC11->UpdateSubresource(gpCBBufferFont, 0, NULL, &gCBFont, 0, 0);
gpDC11->VSSetConstantBuffers(dwSlotFont, 1, &gpCBBufferFont);

```

if I set arbitrarily RectShow.xy to 0,0 the menu appears at it should at the 0,0 screen location. But when I use the calculated offset I see nothing.

Before doing it this way I was creating the menu upon click directly at the mouse position and it was working fine but it appeared less easy to manage as you need to destroy and recreate the meshes for each click. With this second option I can show/hide the meshes when needed and the menu is created only once. But I have to move it at the mouse position.

I’m missing something here probably. Maybe I should use map/unmap to update the menu meshes instead of the shader but it sounds weird.

# Answer
After some arbitrary value setting finally the mistake was in the offset calculation that must be like this:

```
gCBFont.RectShow.x = Pt.x / gViewPort.Width *2;
gCBFont.RectShow.y = -Pt.y / gViewPort.Height * 2;

```
> 0 votes

---
Tags: directx11, transformation, vertex-shader
---


# Question
Title: How best to distribute GameObjects evenly across a fixed length in Unity?
I have anywhere from 1-5 GameObjects that I'd like to distribute horizontally over a fixed distance. For example, if there are 3 GameObjects they might be spread out with a distance X between them like so:

\[G1\] \<--x--\> \[G2\] \<--x--\> \[G3\]

I was writing my own code to do this, when I realized that I could use a Grid Layout Group instead. I started to implement that but realized something: each of my GameObjects has scripts which let them be dragged and dropped around the screen.

If I use a Grid Layout Group to organize the GameObjects on the screen, then they will all be under a Canvas object. But with my drag-and-drop functionality, I only want the GameObjects to be organized in a 1x3 line when they first render. After that, I want to be able to control the location of the GameObjects manually using their Rect Transform positions.

I've never used Canvas before, and a lot of the documentation mentions that they are meant to control the layout of UI elements. My GameObjects are not really UI elements, but are letters and pictures that can be dragged around the screen (it's for an educational app).

Was hoping for some advice from someone experienced with using Canvas to control layouts. Should I:

1. Start off the GameObjects nested under the Canvas with a Grid Layout Group... but when the item is picked up and dragged, unparent the GameObjects from the Canvas
2. Find another way to initially layout the GameObjects without using the Canvas
3. Something else entirely?

Thanks!

# Answer
> 3 votes
Treating those objects as UI widgets of a canvas would probably be a very essential redesign. Objects on a canvas behave very differently from regular game objects. They don't even have the usual Transform component (They use a RectTransform instead). Converting objects back and forth between regular game objects and canvas game objects is certainly not impossible, but it's going to get iffy. But if you want drag&drop functionality, then you probably don't have to unparent those objects from the canvas. You just have to unparent the dragged object from the layout group and parent it to the canvas directly. You can then move it around using absolute positioning.

So it is certainly possible to have a game which plays only on a canvas. Whether or not this is the *right* approach for you and your game is something only you can tell. It depends on how many features you already implemented and if the features you still want to implement would be easier to do on a canvas vs. in scene space.

If you want to do it with objects in scene space, here is an example script which arranges its children in an evenly spaced line between two additional gameObjects (which you need to assign via the inspector):

```
using UnityEngine;

public class AutoArrange : MonoBehaviour {
    public Transform from;
    public Transform to;

    void Update() {
        for (var i = 0; i < transform.childCount; i++) {
            Vector3 childPos = Vector3.Lerp(from.position, to.position, (i + 0.5f) / transform.childCount);
            transform.GetChild(i).transform.position = childPos;
        }
    }
}

```

---
Tags: unity
---


# Question
Title: Send Rate is zero but server movement is still happening
I have a client server scenario, just a player moving about on the client and he moves about on the server using the built in networking provided in Unity 5.

I have my client scene running in the editor and was playing about with the Network Transform script values, more specifically the Network Send Rate.

* Setting this Value to 29 (its highest), the movement on the server is almost smooth.
* Setting this value to 1 and the movement on the server is very laggy, as I expected.
* However, if I set the network send rate to 0 on the client, I expected it not to move at all on the server, but it moves and a lot smoother than the value 29.

Why is it, when the network send rate is set to 0, that my character still moves on the server?

# Answer
> 1 votes
It looks like this API is set up so that a send rate of 0 means "on demand".

If you're continually moving an object that's been set to, say, 10 network updates per second, those transform changes get recorded but not sent right away. Then, when the next 10 Hz window comes around, the latest value is picked up and sent across the network.

But if you've set this value to 0, then there's no regular process checking in on the transform value to send it at regular intervals. So transform changes could get missed entirely.

To prevent changes from not being replicated at all, if a `NetworkTransform` that's not scheduled for regular transform updates moves, Unity sends the message right away to ensure that change isn't lost.

Since the Unity docs say to use this for objects that *don't* move after being created, this should be rare:

| Property | Function |
| --- | --- |
| Network Send Rate (seconds) | Set the number of network updates per second. You can set this slider to 0 for GameObjects that do not need to update after being created, like non-interactive effects generated by a player (for example, a dust cloud left behind that the player cannot interact with). |

Basically this should ensure that a late fix-up to its position after spawning isn't missed. Or if the object occasionally has to be swapped to a new location, you only pay overhead cost once on each teleport, rather than periodically as long as the object exists.

Based on the documentation quoted above, you should *not* set this value to zero on an object that moves continuously. As you observe, that can trigger an effectively unlimited send rate (say, once per display frame / `Update()` call), which could quickly eat into your bandwidth budget at high framerates.

# Answer
> 0 votes
This might be because your movement script doesn't specify where to execute the code, so when you input something, the code is executed on the server.

Make sure your movement code has an `if(isLocalPlayer)` check:

```
private void Update()
{
     if (!isLocalPlayer)
     {
         return;
         //this checks if the code is not running on the local instance of the game
         // if it isn't, it stops executing what's next
     }

     //Your Code here
}

```

---
Tags: networking, unity, unity-networking
---


# Question
Title: Why is part of my render texture see-through in Unity?
I have a camera that is looking at an object with render texture output and I use that render texture on raw image in UI.

Object itself has 2 parts:

1. the ball
2. kind of a semi transparent mask.

And this is an output:

The star is there just for the reference. Problem is that part behind the second object is also transparent on render texture like it is see-through. I need that object transparent in relation to the ball (object one) but I don't want my texture to be see-through.

This is the result I expect:

# Answer
I did manage to fix this kind of by changing my Material blend mode to additive and playing with emission color to get the mask part right. Here is my material:
> 1 votes

# Answer
The reason for this is line 89 (at the time of writing) in the package `com.unity.render-pipelines.universal@12.16/Shaders/Lit.shader`:

```
Blend[_SrcBlend][_DstBlend]

```

This says to use the same blending rules for the Alpha channel as are used for the RGB channels. So if you render low-opacity white over purple and get a blend of white and purple, you're also rendering low-opacity alpha over opaque alpha and getting a blend of low and full opacity: somewhere in the medium opacity range.

For most purposes that doesn't matter, since you're just rendering to screen and don't care what alpha values end up there. But when composing a transparent image in a render target, you do care.

A quick fix is to move the URP package from the `YourProject/Library/PackageCache/` folder to `YourProject/Packages/` \- this gives you an editable version you can modify without your changes getting reverted to the package defaults.

Then go edit line 89 to:

```
Blend[_SrcBlend][_DstBlend], One One

```

This gives a separate blending rule for the alpha channel, which is to strictly add up alpha values rather than blending them. So if you had an opaque background, it stays opaque when you layer transparency on top of it.

Strictly speaking, to pre-compose content in a transparent render target to stamp elsewhere, you'll want to be using pre-multiplied alpha blending (see "Super-Power #2" at that link), but that's a deeper rabbit hole than I'll go into for this answer.
> 1 votes

---
Tags: unity, rendertexture
---