# Question
Title: How to flatten the collider for a tilemap?
I am relatively new to game development, and am working on a simple 2D platformer. I have created a tilemap and painted some tiles for the character to walk on.. but he is getting stuck. Yes, I know this is a common question and I did find some answers (including this one: Player gets stuck on edges between TilemapCollider2D tiles), but none seem relevant for me. The thing is my tiles are not flat.. they have pointy edges due to grass.. see the image below:

As you can see, the edge is not flat. I have overcome the problem of getting stuck by changing the "Edge Radius" to what you see in the above screenshot and that works, but the character now looks like he is floating slightly above the ground. Is there any way I can just tell Unity to ignore the jagged grass and make the collider flat and move the edge of it down a bit? That way it would fix the issue and also have the added bonus of looking like some of the grass is behind him and some in front..

# Answer
> 2 votes
Thanks to @DMGregory, the solution for anyone else with the same question is as follows:

* Find the sprite in your project
* Open the sprite editor from the inspector
* Edit the collider

If you don't set any collider here, it appears Unity will figure it out for you instead.. which in my case was not appropriate. I just made my collider into a box.. as follows:

and so my Scene view now appears as follows:

Additionally, I removed the **Rigidbody 2D** and the **Composite Collider 2D** and unchecked the **Used by Composite** checkbox in the **Tilemap Collider 2D**.

It now works great.

# Answer
> 0 votes
I was having a similar issue as above. DMGregory pointed out that using the custom Physics Shape and also may need to switch the Tile to Grid collision and back to Sprite again for it to load the updated collision shape.

---
Tags: unity, 2d, collision-detection, tilemap, collider
---


# Question
Title: How to make GameObject copy position of other GameObject but react to physics perfectly?
First GO moves by transform.translate (necessary).

Second GO needs to move by physics.

If I do rb.MovePosition on the 2nd GO like:

```
 private void FixedUpdate()
    {
        rb.MovePosition(targetTransform.position);
        rb.MoveRotation(targetTransform.rotation);
    }

```

then it stutters and blinks around crazily, even if I turn on Interpolate.

If I do

```
 rb.AddForce(targetTransform.transform.position - this.transform.position, ForceMode.Acceleration);

```

it moves smoothly and does interact properly physics-wise BUT orbits around the original GO's position rather than perfectly copying it.

If I do:

```
// Calculate your desired position however you like.
    Vector3 desiredPosition = targetTransform.position;

    // What velocity gets us there in one timestep?
    Vector3 desiredVelocity = (desiredPosition - transform.position) / Time.deltaTime;

    // Apply a sufficient impulse to hit reach that velocity.
    rb.AddForce(desiredVelocity - rb.velocity, ForceMode.VelocityChange);

```

then it DOES copy the original GO's position but then annoyingly clips right through other rigidbodies as if moving by transform.translate.

*What* is the perfect secret sauce to making a GO copy another GO's position, but respond to Physics properly? Namely, it needs to actually be stopped when colliding with a Rigidbody that has frozen position+rotation.

# Answer
> 1 votes
The code:

```
// Calculate your desired position however you like.
Vector3 desiredPosition = targetTransform.position;

// What velocity gets us there in one timestep?
Vector3 desiredVelocity = (desiredPosition - transform.position) / Time.deltaTime;

// Apply a sufficient impulse to hit reach that velocity.
rb.AddForce(desiredVelocity - rb.velocity, ForceMode.VelocityChange);

```

works to make one GameObject copy another GameObject's position and react to physics.

However, if the velocity is too high then it can still cause wonky physics, so in my case changing the last line to

```
rb.AddForce(   (desiredVelocity - rb.velocity)/5f , ForceMode.VelocityChange);

```

made it work with physics consistently. :)

---
Tags: unity, physics, rigidbody
---


# Question
Title: Make Minecraft Main Menu Camera movement
I intend to make exactly like this. I highly suggest you watch just 5 seconds of the video because it already explains what I intend to do. I've been trying cosine and sine on vector3s but I can't seem to make it work since I usually get these results:

This however is my **intended result**:

This is my current code:

```
public class CameraWave : MonoBehaviour
{
    [SerializeField] float speed = 1f;
    // how deep and how wide the sine waves should be
    [SerializeField] float depthXY = 2f;
    // radius of the circle
    [SerializeField] float radiusZ = 10f;
    // makes the waves on the y axis and translates it
    [SerializeField] Transform targetLookAt;
    // parent of target look at so we can move it in the z direction
    [SerializeField] Transform lookAtContainer;
    // set angle to middle
    float angle = 0.35f;
    Vector3 cameraOffset;

    void Start() { cameraOffset = targetLookAt.position; }

    void Update()
    {
        // adjust angle
        angle += Time.deltaTime * speed;
        angle %= 360;

        // make cos-sine wave
        float x = Mathf.Cos(angle) * depthXY;
        float y = Mathf.Sin(angle) * depthXY;
        // set to look at
        Vector3 position = new Vector3(x,y);
        targetLookAt.localPosition = position;

        // update container to make it go in circles
        lookAtContainer.position = MakeCircleZ(angle) + cameraOffset;
    }

    Vector3 MakeCircleZ(float angle){
        Vector3 v = Vector3.zero;
        v.x = (radiusZ * Mathf.Cos(angle));
        v.z = (radiusZ * Mathf.Sin(angle));
        return v;
    }
}

```

My hierarchy setup:

any help is appreciated

# Answer
Managed to fix it. The camera offset was creating problems with the math; hence, my camera is in an offset position. I modified the code so that it does what I want.

public class CameraWave : MonoBehaviour
{
    [SerializeField] float speed = .1f;
    // how deep and how wide the sine waves should be
    [SerializeField] float depthXY = 2f;
    // radius of the circle
    [SerializeField] float radiusZ = 10f;

    [SerializeField] float cameraBob = 1;
    // makes the waves on the y axis and translates it
    [SerializeField] Transform targetLookAt;
    // parent of target look at so we can move it in the z direction
    [SerializeField] Transform lookAtContainer;
    // set angle to middle
    float angle = 0.35f;

    Vector3 cameraOffset;
    void Start() {
        cameraOffset.y = targetLookAt.position.y;
    }
    void Update()
    {
        // adjust angle
        angle += Time.deltaTime * speed;
        angle %= 360;

        // make cos-sine wave
        float x = Mathf.Cos(angle) * depthXY;
        float y = Mathf.Sin(angle* cameraBob) * depthXY;
        // set to look at
        Vector3 position = new Vector3(x,y);
        targetLookAt.localPosition = position;

        // update container to make it go in circles
        lookAtContainer.position = MakeCircleZ(angle) + cameraOffset;
    }

    Vector3 MakeCircleZ(float angle){
        Vector3 v = Vector3.zero;
        v.x = (radiusZ * Mathf.Cos(angle));
        v.z = (radiusZ * Mathf.Sin(angle));
        return v;
    }
}
```

> 0 votes

---
Tags: unity, geometry, cinemachine
---


title: How can I highlight ui image?

text:
# Question
Title: How can I highlight ui image?
This is a screenshot showing two small images on the panel and I want that when the mouse cursor is over the image/s to highlight the current image the mouse is over.

On the right the canvas settings and the rawimages.

This script is attached to the canvas :

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

public class SavedGamesSlots : MonoBehaviour
{
    Texture2D thisTexture;
    byte[] bytes;
    string fileName;
    public GameObject[] ImageHolder = new GameObject[1];

    // Start is called before the first frame update
    void Start()
    {
        var imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
        for (int i = 0; i < imagesToLoad.Length; i++)
        {
            thisTexture = new Texture2D(100, 100);
            fileName = imagesToLoad[i];
            bytes = File.ReadAllBytes(fileName);
            thisTexture.LoadImage(bytes);
            thisTexture.name = fileName;
            ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;

        }
    }

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

    }

    public void OnHover()
    {
        Debug.Log("Enter");

    }

    public void OnHoverExit()
    {
        Debug.Log("Exit");
    }
}

```

I have two problems :

How to know what image the mouse is over now ?

How to highlight the current image the mouse is over ?

I also created Trigger Event component on each RawImage then calling this two functions OnHover and OnHoverExit :

And this is when I tried to make one of the rawimages the left one brighter changed it's color to white but still the image is too dark :

# Answer
> 1 votes
It's quite difficult to properly get the whole picture of you project without seeing on which gameobject is what script. But this is be the way I would create a system like this.

Instead of only loading the image, create a prefab with the image as a component. This gameobject will have a script which will deal with the highlighting. Also, if you overlay the RawImage with another Image, you can just change the color and alpha value of this image to highlight/grey it out.

The ImageObject.cs:

```
using UnityEngine;
using UnityEngine.UI;

public class ImageObject : MonoBehaviour {

    [SerializeField] private RawImage rawImage;
    [SerializeField] private Image overlayImage;

    private SavedGameSlots savedGameSlots;

    public void Initialize(Texture2D texture, SavedGameSlots sgs) {
        rawImage.texture = texture;
        savedGameSlots = sgs;
    }

    void OnMouseEnter() {
        ChangeOverlayImageAlpha(0f);
        savedGameSlots.SetCurrentlyHoveredImageObject(this);
    }

    void OnMouseExit() {
        ChangeOverlayImageAlpha(1f);
        savedGameSlots.SetCurrentlyHoveredImageObject(null);
    }

    private void ChangeOverlayImageAlpha(float alpha) {
        var tmpColor = overlayImage.color;
        tmpColor.a = alpha;

        overlayImage.color = tmpColor;
    }
}

```

The Prefab will be the RawImage with another another image, the overlayImage on top. Just set the references in the inspector and give it the ImageObject script as a component. Also to detect the OnMouseEnter you have to add a collider component to the prefab.

I assume you use a grid layout in your "Save Games Canvas"? In your SavedGameSlots:Start you instantiate those ImageObject-GameObjects. Insead of loading them from your resource folder, jsut give it the reference in the inspector.

SavedGamesSlots.cs:

```
public class SavedGamesSlots : MonoBehaviour
{
    public GameObject imageObjectPrefab;
    public GameObject imageObjectCanvas;

    Texture2D thisTexture;
    byte[] bytes;
    string fileName;
    public GameObject[] ImageHolder = new GameObject[1];

    private ImageObject currentlyHoveredImageObject;

    // Start is called before the first frame update
    void Start()
    {
        var imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
        for (int i = 0; i < imagesToLoad.Length; i++)
        {
            thisTexture = new Texture2D(100, 100);
            fileName = imagesToLoad[i];
            bytes = File.ReadAllBytes(fileName);
            thisTexture.LoadImage(bytes);
            thisTexture.name = fileName;
            ImageHolder[i] = Instantiate<GameObject>(imageObjectPrefab, imageObjectCanvas.transform)
            ImageHolder[i].GetComponent<ImageObject>().Initialize(thisTexture, this);
        }
    }

    public void SetCurrentyHoveredGameObject(ImageObject imageObject) {
        currentlyHoveredImageObject = imageObject;
    }
}

```

If you want to set the images in the inspector, just remove the instantiating part and set the references in the inspector:

savedGameSlots:Start():

```
// Start is called before the first frame update
void Start()
{
    var imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
    for (int i = 0; i < imagesToLoad.Length; i++)
    {
        thisTexture = new Texture2D(100, 100);
        fileName = imagesToLoad[i];
        bytes = File.ReadAllBytes(fileName);
        thisTexture.LoadImage(bytes);
        thisTexture.name = fileName;
        ImageHolder[i].GetComponent<ImageObject>().Initialize(thisTexture, this);
    }
}

```

The currentlyHoveredImageObject will be the image you're hovering. When it's null, nothing is hovered. It you don't want to handle the ImageObject as currentlyHoveredObject, you can also pass an index:

```
// Start is called before the first frame update
void Start()
{
    var imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
    for (int i = 0; i < imagesToLoad.Length; i++)
    {
        thisTexture = new Texture2D(100, 100);
        fileName = imagesToLoad[i];
        bytes = File.ReadAllBytes(fileName);
        thisTexture.LoadImage(bytes);
        thisTexture.name = fileName;
        int a = i;
        ImageHolder[i].GetComponent<ImageObject>().Initialize(thisTexture, a);
    }
}

```

Just change ImageObject:Initialize to accept an int instead of the SavedGameSlots, as well as SavedGameSlots:SetCurrentlyHoveredImage and pass the index value.

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


title: Peter Panning Depth Bias Problem

text:
# Question
Title: Peter Panning Depth Bias Problem
No matter how I experiment with RasterizerState Depth Values, I always get a detached shadow which is called peter panning. Ive even adjusted the near plane for the light camera. It always seems to stay at that certain distance. I can get it no closer.

I was wondering on some insight on what the fix could be. Below is the shader code I use when rendering the depth map which has the BIAS values.

```
   cbuffer cbPerObject
{
    float4x4 gWorldViewProj;
};

struct VertexIn
{
    float3 PosL    : POSITION;
};

struct VertexOut
{
    float4 PosH    : SV_POSITION;

};

VertexOut VS(VertexIn vin)
{
    VertexOut vout;

    vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj);

    return vout;
}
RasterizerState Depth
{

    DepthBias = 85000;
    DepthBiasClamp = 0.0f;
    SlopeScaledDepthBias = 10;
};

technique11 Light2Tex
{
    pass P0
    {
        SetVertexShader(CompileShader(vs_5_0, VS()));
        SetGeometryShader(NULL);
        SetPixelShader(NULL);

        SetRasterizerState(Depth);
    }
}

```

# Answer
> 1 votes
That is a very large depth bias value. Good values for depth bias are most likely around -2 to 2 range. However this might be different for floating point vs fixed point (UNORM) depth buffer formats. Also play around with Slope Scaled Depth bias, but only after your depth bias looks mostly right. Read more about depth bias here: https://docs.microsoft.com/en-us/windows/win32/direct3d11/d3d10-graphics-programming-guide-output-merger-stage-depth-bias

Also make sure that your viewport Z range is set up correctly. It should be Znear = 0, Zfar = 1 in most cases. If you don't set up your viewport Z range correctly, then the following issue could occur: https://stackoverflow.com/questions/17286833/can-not-find-a-proper-shadow-mapping-depth-bias

---
Tags: directx11, hlsl, shadow-mapping
---


# Question
Title: Reconciling rotations with Unity and Blender (-360,360)
I'm currently working with Oculus integration trying to export headset (and eventually controller) position and rotation data to a CSV for later use in Blender. My issue comes from the way Unity (or Blender) handles rotations. In Unity, `0 = 360`, whereas in Blender `0 != 360`.

My current solution is to grab the current rotation and subtract it from the rotation in the frame before. I then combine the difference with a running sum (Vector3 for x, y, and z sums). If any sum is greater than 360, I add a rotation to a separate Vector3 that tracks the number of complete rotations for each axis. I subtract rotations for sums less than -360. This way I can calculate the final rotation (x for example) using `360*numRots.x + xrot` to get the overall rotation.

Unfortunately my code doesn't properly store the running total correctly; it always matches the current rotation. For example, if I run the program, the current rotation might be `(270, 23, -9)` and the running total SHOULD be `(0, 0, 0)` (plus or minus some degrees) but the running total always matches the current rotation.

Code:

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

public class Mocap : MonoBehaviour
{

    public GameObject cam;
    static string path = "Assets/test.txt";
    StreamWriter writer;
    private Vector3 rotationSum; // running sums of x, y, z rotations
    private Vector3 numRots; // total number of rotations per axis
    private Vector3 prevRot; // previous rotation values

    void Start()
    {
        writer = new StreamWriter(path, append: false);
        rotationSum = new Vector3(0, 0, 0);
        numRots = new Vector3(0, 0, 0);
    }

    void Update()
    {
        // get camera pos and rot
        double xpos = cam.transform.position.x;
        double ypos = cam.transform.position.y;
        double zpos = cam.transform.position.z;
        float xrot = cam.transform.rotation.eulerAngles.x;
        float yrot = cam.transform.rotation.eulerAngles.y;
        float zrot = cam.transform.rotation.eulerAngles.z;
        Vector3 curr = new Vector3(xrot, yrot, zrot);

        Vector3 tempDiff = curr - prevRot;
        rotationSum += tempDiff;

        // check x
        if(rotationSum.x >= 360)
        {
            rotationSum.x -= 360;
            numRots.x += 1;
        } else if(rotationSum.x <= -360)
        {
            rotationSum.x += 360;
            numRots.x -= 1;
        }

        // check y
        if (rotationSum.y >= 360)
        {
            rotationSum.y -= 360;
            numRots.y += 1;
        }
        else if (rotationSum.y <= -360)
        {
            rotationSum.y += 360;
            numRots.y -= 1;
        }

        // check z
        if (rotationSum.z >= 360)
        {
            rotationSum.z -= 360;
            numRots.z += 1;
        }
        else if (rotationSum.z <= -360)
        {
            rotationSum.z += 360;
            numRots.z -= 1;
        }

        // final rotation
        xrot = 360 * numRots.x + xrot;
        yrot = 360 * numRots.y + yrot;
        zrot = 360 * numRots.z + zrot;

        // update previous values
        prevRot = curr;

        string filetext = xpos + ", " + ypos + ", " + zpos + ", " + xrot + ", " + yrot + ", " + zrot;

        this.writer.WriteLine(filetext);

    }
}

```

**EDIT** I have converted the code to use Quaternions I believe. I display in Euler angles for convenience. The next problem I'm facing is when the calculating the difference between the current and previous rotation and when the rotation jumps from 0-360 or 360-0. If `curr=5` and `prev=355`, the difference is -350 which correctly gets added to the running sum but this still acts as if I rotated through 355 down to 5 rather than looping at 360 to 0 then to 5. My current thinking to fix this is check if the difference is more than say 300. If so, that mean I either a) rotated my head 300 degrees in 1/24th second or b) I looped and should add a rotation to the axis. Advice is appreciated.

Also the reason I have to wait is because the headset rotation is set to (0,0,0) until it loads so I just wait until it doesn't equal (0,0,0).

Code:

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

public class mocapv2 : MonoBehaviour
{
    // misc objects
    public GameObject cam;
    public Text uitext;
    private bool onecheck;
    // quaternion stuff
    private Quaternion previous, sum;
    void Start()
    {
        previous = sum = Quaternion.identity;
        this.onecheck = true;
    }

    private IEnumerator waitasec()
    {
        yield return new WaitForSeconds(.1f);
    }

    void Update()
    {
        // wait for updated headset rotation
        if(this.onecheck)
        {
            this.previous = cam.transform.rotation;
            if(this.previous == Quaternion.identity)
            {
                StartCoroutine(waitasec());
            } else
            {
                this.onecheck = false;
            }
        }

        if(!this.onecheck)
        {
            Quaternion curr = cam.transform.rotation;
            Quaternion difference = curr * Quaternion.Inverse(this.previous);
            this.sum *= difference;
            string text = "curr:" + curr.eulerAngles + "\ndiff:" + difference.eulerAngles + "\nprev:" + this.previous.eulerAngles + "\nsum:" + this.sum.eulerAngles;
            uitext.text = text;
            this.previous = curr;
        }
    }
}
```

# Answer
Holding onto a running total isn't going to work because floating-point doesn't have the level of accuracy to maintain an exact value over time. If you can output quaternions and work with that in Blender that would be ideal. If not extract the Euler angles from the current quaternion value: camera.transform.rotation.euler.
> 0 votes

---
Tags: unity, blender, oculus
---


# Question
Title: Export "Lite" and "Full" versions with different package names for Google Play Console
On the Google Play Console, you can't have two games with the same package name.

Is there a way to have two of the same game with different package names, exported from the same Unity project? For example, a "lite version" with ads and a "full version" without ads.

# Answer
To change the Package Name for an Android project, go to Edit \> Project Settings \> Player \> Other Settings and change the "Package Name". See https://docs.unity3d.com/Manual/class-PlayerSettingsAndroid.html#Other

If you want to partially automate this, you can use Editor scripts, e.g:

```
[MenuItem("MyGame/Switch to Full version" )]
private static void FullVersion() {
    //I am not 100% certain that "applicationIdentifier" is the correct property, but I think it is.
    PlayerSettings.applicationIdentifier = "com.mycompany.mygame";
    PlayerSettings.productName = "My Game";
    PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, "FULL_VERSION");
}

[MenuItem("MyGame/Switch to Lite version" )]
private static void LiteVersion() {
    PlayerSettings.applicationIdentifier = "com.mycompany.mygamelite";
    PlayerSettings.productName = "My Game Lite";
    PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, "LITE_VERSION");
}

```

Depending on your game structure, you may also need to change which scenes are included in your build. I won't get into that here.

The scripting define symbols let you add conditional compilation to your code, e.g.

public class MainMenu : MonoBehaviour {
    void Start() {
#if LITE_VERSION
        LoadAds();
#elif FULL_VERSION
        CheckDailyRewards();
#endif
    }

#if LITE_VERSION
    void LoadAds() {
        //load ads here
    }
#endif

#if FULL_VERSION
    void CheckDailyRewards() {
        //check rewards here
    }
#endif
}
```

> 1 votes

---
Tags: unity, google-play, build-process
---


# Question
Title: Cylindrical billboarding around an arbitrary axis in geometry shader
I found an answer on this site relating to this question already, but it doesn't seem applicable in the context of my project.

Basically I'd like to create a method which fits this signature:

```
float3x3 AxisBillboard(float3 source, float3 target, float3 axis)

```

That is to say, when given a source point (i.e an object's position in world space), a target (camera position in world space), and an axis (the object's up vector, which is not necessarily the global y axis), it produces a 3x3 rotation matrix by which I can multiply the vertices of my point so that it's properly rotated.

I've found many solutions and tutorials online which work nicely assuming I only want to rotate around the y axis.

For example, here's a solution which billboards around the global y axis:

```
float3 dir = normalize(target - source);

float angleY = atan2(dir.x, dir.z);
c = cos(angleY);
s = sin(angleY);

float3x3 rotYMatrix;
rotYMatrix[0].xyz = float3(c, 0, s);
rotYMatrix[1].xyz = float3(0, 1, 0);
rotYMatrix[2].xyz = float3(-s, 0, c);

```

For context, I'm working on a grass shader, and each individual blade of grass should be billboarded to face the camera while remaining aligned with the normal of the terrain.

edit:

Thanks to @DMGregory I'm using his matrix method in the following way:

```
float3 viewDir = normalize(vertexPosition); // camera is at (0, 0, 0)
float3x3 billboardMatrix = transpose(AxisBillboard(worldUp, viewDir));
float3 worldPosition = vertexPosition + mul(billboardMatrix, localPosition);

```

This works correctly when grass is rotated to align with world space. In other rotations, grass is still billboarding 'correctly' around its local y axis but also has another rotation applied. Any ideas?

# Answer
> 1 votes
This isn't as hard as it might seem.

We can simplify two of your arguments to one:

```
float3 viewDirection = target - source;

```

Then our strategy will be to cross the vertical axis and view direction to get a vector perpendicular to both (the right/sideways direction).

Next, we cross this with our vertical axis to complete the basis.

A rotation matrix is just a unit vector in each basis direction, so we can assign our vectors directly to the rows/columns of our matrix.

```
float3x3 AxisBillboard(float3 upAxis, float3 viewDirection) {
    float3 rightAxis = normalize(cross(upAxis, viewDirection));
    float3 forwardAxis = cross(rightAxis, upAxis);

    float3x3 result;
    result[0].xyz = rightAxis;
    result[1].xyz = upAxis;
    result[2].xyz = forwardAxis;

    return transpose(result);
}

```

---
Tags: mathematics, shaders, matrix, billboarding
---


# Question
Title: How to construct a propeller clock in Unity?
I am considering the possibility of using Unity to construct a propeller clock like this one (also called a persistence of vision or POV display).

It's an array of LEDs on a PCB board connected to motor that spins at a high RPM. The LEDS flash on and off such that it generates the appearance of a clock face.

So far, I've tried turning a red pointer in a circular path with high RPM in Unity, but I don't get an image of a circular red disc. Instead I see a pointer showing random discrete movement in a circular path.

Is there any suggestion to rectify this issue?

# Answer
> 5 votes
Here's an example of how we can mimic this appearance in a Unity scene:

My strategy is:

1. First, compose the image that the POV display is *trying* to project.
2. Render that image, with a shader filter that adds artifacts that look like a POV display.

On the left is step 1. I've positioned some sprites representing my clock face and hands. That way it's easy to update the displayed image: I can just rotate the game objects representing the hands.

I created a new RenderTexture in my assets folder, called "Clock Face". Because the POV display is quite low-res, you can get away with a tiny texture here.

Next I made a Camera that looks at these sprites, and outputs the combined image to the RenderTexture. You can put the sprites in a layer that only that camera sees, so they're invisible to your main scene camera.

Lastly I made a quad to display the POV version. I gave that quad a new material, with a custom shader, using the RenderTexture as its Main Texture input.

Here's the shader I cooked up:

```
Shader "Unlit/POVDisplay"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        // Render with transparent objects, after the opaque pass.
        Tags { "RenderType"="Transparent" "Queue"="Transparent"}
        LOD 100

        // Don't write to the depth buffer.
        ZWrite Off
        // Additive blending (add light/glow).
        Blend One One

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                // Shift our texture coordinates so 0 is in the center,
                // and we go to -1 ... +1 at the edges.
                o.uv = (v.uv - 0.5f) * 2.0f;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // Vary this parameter to control how many rings of light you get.
                const float ledCount = 32;

                // Simulate the strip of LEDs spinning around very fast.
                float headAngle = _Time.y * 7.0f;

                // Compute the angle of the pixel we're rendering.
                float angle = atan2(i.uv.y, i.uv.x);

                // Compute how recently we've been illuminated.
                // 0 = head is about to reach us (1 full cycle behind).
                // 1 = head just reached us.
                float difference = frac(headAngle + angle / (2.0f * 3.141592653589f));

                // The approaching LED head shines light on the faded parts nearby,
                // so brighten them back up to 1.
                if (difference < 0.1f)
                    difference = 1.0f - 9.0f * difference;

                // Small timing errors make the display seem to twist/wobble,
                // so we'll distort our angle a bit to mimic this.
                angle += 0.01f * sin(_Time.y * 2.0f + difference * 1.0f);

                // Compute our radius in "LED space"
                float radius = length(i.uv) * ledCount;

                // Round to the nearest LED.
                float rounded = round(radius);

                // Compute a sample point in our texture, using our distorted angle
                // and rounded radius.
                float2 samplePoint = float2(cos(angle), sin(angle))*rounded/ledCount;

                // Sample the RenderTexture at this position.
                fixed4 col = tex2D(_MainTex, samplePoint / (2.0f) + 0.5f);
                // Square the colour to increase saturation, like a pure LED light.
                col *= col;

                // The center of the LED is brighter. Fade it in the gaps between rings.
                float brightness = (radius - rounded) * 2.0f;
                brightness = 1.0f - brightness * brightness;

                // Brighten/darken the colour based on proximity to the ring,
                // and lag behind the spinning head.
                return col * brightness * lerp(9.0f, 1.0f, difference);
            }
            ENDCG
        }
    }
}

```

If we scale down our `_Time.y` input, we can see what this looks like in slow-mo:

Advancing our virtual "LED Head" faster than the display framerate makes the brightest part of the sweep jump around almost randomly, giving that distinctive flickering appearance.

---
Tags: unity, c#, graphic-effects
---


# Question
Title: Best practice where to store Projectile Damage amounts?
I have a projectile and an enemy, both with colliders. On the projectile script, I'm destroying the projectile OnTriggerEnter:

```
public class bulletBehavior : MonoBehaviour
{
    private Rigidbody rb;
    public float smallGunSpeed = 500f;

    void Start()
    {
        rb = this.GetComponent<Rigidbody>();
        rb.AddForce(transform.forward * smallGunSpeed);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Enemy")
        {
            Destroy(this.gameObject);
        }
    }
}

```

On the Enemy Script I'm handling the health and the damage from the different projectiles using tags. Is this the right way to do it? I would much rather attach the damage amount to the projectile but I'm not sure how to "Transfer" the damage value to the NPC script from the projectile script? Storing them on the NPC script seems incredibly inefficient.

public class NPCscript : MonoBehaviour
{
    public int maxHealth = 300;
    public int currentHealth;
    public HealthBar healthBar;
    private GameObject enemy;

    void Start()
    {
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);

        StartCoroutine(AutoHeal());
    }

    void Update()
    {
        if (currentHealth <= 0)
        {
            Destroy(this.gameObject);
        }
    }

    void TakeDamage(int damage)
    {
        currentHealth -= damage;
        healthBar.SetHealth(currentHealth);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Bullet")
        {
            TakeDamage(10);
        }
        else if (other.tag == "Grenade")
        {
            TakeDamage(75);
        }
    }
}
```
</code></pre>

# Answer
> 0 votes
That "NPC script" looks like it's all about managing health and damage. I'd be tempted to call it a `Health` component instead. The NPC's behaviour can live in another component, that can talk to the `Health` component when it needs to check its HP.

By separating the concept of having health and taking damage from being an NPC, you can re-use the same component on damageable player character or destructible objects too.

Then your projectile can look like this - owning its own damage and the dealing of it:

```
public class bulletBehavior : MonoBehaviour
{
    private Rigidbody rb;
    public int damageAmount = 10;
    public float smallGunSpeed = 500f;

    void Start()
    {
        rb = this.GetComponent<Rigidbody>();
        // If you're going to call it "speed" then apply it as a speed
        // in meters per second, not a force in Newtons.
        rb.AddForce(transform.forward * smallGunSpeed, ForceMode.VelocityChange);
    }

    private void OnTriggerEnter(Collider other)
    {
        // Check if we hit something we can damage.
        if (other.TryGetComponent(out Health health)) {
            // If so, damage it and destroy ourselves!
            health.TakeDamage(damageAmount);
            Destroy (gameObject);
        }

        // Depending on your game, you might also want to
        // destroy the projectile if you hit an indestructible wall.
    }
}

```

Now the projectile knows about the `Health` component and damage-taking (kind of unavoidable - dealing damage is a projectile's whole job), but things that have `Health` don't need to know about all the (possibly many) things that can deal damage. We've simplified that relationship to just the simple contract of the `TakeDamage` method, (ie. "I'll tell you how much damage to take")

Your `Health` component doesn't need a trigger/collision callback method at all, since these other scripts will just call its public methods when they need it to do something.

This way, we can easily add lots of different things that have health, and lots of different things that deal damage, without our trigger methods becoming a giant mess of different tag checks.

# Answer
> 0 votes
Hey welcome to the game dev stack exchange. Don't worry about being new to Unity what you want to do is pretty simple and straight forward, plus you are almost ready doing it with "smallGunSpeed".

```
public class bulletBehavior : MonoBehaviour
{
    private Rigidbody rb;
    public float smallGunSpeed = 500f;
    public float damage = 10.0f;

    void Start()
    {
        rb = this.GetComponent<Rigidbody>();
        rb.AddForce(transform.forward * smallGunSpeed);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Enemy")
        {
            Destroy(this.gameObject);
        }
    }
}

public class NPCscript : MonoBehaviour
{
    public int maxHealth = 300;
    public int currentHealth;
    public HealthBar healthBar;
    private GameObject enemy;

    void Start()
    {
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);

        StartCoroutine(AutoHeal());
    }

    void Update()
    {
        if (currentHealth <= 0)
        {
            Destroy(this.gameObject);
        }
    }

    void TakeDamage(int damage)
    {
        currentHealth -= damage;
        healthBar.SetHealth(currentHealth);
    }

    private void OnTriggerEnter(Collider other)
    {
        bulletBehaviour bulletScript = other.transform.GetComponent<bulletBehaviour>();
        if (bulletBehaviour != null)
        {
            TakeDamage(bulletBehaviour.damage);
        }
    }
}

```

Just a heads up (and I learned this today) it is recommended that most simple questions like this are best asked in the chat room for faster support (you may even get some additional tips). But there really is no harm posting a question either.

---
Tags: unity, c#, software-engineering, projectile
---


# Question
Title: Networking to make a single player RPG into multiplayer
I’ve written a few games in Xcode before and would like to turn one into the simplest possible 2D top-down RPG multiplayer game. Essentially just needing movements around a big tiled map (I love drawing), and chat.

Keen to just host my own server on the iMac I use, with python and twisted framework (new to this but happy to take the time to learn). I’m thinking TCP for chat and UDP for tracking movements but do they need to be on separate servers?

Also for games like this I know there isn’t much on the client side. All my map drawing and game logic is set up in Xcode, which I would prefer to keep working in because I’m familiar with the language and love the sprite kits and tile maps. Do I have to redo it all in python on the server side for scaling in the future? Or for cross platform?

I've done lots of research and found plenty of tutorials, just want to know I’m on the right track. I’m not looking to make a WoW killer just something simple I can gradually build on for fun

# Answer
> I’m thinking TCP for chat and UDP for tracking movements but do they need to be on separate servers?

No, they don't need to be on separate servers. *Although separate servers has its own advantages.* By the way, when I say server, I mean the process, not the machine. Servers could be on the same machine, or different machines.

---

> Do I have to redo it all in python on the server side for scaling in the future? Or for cross platform?

Design an application protocol on top of UDP, TCP, both, whatever… As long you implement that protocol, the language you use matters little. In fact, the server and the client could be implemented in different languages. With that said, I would encourage to use a languages and platform with good threading support. There are plenty of option, even cross platform options.

Furthermore, client and server might not be monolithic. For example, you can write them as applications in one language, and use libraries written in another language. *And for the library anything that can expose a C interface is fair game.*

Perhaps your initial instinct is to have your application in your preferred language, and then the network code will be a library it calls. However, let me tell you, it can be the other way around. Have the main application do the networking and call into a library in your preferred language that handles the rest (UI et.al. on the client, and game logic on the server). In fact, the client can be one way and the server the other.

The network is a big scary thing in the middle of your architecture. And deciding how to deal with that can shift your entire architecture. Reason why it is common advice to decide early if you will have networking in your game/engine.

---

I usually suggest to start with TCP (or some other protocol or solution that guarantees reliability), and to start with a chat-like proof of concept. If you can send strings, you can send anything (to be clear, I'm not suggesting to have a human readable string encoding for everything).

However, move to UDP (or similar), so you can have control over the reliability model (either because you roll your own, or by using a third party solution).

As per networking framework, avoid those that:

* Do not give you reliability options.
* Do not support threading.

---

Now, let us say you want to take your existing code and somehow shoehorn networking into it. Start by figuring out what parts need to be on the server, and what parts on the client.

As, you know, the server should not be doing the game UI (if the server has some UI at all, it is to control the server). Thus, the code to draw the map, characters, and so on does not need to exist on the server. But there will be a logic representation of those in the memory of the server.

For the architecture of the client, in preparation of moving to a networking solution, you want to isolate anything that should run on the server. *You will likely want the server to run physics, for example.* That isolated component should not depend on implementation details of the rest of the client to work. And you want to put it behind some form of asynchronous interface.

Then, move that code to a library. Use the library in the server. As long as the server can call into that library, it does not matter if the library and the rest of the server are written in different languages. You would only be forced to recreate that code in a different language for the server, if you cannot create such library.

Once the server has that code, replace the code in the client to connect to the server instead of using the library.

Note: The client can call into the library. But should not be able to get a result synchronously. Furthermore, the library cannot call code on the rest of the client, because that requires knowledge of it. Instead, have a function that the client can call to get any results since the last time it was called. Make calling that part of your game loop equivalent. Once it is not calling into the library, but into the network, that same function will return any network messages since the last time it was called. *It might be possible to build a callback dispatch solution, but it does not always make sense.*
> 1 votes

---
Tags: multiplayer, python, mmo, server, xcode
---


# Question
Title: How I add gap between Instantiated objects?
```
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class SavedGamesSlots : MonoBehaviour
{
    public GameObject saveSlotPrefab;
    public float gap;

    private Transform slots;
    private string[] imagesToLoad;

    // Start is called before the first frame update
    void Start()
    {
        imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
        slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

        for (int i = 0; i < imagesToLoad.Length; i++)
        {
            var go = Instantiate(saveSlotPrefab);
            go.transform.SetParent(slots);

            Texture2D thisTexture = new Texture2D(100, 100); //NOW INSIDE THE FOR LOOP
            string fileName = imagesToLoad[i];
            byte[] bytes = File.ReadAllBytes(fileName);
            thisTexture.LoadImage(bytes);
            thisTexture.name = fileName;
            GameObject ChildGameObject = go.transform.GetChild(1).gameObject;
            ChildGameObject.GetComponent<RawImage>().texture = thisTexture;
            var raw = go.GetComponent<RectTransform>();
            raw.anchoredPosition = new Vector3(1 + 1 * gap, 6, 0);

        }
    }

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

    }
}

```

The way I'm doing it now is not working it's moving all the objects to the same position and not adding equal gap's between them.

In the loop I tried to do it this way in this line :

```
raw.anchoredPosition = new Vector3(1 + 1 * gap, 6, 0);

```

# Answer
> 1 votes
You need to multiply your gap value by the i of your loop. Right now, `1 + gap` is a constant value, whereas `i * gap` will increase when i increase. If you want to offset your objects, add some constant like `c + i * gap` and if you want to increase the gap, well increase your `gap` variable.

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


# Question
Title: Swept AABB: finding collision normal in 3D?
I was following this tutorial which explains how to detect and resolve a 2d swept aabb collisions. I got the detection part working on 3d, but know I need a way to properly make a response, like sliding on the face because right now my player just get stuck on the wall. To do that, I need the surface normal, but I couldn't correctly translate the normal calculation in the tutorial from 2d to 3d. Here is the code, written in Java, but you can always check the tutorial:

```
private float sweptAABB(Vector3f velocity, float x, float y, float z, float minTime){
    // find the distance between the objects on the near and far sides for both x, y and z
    // and find time of collision and time of leaving for each axis
    if (velocity.x > 0.0f) {
        invEntry.x = x - maxI.x;
        entry.x = invEntry.x / velocity.x;
        invExit.x = x + 1 - minI.x;
        exit.x = invExit.x / velocity.x;
    } else if (velocity.x < 0.0f){
        invEntry.x = x + 1 - minI.x;
        entry.x = invEntry.x / velocity.x;
        invExit.x = x - maxI.x;
        exit.x = invExit.x / velocity.x;
    } else {
        invEntry.x = x + 1 - minI.x;
        invExit.x = x - maxI.x;
        entry.x = -Float.MAX_VALUE;
        exit.x = Float.MAX_VALUE;
    }

    if (velocity.y > 0.0f) {
        invEntry.y = y - maxI.y;
        entry.y = invEntry.y / velocity.y;
        invExit.y = y + 1 - minI.y;
        exit.y = invExit.y / velocity.y;
    } else if (velocity.y < 0.0f){
        invEntry.y = y + 1 - minI.y;
        entry.y = invEntry.y / velocity.y;
        invExit.y = y - maxI.y;
        exit.y = invExit.y / velocity.y;
    } else {
        invEntry.y = y + 1 - minI.y;
        invExit.y = y - maxI.y;
        entry.y = -Float.MAX_VALUE;
        exit.y = Float.MAX_VALUE;
    }

    if (velocity.z > 0.0f) {
        invEntry.z = z - maxI.z;
        entry.z = invEntry.z / velocity.z;
        invExit.z = z + 1 - minI.z;
        exit.z = invExit.z / velocity.z;
    } else if (velocity.z < 0.0f){
        invEntry.z = z + 1 - minI.z;
        entry.z = invEntry.z / velocity.z;
        invExit.z = z - maxI.z;
        exit.z = invExit.z / velocity.z;
    } else {
        invEntry.z = z + 1 - minI.z;
        invExit.z = z - maxI.z;
        entry.z = -Float.MAX_VALUE;
        exit.z = Float.MAX_VALUE;
    }
    // find the earliest/latest times of collision
    if (entry.y > 1.0f) entry.y = -Float.MAX_VALUE;
    if (entry.x > 1.0f) entry.x = -Float.MAX_VALUE;
    if (entry.z > 1.0f) entry.z = -Float.MAX_VALUE;

    float entryTime = Math.max(Math.max(entry.x,entry.z),entry.y);

    if(entryTime >= minTime) return 1.0f;

    float exitTime = Math.min(Math.min(exit.x,exit.z),exit.y);

    if(entry.x < 0.0f && entry.y < 0.0f && entry.z < 0.0f) // equals to entryTime < 0.0f
        return 1.0f;

    if (entryTime > exitTime) return 1.0f;

    if(entry.x > 1.0f) {
        if(max.x < x || min.x > x + 1)
            return 1.0f;
    }

    if(entry.y > 1.0f){
        if(max.y < y || min.y > y + 1)
            return 1.0f;
    }

    if(entry.z > 1.0f){
        if(max.z < z || min.z > z + 1)
            return 1.0f;
    }
    return entryTime;

```

Basically, in the tutorial, to get normals, they do a test on the entry values, here is how I tried to translate this to 3d:

```
if (entry.x > entry.y) {
        if(entry.x > entry.z){
            if (invEntry.x < 0.0f)
                normal.x = 1.0f;
            else
                normal.x = -1.0f;

            normal.y = 0.0f;
            normal.z = 0.0f;
        }else{
            if (invEntry.z < 0.0f)
                normal.z = 1.0f;
            else
                normal.z = -1.0f;

            normal.x = 0.0f;
            normal.y = 0.0f;
        }
    } else {
        if (entry.y > entry.z) {
            if (invEntry.y < 0.0f)
                normal.y = 1.0f;
            else
                normal.y = -1.0f;

            normal.x = 0.0f;
            normal.z = 0.0f;

        } else {
            if (invEntry.z < 0.0f)
                normal.z = 1.0f;
            else
                normal.z = -1.0f;

            normal.x = 0.0f;
            normal.y = 0.0f;
        }
    }

```

I'm getting correct directions, but the values are always negative and I have trouble picturing the maths behind the normal testing. My question is: how can I correctly calculate the normals based on the code from the tutorial?

Thanks!

# Answer
> 1 votes
Based on what @DMGregory proposed in the comments, here is the simplified and working code to calculate the normals:

```
if (entry.x > entry.y) {
            if(entry.x > entry.z){
                normal.x = -Maths.sign(velocity.x);
                normal.y = 0.0f;
                normal.z = 0.0f;
            }else{
                normal.z = -Maths.sign(velocity.z);
                normal.x = 0.0f;
                normal.y = 0.0f;
            }
        } else {
            if (entry.y > entry.z) {
                normal.y = -Maths.sign(velocity.y);
                normal.x = 0.0f;
                normal.z = 0.0f;

            } else {
                normal.z = -Maths.sign(velocity.z);
                normal.x = 0.0f;
                normal.y = 0.0f;
            }
        }

```

With `Maths.sign(int a){ return a >= 0 ? 1 : -1; }`

---
Tags: java, collision-detection, 3d, collision-resolution, aabb
---


title: Unity Tilemaps Best practices

text:
# Question
Title: Unity Tilemaps Best practices
I'm pretty new to Unity and I just finished some courses and tutorial found in the official documentation. I'm now in the process to apply what I learned so far using different assets from the ones provided with the tutorial, to see if I understood all the material.

I'm trying to build a simple top-down game with some free asset I found online. My tile palette is composed, among others, of tiles like these:

Now, in order to create something like this:

\[sorry for the quality, I recreated it in gimp since I'm not on the computer where I have Unity now\]

I had to create three Tilemaps under the same Grid. The botton tilemap contains the grass (sort order -2), the middle one contains the fence (sort order -1) and the top one contains the house (sort order 0).

My first question is: given the tileset I have, is this the most efficient way to obtain what I needed?

After having solved this problem I wanted to add a collider to the fence and to the house, but since they are on two different tilemaps I cannot use a composite collider to optimize the collider's layout. Is there another way to do this in a more efficient way? Instead of using tiles for "interactable objects", should I use "proper" game objects instead?

# Answer
> given the tileset I have, is this the most efficient way to obtain what I needed?

Yes, stacking multiple layers of tilemaps is a tried-and-true method which is being used since the 16bit age.

> But since they are on two different tilemaps I cannot use a composite collider to optimize the collider's layout.

That's incorrect. You can merge the TilemapCollider2D of multiple tilemaps into one CompositeCollider2D when you make both tilemaps children of the same Rigidbody2D and put the CompositeCollider2D component on that mutual parent. Just remember to enable "Used by Composite" on both TilemapCollider2D's.

But note that perhaps not all layers *should* have colliders. It's not uncommon to have one or more foreground-layers without collision. That allows the player to walk behind roofs or trees.

The object hierarchy would then look like this:

```
Grid [Grid, Rigidbody2D, CompositeCollider2D]
      Tilemap_Floor [Tilemap, TilemapRenderer, TilemapCollider2D]
      Tilemap_Objects [Tilemap, TilemapRenderer, TilemapCollider2D]
      Tilemap_Foreground [Tilemap, TilemapRenderer]

```
> 3 votes

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


title: Mesh contents get flipped

text:
# Question
Title: Mesh contents get flipped
I am using below shader with my mesh object that is showing a webpage. It is showing fine but the problem is the web page has flipped:

```
 Shader "UI/Default_OverlayNoZTest"
 {
     Properties
     {
         [PerRendererData] _MainTex ("Sprite 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
     }

     SubShader
     {
         Tags
         {
             "Queue"="Overlay"
             "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 Off
         Blend SrcAlpha OneMinusSrcAlpha
         ColorMask [_ColorMask]

         Pass
         {
         CGPROGRAM
             #pragma vertex vert
             #pragma fragment frag
             #include "UnityCG.cginc"

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

             struct v2f
             {
                 float4 vertex   : SV_POSITION;
                 fixed4 color    : COLOR;
                 half2 texcoord  : TEXCOORD0;
             };

             fixed4 _Color;

             v2f vert(appdata_t IN)
             {
                 v2f OUT;
                 OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
                 OUT.texcoord = IN.texcoord;
 #ifdef UNITY_HALF_TEXEL_OFFSET
                 OUT.vertex.xy += (_ScreenParams.zw-1.0)*float2(-1,1);
 #endif
                 OUT.color = IN.color * _Color;
                 return OUT;
             }

             sampler2D _MainTex;

             fixed4 frag(v2f IN) : SV_Target
             {
                 half4 color = tex2D(_MainTex, IN.texcoord) * IN.color;
                 clip (color.a - 0.01);
                 return color;
             }
         ENDCG
         }
     }
 }

```

I am using above shader so that the mesh should be shown on top of everyting.

# Answer
You can add a single line to your vertex shader to invert the texture coordinates.

```
v2f vert(appdata_t IN)
{
     v2f OUT;
     OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
     OUT.texcoord = IN.texcoord;
#ifdef UNITY_HALF_TEXEL_OFFSET
     OUT.vertex.xy += (_ScreenParams.zw-1.0)*float2(-1,1);
#endif

     // Invert the x coordinate to mirror the texture left/right.
     OUT.texcoord.x = 1.0f - OUT.texcoord.x;

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

```

Here I've shown it mirroring on the x. You can use y instead to flip the texture top-to-bottom.
> 0 votes

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


# Question
Title: How can I start a new row when instantiating UI elements in a grid?
```
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class SavedGamesSlots : MonoBehaviour
{
    public GameObject saveSlotPrefab;
    public float gap;

    private Transform slots;
    private string[] imagesToLoad;

    // Start is called before the first frame update
    void Start()
    {
        int counter = 0;

        imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
        //slots = GameObject.Find("Slots").transform;
        slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

        for (int i = 0; i < imagesToLoad.Length; i++)
        {
            var go = Instantiate(saveSlotPrefab);
            go.transform.SetParent(slots);

            Texture2D thisTexture = new Texture2D(100, 100); //NOW INSIDE THE FOR LOOP
            string fileName = imagesToLoad[i];
            byte[] bytes = File.ReadAllBytes(fileName);
            thisTexture.LoadImage(bytes);
            thisTexture.name = fileName;
            GameObject ChildGameObject = go.transform.GetChild(1).gameObject;
            ChildGameObject.GetComponent<RawImage>().texture = thisTexture;
            var raw = go.GetComponent<RectTransform>();

            if (counter == 3)
            {
                raw.anchoredPosition = new Vector3(1 , 0.3f, 0);
                counter = 0;
            }
            else
            {
                raw.anchoredPosition = new Vector3(1 + counter * gap, 6, 0);
            }

            counter++;
        }
    }

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

    }
}

```

Now it's creating a line of 3 objects but then when it's filled with 3 objects in a line I want it to move one step down and start a new line of 3 and so on.

The problem is I can't make it automatic move one step down with the right gap on the Y and start a new line.

I'm doing the new line with this :

```
raw.anchoredPosition = new Vector3(1 , 0.3f, 0);

```

but the result is that the fourth object is too much down :

And it should be like this :

# Answer
> 1 votes
As DMGregory said in a comment: You don't need to write your own code to calculate and set positions of layout elements in this situation. You almost never need to do that with the Unity UI system. You can leave that job to the auto layout system.

In this case the Grid Layout Group seems to be the layouting component of choice. You just set a cell size, and then add child-objects to it. It will arrange its children in cells of the size you picked, and start a new row when it runs out of horizontal space. It even adapts to the screen resolution and uses more or less columns depending on how many pixels it has.

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


title: Creating Sphere Triangles from Vertices

text:
# Question
Title: Creating Sphere Triangles from Vertices
I came across a way to create the vertices of a sphere, located here: https://gamedev.stackexchange.com/a/150293/62793

I converted this to the following C# example:

```
public static GraphicsMesh GenerateSphere(Device device, int numLatitudeLines, int numLongitudeLines, int radius)
        {
            // One vertex at every latitude-longitude intersection,
            // plus one for the north pole and one for the south.
            // One meridian serves as a UV seam, so we double the vertices there.
            int numVertices = (numLatitudeLines * (numLongitudeLines + 1)) + 2;

            Vector3[] positions = new Vector3[numVertices];
            Vector2[] texcoords = new Vector2[numVertices];

            // North pole.
            positions[0] = new Vector3(0, radius, 0);
            texcoords[0] = new Vector2(0, 1);

            // South pole.
            positions[numVertices - 1] = new Vector3(0, -radius, 0);
            texcoords[numVertices - 1] = new Vector2(0, 0);

            // +1.0f because there's a gap between the poles and the first parallel.
            float latitudeSpacing = 1.0f / (numLatitudeLines + 1.0f);
            float longitudeSpacing = 1.0f / numLongitudeLines;

            // start writing new vertices at position 1
            int v = 1;
            for (int latitude = 0; latitude < numLatitudeLines; latitude++)
            {
                for (int longitude = 0; longitude <= numLongitudeLines; longitude++)
                {

                    // Scale coordinates into the 0...1 texture coordinate range,
                    // with north at the top (y = 1).
                    texcoords[v] = new Vector2(
                                      longitude * longitudeSpacing,
                                      1.0f - ((latitude + 1) * latitudeSpacing)
                                   );

                    // Convert to spherical coordinates:
                    // theta is a longitude angle (around the equator) in radians.
                    // phi is a latitude angle (north or south of the equator).
                    float theta = (float)(texcoords[v].X * 2.0f * Math.PI);
                    float phi = (float)((texcoords[v].Y - 0.5f) * Math.PI);

                    // This determines the radius of the ring of this line of latitude.
                    // It's widest at the equator, and narrows as phi increases/decreases.
                    float c = (float)Math.Cos(phi);

                    // Usual formula for a vector in spherical coordinates.
                    // You can exchange x & z to wind the opposite way around the sphere.
                    positions[v] = new Vector3(
                        (float)(c * Math.Cos(theta)),
                        (float)Math.Sin(phi),
                        (float)(c * Math.Sin(theta))
                      ) * radius;

                    // Proceed to the next vertex.
                    v++;
                }
            }
            //Converting it to a Vertex
           Vertex[] vertices = new Vertex[positions.Length];
            for (int i = 0; i < positions.Length; i++)
            {
                vertices[i] = new Vertex(positions[i]);
            }
            return new GraphicsMesh(device, vertices);
        }

```

And it does indeed create all the vertices of a sphere; here's a picture:

My question now, is how do I take those vertices, and create triangles out of them? Or in other words, how do I link said vertices together to form triangle faces?

# Answer
> 1 votes
First up, our triangle count is...

```
 int numTriangles = numLatitudeLines * numLongitudeLines * 2;

```

(That's a middle section of `(numLatitudeLines - 1) * numLongitudeLines` quads, doubled to two triangles each, and a row of `numLongitudeLines` triangles around each pole)

Triple that to get our ultimate count of vertex copies:

```
Vertex[] vertices = new Vertex[numTriangles * 3];

```

Now we can fill this in row by row. The first row of triangles all start at position 0 (the north pole), and connect two consecutive vertex positions from the top latitude line:

```
int v = 0;

for (int i = 0; i < numLongitudeLines; i++) {
    vertices[v++] = new Vertex(positions[0]);
    vertices[v++] = new Vertex(positions[i + 2]);
    vertices[v++] = new Vertex(positions[i + 1]);
}

```

I'm not quite sure what coordinate system you're using, so you might need to exchange the order of two of those lines to flip the winding of the triangle to ensure it faces outward. The same trick works for the other triangle triplets below.

Next, we can connect up the large rectangular section in the middle, by iterating over each row and column.

```
// Each row has one more unique vertex than there are lines of longitude,
// since we double a vertex at the texture seam.
int rowLength = numLongitudeLines +1;

for (int latitude = 0; latitude < numLatitudeLines - 1; latitude++) {
    // Plus one for the pole.
    int rowStart = latitude * rowLength + 1;
    for (int longitude = 0; longitude < numLongitudeLines; longitude++) {
        int firstCorner = rowStart + longitude;

        // First triangle of quad: Top-Left, Bottom-Left, Bottom-Right
        vertices[v++] = new Vertex(positions[firstCorner);
        vertices[v++] = new Vertex(positions[firstCorner + rowLength + 1]);
        vertices[v++] = new Vertex(positions[firstCorner + rowLength]);

        // Second triangle of quad: Top-Left, Bottom-Right, Top-Right
        vertices[v++] = new Vertex(positions[firstCorner);
        vertices[v++] = new Vertex(positions[firstCorner + 1]);
        vertices[v++] = new Vertex(positions[firstCorner + rowLength + 1]);
    }
}

```

And then we finish off with the same loop as we started, but this time for the south pole.

```
int pole = positions.Length - 1;
int bottomRow = (numLatitudeLines - 1) * rowLength + 1;

for (int i = 0; i < numLongitudeLines; i++) {
    vertices[v++] = new Vertex(positions[pole]);
    vertices[v++] = new Vertex(positions[bottomRow + i]);
    vertices[v++] = new Vertex(positions[bottomRow + i + 1]);
}

```

---
Tags: c#, directx, geometry, 3d-meshes
---


# Question
Title: Playing sounds only for specified player entities
I'm making a game mode for Garry's Mod, and I'm trying to write a system in which I play sounds only for certain players.

The problem I'm running across is that doing so from server-side would take a lot of bandwidth, but I'm not sure how I could reliably do it from the client side.

None of the Garry's Mod sound functions seem to take player entity arguments, and `surface.playsound` would resort back to the method of server telling the client what sounds to play for every sound played.

# Answer
Only took 5 years, but to answer your question:

```
hook.Add("PlayerDeathSound", "DeFlatline", function() return true end)
local noise = Sound("death.wav")
hook.Add("PlayerDeath", "NewSound", function(vic,unused1,unused2) vic:EmitSound(noise) end)

```

Here is a link to a video tutorial: https://youtu.be/UPtKeJmLmoA
> 1 votes

---
Tags: lua, garrys-mod
---


# Question
Title: Use ramp and steps meshes as actual ramp in unreal engine 4.26
Is it possible to use a ramp mesh as an actual ramp in UE4? It seems that the system create a rectangle box around the ramp o the character does not climb the ramp, it is over it like on a box.

I know that we can use landscape ramp's generator, but it's one more step that could be avoid.

thanks guys!

# Answer
It sounds like when you've imported the mesh, Unreal has auto created the collision and created it as a simple box collision.

To change it, you need to double click on the mesh itself, choose collision from the menu bar (the green odd shaped cylinder) and select whichever option is needed to highlight your mesh in a coloured box. This is your collision.

Go to Collision on the top menu, select remove collision then whichever option highlights your mesh in the best shape possible:
> 2 votes

---
Tags: unreal-4
---


# Question
Title: Why do the bullets spawn from the middle of the scene?
I'm making a 2D game with Unity. I have a patrol enemy that has to shoot bullets. The problem is that the bullets are being spawned from a random point at the middle of the scene, instead of `bulletSpawnPos` (an empty game object which is a child of the pistol). I also want the enemy to shoot whenever the player is near. But it seems like all the code does is to shoot towards it, no matter if it's near or not. In general I want to solve these two problems that are pretty much related to each other:

1. Bullets should be spawn from`bulletSpawnPos`.
2. Enemy should start shooting whenever the player is near (maybe by triggering something).

Pistol script:

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

public class Pistol : MonoBehaviour
{
    [SerializeField] GameObject bullet;
    [SerializeField] Transform bulletSpawnPos;
    private bool isShooting;
    [SerializeField] private float shootDistance = 5f;
    [SerializeField] private float shootDelay = .5f;
    private Enemy enemy;

    void Start()
    {
        enemy = transform.parent.GetComponent<Enemy>();
        InvokeRepeating("Shoot", 1f, shootDelay);
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        //Detecting hits to the right
        RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, shootDistance);
        //making sure we hit something and it is the player
        if (hit.collider != null && hit.collider.tag.Equals("Player"))
        {
            //We only want to start repeated shooting in case we do not shoot yet
            if (!isShooting) InvokeRepeating("Shoot", 0f, shootDelay);
            isShooting = true;
        }
        else
        {
            //Stopping ongoing shooting
            if (isShooting) CancelInvoke("Shoot");
            isShooting = false;
        }
    }
    void Shoot()
    {
        GameObject b = Instantiate(bullet);
        b.GetComponent<Bullet>().StartShoot(enemy.IsFacingLeft());
        b.transform.position = bulletSpawnPos.transform.position;
    }
}

```

Bullet script:

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

public class Bullet : MonoBehaviour
{
    [SerializeField] float speed;
    [SerializeField] int damage;
    [SerializeField] GameObject bullet;
    GameObject Enemy;
    float timeToDestroy = 3;

     NewPlayer target;
    Vector2 moveDirection;

    void Start()
    {
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        target = GameObject.FindObjectOfType<NewPlayer>();
        moveDirection = (target.transform.position - transform.position).normalized * speed;
        rb.velocity = new Vector2(moveDirection.x, moveDirection.y);
        Destroy(gameObject, 3f);
    }

    public void StartShoot(bool isFacingLeft)
    {
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        if (isFacingLeft)
        {
            rb.velocity = new Vector2(-speed, 0);
        }
        else
        {
            rb.velocity = new Vector2(speed, 0);
        }

        Destroy(gameObject, timeToDestroy);
    }

    private void OnTriggerEnter2D(Collider2D collision)
     {
         if (collision.gameObject.name.Equals ("Player"))
         {
             Destroy(gameObject);
         }
     }
}

```

Enemy script:

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

public class Enemy : PhysicsObject
{
    [Header("Attributes")]
    [SerializeField] private int attackPower = 10;
    private int direction = 1;
    public int health = 100;
    private int maxHealth = 100;
    [SerializeField] private float maxSpeed;
    [SerializeField] private LayerMask rayCastLayerMask; //Which layer do we want the raycast to interact with?
    [SerializeField] private Vector2 rayCastOffset; //Offset from the center of the raycast origin
    [SerializeField] private float rayCastLength = 2;
    bool isFacingLeft;
    public bool IsFacingLeft()
    {
        return isFacingLeft;
    }

    [Header("References")]
    private RaycastHit2D rightLedgeRaycastHit;
    private RaycastHit2D leftLedgeRaycastHit;
    private RaycastHit2D rightWallRaycastHit;
    private RaycastHit2D leftWallRaycastHit;

    // Update is called once per frame
    void Update()
    {
        targetVelocity = new Vector2(maxSpeed * direction, 0);

        if (targetVelocity.x < -.01)
        {
            transform.localScale = new Vector2(-1, 1);
            isFacingLeft = true;
        }
        else if (targetVelocity.x > .01)
        {
            transform.localScale = new Vector2(1, 1);
            isFacingLeft = false;
        }

        //Check for right ledge!
        rightLedgeRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x + rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down, rayCastLength);
        Debug.DrawRay(new Vector2(transform.position.x + rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down * rayCastLength, Color.blue);
        if (rightLedgeRaycastHit.collider == null) direction = -1;

        //Check for left ledge!
        leftLedgeRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x - rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down, rayCastLength);
        Debug.DrawRay(new Vector2(transform.position.x - rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down * rayCastLength, Color.green);
        if (leftLedgeRaycastHit.collider == null) direction = 1;

        //Check for right wall!
        rightWallRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y), Vector2.right, rayCastLength, rayCastLayerMask);
        Debug.DrawRay(new Vector2(transform.position.x, transform.position.y), Vector2.right * rayCastLength, Color.red);
        if (rightWallRaycastHit.collider != null) direction = -1;

        //Check for left wall!
        leftWallRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y), Vector2.left, rayCastLength, rayCastLayerMask);
        Debug.DrawRay(new Vector2(transform.position.x, transform.position.y), Vector2.left * rayCastLength, Color.magenta);
        if (leftWallRaycastHit.collider != null) direction = 1;

        //If health < 0, destroy me
        if (health <= 0)
        {
            Destroy(gameObject);
        }
    }

    //If I collide with the player, hurt the player (health is going to decrease, update the UI)
    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject == NewPlayer.Instance.gameObject)
        {
            //Hurt the player, then update the UI!
            NewPlayer.Instance.health -= attackPower;
            NewPlayer.Instance.UpdateUI();
        }
    }
}

```

This is the pistol inspector window.

Enemy object structure

# Answer
> 0 votes
Assuming you have your whole enemy structured like this:

Your pistol script is on the `Pistol` part, you need to access the `parent` if you want to get it the `Enemy` with `GetComponent`. GetComponent works always from the element you are currently on, if it is a child of Enemy, you need to ask the parent for the component. You can as well make the enemy variable public and assign it in the editor.

```
enemy = transform.parent.GetComponent<Enemy>();

```

Make sure that your Enemy is at 0/0/0 to avoid weird bugs later if you spawn them.

To address your shooting with a distance check. One option would be to use a Raycast (basically a line that you can check if it hits something). Since you can set how far it goes, you can define a distance check with it quite easily. This is added to your Pistol script. Try to adjust it yourself to make it work when the Enemy is facing left. Make sure that your Player has a collider2D and is tagged as Player.

```
[SerializeField] private float shootDistance = 5f;
private void FixedUpdate()
{
    //Detecting hits to the right
    RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, shootDistance);
    //making sure we hit something and it is the player
    if (hit.collider != null && hit.collider.tag.Equals("Player"))
    {
        //We only want to start repeated shooting in case we do not shoot yet
        if (!isShooting) InvokeRepeating("Shoot", 0f, shootDelay);
        isShooting = true;
    }
    else
    {
        //Stopping ongoing shooting
        if (isShooting) CancelInvoke("Shoot");
        isShooting = false;
    }
}

```

The InvokeRepeating is taking care of the delay between each firing. As long as the player stands in front of the Enemy (currently to his right only), he would fire.

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


# Question
Title: How to prevent collisions between instantiated prefabs
I'm creating a virtual creature evolution system like here. This type of project requires to define creatures, which are made of some 3d boxes and simulate them over and over again, making little changes along the way, until the point where they are good enough at a certain task. Basically, I'm using Genetic algorithms. I'm going to be doing a lot of simulation (a few hundred creatures each generation, times X generations, where X could be in the thousands). In order to save time, I want to simulate multiple creatures at once, so I must run collision checks efficiently. Each creature exists on its own and therefore should not be bothered by other colliders except himself and the ground.

I have a prefab of a creature. Each creature is made of multiple 3d boxes with colliders. The nodes in the same creature should collide with themselves but should not collide with nodes that are in other creatures (because it should learn to perform based on the environment as it is). What is the most efficient way I could do this?

I thought about checking the root of the collision object but that just prevents the collision and doesn't eliminate the useless checks that are being made. I've also looked at solutions involving the "Layer Collision Matrix" but still could not find a way to make it work.

Thanks in advance.

# Answer
> 1 votes
I ended up using the suggestion of @allnodcoms to use layers. I queue up a full generation to be simulated on 16 separate layers using a `SimulationManager`. Although this isn't the large amount I was looking for, it allows me to increase the speed of the simulation more than if I were to simulate 100 creatures at once.

# Answer
> 0 votes
I don't know about its efficiency but you can use ignore collision function: Physics.IgnoreCollision

It enables you to ignore collisions of two specific collider.

# Answer
> 0 votes
This is a pretty specific requirement, and without knowing more about *why* you need this functionality it's difficult to suggest a tailored solution.

I would initially suggest removing the collisions entirely and adding a script to the main creature container which checks the relationship between the various child objects, but again, without knowing why you need to check for internal collisions and not external ones, it is hard to suggest a more definitive alternative.

Danny

# Answer
> 0 votes
Well I know this is answered already, but I did a little research of my own for a personal project and I believe this should work for any prefab looking to avoid contact with any of the same item. If you give the prefab object (if it's a group this applies to all objects with colliders) a unique tag, like "ObjectTag" for example then you can simply use:

```
Physics.IgnoreCollision(prefabObject.GetComponent<Collider>(), GameObject.FindGameObjectWithTag("ObjectTag").GetComponent<Collider>());

```

with of course "prefabObject" and "ObjectTag" being replaced by whatever names you wish to use. As prefab objects keep their tags this essentially allows you to bypass the rule of not being allowed to refer to the same object twice in `Physics.IgnoreCollision`.

I am very new to coding and Unity so if I missed anything I apologize.

---
Tags: unity, collision-avoidance
---


# Question
Title: Player clips into the ground when I press the restart button
The title says it all. I have a subway surfers like game prototype, where I just added a restart button that can reload the scene. However whenever I press restart the charaters gets into a slightly lower position. After a few deaths the player is clipped into the ground and cannot jump at all. I looked up so many similar questions, all about checking colliders and rigidbodies but I personally couldn't find anything. It also has to do something with my gravity and stuff. Because I have a gravity modifier that if I set to 1, this issue never happens. The problem is, that then the player jumps around like he is on the moon. I also tried an experiment where I started my player from the air, not from the ground. And with every single restart the player fell faster and faster eventually falling trough the ground once again. So something can be with gravity. This is what I have in the character controller. I wasn't satisfied with my physics and I wanted it to make a bit more interesting.

I tried readding colliders, putting the same scripts on brand new objects, checking on and off rigidbody options.

```
void Start()
    {
        playerRb = GetComponent<Rigidbody>();
        Physics.gravity *= gravityModifier;
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 xPos = new Vector3(xRange, 0, 0);
        if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
        {
            playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            isOnGround = false;
        }

```

# Answer
The error happens because you do not only change the Physics once but each time you die. It is independent of your scene. Now you do not only change it each time you die, you use the old value and multiply it again. The fast fix would be to switch to the constant that your first change gave you.

```
Physics.gravity = newGravityValue;

```

What you wrote is

```
Physics.gravity = Physics.gravity * gravityModifier;

```

which is the same as

```
Physics.gravity *= gravityModifier

```

The correct way would be to change the settings under the Project Settings
> 1 votes

---
Tags: physics, clipping
---


# Question
Title: Best Practices for Texturing Large Objects
Kind of a 3D graphics newbie here. This is the biggest prop I've ever tried to texture, and I'm kind of stumped. How do you get a decent resolution on large meshes like this without exporting enormous maps? Texture atlases? Tiling textures? And what's the best way to set up the UVs, if so?

# Answer
> 0 votes
You can reuse areas of the texture on more than one polygon to get more effective resolution out of a texture. That is pretty much the same concept as tiling a texture, except you're doing it by manipulating the UVs, rather than as a setting in the material/shader.

In your pictured model for example, you can easily have all the inset panel share the same portion of the texture. When assigning texture coordinates, simply have the UVs for those panels overlap. Now you only paint one panel on the texture image and poof! all the panels have that texture.

And yes I am talking about texture atlases, where every polygon in the model has UV coordinates mapping different parts of the texture image to that polygon.

For one visual example, refer to the vertical columns in this tutorial. The wall with a bolt-thing only appears once in the texture image, but there are 4 columns sharing that image in the 3D scene.

# Answer
> 0 votes
If anyone's wondering, like me, how this changes for texturing levels, like for walls and stuff, here's another video I just found that talks about that.

https://www.youtube.com/watch?v=nvUfry7gKvU

What this video explains is extending UVs outside the 0-1 texture space in order to tile the texture. Technically textures don't *have* to repeat like this, but they usually do. The rendering engine can set textures to repeat or clamp (the technical term for, well, staying in the box).

---
Tags: textures, 3d-meshes, uv-mapping
---


# Question
Title: Argument 2: cannot convert from 'UltimateSurvival.ItemProperty.Value' to 'int'
I have a database which holds a list of items and properties. I am trying to fine tune this smelting station to output a certain amount of X item depending on the value found in `InputSlot.CurrentItem.GetPropertyValue("Quantity")` which should contain an `int`, but I am getting this error and even after casting it to `int` still same error.

Error:

```
Assets\Ultimate Survival\Scripts\By Namespace\UltimateSurvival\Player\Interaction\SmeltingStation.cs(161,45): error CS1503: Argument 2: cannot convert from 'UltimateSurvival.ItemProperty.Value' to 'int'

```

Code:

```
    private void On_HolderUpdated(ItemHolder holder)
    {
        bool shouldStopBurning = false;

        if(FuelSlot.HasItem && InputSlot.HasItem)
        {
            // The items have the correct properties, and the burn process can begin.
            if(FuelSlot.CurrentItem.HasProperty("Fuel Time") && InputSlot.CurrentItem.HasProperty("Burn Time") && InputSlot.CurrentItem.HasProperty("Burn Result"))
            {
                if(IsBurning.Is(false))
                {
                    m_FuelTimeProperty = FuelSlot.CurrentItem.GetPropertyValue("Fuel Time");
                    m_BurnTimeProperty = InputSlot.CurrentItem.GetPropertyValue("Burn Time");
                    m_ItemResult = InputSlot.CurrentItem.GetPropertyValue("Burn Result").String;

                    IsBurning.Set(true);
                    m_BurningHandler = StartCoroutine(C_Burn());

                    return;
                }
            }
            else
                shouldStopBurning = true;
        }
        else
            shouldStopBurning = true;

        if(IsBurning.Is(true) && shouldStopBurning)
            StopBurning();
    }

    private IEnumerator C_Burn()
    {
        while(true)
        {
            yield return m_UpdateInterval;

            // If the fuel, or the items to burn finished, stop burning.
            if(!FuelSlot.CurrentItem || !InputSlot.CurrentItem)
            {
                StopBurning();
                yield break;
            }

            var burnTime = m_BurnTimeProperty.Float;
            burnTime.Current -= UPDATE_INTERVAL;
            m_BurnTimeProperty.SetValue(ItemProperty.Type.Float, burnTime);

            Progress.Set(1f - burnTime.Ratio);

            if(burnTime.Current <= 0f)
            {
                ItemData resultedItem;
                if(GameController.ItemDatabase.FindItemByName(m_ItemResult, out resultedItem))
                    CollectionUtils.AddItem(resultedItem, InputSlot.CurrentItem.GetPropertyValue("Quantity"), LootSlots);
                else
                    Debug.LogWarning("The item has burned but no result was given, make sure the item has the 'Burn Result' property, so we know what to add as a result of burning / smelting.", this);

                if(InputSlot.CurrentItem.CurrentInStack == 1)
                {
                    InputSlot.SetItem(null);
                    StopBurning();
                    yield break;
                }
                else
                {
                    burnTime.Current = burnTime.Default;
                    m_BurnTimeProperty.SetValue(ItemProperty.Type.Float, burnTime);
                    InputSlot.CurrentItem.CurrentInStack --;
                }
            }

            var fuelTime = m_FuelTimeProperty.Float;
            fuelTime.Current -= UPDATE_INTERVAL;
            m_FuelTimeProperty.SetValue(ItemProperty.Type.Float, fuelTime);

            if(fuelTime.Current <= 0f)
            {
                if(FuelSlot.CurrentItem.CurrentInStack == 1)
                {
                    FuelSlot.SetItem(null);
                    StopBurning();
                    yield break;
                }
                else
                {
                    fuelTime.Current = fuelTime.Default;
                    m_FuelTimeProperty.SetValue(ItemProperty.Type.Float, fuelTime);
                    FuelSlot.CurrentItem.CurrentInStack --;
                }
            }
        }
    }

```

# Answer
`InputSlot.CurrentItem.GetPropertyValue("Quantity")`

should be

`InputSlot.CurrentItem.GetPropertyValue("Quantity").Int.Current`
> 1 votes

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


# Question
Title: Rotate camera around offset to player position (third person shooter view)
I'm trying to rotate my camera 'next to' the player object so that the player is not in the way of the screen-centered reticle. What I am trying to achieve is something like the targetting system of Fortnite, GTA 5 or Red Dead Redemption (or most third-person shooters), where the camera/player are offset slightly so that you can see directly in front of them.

My code so far allows me to rotate the camera about the player (`object` here) and it follows the player's position. I cannot figure out how to offset it.

```
public void update(final GameObject object)
    {
        this.newMouseX = Input.getMouseX();
        this.newMouseY = Input.getMouseY();

        final float dx = (float) (this.newMouseX - this.oldMouseX);
        final float dy = (float) (this.newMouseY - this.oldMouseY);

        // Rotate the camera on mouse move
        this.verticalAngle -= dy * this.mouseSensitivity;
        this.horizontalAngle += dx * this.mouseSensitivity;

        // Distances from side view
        final float horizontalDistance = (float) (this.distance * Math.cos(Math.toRadians(this.verticalAngle)));
        final float verticalDistance = (float) (this.distance * Math.sin(Math.toRadians(this.verticalAngle)));

        // Distances from top view
        final float xOffset = (float) (horizontalDistance * Math.sin(Math.toRadians(-this.horizontalAngle)));
        final float zOffset = (float) (horizontalDistance * Math.cos(Math.toRadians(-this.horizontalAngle)));

        this.position.set(object.getPosition().getX() + xOffset, object.getPosition().getY() - verticalDistance + VERT_OFFSET, object.getPosition().getZ() + zOffset);

        this.rotation.set(-this.verticalAngle, this.horizontalAngle, 0);

        this.oldMouseX = this.newMouseX;
        this.oldMouseY = this.newMouseY;
    }

```

This is the sort of thing I'm trying to achieve:

# Answer
Thanks for the responses, but I have solved it myself after multiple attempts at the maths. I had to modify `xOffset` and `zOffset` with the following:

```
final float D = 20f;
final float d = 2f;
final float xOffset = (float) ((d * Math.cos(Math.toRadians(-this.horizontalAngle))) + (D * Math.cos(Math.toRadians(90 - -this.horizontalAngle))));
final float zOffset = (float) ((D * Math.sin(Math.toRadians(90 - -this.horizontalAngle))) - (d * Math.sin(Math.toRadians(-this.horizontalAngle))));

```
> 0 votes

# Answer
Your character object should have vectors representing its facing (forward, right, up). If you take the normalized right vector and multiply it by a scaling factor, you will create an offset vector. Add the offset to the player position and store it in a separate variable. This is where your camera will rotate around, roughly speaking. Don't forget to update the offset each frame.
> 1 votes

# Answer
first thing, I didn't made any game in third person view yet. But as of camera follow it should be easy. What I do is:-

I creates a public vector 3 variable named offset and use that as it:-

```
void Update()
{
   transform.position = player.position; /* this script should be in camera
   object and player is a transform variable which you can assign */
   transform.position += offset;
}

```

then I will go in game view and change the value of offset to put it as of third person view. Then I will copy the values or remember them, will exit from game view and set that in the offset variable. This is what I will do, I hope it also works for you. You can use any function for moving camera just remember the logic behind it.
> 0 votes

---
Tags: camera, rotation, third-person-view
---


# Question
Title: How to expose a child node’s texture from the parent in Godot
I built a simple scene that I instanciate at will. Simply a `KinematicBody2D` as root, containing a `Sprite` and a `CollisionShape2D`. There is a script linked to the root node that basically expose a few properties to describe an orbit and make it move in orbit around its parent. The point being to make a very basic solar system simulation or anything that requires a node to move around another in a circular fashion.

The movement work fine and I’ve been playing around my scene tree, instancing a bunch and watching them move around as moons of planets, etc. But the texture is all the same. If I make children editable, I can go change the texture of the sprite, but I’d like to expose that property from the root node so I can access it directly from the editor.

I tried adding an exposed property with a setter and a getter to assign and retrieve the texture, but it seems to crash Godot completely with this code:

```
export(Texture) onready var texture setget texture_set, texture_get

func texture_set(newtexture):
    $"Sprite".texture = newtexture

func texture_get():
    return $"Sprite".texture

```

Is there a solution for that? Or simply another way?

# Answer
I would export the texture variable from the root node and simply set the child texture in \_ready(), rather than mess around with getters and setters.

```
export(Texture) var my_texture

func _ready():
    get_node("Sprite").texture = my_texture

```
> 1 votes

# Answer
Let us start with your code:

```
export(Texture) onready var texture setget texture_set, texture_get

func texture_set(newtexture):
    $"Sprite".texture = newtexture

func texture_get():
    return $"Sprite".texture

```

Oh, yes we have an error, don't we? The problem is that these variables are being set before the node is added to the scene tree. Let's fix that:

```
export(Texture) onready var texture setget texture_set, texture_get;

func texture_set(newtexture):
    if not is_inside_tree():
        yield(self, 'ready');

    $"Sprite".texture = newtexture;

func texture_get():
    return $"Sprite".texture;

```

Here `is_inside_tree` will be false on initialization. So we use `yield` to have the execution of the function halt until we get the signal `ready` (at which point the node is in the scene tree and ready to interact with other nodes).

Wait, we cannot read it. Same reason as before. So, let us store the value of the property locally, and only talk to `$"Sprite"` when we are in the tree.

```
export(Texture) onready var texture setget texture_set, texture_get;

func texture_set(newtexture):
    texture = newtexture;
    if not is_inside_tree():
        yield(self, 'ready');

    $"Sprite".texture = texture;

func texture_get():
    if is_inside_tree():
        texture = $"Sprite".texture;

    return texture;

```

Et voilà. This should work.

Of course, an alternative is to have `_ready` copy the value to the child as per GrimGrom's answer. However, this approach will allow any changes of the value on the parent to be transferred to the child in runtime.

By the way, you can add `tool` at the start of the file (before `extends`, and before `class_name` if you have that) to have the changes also work in the editor. If you set this up with `tool`, you can use `Engine.editor_hint` to tell if it is running in the editor or not.

---

Bruno Ely said:

> Reviving this because I've been giving this issue some thought recently. What happens when some external actor decides to set my\_texture on the parent? Is there a way to make it read-only?

Well, yes. Make the set function do nothing:

```
func texture_set(_newtexture):
    pass;

```

You can even generate an error:

```
func texture_set(_newtexture):
    push_error("Hey, your code is trying to set something you don't want to be set.");

```

You might also be interested in `push_warning(String);`, `assert(bool, String);` and `breakpoint;` Similarly to `push_error(String);`, this only work on debug builds and on the editor.

---

*Semicolons not necessary.*
> 1 votes

---
Tags: textures, instancing, inheritance, godot
---


# Question
Title: What is the easiest way to find a child?
```
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class SavedGamesSlots : MonoBehaviour
{
    public GameObject saveSlotPrefab;
    public float gap;

    private Transform slots;
    private string[] imagesToLoad;

    // Start is called before the first frame update
    void Start()
    {
        int counter = 0;

        imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
        slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

        for (int i = 0; i < imagesToLoad.Length; i++)
        {
            var go = Instantiate(saveSlotPrefab);
            go.transform.SetParent(slots);

            Texture2D thisTexture = new Texture2D(100, 100); //NOW INSIDE THE FOR LOOP
            string fileName = imagesToLoad[i];
            byte[] bytes = File.ReadAllBytes(fileName);
            thisTexture.LoadImage(bytes);
            thisTexture.name = fileName;

            go.GetComponent<RawImage>().texture = thisTexture;

            // Here to assign the fileName to the go(saveSlotPrefab) Text child

            counter++;
        }
    }

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

    }
}

```

This screenshot show example of fileName content :

And this screenshot show the part of the file name I want to extract and assign to the text :

And this screenshot show how the prefab/s are built the Text I want to assign to the file name part is the second child of the prefab. This prefab is the prefabs I'm Instantiating (saveSlotPrefab)

# Answer
> 2 votes
`GameObject.Find` will search for a GameObject in the scene. To search a GameObject for a child, use Transform. Here is how I do it:

```
transform.Find("childname")

```

I found that from here.

# Answer
> 3 votes
To answer the original question, as @DMGregory pointed out, typically the best/fastest way to find a child during runtime is using the GetComponentInChildren() or GetComponentsInChildren(). This isn't exactly the fastest solution in the world, but it works much better than searching by GameObject name, although honestly in most cases it probably wont be much of an issue. The main draw back to this approach is if you have two components of the same type as child, for example a Text component a players current HP and another for their MP/name/exp/whatever.

In your case I would recommend adding some helper scripts as well to make things easier to use/find:

```
public class SaveSlotUi : MonoBehaviour
{
    // Assign these in the prefabs inspector
    public RawImage saveImage;
    public Text filePathText;
    public Text saveFileNameText;
}

public class SavedGamesSlots : MonoBehaviour
{
    public GameObject saveSlotPrefab;
    public Transform slots; // why search if you can assign in the Editor
    public float gap;

    private Transform slots;

    // Start is called before the first frame update
    void Start()
    {
        // Counter is same as for loops "i" and is unused
        // We only use this once so why keep it stored
        string[] imagesToLoad = Directory.GetFiles(Path.Combine(Application.dataPath, "/screenshots"), "*.png");

        for (int i = 0; i < imagesToLoad.Length; i++)
        {
            var go = Instantiate(saveSlotPrefab);
            go.transform.SetParent(slots);

            SaveSlotUi slotUi = go.GetComponent<SaveSlotUi>();
            ui.saveImage.texture = LoadTexture(imagesToLoad[i]);
            ui.filePathText = imagesToLoad[i];
            ui.saveFileNameText = Path.GetFileName(imagesToLoad[i]);
        }

        // this is a pretty helpful helper function, you may want to bring this out later to a static class so anyone can use it on demand
        private Texture2D LoadTexture(string path)
        {
            Texture2D thisTexture = new Texture2D(2, 2);
            byte[] bytes = File.ReadAllBytes(path);
            thisTexture.LoadImage(bytes);
            thisTexture.name = path;
            return thisTexture;
        }
    }
}

```

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