# Question
Title: How to do "Screen Space Texture" mapping on a Unity UI Image?
So I'm fairly new to the shader and I've been trying to achieve this kind of effect from Ronja Tutorials, but instead of using it for normal mesh object, I'm trying to use it for Screen Space UI Image instead, this is what I've done so far

```
Shader "UI/CustomScreenSpaceTexture"
{
        Properties
        {
                [PerRendererData] _MainTex ("Texture", 2D) = "white" {}
                _Color ("Tint", Color) = (1,1,1,1)

                _StencilComp ("Stencil Comparison", Float) = 8
                _Stencil ("Stencil ID", Float) = 0
                _StencilOp ("Stencil Operation", Float) = 0
                _StencilWriteMask ("Stencil Write Mask", Float) = 255
                _StencilReadMask ("Stencil Read Mask", Float) = 255

                _ColorMask ("Color Mask", Float) = 15

                [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0
        }

        SubShader
        {
                Tags
                {
                        "Queue"="Transparent"
                        "IgnoreProjector"="True"
                        "RenderType"="Transparent"
                        "PreviewType"="Plane"
                        "CanUseSpriteAtlas"="True"
                }

                Stencil
                {
                        Ref [_Stencil]
                        Comp [_StencilComp]
                        Pass [_StencilOp]
                        ReadMask [_StencilReadMask]
                        WriteMask [_StencilWriteMask]
                }

                Cull Off
                Lighting Off
                ZWrite Off
                ZTest [unity_GUIZTestMode]
                Blend SrcAlpha OneMinusSrcAlpha
                ColorMask [_ColorMask]

                Pass
                {
                        Name "Default"
                        CGPROGRAM
                        #pragma vertex vert
                        #pragma fragment frag
                        #pragma target 2.0

                        #include "UnityCG.cginc"
                        #include "UnityUI.cginc"

                        #pragma multi_compile_local _ UNITY_UI_CLIP_RECT
                        #pragma multi_compile_local _ UNITY_UI_ALPHACLIP

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

                        struct v2f
                        {
                                float4 vertex   : SV_POSITION;
                                fixed4 color    : COLOR;
                                float2 texcoord  : TEXCOORD0;
                                float4 worldPosition : TEXCOORD1;
                                float4 screenPosition : TEXCOORD2;
                                UNITY_VERTEX_OUTPUT_STEREO
                        };

                        sampler2D _MainTex;
                        fixed4 _Color;
                        fixed4 _TextureSampleAdd;
                        float4 _ClipRect;
                        float4 _MainTex_ST;

                        v2f vert(appdata_t v)
                        {
                                v2f OUT;
                                UNITY_SETUP_INSTANCE_ID(v);
                                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
                                OUT.worldPosition = v.vertex;
                                OUT.vertex = UnityObjectToClipPos(OUT.worldPosition);
                                OUT.screenPosition = ComputeScreenPos(OUT.vertex);

                                OUT.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);

                                OUT.color = v.color * _Color;
                                return OUT;
                        }

                        fixed4 frag(v2f IN) : SV_Target
                        {
                                float screenAspect = _ScreenParams.x / _ScreenParams.y;
                                float2 coord = IN.screenPosition.xy / IN.screenPosition.w;

                                coord.x = coord.x * screenAspect;
                                coord = TRANSFORM_TEX(coord, _MainTex);

                                half4 color = tex2D(_MainTex, coord);
                                color *= _Color;

                                return color;
                        }
                        ENDCG
                }
        }
}

```

This is my texture atlas

I was going to use the leftmost image that looks like a grid, the problem is if I use the shader this happened

1. The Image uses whole texture instead of the specified one (Yes, I use the texture as atlas so I could use specific child texture)
2. Because of the image uses whole texture, I have no control over options like Tiling, like what from Ronja Tutorials has (The option is still there on Image component, but it has no effect)

For comparison, this is what the Image look like if it uses default material/shader

So I'm trying to achieve Screen Space Texture style of mapping so the background will fits nicely if I have more than 1 Image with the different position but using the same texture without worrying the "Visible Seam" but still be able to do something like "Tiling" so I can control how big/small the grid tile is for the whole screen like default example as seen above.

This is what I was trying to solve with the shader

* So how would I achieve that? What part from my shader is wrong? (Again, I'm fairly new, so maybe the whole shader is wrong)

# Answer
A couple of alternative ways to approach your problem:

1. Write a shader that draws a grid based on the world-space coordinates of each pixel (the appearance is calculated entirely in-shader, with no source texture at all). I've done this before and it works nicely.
2. Make the grid a full-screen background image, and make the movable rectangle a mask using the mask feature already built into Unity.
> 1 votes

---
Tags: unity, shaders, shaderlab
---


# Question
Title: How to connect a GUI button to function?
I am developing a new Roblox game where you can setup and control you're own virtual machine using SurfaceGUIs on a modeled screen. I am trying to make a confirmation GUI where if you click YES, then it starts the VM, and if you click NO, then it closes the GUI and doesn't start a VM. But when I click on NO, nothing happens! Here is my code:

```
local gui = script.Parent.Parent
local button = script.Parent

local function cancel()
    gui.Visible = false
end

button.Activated:Connect(cancel())

```

Please help!
P.S: The confirmation frame is in the ScreenGUI, the button is in the frame, and the LocalScript is in the button.

# Answer
> 1 votes
Instead of connecting your event to a **FUNCTION**, you are calling it.

I'll leave a sample on how to correctly use it

```
local Button = ... --where your button is located

local function Cancel()
  --code
end

Button.MouseButton1Click:Conect(Cancel)

```

MouseButton1Click is an event which fires after the **GUI BUTTON** is clicked.

---
Tags: lua, roblox
---


# Question
Title: How come non creatable/destroyable Roblox instances have :Destroy() :Clone() etc?
Roblox has many types of instances. But services and other NonCreatable Instances (ReplicatedStorage, Workspace, etc.) still have methods for creating or destroying. Why? Why do they have :Destroy() and :Clone() methods if they cannot be destroyed or created? What's the point of inheriting these from the Instance class?

What's the point of inheriting a property that can't be used?

# Answer
> 0 votes
I can't speak to whether this applies to Roblox specifically (hopefully someone with in-depth knowledge of that tool can share a more detailed answer), but **most programming languages don't give you a choice of which *parts* of a parent type to inherit or which ones to skip**.

Once you inherit from a particular type, you get *everything* that type defines, even if you don't plan to use half of it.

So you often end up leaving the items you don't need with their default implementation, or overriding them with an implementation that throws an error in case someone uses these unsupported methods by mistake.

Even if this inheritance restriction does not apply to Lua scripting directly, it may apply to the underlying back-end code that the script interfaces with.

The actual inherited methods cost practically nothing (just one extra entry in a VTable somewhere, not even an entry per instance), so it's often not worth the grief of refactoring the inheritance hierarchy into a more complex form to avoid this unnecessary inheritances.

That said, this kind of inheritance complication is one reason why game developers often favour composition over inheritance, as a way to glue-together only the functionality a particular entity needs, without hauling in a pile of unnecessary inheritance, or locking the types into a rigid contract with one another that's difficult to modify later.

# Answer
> 0 votes
Every Roblox instance has these methods, they could "remove" them for these particular instances but there's no need as you are not expected to use them anyways.

---
Tags: roblox
---


# Question
Title: Does indexing arrays with temporary objects leak memory?
For example, if I have something like this:

```
Array = {}
RemoteEvent.OnServerEvent:Connect(function(Player)
    local Part = Instance.new("Part", workspace)
    Array[Part] = Player.UserId
    wait(10)
    Part:Destroy()
end)

```

Will that leak memory? Will it automatically remove the index for that part once it detects that it's been removed? Or do I need to manually set it to nil when removing it?

# Answer
The answer is yes, yes it will, you initialize / localize the Table outside the scope therefor anything cached / stored inside it won't be garbage collected, part itself still get's deleted although Table itself will still contain its data.

Easy way to prove my answer is by iterating through the array after the scope ends and as you will see it will still print out the "Part" instance.

**--\> Code**

```
local Table= {}

local function CachePart()
    --> Create a new scope

    local Part = Instance.new("Part")

    Table[Part] = Part
    Part:Destroy()
end

CachePart()

for i, v in next, Table do
    print(i,v) -- prints Part, Part
end

```

Although the instance's Data is still saved it does not mean it can be used, trying to parent it will error.

**--\> How to fix**

Either you localize your Table within the scope or manually remove it after by doing:

```
Table[index] = nil

--or

table.remove(Table, Index)

if your index is unknown you can use table.find

local Index = table.find(Table, Value)

```
> 1 votes

---
Tags: roblox
---


# Question
Title: Fragment shader - map dot texture repeatedly over the sphere
I have a sphere and in Fragment shader, I have available lat / lon position (in radians) for every fragment. I have a texture of a single dot. I need to map this single dot (or any other texture) repeatedly over the sphere and create a pattern like a "golf ball" (for example this sample: https://www.shadertoy.com/view/Xs2fWy \- however the dots are calculated directly from raytracing plus the code is not commented, so not very clear). I donw want to pregenerate texture, because I want to dynamicly change the number of dots.

Is there a solution how to achieve this only in fragment shader? I cannot modify anything else.

# Answer
Here's a starting point, using a float variable `_Density` to control how many repeats you get.

```
        float3 n = normalize(IN.worldNormal);
        // Get longitude (x) in the range -1...1, and latitude (y) in the range (-0.5...0.5).
        float2 longLat = float2(atan2(n.z, n.x), asin(n.y)) / 3.141592653589f;

        // Count how many rows we can fit top to bottom at our selected density.
        float rowCount = ceil(_Density);
        // If it's odd, the 0th row sits at the equator. Otherwise, we need to shift it half a row.
        float even = fmod(rowCount + 1.0f, 2.0f);

        // Scale and rount our latitude to find which row this fragment is in.
        float y = longLat.y * rowCount;
        float row = round(y - 0.5f * even);

        // Compute the radius around the sphere along the center of this row.
        float rowRadians = (row + 0.5f * even) * 3.141592653589f / rowCount;
        float rowRadius = cos(rowRadians);
        // Round this to get the number of texture repeats horizontally.
        float rowRepeats = round(rowRadius * _Density * 2.0f);

        // Make our texture coordinates.
        float2 uv;
        uv.x = longLat.x * rowRepeats/2.0f;
        uv.y = y - row + (1.0f - even) * 0.5f;

        // TODO: Calculate mipmap/gradients to avoid artifacts at seams.
        fixed4 c = tex2D(_MainTex, uv).a * _Color;

```

Because we jump around UV space when we transition between rows, or where a row wraps-around on itself, we get some shimmery mipmapping artifacts at these transitions. An improved version would calculate which mip level to sample with `tex2Dlod`, or better yet, compute gradient vectors to use for anisotropic filtering with `tex2Dgrad`, to avoid the artifacts in the auto-calculated versions.

Another potential improvement would be to stamp one copy of the texture at each of the north and south poles, so that the tightest ring isn't quite so pinched in the middle.
> 1 votes

---
Tags: textures, fragment-shader, sphere
---


# Question
Title: How can I import an Excel file in an Unity WebGL game?
Currently, we have a project that runs on Windows and uses an Excel spreadsheet to save/retrive some data/information. Now we want to build that project for WebGL. The problem is that file reading support is not available on the WebGL platform. How do I solve this problem? Do I need to write a backend or there another way to use excel in WebGL platform even though the file reading API of the .NET framework is not supported on WebGL?

# Answer
> 1 votes
When your WebGL game needs to read an arbitrary file, then you can add it to the game build by turning it into a text asset. You need to rename it to give it the file extension `.bytes`, so Unity recognizes it as a binary file (for example: `items.xlsx.bytes`). To ensure that the file is included in the WebGL build, you need to store it in an Assets/Resources folder or in an asset bundle which you then export to your WebGL build.

If you decided to use resources:

```
TextAsset txt = Resources.Load("items.xlsx") as TextAsset;

```

If you decided to use an asset bundle:

```
AssetBundle bundle = myLoadedAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, "myassetBundle"));
TextAsset txt = bundle.Load("items.xlsx", typeof(TextAsset)) as TextAsset;

```

Now you can get the binary data from that text asset with

```
byte[] bytes = txt.bytes;

```

and feed it into the code you already have for parsing Excel workbooks.

---
Tags: unity, webgl, file
---


# Question
Title: Rotating gradually in response to input, instead of snapping
I'm trying to replicate Silent Hill's mechanic where if you press a button, the character does a 180, but instead of getting a smooth turn around, my character is snapping from one rotation to another.

This is the code I have so far:

```
if (Input.GetKeyDown(KeyCode.Tab))
{
    transform.Rotate(0f, 180f, 0f);
}

```

I also have a Sprint(); function and I want to disable this feature if the character is sprinting. Here's the code for that:

```
private void Sprint()
{
    float newTurnSpeed = _turnSpeed - 1.4f;

    vertical = Input.GetAxis("Vertical");
    horizontal = Input.GetAxis("Horizontal");

    Vector3 direction = new Vector3(0f, 0f, vertical);
    Vector3 movement = transform.TransformDirection(direction) * _sprintSpeed;

    transform.Rotate(0f, horizontal * newTurnSpeed, 0f); //add the new turn speed
    isGrounded = _characterController.SimpleMove(movement);
}

```

Any help is appreciated!

# Answer
```
public string sprintButton;
public string turnAroundButton;

public float rotationSpeed = 360.0f;

Quaternion _targetRotation;
Coroutine _rotation;

IEnumerator RotateToTargetOverTime() {
    // Keep running this behaviour every frame until we're within 1 degree of our goal.
    while(Quaternion.Angle(transform.rotation, _targetRotation) > 1f) {

        // Keep rotating toward the target orientation.
        transform.rotation = Quaternion.RotateTowards(
                                 transform.rotation.
                                 _targetRotation,
                                 rotationSpeed * Time.deltaTime
                             );

        // Wait till next frame.
        yield return null;
    }

    // We're done rotating - clear out the coroutine.
    _rotation = null;
}

void Update() {
    if(Input.GetButton(sprintButton)) {
        // Abort the 180 turn in progress, if any.
        if(_rotation != null) {
            StopCoroutine(_rotation);
            _rotation = null;
        }

        // Call your existing sprint behaviour.
        Sprint();

    // Check for turn around input if and only if we're not sprinting.
    } else if(Input.GetButtonDown(turnAroundButton)) {
        // Update our target rotation to move towards.
        _targetRotation = Quaternion.Euler(0, 180, 0) * transform.rotation;

        // If we're not already rotating, start a new coroutine to finish the rotation.
        if(_rotation == null)
            _rotation = StartCoroutine(RotateToTargetOverTime());
    }

    // ...other Update stuff...
}

```
> 0 votes

---
Tags: unity, c#, rotation, movement
---


# Question
Title: Why are committed resources better than placed resources?
This NVIDIA document regarding dos and don'ts in DirectX 12 states the following:

> Use committed resources where possible to give the driver more knowledge
>
> * This allows the driver to better manage GPU memory
> * A good use case for placed resources are resource heaps that are e.g. used during streaming and do hold different sets of read-only textures over their life time

But this raises more questions than it answers:

* What additional knowledge is given to the driver if I use a committed resource? The information on the resource that I pass to both `CreateCommittedResource` and `CreatePlacedResource` is pretty much the same...
* What does it mean that the driver will better manage GPU memory?
* If I know what the allocation/deallocation patterns look like in my game, isn't it better if I manage GPU memory manually with placed resources, instead of letting the GPU decide where to place each resource, and potentially run into VRAM fragmentation in the long run? Or will the driver perform heap defragmentation?
* `CreateCommittedResource` creates an implicit heap each time it is called, while `CreatePlacedResource` simply creates the resource over the memory I choose on an existing heap, and is therefore much faster. Wouldn't it be preferable in most cases to use placed resources instead? Especially if I am interested in creating loading screens that don't miss a single frame deadline?

I am quite surprised to read from NVIDIA that committed resources are preferable to placed resources. Could anybody explain in more detail what else is happening under the hood, so committed resources are preferable to placed resources?

# Answer
You will get **contradicting suggestions from their own**: http://developer2.download.nvidia.com/assets/gameworks/downloads/regular/GDC17/DX12CaseStudies\_GDC2017\_FINAL.pdf

Page 14: "**Sub-allocation from a larger heap (as intended) improved performance by ~15%**"

Page 46: "Creating **committed resources for everything will use tons of memory**"

https://developer.nvidia.com/sites/default/files/akamai/gameworks/blog/GDC16/GDC16\_gthomas\_adunn\_Practical\_DX12.pdf

Pages 25 ~ 26

The philosophy of the new-generation APIs is to **offload burden from drivers (implicit, extra guess work) to applications who know the needs better (explicit, do only what you need**), to boost CPU performance and **save GPU memory (less fragmentation, better reuse)**. D3D12 Committed resources are just like D3D11 resources, if you use Committed resources then you **go back to D3D11 with driver and possibly paging (on over-subscription) costs**.

https://software.intel.com/content/www/us/en/develop/blogs/direct3d-12-overview-part-3-resource-binding.html

"Resource residency management:

GPUs like to use a lot a video memory, more in fact that is often available. This can be more of problem with discrete video cards with a set amount of memory. So we have resource residency management that **pages things in and out of memory** as the commands flow. To the game it **looks like there is unlimited memory**, when really it is just memory management. Once again this comes at a **cost of reference counting and tracking**.

Just like resource lifetime, the game gets explicit control over resource residency. D3D 11 tracks the residency counts and control flow in the operating system. Typically though the game already knows that a sequence of rendering commands refers to a set of resources. In D3D 12 the game can now explicitly tell the operating system to move them into memory. Later on when the commands have been executed the game can have the resources removed from memory."

Allocations **call into the kernel-model driver**, which is costly.

Vulkan even has a **limit in # of allocations**.

https://docs.microsoft.com/en-us/windows/win32/direct3d12/memory-management-strategies

Search for "**sub-allocation" + "Direct3D 12"/"Vulkan"/"Metal", you will basically get the same answer except in this NVIDIA DX12 Do's And Don'ts**.
> 4 votes

---
Tags: directx, nvidia, directx12
---


# Question
Title: Why does the platform created with for cycle go over the border limit?
ve started programming just recently and I've learned the basic concepts of classes and objects and how to create them. So I decided to try and create a simple game of breakout with what I've learned so far. I've only created the main movable platform with a for cycle and make it move horizontally with the directional keys so far. I've also created a void so the platform doesn't go over the border of the screen but it doesn't work and I've tried all I could think of. Can someone please tell me what I'm doing wrong?

```
 Game::Game( MainWindow& wnd )
    :
    wnd( wnd ),
    gfx( wnd )
{
}

void Game::Go()
{
    gfx.BeginFrame();
    UpdateModel();
    ComposeFrame();
    gfx.EndFrame();
}

void Game::UpdateModel()
{
    if (wnd.kbd.KeyIsPressed(VK_RIGHT))
    {
        platform.vx += 3;
    }

    if (wnd.kbd.KeyIsPressed(VK_LEFT))
    {
        platform.vx -= 3;
    }

    platform.ScreenLimit();
}

void Game::ComposeFrame()
{
    for (platform.x = 460; platform.x <= platform.w; platform.x++)
    {
        for (platform.y = 500; platform.y <= platform.h; platform.y++)
        {
            gfx.PutPixel(platform.x + platform.vx, platform.y, 255, 255, 255);
        }
    }
}

```

and here's the header file and source file of the class I created for the platform:

Platform.h

```
#pragma once
#include "Graphics.h"
class Platform
{
public:

    int x = 460;
    int y = 500;
    int vx = 0;
    int width = 60;
    int heigth = 10;
    int w = x + width;
    int h = y + heigth;

    void ScreenLimit();

private:

};

```

Platform.cpp

```
#include "Platform.h"

void Platform::ScreenLimit()
{
    const int left_base = x;
    const int right_base = w;

    if (right_base >= Graphics::ScreenWidth)
    {
        x = (Graphics::ScreenWidth - 6) - width;
    }
    else if (left_base <= 0)
    {
        x = 0;
    }
}

```

# Answer
Based on your code, the variable **x** and **w** seem to never be updated. And apparently they represent the "start" position. Other variables' meanings are also unclear to me. However, it seems that you are not really looking at the bounds that you expect.

Considering your code, your limits should probably be:

```
right_base = x + vx + width
left_base = x + vx

```

Assuming that **x** is the start position, **vx** an offset and **width** the bar width.

However, I would suggest you rethink your variable usage/naming. Also, the rendering loop changing the state of the platform seems unnecessary.

You can probably get away with just 4 variables:

* x: Current position x
* y: Current position y
* width: Bar width
* height: Bar height

I believe you wanted the extra variables to avoid having to recalculate correct positions every time. Which is ok. But make sure your variables are used properly. In that case, I would use more meaningful names. Such as: -initial\_x -initial\_y -offset\_x -offset\_y -width -height

The platform rendering loop could then be simply:

```
int xend = platform.x + platform.width;
int yend = platform.y + platform.height;
for (int x = platform.x; x <= xend; x++)
{
    for (int y = platform.y; y <= yend; y++)
    {
        gfx.PutPixel(x, y, 255, 255, 255);
    }
}

```

Note that we never change the state of the platform, our objective is just to render it!

Another note: I'm not familiar with this library, however, I would check if there is a way to render a rectangle or line, which could be more efficient than plotting individual pixels. If not, then you can create your own function to clean up the code and make it easier to render more rectangles.
> 0 votes

---
Tags: c++
---


title: ECS: Movement system

text:
# Question
Title: ECS: Movement system
I'm a game developer enthusiast. I've decided to implement a game, however I'm pretty confused about all the movement mechanics (kinematics). Here goes a couple questions:

Velocity x acceleration x speed:

1. How do you apply acceleration/deceleration to your movement?
2. When moving (player input), do we either increase the velocity vector or the acceleration/speed value, or actually both? How does it really work?
3. How do you apply object weight to the movement?
4. How do you apply friction & gravity to the movement (should be applied to both axis, as this is going to be a 2D top-down view)?

Questions might be quite simple and/or stupid, but I'm just beginning (and also re-studying physics).

# Answer
Distance is time multiplied by velocity, velocity is time multiplied by acceleration and acceleration is force divided by mass. So you can calculate it in your physics system like this:

```
acceleration = force / mass;
velocity += acceleration * deltaTime;
position += velocity * deltaTime;

```

force, acceleration, velocity and position are all two-dimensional vectors in this example: a data-structure with two fields: x and y. Basic math operations on vectors, like adding them or multiplying them by a single number, are not hard to implement. But it's usually easier and more reliable to just use a vector library for your programming language of choice.

Note that not all games simulate all of this. Some games don't bother simulating mass and force and just use constant acceleration. Some games don't even bother with simulating acceleration and just use constant velocity. Some games don't bother with velocity either and just teleport entities to where they are supposed to be. What level of simulation you need depends on the requirements of your game.

When you are following an ECS architecture, then you might want to split these three operations into three different systems `ForceSystem`, `AccelerationSystem` and `VelocitySystem` which each one setting values in the components for the next one.

Gravity is a constant downwards acceleration. So when you have a `VelocitySystem`, then you just need to create a `GravitySystem` which adds a constant vector to the velocity (also multiplied by delta-time, of course). On the surface of the real planet Earth, the gravity vector's y-value is -9.81, but that value rarely feels right in games. Which is why most games change that value.

Friction is a force which acts in the opposite direction of the current velocity and increases with the velocity squared. You usually have a friction coefficient which is somewhere between 0 (no friction) and 1 (infinite friction). Unfortunately you can't just multiply the velocity with itself, because then a velocity vector with negative x or y turns positive. So you have to separate it into direction and magnitude, square the magnitude, and then turn it back.

```
frictionDirection = -normalizeVector(velocity)
frictionMagnitude = magnitudeVector(velocity) * magnitudeVector(velocity)
frictionVector = frictionDirection * frictionMagnitude;
velocity += frictionCoefficient * frictionVector * deltaTime;

```
> 1 votes

---
Tags: movement, vector, entity-component-system
---


# Question
Title: How do I rotate a gameobject towards a point in world space?
I wanted to create a very simply turret. This turret should aim at the point on the screen where the mouse pointer is currently located.

I have added a cube to serve as a very simple turret in my scene. To visualize its aiming direction, I'm drawing a ray from it.

To rotate the "turret" to the mouse pointer position, I have created a script and added it to the "turret" gameobject:

```
void Update()
{
    var mousePos = Input.mousePosition;
    mousePos += Camera.main.transform.forward * 10f; // Make sure to add some "depth" to the screen point
    var aim = Camera.main.ScreenToWorldPoint(mousePos);

    transform.LookAt(aim);

    RaycastHit hit;

    int layerMask = 1 << 8;
    layerMask = ~layerMask;

    Color color;
    if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
    {
        color = Color.green;

    }
    else
    {
        color = Color.red;
    }

    Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 10000, color);
}

```

However, there must be something wrong in my code.

In this screenshot, I have added a red arrow that points to the position of the mouse pointer:

The mouse pointer is over that orange tool. However, the turret is rotated towards the floor while it should be rotated upwards to the orange tool.

I do believe that my turret is well positioned (the blue arrow points forward):

How do I change my code so that it aims correctly, and what is my mistake?

I guess the problem is in these 2 lines, but I don't see what's wrong about it:

```
    mousePos += Camera.main.transform.forward * 10f; // Make sure to add some "depth" to the screen point
    var aim = Camera.main.ScreenToWorldPoint(mousePos);

```

Thank you.

Edit: I finally understand what Kevin wanted to tell me. I made a thinking mistake, and really need the Raycast to determine where my Worldspace point actually is.

Here is why:

Even though the Y screen coordinate of the mouse position is just a few pixels different in each game window on the right side, the worldspace point is totally different (as can be seen in the scene view window on the left side).

I thought in 2D space, while I should have thought in 3D space.

# Answer
Your problem is indeed with the first few lines:

```
var mousePos = Input.mousePosition;
mousePos += Camera.main.transform.forward * 10f; // Make sure to add some "depth" to the screen point
var aim = Camera.main.ScreenToWorldPoint(mousePos);

```

Here you are adding the Camera's forward vector, which is in 3D, to a mouse's 2D coordinates. This is not going to add "depth" to the screen point, it's going to send it off in a seemingly random direction.

Do this:

```
var mousePos = Input.mousePosition;
mousePos.z = 10; // Make sure to add some "depth" to the screen point
var aim = Camera.main.ScreenToWorldPoint(mousePos);

```

Setting the z to a positive value like 10 is all you need to do; this moves the position we got from the cursor "forward" regardless of the orientation of the camera. When you convert to world space, the world space point will be in front of the camera where you expect it to be.

Alternatively, you might need to do a raycast to determine distance if it matters how far away the object under the cursor is:

```
Ray ray = Camera.main.ScreenPointToRay(mousePos);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
    Vector3 target = hit.point;
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Diamond shaped map: converting tile number to coordinates and back
I have a diamond shaped map that is displayed as follows:

```
*  *  *  0  1  *  *  *
*  *  2  3  4  5  *  *
*  6  7  8  9 10 11  *
12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27
* 28 29 30 31 32 33  *
*  * 34 35 36 37  *  *
*  *  * 38 39  *  *  *

```

The tiles are stored as a uni-dimensional array in a file. So, I need to convert from tile number to coordinates, so I can make an array of arrays `map[i][j]`. I want to convert the tile number to its coordinates in the `map` (i, j) and back.

To do this, I have simplified it to this form (all tiles flushed to the left):

```
   j  0  1  2  3  4  5  6  7
i
0     0  1  *  *  *  *  *  *
1     2  3  4  5  *  *  *  *
2     6  7  8  9 10 11  *  *
3    12 13 14 15 16 17 18 19
4    20 21 22 23 24 25 26 27
5    28 29 30 31 32 33  *  *
6    34 35 36 37  *  *  *  *
7    38 39  *  *  *  *  *  *

```

I have managed to convert a coordinate to its tile number like so:

```
def get_tile_number(i, j):
    # Given a map width and height n:
    if i < (n/2):
        number = i*(i+1) + j
    else:
        number = (2*((n/2)*((n/2)+1))) - ((n-i)*(n-i+1))) + j

So:
get_tile_number(0, 0) -> 0;
get_tile_number(6, 0) -> 34;

```

However, I cannot figure out to go back to the coordinates from the tile numbers, because I have trouble with distilling the i parameter from the tile number.

I have tried googling with terms like "diamond shaped map tile numbers coordinates convert", but no luck.

Can someone point me in the right direction?

# Solution

Based on Ed Marty's answer, the formula looks as follows:

```
def get_ij(tile_number):
    n_serialized_tiles = (2*((n/2)*((n/2)+1)))
    if tile_number < n_serialized_tiles/2: # If before the halfway point of the diamond
        i = math.floor(0.5 * ((math.sqrt((4 * tile_number) + 1)) - 1))
    else:
        i = math.floor(n- (0.5 * ((math.sqrt((4 * ((2 * ((n/ 2) * ((n/ 2) + 1))) - tile_number)) + 1)) - 1)))

```

This finds the i component, after which I can find j by imputing `get_tile_number(i, j=0)` in the previous formula which gets me the tile\_number at the start of that row. I then subtract the real tile\_number from that number to get j `j = tile_number - get_tile_number(i, j = 0)`.

# Answer
I tried it out in the Online Encyclopedia of Integer Sequences and found this one for the top half of the diamond:

```
i = floor((-1 + sqrt(1+4*number))/2)

```

The bottom half just needs to be reversed, like you’ve already done when going the other way.
> 2 votes

---
Tags: mathematics, maps, coordinates
---


# Question
Title: Gradual strafe rotation with focus on mouse (circle-strafe)
I'm pretty new to Unity and C# programming, and am trying to get a player-controlled object to do a controlled rotation around the mouse pointer. The functional purpose is to be able to circle-strafe around that pointer and remain facing the pointer, but if the player object's rotation speed isn't fast enough, they can't track it. As a space shooter, I intend to have large and small ships that turn at different speeds, and the intent is to make it harder for larger ships to track smaller objects.

My code right now does everything for movement *except* control rotation speed. I'm really struggling to get that single element into place. It switches from free rotation smoothly to circle-strafe rotation around the mouse cleanly... it's just that the ship then rotates as fast as I whirl the mouse around it.

I've tried a number of different techniques recommended in searches, but none of them actually work for my scenario when implemented. I'm almost certain I need "Time.deltaTime * v\_rotationSpeed" blended into this somewhere, but can't get it working.

I'm hoping someone can help, or at least guide me in the right direction.

```
using System.Collections;

public class Space2DStrafeMove : MonoBehaviour

{
    //movement variables
    public float v_speed = 3;
    public float v_rotationSpeed = 0.25f;

    //private calculation variables
    private Vector3 v_cursorLocation;
    private float v_lookAngle;

    //object variables
    private Rigidbody2D v_rigidBody2D;

    // Use this for initialization
    void Start()
    {
        //store a reference to the attached Rigidbody2D object
        v_rigidBody2D = GetComponent<Rigidbody2D> ();

    }

    //FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
    void FixedUpdate()
    {
        //Store the current horizontal input in the float moveHorizontal.
        float v_moveHorizontal = Input.GetAxis ("Horizontal");

        //Store the current vertical input in the float moveVertical.
        float v_moveVertical = Input.GetAxis ("Vertical");

        //strafe toggle, ship remains oriented towards mouse cursor
        if (Input.GetKey(KeyCode.LeftShift))
        {
            //Establish the mouse position in the camera relative to the position of the ship
            v_cursorLocation = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;

            //Create an angle that the ship will need to move towards in order to look at the mouse cursor
            v_lookAngle = Mathf.Atan2(v_cursorLocation.y, v_cursorLocation.x) * Mathf.Rad2Deg;

            //Use the two store floats to create a new Vector2 variable movement.
            Vector2 v_movement = new Vector2 (v_moveHorizontal, v_moveVertical);

            //Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
            v_rigidBody2D.AddRelativeForce(v_movement * v_speed);

            //Rotate the ship towards the established angle, -90f to account for ship alignment, over time
            //Rotates instantly, not desirable
            transform.rotation = Quaternion.Euler(0f, 0f, v_lookAngle - 90f);

            //turns the ship as fast as I move the cursor, and in the right direction
            //transform.rotation = Quaternion.AngleAxis(v_lookAngle-90, Vector3.forward);

            //instantly snaps the ship "up"
            //transform.rotation = Quaternion.Euler(0f, 0f, v_lookAngle - 90f * Time.fixedDeltaTime) ;

            //instantly snaps the ship "up"
            //transform.rotation = Quaternion.Euler(0f, v_lookAngle - 90f * v_rotationSpeed * Time.deltaTime, 0f);

            //undesirable result
            //transform.eulerAngles = Vector3(0, v_lookAngle, 0);

            //undesirable result
            //transform.rotation = Quaternion.Slerp(v_lookAngle, v_lookDirection.y, Time.time - startTime);

            //undesirable result
            //transform.rotation = Quaternion.RotateTowards(transform.rotation, v_lookDirection, Time.deltaTime * 10f);

            //smooth rotation to the Z axis (flips the ship over)
            //transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(v_lookDirection - transform.position), v_rotationSpeed * Time.deltaTime);

            //undesirable result
            //transform.rotation = Quaternion.AngleAxis(v_lookAngle, Vector3.forward);

            //ship spins smoothly over onto it's back
             //transform.rotation = Quaternion.Slerp(this.transform.rotation, v_lookAngle, Time.deltaTime * v_rotationSpeed);

        }

        //this creates smooth up and down, rotate left and right, fly in direction the transform is pointing
        if (!Input.GetKey(KeyCode.LeftShift))
        {
            //Use the two store floats to create a new Vector2 variable movement.
            Vector2 v_movement = new Vector2(0, v_moveVertical);

            //rotate the transform on the horizontal axis
            transform.Rotate(0, 0, -v_moveHorizontal);

            //apply force relative to the existing heading of the ship
            v_rigidBody2D.AddRelativeForce(v_movement * v_speed);
        }
    }
}

```

# Answer
> 1 votes
This thread gave me the line I needed. It just happened to pop up a few hours after my post and grabbed my eye.

Rotating gradually in response to input, instead of snapping

The answer there was to put the rotation inside a Coroutine. I tried that, but while it did successfully rotate my ship on the correct axis after a little tinkering, it didn't care how fast it rotated.

I pulled the rotation line out of the Coroutine and stuck it into FixedUpdate. It still didn't work. In the end I had to re-declare v\_rotationSpeed inside the FixedUpdate for it to work. I'll have to figure that one out. Now that section from my first post looks like this:

```
if (Input.GetKey(KeyCode.LeftShift))
        {
            //set v_rotationSpeed; not sure why it's not using the public variable
            float v_rotationSpeed = 60f;

            //Establish the mouse position in the camera relative to the position of the ship
            v_lookDirection = Camera.main.ScreenToWorldPoint(v_mousePosition) - transform.position;

            //Create an angle that the ship will need to move towards in order to
            //look at the mouse cursor
            v_lookAngle = Mathf.Atan2(v_lookDirection.y, v_lookDirection.x) * Mathf.Rad2Deg;

            //Use the two store floats to create a new Vector2 variable movement.
            Vector2 v_movement = new Vector2 (v_moveHorizontal, v_moveVertical);

            //Call the AddForce function of our Rigidbody2D supplying movement
            //multiplied by speed to move our player.
            v_rigidBody2D.AddRelativeForce(v_movement * v_speed);

            //Update our target rotation to move towards.
            v_targetRotation = Quaternion.Euler(0f, 0f, v_lookAngle-90f);

            //gradually rotates the ship towards the mouse pointer
            transform.rotation = Quaternion.RotateTowards(transform.rotation,
                                                          v_targetRotation,
                                                          v_rotationSpeed * Time.fixedDeltaTime);
        }

```

# Answer
> -1 votes
**EDIT:** D'oh! You've apparently already tried this in your commented-out code that I ignored. Hmm, re-thinking.

You probably want to `Lerp` or `Slerp`:

```
var targetRotation = Quaternion.Euler(0f, 0f, v_lookAngle - 90f);
var lerpRate = .15f;
var newRotation = Quaternion.Lerp(transform.rotation, targetRotation, lerpRate);
transform.rotation = newRotation;

```

`Lerp` and `Slerp` smoothly interpolate from one value to another. The third argument (labelled `t`), is a normalized value (0 - 1) representing the percentage to move from the start value to the end value. Note that adjusting the lerp rate even a small amount may drastically affect the animation. It's usually good to start with a very low value and play around with it from there.

---

**Idea #2:**

Maybe something like this?

```
//Transform cursor position to world coordinates
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = 10;
mousePosition = Camera.main.ScreenPointToWorldPoint(mousePosition);
mousePosition.y = transform.y;

//Rotate towards the cursor
float lerpRate = .15f;
Quaternion targetRotation = Quaternion.LookRotation(mousePosition - transform.position, Vector3.up);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, lerpRate);

```

---
Tags: unity, c#, 2d, movement
---


# Question
Title: Sending light data from Vertex Shader to Pixel Shader?
We have a pixel shader constant buffer that contains the light data for the item that is currently rendered.

To implement tangent space normal mapping, i would need to transform each light into tangent space.

Is it a valid approach to instead bind the light data to the vertex shader and then send the transformed Light Data to the pixel shader since the vertex shader runs less frequently than the pixel shader?

As a side note: I am using forward rendering with a limited light count.
Our pixel shader constant buffer looks like this:

```
struct RendererLight {
    float3 Position;
    float3 Color;
    float3 Direction;
    float Intensity;
    float In;
    float Out;
    float Range;
};

cbuffer LightsBuffer : register(b2)
{
    RendererLight Lights[8];
    uint NumLights;
};

```

# Answer
> 3 votes
It's valid, but you have a limited number of interpolators between the two shader stages, and depending how much data you're sending you may bump into that limit. You'll almost certainly need to split your cbuffer in two - lights per-vertex and lights per-pixel - with the per-vertex buffer containing the bare minimum of data.

However, you should also bear in mind that modern GPUs are very unlikely to be ALU-bound with the number of computations you're currently doing, and that in certain cases you can almost treat ALU as if it were effectively free. Compare that to the trade-offs involved in splitting your cbuffer, complicating your shaders, and using those extra interpolators (which are very much not free) and you will probably be better off just leaving your shaders as they are.

Ultimately what it comes down is: have you benchmarked this, and is it actually a performance problem for you?

---
Tags: lighting, hlsl, fragment-shader, vertex-shader
---


# Question
Title: How can I move an object over linerenderer lines positions?
I have 4 cubes the first 3 cubes connected with two lines one of the lines is curved. The fourth cube I want to move over the lines. The lines is built using linerenderer and in the linerenderer there are 397 positions. I created a small script that move an object over the positions. I checked and I have in the array 397 positions and the loop get to 397 but the object (Cube (3)) never moving all the positions only some. Or maybe the positions I get are not the same in the linerenderer ?

This screenshot show some of the positions in the linerenderer this is the positions I want the object to move on :

Why the object is not moving over all the positions , only on some ? And this is the script I created that should move it :

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

public class MoveOnCurvedLine : MonoBehaviour
{
    public LineRenderer lineRenderer;
    public GameObject objectToMove;
    public float speed;

    private Vector3[] positions = new Vector3[397];
    private Vector3[] pos;
    private int index = 0;

    // Start is called before the first frame update
    void Start()
    {
        pos = GetLinePointsInWorldSpace();
    }

    Vector3[] GetLinePointsInWorldSpace()
    {
        //Get the positions which are shown in the inspector
        var numberOfPositions = lineRenderer.GetPositions(positions);
        //Iterate through all points, and transform them to world space
        for (var i = 0; i < numberOfPositions; i += 1)
        {
            positions[i] = transform.TransformPoint(positions[i]);
        }

        //the points returned are in world space
        return positions;
    }

    // Update is called once per frame
    void Update()
    {
        if(index <= pos.Length - 1)
        {
            objectToMove.transform.position += pos[index] * Time.deltaTime * speed;
            index++;
        }
    }
}

```

Now I checked using a breakpoint the first position in the linerender at index 0 is : X = 30.57, Y = -6.467235, Z = 4.98

But in my script in the pos array I see that in index 0 the position is :

X = 30.6, Y = -6.5, Z = 5.0

And the result is that the object that move Cube(3) is moving only some of the way and also it's not exactly on the line :

Why the object is not moving over all the positions , only on some ?

Something is wrong in my script with getting the right positions from the linerenderer and maybe also the loop and the move is wrong. I can't figure out ho to do it.

# Answer
> 1 votes
Working script :

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

public class MoveOnCurvedLine : MonoBehaviour
{
    public LineRenderer lineRenderer;
    public GameObject objectToMove;
    public float speed;

    private Vector3[] positions = new Vector3[397];
    private Vector3[] pos;
    private int index = 0;

    // Start is called before the first frame update
    void Start()
    {
        pos = GetLinePointsInWorldSpace();
        objectToMove.transform.position = pos[index];
    }

    Vector3[] GetLinePointsInWorldSpace()
    {
        //Get the positions which are shown in the inspector
        lineRenderer.GetPositions(positions);

        //the points returned are in world space
        return positions;
    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }

    void Move()
    {
        objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position,
                                                pos[index],
                                                speed * Time.deltaTime);

        if (objectToMove.transform.position == pos[index])
        {
            index += 1;
        }

        if (index == pos.Length)
            index = 0;
    }
}

```

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


title: Tile map click to walk UX

text:
# Question
Title: Tile map click to walk UX
My game is a top down mobile game where the player clicks a tile to walk to it.

However, it isn't clear where tile boundaries are from just looking at a level, so you could click on the edge of a tile expecting the player to walk there- but they walk to the center.

For instance, you could click on the center of the island shown below expecting it to be a tile- but the center is actually a corner in-between 4 tiles- so clicking there could result in walking to any of the 4 surrounding tiles.

Should I let the player walk freely, even between tiles, or is there a better solution in terms of UX?

# Answer
> 2 votes
I noticed that Oskar Stålberg's games like Bad North and Townscaper flirt with this ambiguity in the way they distort and disguise the tile grid to make the world feel more organic.

To solve the UX problem this could cause, they overlay an affordance that highlights the tile to be selected, or all tiles when a move is about to be issued.

This gives the player clarity and confidence about what moves are possible and what the outcome of their action will be, without changing the underlying aesthetic of the tileset when not actively navigating.

---
Tags: game-design, tiles, mobile, user-experience
---


# Question
Title: Bring a Blender .blend file into Unity and replace its materials
I bring my .blend file (from Blender) into the assets/prefab folders in Unity. The model is a house with a lot of windows. In Unity, my glass material become solid/opaque.

My questions:

1. Since the material is locked, I can't change it in Unity, so is there any way to do it in Blender? Is there some setting in Blender I can modify so that glass material will be imported as a transparent type material in Unity?
2. If I replace it with a new glass material in Unity, is there any way I can do it to replace *all* the glass (same glass material) without doing it manually one by one?

# Answer
> 1 votes
When you import a .blend file into Unity, what really happens behind the scenes is that Unity will call Blender’s export scripts to generate a .fbx file, and then import this file into Unity. At first that sounds like both paths should be 100% equivalent. However, that is not the case! Unity won't use Blender materials, or any other materials from other 3d software. Materials in Blender are generally meant for offline rendering, and Unity uses a much more optimized real-time renderer, which, like any real-time renderer, fakes a lot of things instead of doing the calculations.

To get a slight transparency (similar to glass) change your material Shader from Diffuse to FX\>Flare this will lighten the material and give it slight transparency.

* Click the Extract Materials button to extract Materials that are embedded in your imported Asset. This is greyed out if there are no materials to extract. And edit them like any other material, You can extract all the glass like materials and change their transparency.
* If you're working with prefabs you can right click on the prefab and select extract material and edit them.

There are ways to get things from Blender into Unity however. If you are using Blender's internal textures, you are going to have to bake them. Unity(and other 3d engines) need materials in the form of textures, and the models need to be properly UV mapped unless you use a specialty shader that does automatic UV mapping, as long as your model contains UV map information you can simply drop your textures on to the Unity model.

Textures and diffuse color are not assigned automatically. You can manually assign them by dragging the texture onto the mesh in the Scene View in Unity.

Importing materials from blender can be tedious at times. I recommend you to just make a greyed out model or just add the base colours(Diffuse) and add the other fx materials from inside of unity as both use different rendering and effects the scene.

Alternatively, if you're familiar with Blender materials and nodes maybe you should try Substance Designer to recreate Blender material setup and this can be easily imported to Unity with all switches and sliders.

---
Tags: unity, blender
---


# Question
Title: Can I add rigging bones to a model imported from Blender inside Unity?
I created a model in Blender but recently I stumbled upon a video claiming that you can add rigging to a model in Unity. So instead of rigging in Blender, is it possible to do it in Unity?

# Answer
> 2 votes
3D packages provide a number of ways to create joints for your humanoid rig. You must use an external 3d modelling software to manually rig and add weights, you cannot do it in Unity.

But before we explore what's with the new animation rigging let's see how animation layers work in unity. Unity uses Animation Layers for managing complex state machines for different body parts. An example of this is if you have a lower-body layer for walking-jumping, and an upper-body layer for throwing objects / shooting. It's an easy way to override and map different animations at once. But this has its own constraints. What if you want to add an animation where you want your character to pick up something while walking you need an animation for walking and picking up and then add a interactables layer and override the top part of the body to use the pick up animation. This requires you to make many animations.

Using layers require pre-made animations and it enables overriding certain parts of the rig. This is a great feature, but what if we could override certain parts of rig to work procedurally? That would lead to amazing possibilities. Unity made a clever decision by combining procedural animation with layer rig overriding. Complete procedural animation doesn't look that good but combining it with pre-made animation, we can create some amazing stuff. Imagine being able to control certain parts of the rig using code and remaining using the pre-made animations.

The Animation Rigging package for Unity enables to set up procedural motion on animated skeletons at runtime. You can use a set of predefined animation constraints to manually build a control rig hierarchy for a character or develop your own custom constraints in C#. This makes it possible to do powerful things during gameplay such as world interactions, skeletal deformation rigging, and physics-based secondary motion.

---
Tags: unity, blender, rigging
---


# Question
Title: Linear interpolation: reach moving destination regardless its speed
I'm implementing a camera for a game and I'm using the LERP formula for smooth chasing. However, if the target moves fast enough, the camera can never reach it unless the `t` ((1 - t) * v0 + t * v1) value is high enough, but that is exactly the problem: some targets might still move faster than the current `t` value.

This might lead to 2 problems:

1. The camera will never reach the object if it's super fast
2. The camera will very slowly reach the object, depending on its current speed

How do I scale up my `t` when the delta distance (`abs(v1 - v0)`) gets lower, so that the camera will starts at a slow chasing rate and increases as it gets closer (therefore no targets could run away)?

# Answer
> 2 votes
I managed to solve this by increasing `t` over time, as it will eventually reach 1, on which LERP would return the `v1`'s value, like so:

```
f = some constant smoothing factor between 0 and 1
t = min(t + f, 1)
v0 = (1 - t) * v0 + t * v1 // lerp

```

This guarantees to reach `v1` even if it's moving, regardless its speed. When moving the camera to a different object, `t` must be reset for the smoothness effect.

However, if there are any approaches that doesn't require to sum up `t` every game tick, please leave a comment!

---
Tags: physics, camera, lerp
---


# Question
Title: Planck.js (rewritten of Box2D.js) - 8 direction box movement
I have a box in Planck.js. I want to move this box with some keys. How can I do that? My code:

```
planck.testbed("boxworld", function(testbed) {
  var pl = planck,
    Vec2 = pl.Vec2;
  var world = new pl.World(Vec2(0, 0));

  //Box

  var box = world
    .createDynamicBody(Vec2(0.0, 10.0))
    .createFixture(pl.Box(0.5, 0.5), 20.0);
  box.render = { fill: "#FA8072", stroke: "black" };

  return world;
});

```

# Answer
> 0 votes
You could set velocity for the box, apply force or directly change location.

---
Tags: javascript, box2d
---


# Question
Title: NullReferenceException when translating instantiated prefab
I keep getting this error:

> NullReferenceException: Object reference not set to an instance of an object moveBlock.Update () (at Assets/Scripts/moveBlock.cs:27)

whenever I press Play in Game or when I press Space while in play. I looked at other questions posted but it is not clear to me what the solution is. I think I am missing a `GetComponent` line, but I'm not sure.

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

public class moveBlock : MonoBehaviour
{

    public float speed = 10;
    public GameObject[] blocks;
    private GameObject b;

    void Update()
    {
        Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
        Vector3 direction = input.normalized;
        Vector3 velocity = direction * speed;
        Vector3 moveAmount = velocity * Time.deltaTime;

        if (Input.GetKeyDown(KeyCode.Space))
        {
            b = (GameObject)Instantiate(blocks[Random.Range(0, 7)], new Vector3(0, 6, 0), Quaternion.Euler(Vector3.right));
            //b.AddComponent<Rigidbody>().isKinematic = false;
        }
        b.transform.Translate(moveAmount); // <-- Line 27 throws the exception.
    }
}

```

# Answer
In this part:

```
    if (Input.GetKeyDown(KeyCode.Space))
    {
        b = (GameObject)Instantiate(blocks[Random.Range(0, 7)], new Vector3(0, 6, 0), Quaternion.Euler(Vector3.right));
        //b.AddComponent<Rigidbody>().isKinematic = false;
    }
    b.transform.Translate(moveAmount);

```

In the last line, you try to access **b**, however, it will only be valid **after** you press space once. You probably need to check if **b** is valid before using it.

```
if (b) {
    b.transform.Translate(moveAmount);
}

```

Note that if you press space multiple times, you will be missing the previous references to **b**. And you will only move the last one created.
> 2 votes

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


# Question
Title: Determine when a PIXI texture is loaded to clone it
I'm in the latest PIXI v5, where my texture is made like `let texture = PIXI.Texture.from(TEXTURE_URL)`.

The texture isn't loaded synchronously- Pixi just covers this up. That would be fine but when I try to apply a frame, the following error is thrown because the texture has no dimensions because it isn't loaded yet. I have no way of determining whether it's loaded or not!

```
Error: Texture Error: frame does not fit inside the base Texture dimensions: X: 8 + 8 = 16 > 0 and Y: 0 + 8 = 8 > 0

```

**How can I get a promise for when a Pixi texture is loaded or clone it anyway?**

# Answer
Another solution is to pass the texture's dimensions into the `PIXI.Texture.from()` method.

```
let texture = PIXI.Texture.from('img/character.png', {width: 256, height: 256});
texture.frame = new PIXI.Rectangle(0, 0, 86, 132);
// display texture here

```

**Character sprite sheet**

**After cropping with frame**

Other arguments accepted by `from()` can be found in PixiJS Docs.
> 2 votes

# Answer
Use PIXI.Loader, here's an example from that link:

```
const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use.

// Chainable `add` to enqueue a resource
loader.add('bunny', 'data/bunny.png')
      .add('spaceship', 'assets/spritesheet.json');
loader.add('scoreFont', 'assets/score.fnt');

// The `load` method loads the queue of resources, and calls the passed in callback called once all
// resources have loaded.
loader.load((loader, resources) => {
    // resources is an object where the key is the name of the resource loaded and the value is the resource object.
    // They have a couple default properties:
    // - `url`: The URL that the resource was loaded from
    // - `error`: The error that happened when trying to load (if any)
    // - `data`: The raw data that was loaded
    // also may contain other properties based on the middleware that runs.
    sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture);
    sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture);
    sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture);
});

```

For your convenience, these functions are also available:

```
// throughout the process multiple signals can be dispatched.
loader.onProgress.add(() => {}); // called once per loaded/errored file
loader.onError.add(() => {}); // called once per errored file
loader.onLoad.add(() => {}); // called once per loaded file
loader.onComplete.add(() => {}); // called once when the queued resources all load.

```

This way, when you call `new Texture(...)` with one of those assets, it will be initialised instantly, and its dimensions will be available to you.
> 1 votes

# Answer
One solution is to wait (and keep polling) to see whether the texture dimensions have changed.

```
  async function() {
    await new Promise(resolve => {
      let interval = setInterval(() => {
        if(texture.orig.width !== 0) {
          resolve();
        }
      }, 20);
    });

    // do things here, texture is loaded
  }

```
> 0 votes

---
Tags: javascript, pixi.js
---


# Question
Title: How to save boolean to player prefs in Unity?
I'm making a player settings thing where the user can turn off or turn on the game music by clicking buttons. I had this script below and everything was working fine.

```
 private GameObject music;

 public void Start()
 {
     music = GameObject.FindGameObjectWithTag("Music");
 }
 public void YesButton()
 {
     music.SetActive(true);
 }

 public void NoButton()
 {
     music.SetActive(false);
 }

```

I want to save it as player preferences so when they go out and back into the game, their settings would be saved. How would I do this? This is what I tried:

```
 private GameObject music;
 private bool musicOn = true;

 public void Start()
 {
     music = GameObject.FindGameObjectWithTag("Music");
 }

 public void YesButton()
 {
     musicOn = true;
     PlayerPrefs.GetInt("MusicOn", (musicOn ? 1 : 0));
 }

 public void NoButton()
 {
     musicOn = false;
     PlayerPrefs.GetInt("MusicOn", (musicOn ? 1 : 0));
 }

 void Update()
 {
     PlayerPrefs.SetInt("MusicOn", (musicOn ? 1 : 0));

     int value;

     value = musicOn ? 1 : 0;

     if (musicOn)
     {
         value = 1;
         music.SetActive(true);
     } else if (!musicOn)
     {
         value = 0;
         music.SetActive(false);
     }
 }

```

But it doesn't work. When I click the "no" button, the music turns off but it turns back on when I go back into the game. How would I fix this problem? Thanks for your help!

New code that mostly works:

```
public GameObject music;
public bool musicOn = true;

public void Start()
{
    music = GameObject.Find("Music");
    bool musicOn = PlayerPrefs.GetInt("MusicOn", 0) > 0;
    if (musicOn)
        YesButton();
    else
        NoButton();
}

public void YesButton()
{
    music.SetActive(true);
    PlayerPrefs.SetInt("MusicOn", 1);
}

public void NoButton()
{
    music.SetActive(false);
    PlayerPrefs.SetInt("MusicOn", 0);
}

```

# Answer
It is because you are setting PlayerPref in Update method. Now, you start your game, ant object's values are reset to initial value. So music object becomes null and musicOn becomes true (because you defined it explicitly to be initialized with true). You don't retrive actual value from PlayerPrefs when object is created in scene (Start method), thus on first Update your PlayerPrefs value is set to 1 (true).

There's two solutions to your problem, the ugly and the nice.

The ugly solution is to load your PlayerPref value in Start method.

The nice solution is to load your PlayerPref value in Start method **AND** move PlayerPrefs.SetInt from Update to YesButton and NoButton methods, after musicOn value is set. Add music.SetActive() to YesButton and NoButton methods as well. Delete Update method as it is no longer needed.
> 2 votes

# Answer
```
public bool MusicOnBool;

// This method will toggle the MusicOnBool and saves it to playerprefs
public void ToggleButton()
{
    MusicOnBool = !MusicOnBool; // sets it to its opposite state
    music.SetActive(MusicOnBool);
    // Below we save the bool (which is either a 1 or 0) to "MusicOn"
    PlayerPrefs.SetInt("MusicOn", MusicOnBool ? 1 : 0); // condition ? true : false, so if the condition is true, itll be 1, otherwise it'll be 0.
    music.SetActive(MusicOnBool);
}

// This method can be called wherever, such as the Start() method in your script and basically it'll load the saved int and check to see if it's 1 which would be true. So if 0, it'll be false, if 1, it'll be true.
public void Load()
{
    MusicOnBool = PlayerPrefs.GetInt("MusicOn", 1) == 1;
    // EX: MusicOnBool = 0 == 1 will result in false
    music.SetActive(MusicOnBool);
}

```
> 0 votes

---
Tags: unity, c#, scripting, boolean
---


# Question
Title: Check if 2 objects with multiple colliders overlap using bounds
I'm writing a script which instantiates buildings in a scene, but in such a way that 2 buildings don't overlap with each other. Every building consists of approx. 10 parts, of which each has a box collider.

The way I do this is by first instantiating the first building and adding it to a list. In this example I instantiate 2 buildings.

By the way, this doesn't need to run in real-time, my intention for this is to press a button in the editor and have a lot of buildings instantiated at once.

```
        for (int j = 0; j < 2; j++)
        {

            if(j == 0)
            {
                _buildingList.Add(GameObject.Instantiate(GetBuilding(Vector3.zero), _parent));
            }

```

Now in this same for loop, I instantiate the next building, add it to the list and check if it collides with the previous building in the list, like so:

```
            else
            {
                _buildingList.Add(GameObject.Instantiate(GetBuilding(Vector3.zero), _parent));
                if (_buildingList.Count > 1)
                {
                    int amountOfRepositioningAttempts
                    while (AreObjectsIntersecting(_buildingList[_buildingList.Count - 1], _buildingList[_buildingList.Count - 2]) && amountOfRepositioningAttempts < 10000)
                    {
                        amountOfRepositioningAttempts++;
                        GameObject buildingToMove = _buildingList[_buildingList.Count - 1];

                        buildingToMove.transform.Translate(Vector3.right);

                    }
                }
            }
        }

```

As you can see I have a few helper methods, which look like this

```
public GameObject GetBuilding(Vector3 position)
{
    GameObject buildingToInstantiate = _buildingPrefabContainer.GetRandomBuilding();

    Vector3 lookDirection = Vector3.zero - position;
    Quaternion lookRotation = Quaternion.LookRotation(lookDirection);

    buildingToInstantiate.transform.position = position;

    return buildingToInstantiate;
}

```

**And the method from which I get unexpected results:**

```
public bool AreObjectsIntersecting(GameObject object1, GameObject object2)
{
    BoxCollider[] _collidersObject1 = object1.GetComponentsInChildren<BoxCollider>();
    BoxCollider[] _collidersObject2 = object2.GetComponentsInChildren<BoxCollider>();
    for (int i = 0; i < _collidersObject1.Length; i++)
    {
        for (int j = 0; j < _collidersObject2.Length; j++)
        {
            if (_collidersObject1[i].bounds.Intersects(_collidersObject2[j].bounds))
            {
                return true;
            }
        }
    }
    return false;
}

```

The intention here is that I go over each buildings collider, and if one of those colliders overlaps with one of the colliders of another building, then the building gets repositioned, and the check happens again. **But the method AreObjectsIntersecting() seems to always return true, and I don't see why.** I know this because

```
    int amountOfRepositioningAttempts

```

Always ends up being 10000, while the 2 objects should have stopped intersecting with each other after only a few iterations of moving them. Can anyone help me out here?

Thanks in advance!

# Answer
> 0 votes
Remember that colliders and collision/overlap checks are part of the physics engine, while transforms are part of the game engine. These are two separate systems with their own data, and synchronizing that data has a non-zero cost.

By default, Unity will synchronize the physics data to align with changes to the transforms before each physics step, and synchronize physics movement back to the transforms at the end of the physics step / in time for collision handling callbacks.

But here, there's no physics step happening inside your `while` loop between you repositioning the building and checking its overlaps, so you're still checking overlaps with stale, out-of-sate physics info.

To fix this, you can call Physics.SyncTransforms to force any updated transform data to be passed over to the physics engine, so you can do overlap testing with the latest transform positions.

---
Tags: unity, c#, collider, prefabs
---


# Question
Title: Applying texture maps from Blender to Unity material properties
When I bring my Blender file into Unity, I will attach the texture maps from my Blender material (left) to the Unity material (right) as follows:

* diffuse/color map --\> albedo
* normal --\> normal
* roughness --\> ?
* specular --\> ?
* displace ---\> ?
* metalness --\> metalic ?

I haven't found matches for the roughness, specular, or displacement maps. What should I do with those maps?

# Answer
> 2 votes
> the problem is the smoothness parameter does not have the little box on its left where i can drag drop texture there

That's because smoothness only needs a single channel, so it's common to pack this data in as the alpha channel of another map you're using to be more efficient with texture lookups in the shader.

(Remember that since smoothness is the opposite of roughness, you may need to invert the roughness map you're using when applying it as an alpha channel. You'll also want to save the result as something like .TGA or .PSD, as PNG compressors like to assume that zero-alpha regions are transparent/invisible so they can change the colours there to make the image compress better)

In the built-in or Universal Rendering Pipeline default shader, you have the option to take your smoothness from the alpha channel of either your Metalness texture, or the Albedo texture.

If you're using the High-Definition Rendering Pipeline, the setup is a little different, and you have multiple different variants you can use. Since it looks like you're using specular and displacement maps, you can set the "Material Type" to "Specular Color" and the "Displacement Mode" to pixel or vertex displacement, whichever is more appropriate for your effect.

That gives you a set of parameters that looks like this:

Your displacement map would go into the "Height Map" property, and your specular map into the "Specular Color" property.

Metalness and Smoothness are packed as channels into a single "Mask Map" as laid out in the documentation:

```
Color channel     Map
-----------------------------
Red               Metallic
Green             Occlusion
Blue              Detail mask
Alpha             Smoothness

```

If you want a material effect that's not adequately covered by the options above, I'd recommend posting a specific question about that. Show what the material should look like (in Blender or other references), and how you've attempted to build it in Unity so far, and users here can recommend options to better-match that effect - even creating your own new material shaders if you need a unique mix of features not present in the built-in assets or options available on the Asset Store.

---
Tags: unity, blender, materials
---


# Question
Title: Compute shader: Property at kernel index is not set
I am trying to follow this excellent Coding Adventure: https://www.youtube.com/watch?v=lctXaT9pxA0 in order to get a very simple mesh deformation on a mesh using a compute shader.

I'm getting an error that reads:

> Compute shader (NewComputeShader): Property (vertices) at kernel index (0) is not set UnityEngine.ComputeShader:Dispatch(Int32, Int32, Int32, Int32) MoonShader:runShader() (at Assets/MoonShader.cs:27) MoonShader:Update() (at Assets/MoonShader.cs:15)

I'm calling runShader() in Update (maybe that's a terrible idea, but I don't think it's contributing to this specific problem yet).

Do I need to somehow pass my mesh's vertices into `StructuredBuffer<float3> vertices;`? If so, how am I supposed to do that?

This is the call to the compute shader in my .cs file.

```
void runShader() {
    int kernelHandle = computeShader.FindKernel("CSMain");
    computeShader.Dispatch(kernelHandle, 512, 1, 1); //this is the line it appears to be complaining about
}

```

This is my .compute file.

```
#pragma kernel CSMain
StructuredBuffer<float3> vertices;
RWStructuredBuffer<float> heights;
uint numVertices;
float testValue = 20;

[numthreads(512,1,1)]
void CSMain (uint id : SV_DispatchThreadID) {
    if(id >= numVertices) {

    } else {
        float3 vertexPosition = vertices[id];
        heights[id] = 1 + sin(vertexPosition.y * testValue) * 0.05;
    }
}

```

Link to repo if it's helpful: https://github.com/glenpierce/proceduralPlanets

# Answer
You need "link" your StructuredBuffer to a ComputeBuffer that you initialize in the CS script. In your code, you've never specified a compute shader to write to, so the compiler is basically saying, "yo, there's nowhere to write this data to!"

In your .cs file, you should have:

```
void runShader() {

    int kernelHandle = computeShader.FindKernel("CSMain");
    //New Things here
    ComputeBuffer vertexBuffer = new ComputeBuffer(mesh.vertices.Length, sizeof(float) * 3); //make new compute buffer with specified size, and specified "stride"
    //stride is like the size of each element, in your case it would be 3 floats, since Vector3 is 3 floats.
    vertexBuffer.setData(mesh.vertices); //set data inside buffer

    computeShader.setBuffer(kernelHandle, "vertices", vertexBuffer); //Linking the compute shader and cs shader buffers

    computeShader.Dispatch(kernelHandle, 512, 1, 1);
}

```

I hope that helps!

I'd also recommend checking out these two ComputeShader guides, the OP walks you through his own personal project and explains things pretty well.

(Easy) https://www.reddit.com/r/Unity3D/comments/7pa6bq/drawing\_mandelbrot\_fractal\_using\_gpu\_compute/

(Hard) https://www.reddit.com/r/Unity3D/comments/7ppldz/physics\_simulation\_on\_gpu\_with\_compute\_shader\_in/
> 1 votes

---
Tags: unity, compute-shader
---


# Question
Title: Prevent mesh generation function from blocking other functions from running
So, I have a procedural mesh generation system with chunks that load in and generate as the player walks into a nearby cell, and get removed when the player walks out. When each set of 9 cells is getting generated, this takes around 1500 ms. When they are being generated, the game thus freezes. Is there a way to make the game NOT freeze and allow the player to continue doing things in their current chunk while the area is being generated? Like having the terrain gen happening in the background? EDIT- From @DmGregory- the ob struct seems like it would work, but I am a bit confused as to whether or not I can include all of mymesh geneartion and update function in it,or if I need to find a way to pass out the mesh and verts from the job. What is the best way to do this?

I haven't fully started writing code in the struct as i am unsure of where to begin in terms of the mesh update system. Essentially, my code is as follows- In a for loop, it generates vertices, and for every one of these vertices, it uses a noise function to generate height. It then enters another for loop that connects the verts together via triangles. Without the noise function, it essentially forms a plane. The noise function is almost certainly the culprit for the lag, as it gets repeated 65025 times per chunk. I do want to convert the entire gen function into a job, however.

EDIT 2- I am using the coroutine system suggested by @DMGregory, and so have written my coroutine mesh gen as such. It is a combination of my update mesh and mesh generation methods. This now DOES NOT freeze the game, but fails to generate the mesh at all, however, the game is smooth. This is what the code looks like for the co-routine-

```
IEnumerator meshGen(){

        vertices = new Vector3[(xSize + 1) * (zSize + 1)];

   for (int i=0, z = 0; z <= zSize; z++){
       for(int x = 0; x <= xSize; x++){

           vertices[i] = new Vector3(x, generateNoise(x, z), z);
           i++;
           yield return null;
       }
   }

   triangles = new int[6 * xSize * zSize];

    int vert = 0;

    int tris = 0;

    for( int z = 0; z < zSize; z ++){
        for(int x = 0; x < xSize; x++)
        {
         triangles[0 + tris] = vert + 0;
         triangles[1 + tris] = vert + xSize + 1;
         triangles[2 + tris] = vert + 1;
            triangles[3 + tris] = vert + 1;
         triangles[4 + tris] = vert + xSize + 1;
         triangles[5 + tris] = vert + xSize + 2;

            vert ++;

            tris +=6;
         }
         vert ++;
    }

    mesh.Clear();
    mesh.vertices = vertices;
    mesh.triangles = triangles;

    mesh.RecalculateNormals();

    }

```

And this is what the code looks like for the generateNoie(x, z) function-

```
float generateNoise(float x, float z){

    //float k = (-1 * noise.Evaluate(new Vector3(x * 0.01f, 0, z * 0.01f)));
    float k = (-1 * evalNoise(x, z, 0.01f));
    k = Mathf.Pow(k, 2);

  //  float ty = Mathf.Clamp(1 - Mathf.Abs(noise.Evaluate(new Vector3(x * 0.015f, 0, z * 0.015f))), 0, 1);
  float ty = Mathf.Clamp(1 - Mathf.Abs(evalNoise(x, z, 0.015f)), 0, 1);

    //float y = (1 - Mathf.Abs(noise.Evaluate(new Vector3(x * 0.03f, 0, z * 0.03f)))) * 5f + 5f;
    float y = (1 - Mathf.Abs(evalNoise(x, z, 0.03f))) * 5f + 5f;

    y*= ty;

    y *= k;

   y -= (1 - k) * 1;

   float freq = 1;
   float ampl = 1;
    if(y > CutOffHeight && y < maxCutOffHeight){
        for(int i =1; i <= octaves; i++){
            freq *= 2;
            ampl *= 0.5f;
            //y += noise.Evaluate(new Vector3((x * freq),0, (z*freq)/octaves)) * (ty * 2) * k * ampl;
            y += evalNoise(x,z, freq) * (ty * 2) * k * ampl;
      //print(i);
    }
    }

   // y -= 1- Mathf.Abs(noise.Evaluate(new Vector3(x * 0.05f, 0, z * 0.05f))) * ty;
   y -= 1- Mathf.Abs(evalNoise(x,z,0.05f)) * ty;

    //float uy = Mathf.Clamp(Mathf.Pow(noise.Evaluate(new Vector3(x * 0.01f, 0, z * 0.01f)), 2), 0, 1);
    float uy = Mathf.Clamp(Mathf.Pow(evalNoise(x,z,0.01f), 2), 0, 1);

    y+= uy;

    y -= ty;

    y *= 2f;

    float r = evalNoise(x,z, 0.002f);

    y *= 1- Mathf.Clamp(Mathf.Pow(r, 3), 0, 1);

    if(y <= IslandHeight){
        float tempGrad = Mathf.Abs(y - IslandHeight);
        y -= Mathf.Abs(tempGrad);
    }

    return y;
}

```

# Answer
If you want to keep using your coroutine approach, you'll want to the coroutine do more work each time it takes a turn, so that it finishes after a smaller number of frames.

How much work is enough to finish in a decent amount of time, but small enough that it won't cause a noticeable stutter? That might vary depending on the hardware, or the current load on the system. So one common trick to use here is to allocate it a time budget, and do as much as you can within that limit.

```
IEnumerator MeshGen(){
        // Set up a clock to watch how long we're running.
        var stopwatch = System.Diagnostics.Stopwatch.StartNew();

        float millisecondBudget = 3.0f; // Adjust this to suit your needs.
        long tickBudget = (long)(System.Diagnostics.Stopwatch.Frequency
                          * millisecondBudget/1000f);

        vertices = new Vector3[(xSize + 1) * (zSize + 1)];

        for (int i=0, z = 0; z <= zSize; z++){
            for(int x = 0; x <= xSize; x++){
                vertices[i] = new Vector3(x, generateNoise(x, z), z);
                i++;
            }

            // After finishing each line of vertices, check if we're running overtime:
            if(stopwatch.ElapsedTicks > tickBudget) {
                // If so, let the game run for a frame, and resume the work next frame.
                yield return null;
                stopwatch.Restart();
            }
        }

```

You can pepper similar yields in other places where your method takes a long time in your testing.

One potential area of risk is `mesh.RecalculateNormals();` which has to run to completion - we don't have an opportunity to inject yields midway through that function. If you find that this line alone takes longer than your budget for a frame, and causes a noticeable hitch, then you may want to consider generating your normals as you go. Many noise functions can be adapted to return not just a noise value, but also an analytic or partial derivative in a single pass, letting you assign the normals one-by-one in the same code that generates your vertex positions, letting you split the work into bite-sized chunks that won't cause a stutter.

Of course, this work is what we call embarrassingly parallel, so using threads, jobs, or even GPU compute is a significantly better solution here on platforms where you can. But that's a more complicated answer I'll have to save for another time (or maybe someone else will beat me to it).

A simple threaded version can be found in the link I gave you earlier - you'll just have to defer the interaction with the `Mesh` class to the main thread after your worker thread has finished populating all the arrays for it to use.
> 1 votes

---
Tags: unity, c#, procedural-generation, optimization, mesh
---


# Question
Title: How can I cast light onto a sprite in 3D environment?
I'm making a 2.5D game, where 2D sprites are in a 3D environment. I'm using URP and I have a problem with lighting the sprites. The sprites are lighting up from behind, and not front. I tried with directional, spot and point lights but the result is the same no matter what official shader I use they only light up when they receive light from behind. Front light has no effect whatsoever on the sprites.

I spent the entire day looking for a solution but I've got almost nothing. Only solution I saw someone else mention is making the game object with the "sprite renderer" on, a child of another gameobject and rotate it 180 degrees on Y. But that is not an option for me cause I'm using custom scripts to rotate that game object already.

So can there be a custom shader? Can one be created using shadergraph maybe? I know some others have faced the same problem but did anyone really solve it?

Thanks.

# Answer
> 1 votes
Ok, this problem apparently occurs because at some point I enabled "GPU Instancing" under the materials "Advanced" options. Material is using the shader "URP/SimpleLit" with its Albedo set to the sprite texture. So if anyone else runs into this kind of lighting problem in their projects "GPU Instancing" might be why the lighting is acting weird.

---
Tags: unity, shaders
---


# Question
Title: Position/orient parent to place child at a particular position/orientation
I have a GameObject for which I know its world position and rotation.

From another app, I receive a new rotation and position, which should represent the local position and rotation of my GameObject.

How can I compute the position and rotation of the parent object knowing the (world) position, the (world) rotation, the localPosition and the localRotation of its child? How can I find the necessary transform to obtain the second pair of coordinates from the first pair of coordinates?

# Answer
> 0 votes
If you want a parent world rotation\\$P\_W\\$ that takes the child local rotation \\$C\_L\\$ to the provided child world rotation \\$C\_W\\$, we can express that as an equation:

$$C\_W = P\_W \cdot C\_L$$

Then you can simply solve for the parent rotation algebraically:

$$C\_W \cdot C\_L^{-1}= P\_W \cdot C\_L \cdot C\_L^{-1} = P\_W \cdot I = P\_W$$

So, `parent.rotation = childTargetWorldRotation * Quaternion.Inverse(child.localRotation);`

(Note that the order of the multiplication here is important - putting the inverse on the left side of the multiplication does *not* produce the same rotation, in general)

Now that we know the rotation, we can work out how that transforms the parent-to-child vector:

`Vector3 worldOffset = parent.TransformVector(child.localPosition);`

And then reverse that vector to find where to place the parent:

`parent.position = childTargetWorldPosition - worldOffset;`

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


title: AntiGravity Vehicle?

text:
# Question
Title: AntiGravity Vehicle?
I'm making a racing game akin to F-Zero and Mario Kart 8 with AG mechanics. I currently have a vehicle that is a rigidbody with normal gravity pointing down. True to AG games, I want the gravity to always be applied against the surface of the track (e.g. the player will stick to the surface of an upside-down track). I figure I have two options:

1. Shoot a raycast below the vehicle that returns the normal of the surface. Apply gravity in the direction of that normal.
2. Have several "checkpoints" that determine the direction of gravity in that area. When inside, the vehicle is affected by that new gravity.

The issue with option #1 is that it may not work if I wanted ramps or airtime. I could possibly extend the raycast down a lot further to get the normal even in the air, but that could lead to a lot of glitches. There's also the instance that there is no floor below the player. I noticed MK8 even had gliding sections in anti-gravity where you would twist in the air back to normal gravity, which leads me to believe they had something like #2. The issue with #2 however is that it may require a LOT of checkpoints to be manually placed.

I'm wondering if anyone has an idea to some simpler alternative?

# Answer
Your raycasting sensor sounds like a good baseline to build upon.

You can extend this in three ways:

* Create a layer that's visible to the player and to physics collisions, but invisible to your gravity sensor raycast. Use this layer for any objects that might distract the sensing, or that you want to deliberately exclude from consideration (small bumpy details, ramps, etc)
* Add "Gravity Hint" objects that are just the opposite: visible to your sensor raycast, but invisible to the player and other systems. Now you can bridge the "empty" sections or anywhere else the sensor needs a helping hand with hidden geometry to control exactly what it does.
* Add "Gravity Checkpoint" objects that turn off the sensor and switch your vehicle into a different mode (say, using some fixed gravity, or entering "airtime mode", or aligning to a spline they provide, or any other exotic behaviour you need), and switch the vehicle back to its default on the other side. These let you create localized exceptions to the rules, if even hiding and hinting isn't enough to make a particular section work right.

Out of the box, in a vanilla level where none of these items are in play, you get decent baseline behaviour from your raycasting solution.

By judiciously adding these extra elements where you need them, you have the ability to locally tweak and refine that behaviour to the extent that you need to, without burdening yourself with undue amounts of setup/markup just to get the "normal" sections working.
> 1 votes

---
Tags: rotation, movement
---


# Question
Title: Need help accessing booleans from other script Unity3D
I'm making an endless runner game where platforms move towards the player so it makes it seem like the player is running across them. I'm trying to make it so that when the player dies, the platforms stop moving. What I have isn't working, when the player dies, the platforms just keep moving as if nothing has happened. Here is the script I have that is attached to the player:

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

 public class CoinColliderScript : MonoBehaviour
 {
     void OnTriggerEnter(Collider target)
     {
         if (target.tag == "Enemy")
         {
         StartCoroutine(Died());
         }
     }

     IEnumerator Died()
     {
         PlatformMover.dead = true;
         gameObject.GetComponentInParent<Animator>().Play("Male Died");
         yield return new WaitForSeconds(0.5f);
         SceneManager.LoadScene("MainMenu");
     }
 }

```

Here is the script I have that is attached to the platforms:

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

public class PlatformMover : MonoBehaviour
{
    private Vector3 newPlatPos;

    public float platMoveSpeed;

    public static bool dead;

    public void Start()
    {
        dead = false;
    }

    void Update()
    {
        if (dead)
        {
            newPlatPos = new Vector3(transform.position.x, transform.position.y, transform.position.z);
        } else if (!dead)
        {
            newPlatPos = new Vector3(transform.position.x, transform.position.y, transform.position.z - platMoveSpeed);
        }
        transform.position = newPlatPos;
    }
}

```

New Code:

Attached to platforms:

```
public class PlatformMover : MonoBehaviour
{
    private Vector3 newPlatPos;

    public float platMoveSpeed;

    void Update()
    {
        if (!CoinColliderScript.Dead)
        {
            newPlatPos = new Vector3(transform.position.x, transform.position.y, transform.position.z - platMoveSpeed * Time.deltaTime);
        }
        transform.position = newPlatPos;
    }
}

```

Attach to player:

```
public class CoinColliderScript : MonoBehaviour
{
    private static bool dead = false;
    public static bool Dead
    {
        get => dead;
        set
        {
            dead = value;
            print("'Dead' changed to " + value);
        }
    }

    void OnTriggerEnter(Collider target)
    {
        if (target.tag == "Enemy")
        {
            StartCoroutine(Died());

        }
    }

    IEnumerator Died()
    {
        dead = true;
        gameObject.GetComponentInParent<Animator>().Play("Male Died");
        yield return new WaitForSeconds(0.5f);
        SceneManager.LoadScene("MainMenu");
    }
}

```

# Answer
As DMGregory observed, it seems like your root issue is that you are setting `dead` to `false` each time you spawn a platform:

```
public void Start()
{
    dead = false;
}

```

You asked

> doesn't that mean it's set to false only once at the very start?

As noted in the Unity documentation, "Start is called on the frame when a script is enabled just before any of the Update methods are called the first time." If it's not clear, that means that the `Start()` function will be called once on *each instance* of `PlatformMover` when you first instantiate or activate it.

Using public static variables like this is generally considered bad coding practice, partially because it can easily cause issues exactly such as this. There are lots of other ways to structure your code, but I don't want to get off on too much of a tangent, so I'll focus on how to improve your existing approach.

A key issue is that the `dead` variable is in the wrong place conceptually. Right now, you run this when the player dies: `PlatformMover.dead = true;` Look at that code by itself, and think about it out of context. It looks a lot like you're saying that the PlatformMover is dead. It's not at all obvious that the *player* is dead. Likewise, because the `dead` variable is in the wrong place, you're trying to initialize it in the wrong place - in the `Start()` function for `PlatformMover`.

It would make much more sense to put your dead variable in a `Player` script, so you could write `Player.dead = true;` and your platforms could check `if (!Player.dead)`

However, using a variable is still a bad idea. If you want to do something that isn't much more complicated but is still more maintainable, try this:

```
public class Player {
    private static bool dead = false;
    public static bool Dead {
        get => dead;
        set {
            dead = value;
            print("'Dead' changed to " + value);
        }
    }
}

```

Here we've created a *property* that we can use like a variable (`Player.Dead = true;`, `if (Player.Dead)`) but actually behaves like a function. This is better than using a public variable, because we can run other code when we change the value of "dead". In this case, I've added a `print()` command that will log to the console, so you can more easily keep track of when something is changing the value of `Dead`. That's probably enough to help you find and remove any other problematic code.

Some additional tips regarding your movement code:

```
 if (dead)
 {
     newPlatPos = new Vector3(transform.position.x, transform.position.y, transform.position.z);
 } else if (!dead)
 {
     newPlatPos = new Vector3(transform.position.x, transform.position.y, transform.position.z - platMoveSpeed);
 }
 transform.position = newPlatPos;

```

The first condition is completely pointless and can be removed (it effectively says `transform.position = transform.position`). The second condition can be simplified using `transform.Translate()`. You've also forgotten to factor in `Time.deltaTime` to make the movement framerate-independent. Combined with my above suggestions, it should probably look more like this:

```
if (!Player.Dead) transform.Translate(new Vector3(0, 0, -platMoveSpeed * Time.deltaTime));

```

Note that you will need to increase the value of `platMoveSpeed` (probably by multiplying it by 60) so that it looks the same when you include `Time.deltaTime`.
> 1 votes

---
Tags: unity, c#, platformer, scripting, boolean
---


# Question
Title: Player hitting bottom of tile when beside it?
So my player checks if it is colliding with tiles, and it works pretty good. However, when the player is against a wall, moving upwards and sideways, it detects it as hitting the bottom of the wall since the player checks for up and down collision first. How do I prevent this? Maybe there is another collision method I could use? Thanks in advance

Here's the collision code:

```
player.checkCollision = function (obj) {

            const top = obj.y - this.h;
            const bottom = obj.y + obj.h;

            const left = obj.x - this.w;
            const right = obj.x + obj.w;

            if (this.x > left && this.x < right) {

                if (this.y >= top && this.y - this.vel.y <= top) {

                    this.y = top;
                    this.vel.y = 0;

                    return 1;

                }
                if (this.y <= bottom && this.y - this.vel.y >= bottom) {

                    this.y = bottom;
                    this.vel.y = 0;

                    return 1;

                }

            }
            if (this.y > top && this.y < bottom) {

                if (this.x >= left && this.x - this.vel.x <= left) {

                    this.x = left;
                    this.vel.x = 0;

                    return 1;

                }
                if (this.x <= right && this.x - this.vel.x >= right) {

                    this.x = right;
                    this.vel.x = 0;

                    return 1;

                }

            }

            return 0;

        }

```

# Answer
So is the problem that when the player is moving in both directions at the same time a collision is detected and the player stops moving?

You can either redo the whole collision detection function which probably isn't a bad idea or simply try moving in each direction separately and see if that works.
> 0 votes

---
Tags: collision-detection, javascript
---