title: Unity - Set quad to angle of floor mesh

text:
# Question
Title: Unity - Set quad to angle of floor mesh
I have a cursor object (simple quad) that I'm moving around above a floor mesh. The floor mesh has varying heights (hills and such).

How can I set my quad to sit at the same angle as the mesh floor?

I'm using a raycast to cast down on the position of the cursor and get the angle of the floor mesh using hit.normal, then reflect.

```
RaycastHit hit;
var rayStart = new Vector3(transform.position.x, transform.position.y + 5f, transform.position.z);
if (Physics.Raycast(rayStart, Vector3.down, out hit, 10f)) {
    if (hit.collider.tag == "Floor") {
        Vector3 incomingVec = hit.point - rayStart;
        Vector3 reflectVec = Vector3.Reflect(incomingVec, hit.normal);
        cursorSprite.transform.eulerAngles = reflectVec;
        }
    }

```

(I've left out the position code, that works, its just the angle code that doesnt)

I've tried a bunch of variations, altering the reflectVec angle x, y and z but I can't figure out how to get it correct :/

# Answer
This code is meaningless:

```
Vector3 incomingVec = hit.point - rayStart;
Vector3 reflectVec = Vector3.Reflect(incomingVec, hit.normal);
cursorSprite.transform.eulerAngles = reflectVec;

```

There is no particular relationship between the orientation you want, and the reflection of the incident ray by the hit normal. There is no relationship at all between a direction vector in cartesian coordinates and Euler angles in degrees - the units don't even match.

It looks like you want something more like this:

```
cursorSprite.transform.rotation = Quaternion.LookRotation(-hit.normal, Camera.main.transform.up);

```

This points the "forward" vector of your sprite (its local z+ axis) down into the ground, perpendicular to its surface, so the object's local xy plane sits parallel to the surface. It tries to align the object's local y+ axis toward the camera's up axis. This works for sprites and quads which by default are made to be viewed from their z- side.
> 0 votes

---
Tags: unity, raycasting
---


# Question
Title: how can I make camera to follow smoothly
What I meant by slow parent is that I want the camera to not move immediately my third person controller moves so it won't look as though the earth is moving. The camera is the child of the player

# Answer
> 3 votes
Well, `CameraFollow` or `SmoothFollow` script may help you in this issue. Here I'm pasting the `SmoothFollow` code.

* Make a script named `SmoothFollow`.
* Attach it to Camera
* Give the target transform from inspector (your player in your case)
* Play with other attributes to set your desired behaviour.

Code,

```
using UnityEngine;
using System.Collections;

public class SmoothFollow : MonoBehaviour
{
    public bool shouldRotate = true;

    // The target we are following
    public Transform target;
    // The distance in the x-z plane to the target
    public float distance = 10.0f;
    // the height we want the camera to be above the target
    public float height = 5.0f;
    // How much we
    public float heightDamping = 2.0f;
    public float rotationDamping = 3.0f;
    float wantedRotationAngle;
    float wantedHeight;
    float currentRotationAngle;
    float currentHeight;
    Quaternion currentRotation;

    void LateUpdate ()
    {
       if (target){
           // Calculate the current rotation angles
           wantedRotationAngle = target.eulerAngles.y;
           wantedHeight = target.position.y + height;
           currentRotationAngle = transform.eulerAngles.y;
           currentHeight = transform.position.y;
           // Damp the rotation around the y-axis
           currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
           // Damp the height
           currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
           // Convert the angle into a rotation
           currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
           // Set the position of the camera on the x-z plane to:
           // distance meters behind the target
           transform.position = target.position;
           transform.position -= currentRotation * Vector3.forward * distance;
           // Set the height of the camera
           transform.position = new Vector3 (transform.position.x, currentHeight, transform.position.z);
           // Always look at the target
           if (shouldRotate)
               transform.LookAt (target);
       }

    }
}

```

# Answer
> 2 votes
Create a camera smooth follow script eg:

```
public class SmoothFollow : MonoBehaviour
{
    [SerializeField] //for explicity sake
    public GameObject player; //assign this in the editor or find it in the start function.

    private Vector3 _velocity = Vector3.zero;

    //private void Start(){
    //
    //}

    private void Update () {
        this.gameObject.transform.position = Vector3.SmoothDamp(this.gameObject.transform.position, Camera.main.transform.position, ref _velocity, 0.5f);
        //change the last value to the time you want to complete the movement.
    }
}

```

Now obviously this is a very simple example and may not compile (I'm 75% sure I didn't make any typos.)

Unity3D Vector3.SmoothDamp function

Cheers, Hope this helps.

# Answer
> 0 votes
Demetry-\> **FIXED CODE:**

```
[SerializeField] //for explicity sake
public GameObject player; //assign this in the editor or find it in the start function.
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;

//private void Start(){
//
//}

void LateUpdate()
{
    this.transform.position = Vector3.SmoothDamp(this.transform.position, player.transform.position, ref velocity, smoothTime);
    //change the last value to the time you want to complete the movement.
}

```

---
Tags: motion
---


# Question
Title: Position sprite vertices in 3D to conform to terrain
Rookie here, still learning the basics of Unity.

I've been using a quad as a cursor sitting flat on top of a hilly terrain mesh. I've been getting the terrain angle by raycasting down at all four corners of the quad and finding where it hits the floor, then editing the quad vertices to shape it to the terrain angle. Probably not the ideal way but it works great for what I needed.

So the next step is replacing it with a sprite. I changed from quad to a sprite renderer, and added a little animation to it. I went to edit the vertices and the setup is completely different (it seems to have 20+ vertices now instead of 4).

I did notice the SpriteRenderer has 4 triangles, but the points are Vector2s rather than Vector3, so I guess that won't work either since I'm applying it to a 3d world?

Can anyone with experience point me in the right direction with this?

# Answer
It sounds like you should just rotate the sprite instead of manipulating individual vertices. We can easily do this using the normal vector. This code should accomplish what you want and only needs three input points.

```
//compute the normal vector
var a = points[0].position;
var b = points[1].position;
var c = points[2].position;
var side1 = b - a;
var side2 = c - a;
var normal = Vector3.Cross(side1, side2).normalized;

//sprite faces along normal
sprite.rotation = Quaternion.LookRotation(normal);
//position sprite at the median between the three points
sprite.position = (a + b + c) / 3f;

```

Sprite renderers are one-sided, so you'll probably need a little bit of extra code to ensure the normal isn't reversed. Sprites are visible from their back side, so you actually want the sprite's transform to be pointed *away* from the camera. Or you can avoid this by putting two sprites, facing opposite directions, inside the same GameObject, so that one of the two sides is always facing the camera.

There are very few situations where you would need to manipulate the individual vertices of an object from code.
> 1 votes

---
Tags: unity, 3d, sprites, vertex
---


title: How to generate smoother Perlin Noise?

text:
# Question
Title: How to generate smoother Perlin Noise?
So, recently I've been learning procedural generation stuff (Perlin noise specifically) and I've kind of hit a wall.  This is the result that I've seen everyone get, but this is what I'm getting,

This is my code, (I'm using python):

```
import random
import math
import PIL.Image

class Noise:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def lerp(self, start, stop, t):
        return start*(1-t) + (stop*t)

    def smoothstep(self, t):
        return 3*(t**2) - 2*(t**3)

    def gradients(self):
        grads = []
        for _ in range(4):
            x = random.randrange(0, 361)
            y = random.randrange(0, 361)
            grads.append((math.cos(x), math.sin(y)))
        return grads

    def cvectors(self):
        botleft = (self.x, self.y)
        botright = (self.x-1, self.y)
        topleft = (self.x, self.y-1)
        topright = (self.x-1, self.y-1)
        cvecs = [botleft, botright, topleft, topright]
        return cvecs

    def makenoise(self):
        dot = []
        grads = self.gradients()
        cvecs = self.cvectors()
        for i in range(4):
            (x, y) = cvecs[i]
            (a, b) = grads[i]
            dot.append((x*a)+(y*b))
        st = self.lerp(dot[0], dot[1], self.smoothstep(x))
        uv = self.lerp(dot[2], dot[3], self.smoothstep(x))
        stuv = self.lerp(st, uv, self.smoothstep(self.y))
        return stuv

    size = 128
    img = PIL.Image.new('L', (size, size))
    for x in range(size):
        for y in range(size):
            perlin = Noise(random.uniform(0, 1), random.uniform(0, 1))
            img.putpixel(tuple([x, y]), perlin.makenoise())
    img.save("nois.png")

```

This is just a guess, but I feel like it's a scaling issue. Thanks in advance, and apologies, as well, for the horrible code.

# Answer
Instead of passing in some random points to your noise function, you probably want to pass the X and Y coordinates of the pixel scaled in, try something like `perlin = Noise(x /128.0, y /128.0)`
> 2 votes

# Answer
There is a **noise** module for python which you can install from pypi using pip. you can then import it and use its perlin noise function:

```
import noise
from noise import *

seed = random.randint(100)

num = noise.pnoise2(x/15, y/15, octaves=1 base=seed)

```

That is what I am using for my game to generate a tilemap of islands and oceans.
> 1 votes

---
Tags: procedural-generation
---


# Question
Title: if touching line renderer (do something)
I have this laser script for a ship and I am trying to make it kill an enemy when it is hit with the line rendered laser. How can I achieve this. All things I found online I just could not get to work. An outline of the code would be (this isnt real code).

```
public gameobject linerenderer;

void update()
{
   if (touching gameobject.linerenderer)
   {
       die
   {
}
```

```
 private LineRenderer lr;
    void Start()
    {

        lr = GetComponent<LineRenderer>();
    }

    void Update() // consider void FixedUpdate()
    {

        lr.SetPosition(0, transform.position);
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.forward, out hit))
        {
            if (hit.collider)
            {
                lr.SetPosition(1, hit.point);
            }
        }
        else lr.SetPosition(1, transform.forward * 5000);

    }
```

However there is an anoying bug with this code... Before:

After you play the game for about 30 secs:

Settings:

# Answer
> 1 votes
LineRenderer is not your friend here. While you can somehow make it work (you would need to dynamically create and update the colliders by code), that is not something you want to do. (As reference https://answers.unity.com/questions/470943/collider-for-line-renderer.html)

If you want to use your laser to kill something, it is just a bunch of stretched shiny bullet packed together. All you need to do is create a small laser prefab with an image of your laser and you spawn them in quick succession. Each of those laser bullets can have their own collider and therefore your collision/ die/ kill etc call.

With a bullet prefab, you can for example easily move your ship, continue shooting and you don't care about already shot bullets. The line renderer would just stay where it is. You will have a really hard time to update it to match your movement pattern of the ship.

1. instantiate a prefab should have no influence on your ships movement, if it does, you do it wrong. That would be a different problem and can only be helped if you post your implementation of it.
2. You don't enable/ disable bullet prefabs. You instantiate them and usually have an offscreen collider that destroys them. Upgraded version is a pool manager for them but for starters offscreen destroyer will do.
3. If you really want to use a linerenderer, you could take a look at raycasting and if that is an option for you. If the raycast hits, so should your laser if you use the same direction of it.

# Answer
> 0 votes
1. Get the array of points from your line renderer.
2. In cycle, iterate these points, doing raycast from one to another.
3. If something met in raycast - kill it. Or interrupt cycle, remove further points, and put it back to line renderer, if you met something indestructible. In this way you can even implement reflecting laser (use vector3.reflect).

The cycle is something like this (pseudocode):

```
 for(int i= 1; i < points.Length; ++I)
 {
      Vector3 origin = points[i-1];
      Vector3 direction = points[i] - origin;
      float distance = origin.magnitude;

      if ( Do standard raycast)
      {
           Destroy (hit.collision.collider.gameobject);
           Break;
      }
 }

```

---
Tags: collision-detection, line-renderer
---


# Question
Title: How to clamp a mouse angle within a field of view range of the facing direction
In my top down shooter game, the player can face in any of the 8 compass directions using the keyboard.

Depending on the direction, the player will have a 90 degree field of view to turn based on the angle selected by the mouse position. Obviously the mouse can go anywhere so it has to be restricted within -45 and 45 of the angle faced.

The eight direction angles:

```
    135 90 45
180            0
   225 270 305

```

So if the player is facing to the left at 180, their range of view will be -45 and 45 of that ie 135 to 225. So it's simply `mouseAngle - facingAngle`, which works fine, except if the player is facing around 0, 45 or 305 degrees where the mouse angle passes zero causing issues in calculation.

As it is I'm using this formula.

```
private void setAngleFOV() {
    if (facing == 0 || facing == 360)
        facing = mouseAngle < 360 && mouseAngle >= 180 ? 360 : 0;
    angleFOV = mouseAngle - facing;
    angleFOV = Math.max(Math.min(angleFOV, 45), -45);
}

```

It can either be 0 or 360 for either `facing` or `mouseAngle`, whichever works best but I haven't found an ideal solution. The above formula works for facing right at angle 0, but not with diagonal angles 45 and 305.

It could maybe work with lots of `if` statements and such, but I feel there must be a better way?

# Answer
Looks like you need to compare angles and work out their difference.

Here's one way to do it:

```
// Returns the difference between two angles, from -180 to +180 degrees.
float deltaAngle(float aDegrees, float bDegrees) {
    float difference = aDegrees - bDegrees + 180.0f;
    return (float)(difference - Math.floor(difference/360.0f) * 360.0f - 180.0f);
}

// Clamps the angle difference between -rangeDegrees and +rangeDegrees.
float clampRelativeAngle(float angleDegrees, float centreDegrees, float rangeDegrees) {
    float difference = deltaAngle(angleDegrees, centreDegrees);
    return (float)Math.min(Math.max(difference, -rangeDegrees), rangeDegrees);
}

// Clamps one angle within a range of a centre angle, and returns the result from 0 to 360 degrees.
float clampAbsoluteAngle(float angleDegrees, float centreDegrees, float rangeDegrees) {
    float absolute = centreDegrees + clampRelativeAngle(angleDegrees, centreDegrees, rangeDegrees);
    return (float)(absolute - Math.floor(absolute/360.0f) * 360.0f);
}

```
> 2 votes

---
Tags: java, angles, aiming
---


# Question
Title: How to write depth texture and read values from it
I am new in Unity and specializing in another field. But now I have to rapidly study it for a new project. I will be very thankful if anyone explain me how to read values of the depth buffer. I wrote a shader, which creates depth image:

```
Shader "Custom/MyDepthShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}

    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert // compile function vert as vertex shader
            #pragma fragment frag // compile function frag as fragment shader

            #include "UnityCG.cginc"

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

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

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;
            sampler2D _CameraDepthTexture;

            fixed4 frag (v2f i) : SV_Target
            {
                float depth = tex2D(_CameraDepthTexture, i.uv).r;
                depth = Linear01Depth(depth);
                depth = depth * _ProjectionParams.z;
                return depth;
            }
            ENDCG
        }
    }
}

```

Now I need to get depth information into a texture and save float values of this texture to for example txt file for further processing. I didn't found yet answer to this question after two days of googling and reading guides. For testing this shader I am using OnImageRender(RT src, RT dst, material).

# Answer
I found an answer to my question. Thanks DMGregory for your participation. I only needed to add two rows of code into the OnPostRender()-function:

```
Graphics.Blit(renderTexture, depthRendTex, mat);
depthTex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);

```

depthText (Texture2D) now contains all the values. By using function GetPixel(i,j) I gained access to each value in the texture.
> 1 votes

---
Tags: unity, shaders, depth-buffer, depth
---


# Question
Title: How to render a grid of dots being exactly 1x1 pixel wide using a shader?
I would like to render a grid with many dots, all equally spaced and being exactly 1 pixel wide. What I was able to achieve so far is this :

What I would like is (simulated using image editing program):

Here is the shader I wrote (which give result of 1st image). This is rendered as a giant quad.

```
Shader "Custom/Grid"
{
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct vertInput {
                float4 pos : POSITION;
                float4 uv : TEXCOORD1;
            };

            struct vertOutput {
                float4 pos : SV_POSITION;
                float4 uv : TEXCOORD0;
            };

            vertOutput vert (vertInput input)
            {
                vertOutput o;
                o.pos = mul(UNITY_MATRIX_MVP, input.pos);
                o.uv = input.uv;
                return o;
            }

            fixed4 frag (vertOutput output) : SV_Target
            {
                float4 uv = output.uv;
                float x = step((uv.x * 100.0 + 0.025) % 1.0, 0.05);
                float y = step((uv.y * 100.0 + 0.025) % 1.0, 0.05);
                float c = min(x, y);
                return float4(c, c, c, 1.0);
            }
            ENDCG
        }
    }
}

```

Is it possible to achieve what I want using a shader ? What is needed from first draft is to control the size of each dot. I have tried to use partial derivatives (`ddx` and `ddy`) but was not able to make it work.

# Answer
This does pretty well, though I found I needed to add a small fudge factor to avoid dots occasionally winking out when the grid point exactly straddled the border between pixels, but this does create a rare doubled pixel.

(The dots look inconsistent in the preview due to scaling - click to see it at native resolution)

Multiply the `uv` you provide as input to control the spacing between dots.

```
fixed4 frag (v2f i) : SV_Target
{
    // Partial derivatives of grid in x & y screenspace directions.
    float2 dx = ddx(i.uv);
    float2 dy = ddy(i.uv);

    // Think of these two vectors as a matrix,
    // |  dx.x    dy.x  |
    // |  dx.y    dy.y  |
    // and compute its matrix inverse.

    float invDet = 1.0f/(dx.x*dy.y - dx.y*dy.x);

    float2 toX = float2(dy.y, -dy.x) * invDet;
    float2 toY = float2(-dx.y, dx.x) * invDet;

    // Measure our signed distance from the nearest grid line in uv space.
    float2 fromZero = frac(i.uv + 0.5f) - 0.5f;

    // Transform this to a signed distance in pixel space,
    // by multiplying by our inverse matrix.
    float2 transformed = float2(dot(fromZero, toX), dot(fromZero, toY));

    // Zero-out any pixels that are more than half a pixel stride from a grid line.
    float on = 1.0f;
    on *= (transformed.x > -0.5f) * (transformed.x <= 0.505f);
    on *= (transformed.y > -0.5f) * (transformed.y <= 0.505f);

    // What remains should be single-pixel dots at the lattice points.
    return on;
}

```
> 3 votes

---
Tags: unity, shaders, gpu, pixel
---


# Question
Title: Unity - Issue applying Render Texture to object imported from Blender
I'm new to Unity and am trying to create a sort of CRT computer monitor/terminal with text. To draw the text, I set up a Text Mesh Pro with its own camera, which renders to a Render Texture.

I then designed a simple computer monitor model in Blender split into two objects: one for the glass part of the screen, and another for the 'rest' of the monitor exterior case. I saved a copy of the .blend file into the Assets folder and imported this into Unity.

My blender model: (two separate objects, with the separate "screen" piece moved out of the screen)

When I try to apply the Render Texture onto the screen object, the texture is rotated 90 degrees anti-clockwise and is too zoomed in:  I can't seem to rotate the texture so that it is the right way up to read the text, and only some of the text is visible. I have tried rotating the object 90 deg. clockwise in Blender and "applying" the transform so unity then thinks the object is oriented correctly. this still caused the texture to be rotated.

I also tried exporting as an .obj file, with "Up" set to "Y-Up", but this didn't work. I then tried applying the Render Texture to a material, which I then applied to the screen object which didn't work either. If I apply the texture to a standard cube in Unity, it works fine and is rotated and scaled correctly to fit the cube.

How can I get the blender object oriented correctly so that the Render Texture applies in the correct orientation and scales so the whole of the Render Texture fits and is not zoomed in?

I'm using Unity 2019.3 and Blender 2.82.

# Answer
As pointed out by DMGregory, the problem was with the UV Texture Coordinate unwrap in Blender (which I think must have been caused by the way I created the two separate parts of my model).

To reset the unrwap, I selected the faces of my "screen" object in Edit mode, then selected "Unwrap" from the UV menu. (This can also be done by pressing `U` with the faces selected)

With the UV map reset back to its default, the orientation and scaling of the Render Texture was now correct, and I was able to tweak the exact positioning/scaling of the texture with the Tiling and Offset controls for my material in Unity.
> 1 votes

# Answer
You're making this way more complicated than it needs to be. Create a world-space canvas to display the text, and attach it to the front of the monitor GameObject.
> -1 votes

---
Tags: unity, blender
---


title: LWJGL 3 HelloWorld example crashing

text:
# Question
Title: LWJGL 3 HelloWorld example crashing
I'm trying to start LWJGL 3 development and I am having an issue with getting things working. I have created a new Gradle project and successfully built the HelloWorld example from https://www.lwjgl.org/guide but when I run I get an error. However the error seems to be different each time. Here is one example:

```
Hello LWJGL 3.2.3 build 13!
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007fff6d4fe829, pid=4595, tid=5891
#
# JRE version: Java(TM) SE Runtime Environment (14.0.1+7) (build 14.0.1+7)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (14.0.1+7, mixed mode, sharing, tiered, compressed oops, g1 gc, bsd-amd64)
# Problematic frame:
# C  [libobjc.A.dylib+0x6829]  objc_msgSend+0x29
#
# No core dump will be written. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /Users/rob/Projects/Personal/cc/hs_err_pid4595.log
#
# If you would like to submit a bug report, please visit:
#   https://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

```

Another:

```
Hello LWJGL 3.2.3 build 13!
[thread 9731 also had an error]
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007fff34cc1027, pid=4579, tid=775
#
# JRE version: Java(TM) SE Runtime Environment (14.0.1+7) (build 14.0.1+7)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (14.0.1+7, mixed mode, sharing, tiered, compressed oops, g1 gc, bsd-amd64)
# Problematic frame:
# C  [CoreGraphics+0x73027]  CGClipRelease+0xe
#
# No core dump will be written. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /Users/rob/Projects/Personal/cc/hs_err_pid4579.log
#
# If you would like to submit a bug report, please visit:
#   https://bugreport.java.com/bugreport/crash.jsp
#

```

What should I start looking at to resolve this?

# Answer
Given that the crash is inconsistent, it's probably a threading issue. The link you shared says

> MacOS users should start their application passing "-XstartOnFirstThread" as a VM option.

so I'm guess that you're not properly setting the VM option. Setup a run configuration in build.gradle.

Example run config for Gradle:

**Add to build.gradle**

```
run {
  if(project.hasProperty('arg')){
    args(arg.split(','))
  }
  main = "MyPackage.MyEntry"
  classpath = sourceSets.main.runtimeClasspath
  jvmArgs = [
    "-XstartOnFirstThread"
  ]
  systemProperties System.getProperties()
}

```
> 0 votes

---
Tags: java, macos, lwjgl3
---


title: How should I implement stair climbing?

text:
# Question
Title: How should I implement stair climbing?
Im using raycast to detect if a block is to my side. I can use raycast to see if i need to climb stairs but the transition is bad. I immediately reach the top of the stairs when trying to go on them.

```
extends KinematicBody2D

signal collected

const ACCELERATION = 200
const GRAVITY = 10
var JUMP = -400
var SPACE_JUMP = JUMP * 1.25
var LEDGE_JUMP = JUMP * .75

var state = "idle"
var prev_state = "idle"
var velocity = Vector2.ZERO
var acceleration = Vector2(200,0)
var deceleration = Vector2(500,0)
var terminal_velocity = Vector2(200,0)
onready var collisionShape2D = $CollisionShape2D
var gravity = Vector2(0,10)
var jump = -400
var timer = 0
var facing = 1
var threshold = .5

var floor_normal = Vector2(0,-1)

func _ready():
    collisionShape2D.shape.radius = 28
    #collisionShape2D.shape.extents = Vector2(31.9,31.9)

func _physics_process(delta):
    timer += delta
    var ax = Input.get_joy_axis(0,0)
    var ay = Input.get_joy_axis(0,1)
    var space_rid = get_world_2d().space
    var space_state = Physics2DServer.space_get_direct_state(space_rid)
    var ray_down = space_state.intersect_ray(global_position, global_position + Vector2(0,32),[self])
    var ray_side1 = space_state.intersect_ray(global_position, global_position + Vector2(facing*32,-16),[self])
    var ray_side2 = space_state.intersect_ray(global_position, global_position + Vector2(facing*32,0),[self])
    var ray_up = space_state.intersect_ray(global_position + Vector2(facing*32,-32), global_position + Vector2(facing*32,-64))

    if ay > .25 and state == "ledge_grab":
        state = "jump"
        gravity.y = GRAVITY
    elif ay > .25 and state == "idle":
        state = "ball"
        collisionShape2D.shape.radius = 14
    elif ay < -.25 and state == "ball" and not ray_up.has("collider"):
        state = "idle"
        collisionShape2D.shape.radius = 28
    if is_on_floor():
        if state == "jump": state = "idle"
        acceleration.x = ACCELERATION
    if abs(ax) < .1:
        ax = 0
        if state == "moving":
            state = "idle"
    else:
        if state == "idle":
            state = "moving"
    if ax < -threshold:
        facing = -1
        velocity.x -= acceleration.x * delta
    elif ax > threshold:
        facing = 1
        velocity.x += acceleration.x * delta
    else:
        velocity.x += -sign(velocity.x) * deceleration.x * delta

    if abs(velocity.x) < 1: velocity.x = 0
    velocity.x = clamp(velocity.x,-terminal_velocity.x,terminal_velocity.x)
    velocity += gravity

    if not ray_up.has("collider") and ray_side1.has("collider") and state != "ledge_grab" and state != "jump":
        state = "ledge_grab"
        position.y = ray_side1.metadata.y * 32 + 32
        gravity = Vector2.ZERO
        velocity = Vector2.ZERO
        position.x -= facing
    if not ray_up.has("collider") and ray_side2.has("collider") and ray_down.has("collider"):

        #What should i do here?
        position.y -= 32
        position.x += facing * 24
    if state == "idle" or state == "moving" or state == "jump" or state == "ball":
        velocity = move_and_slide(velocity,floor_normal)

    var collision = move_and_collide(velocity * delta,true,true,true)
    if collision:
        if collision.collider.name == "StaticBody2D":
            jump = SPACE_JUMP
            collision.collider.free()
    print(state)

func jump():
    if is_on_floor() and state != "ball":
        velocity.y = jump
        acceleration.x += -jump
        state = "jump"
    if state == "ledge_grab":
        gravity.y = GRAVITY
        velocity.y = LEDGE_JUMP
        acceleration.x += -jump
        state = "jump"
func _unhandled_input(event):
    if event is InputEventJoypadButton:
        if event.pressed and event.button_index == 0:
            jump()

```

# Answer
**Make the stairs a slope:**

You wouldn't have to add any code, only another collision shape with a ray, so the player doesn't slide down the slope. This method would result in visible clipping and wouldn't look that great.

**Teleport the player:**

Like you already did in code, you could test if there is a stair in front of the player, and if there is, teleport him on top of the stair. That doesn't look very elegant though.

**Animate the player with Tweens:**

I added a raycast to find the position of the stair, then used this code to animate the player:

```
if not ray_up.has("collider") and ray_side2.has("collider") and ray_down.has("collider") and state != "walking_stair" and $RayCast2D.get_collider():
    state = "walking_stair"
    var stair_pos = $RayCast2D.get_collision_point()
    stair_pos.y -= 2
    $Tween.interpolate_property(self, "global_position", global_position, Vector2(global_position.x, stair_pos.y), .1)
    $Tween.start()
    yield($Tween, "tween_completed")
    $Tween.interpolate_property(self, "global_position", global_position, stair_pos, .1)
    $Tween.start()
    yield($Tween, "tween_completed")
    global_position = stair_pos
    state = "idle"

```
> 4 votes

---
Tags: godot, gdscript
---


title: Random Coroutine Delay?

text:
# Question
Title: Random Coroutine Delay?
```
IEnumerator Shooting()
    {
        //Random Delay
        rand2 = random.Next(1, 4);

        if (!audioSource.isPlaying)
        {
            enemyParticles.SetActive(true);
            particle.Play();
            audioSource.Play();

            rand = random.Next(0, 5);
            Vector3 vel = rb.velocity;

            if (rand == 2)
            {
                if (vel.x < 6f || vel.y < 6f || vel.z < 6f)
                {
                    health.numOfHearts -= 1;
                }
            }
        }
        yield return new WaitForSeconds(rand2);
    }

```

This script is tied to several enemy objects.

`random` is initialized in the Start method with a different seed for every object. For some reason that I can't figure out, the delay is not randomized here.

The AudioSource for instance is played for all the enemies at the same time with the same delay every time. I'm not too familiar with coroutines and how they are executed, but I always put the `WaitForSeconds()` statement at the beginning or end which usually works for me.

Here is the Start method:

```
//Random Seed
    public int RandomSeed;
    private System.Random random;
    private int rand;

    //Random Delay
    private int rand2;

    void Start()
    {
        //Random
        random = new System.Random(RandomSeed);
    }

```

Could someone explain why the AudioSources of all the enemy objects are played at the same time when I encounter them? Thanks in advance. :)

# Answer
> 1 votes
I fixed it, figured out that since the `StartCoroutine()` is in the Update method, the AudioSource plays constantly every time it stops playing as the `StartCoroutine()` is called every frame. To fix this, I did this:

```
if (entered == false)
            {
                StartCoroutine(Shooting());
                entered = true;
            }

```

in the Update method, and this in the Coroutine:

```
IEnumerator Shooting()
    {
        while (true)
        {
            //Random Delay
            rand2 = random.Next(1, 4);

            if (!audioSource.isPlaying)
            {
                enemyParticles.SetActive(true);
                particle.Play();
                audioSource.Play();

                rand = random.Next(0, 5);
                Vector3 vel = rb.velocity;

                if (rand == 2)
                {
                    if (vel.x < 6f || vel.y < 6f || vel.z < 6f)
                    {
                        health.numOfHearts -= 1;
                    }
                }
            }
            yield return new WaitForSeconds(rand2);
        }

    }

```

That fixes the issue and now I get randomized shooting delays!

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


# Question
Title: An error comes up in console when trying to enter play mode in unity
Hay folks, i pray for everyone's wellbeing. I want to ask a question that whenever i enter playmode in unity, error message is displayed even though there is nothing in the console. This doesn't get fixed even after restarting unity. Any help would be great.

# Answer
What i have done is that remove all the packages that the project had and reinstalled them. Moreover i removed my scripts from the assets folder and reimported them. All these solved the issue.
> 1 votes

---
Tags: unity, c#, 3d, console
---


# Question
Title: How to store data and behaviour for what happens within a level?
I made a game a year ago featuring a custom scripting language, but I realised that it took far too long to actually make the language and there were many commands that were very rarely used.

I'm trying now to do something similar with a game I'm working on, and I'm wondering what the simplest way to store level data would be. There are programs like Tiled that let you store some `JSON` data and tiles and `.png`'s and whatnot, but I want to be able to store commands for what happens within a level gameplay wise. I'll give some examples.

I could have a file for the starting room that has commands that run when you enter the room, e.g. to have some text pop up, have a character walk up to the player, etc. I could also have individual commands for what happens when you interact with an object or with a character. What's a good way to store this data without having to write my own scripting language? It's not too difficult to make a very basic one with minimal functionality, but I feel like there are much better ways out there.

# Answer
There are fundamentally two parts to anything in a video game; **data** and **behaviour**.

An example of **data** would be the speed of the player, how high they can jump, how many enemies should spawn in a certain room, etc.

An example of behaviour would be that the player jumps when `SPACEBAR` is pressed, the enemies spawn when the player picks up the golden coin in the room, and that there should be a cut-scene when all the enemies are dead.

The reason I mention the difference is because you are approaching this problem in the wrong way. A *data file* (`json`, `xml`, `ini`, etc.) does **NOT** store behaviour! Storing behaviour is the role of a *programming language*! Or in your case a *scripting languages* that the main program can interpret at runtime. This means your previous approach of a custom scripting language was actually correct (except for the "custom" part. Use an already existing one)!

Luckily for you a programming language quite neatly doubles as a way to store data, so I would recommend to store your maps in the programming language as well. Personally I use `Java` as my "main" language, `JavaScript` as my scripting language (for behaviour) and `Json` as my data storage language (since it couples nicely with `JavaScript`). A map file in my game looks something like this:

```
// P.S. this is TypeScript that I transpile (convert) into JavaScript.
// Highly recommended if you want typing in your scripting language!
const spriteSheetPath = "my_sprite_sheet.png";
preloadAsset(spriteSheetPath, "Texture");

const grassTexture = texture(spriteSheetPath, { x: 5, y: 0, w: 16, h: 16, margin: 1 });
const grass = tile(grassTexture);

const bushTexture = texture(spriteSheetPath, { x: 19, y: 9, w: 16, h: 16, margin: 1 });
const bush = interactive(tile(bushTexture), (entity) => {
    // Function is called when an entity interacts with this bush
    // Give the entity 1-4 berries
    entity.inventory.add(ItemAtlas.create("berry", Math.random(1, 4)));
});

function layout(): TileOrAlias[][][] {
    return [
        [ // Layer 1
            [2, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        ],
        [ // Layer 2
            ...
        ]
    ];
}

function map(): GameMap {
    const width = 10;
    const height = 10;
    const noAliasLayout = replaceAliases(layout(), {
        1: grass,
        2: bush
    });
    const navGrid = generateNavgrid(noAliasLayout, width, height);

    return {
        width,
        height,
        layout: noAliasLayout,
        navGrid
    };
}
map;

```

I would then run this file from my main language, call the `map` function that is returned by the file, and convert the data that is returned from it into a `Map` object that my main language can interact with!

P.S. Like I said above I would definitely **not** create your own scripting language! Use an already existing one such as `JavaScript`, `Lua`, or `Python`.
> 2 votes

---
Tags: scripting, map-editor, data-driven
---


# Question
Title: Hardware for testing Mapper 30 NES homebrews
For someone wanting to get into NES/Famicom game development, and test on hardware (original and/or clones) to make sure the controls feel right, and to make sure the game is compatible for hardware play, what is a sure method for doing this?

Two SD/MicroSD hardware solutions I am aware of are **EverDrive N8** and **KrzysioCart**.

Below are the Famicom versions of these cartridges respectively:

The end goal would be to flash the game to Muramasa hardware, so the game should play the same on the testing hardware as it does on the final hardware. What I know about these boards, I learned from this video. When it comes to distinctions between the various types of boards, I still have lots of questions, but that's another post for another day.

If the best solution is to strictly test through the Muramasa hardware (skipping SD/MicroSD cart solutions) by flashing to it each time (since that would be the final destination), then that's fine. I don't really know what workflow will be quickest when going back and forth between coding and testing. While not all testing will be through hardware (probably most will be via ROM), periodic hardware testing seems like a good idea, and so a quick workflow for that is desirable.

When it comes to flashing cartridges, the INLretro is the only hardware I am currently aware of for that, and I'm not sure how quick it would be workflow wise to flash with this over and over, or whether that's even a good idea. Workflow speed and ease of use are the main factors that have led me to look at SD cartridge solutions for testing.

Hardware testing workflow criteria:

* Must support Mapper 30, which NESmaker uses.
* Must work the same on the SD cart as on the final Muramasa hardware (if SD is used).
* Must work with Famicom (my console is Japanese).

I've come across various forum threads discussing Mapper 30 compatibility with the SD cartridge solutions mentioned above, but couldn't pin down a definitive answer.

I realize this is a somewhat niche topic, but hopefully someone here has some experience with it and can offer some guidance. Thanks.

# Answer
> 1 votes
I have KrzysioCart with mapper 30 support and it plays fine. I have an old version with that special feature (not every KC version has it)... however, there is a new release of KrzysioCart with default support for mapper 30, battery saving and some GUI improvements. You can find it here. I'm not sure if Kris sends item worldwide, you should ask.

---
Tags: hardware, nintendo, workflow, assembly
---


# Question
Title: How to convert depth values into Unity's distance
I am new in Unity and now only studying for my work project. I need help with computing real distances from depth values. Can't figure it out. My shader is:

```
Shader "Custom/MyDepthShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}

    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert // compile function vert as vertex shader
            #pragma fragment frag // compile function frag as fragment shader

            #include "UnityCG.cginc"

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

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

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;
            sampler2D _CameraDepthTexture;

            fixed4 frag (v2f i) : SV_Target
            {
                float depth = tex2D(_CameraDepthTexture, i.uv).r;
                depth = Linear01Depth(depth);
                depth = depth * _ProjectionParams.z;
                return depth;
            }
            ENDCG
        }
    }
}

```

I Blit then these values from renderTexture to texture2D and use function GetPixel(i,j). Knowing, that a cube is at 1.5 units distance from camera I can't get this value from depth texture. Thank you for your help. Now I suspect that I have got distance values, but they are biased by 0.5 for some reason... Can anyone explain this as well?

I found how to get distances from depth texture, so basically I can answer this question, but there is still unexplained bias in measurements.

# Answer
As described in the docs, `Linear01Depth()` is for getting the depth as a fraction of the way between the near and far planes.

To get an eye space depth value in world units, you want `LinearEyeDepth()`
> 1 votes

---
Tags: unity, textures, rendertexture, depth
---


# Question
Title: debug unreal engine c++ - how to run in break mode
I have a number of things not working properly with my FBX imports and I would like to understand how FBX imports work internally. Now, I am noob in software development, so how do I debug the internal C++ code of Unreal? I want to set a breakpoint in Visual Studio Code and explore variables / memory etc. I have found some sources, but for my level of knowledge, they explain nothing to me To make it clearer: I need to debug internal code, for fbx imports, like not the code that I am writing for my game objects. Basically, I want the engine to stop at the break point once it starts importing fbx (I have found functions seemingly responsible for that)

# Answer
> 1 votes
The binary distribution of the engine you get from the epic launcher is a Development build from the engine, so it will have the typical "release config" issues of debugging, with jumping around in execution and not having all local vars. Getting debug symbols from the launcher helps with call stacks and such but still won't let you go line by line

If you want to completely debug it you will have to download the source version from github and compile it in a debug configuration and run your project on that engine.

---
Tags: c++, unreal, debugging
---


# Question
Title: How to set LOD specifications for all meshes in unreal at once?
I have a large model and want to avoid separately setting the LOD specifications for each component in the model. Is there are way set LOD specifications for all meshes in unreal at once since I want to set the same specifications for each one? (percentages, how many LOD's, and at what screen distance they kick in, using Unreal's autogenerated LOD's).

# Answer
As far as I am aware this is not possible, normally changing properties like this would be easily doable through the bulk edit via property matrix, but not for LODs.

The LoD settings you see in the editor on the meshes is not really a property, but just a details panel customization that updates the mesh when one of the properties is changed.

We had a similar thing that we needed and we solved this by writing a custom tool to adjust the LoDs of all selected meshes or in folder.

So to answer this in short, I don't think it's possible without writing a custom tool.
> 1 votes

---
Tags: unreal, level-of-detail
---


# Question
Title: Crash when creating RenderTargetViews for Cubemap
I want to create a cubemap and I want to render to it and later sample from it for reflections. However, It crashes when I try to create the faces for the cubemap. Here is my code:

```
RenderTargetCube::RenderTargetCube(ID3D11Device* device, int resolution, DXGI_FORMAT format) {

    D3D11_TEXTURE2D_DESC desc = {};
    desc.Width = resolution;
    desc.Height = resolution;
    desc.MipLevels = 1;
    desc.ArraySize = 6;
    desc.Format = format;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.Usage = D3D11_USAGE_DEFAULT;
    desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
    desc.CPUAccessFlags = 0;
    desc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;

    HRESULT res = device->CreateTexture2D(&desc, NULL, &Texture);
    throwIfFailed(res);

    D3D11_RENDER_TARGET_VIEW_DESC viewDesc = {};
    viewDesc.Format = desc.Format;
    viewDesc.Texture2DArray.ArraySize = 6;
    viewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
    for (int i = 0; i < 6; i++) {
        viewDesc.Texture2DArray.FirstArraySlice = D3D11CalcSubresource(0, i, 1);
        res = device->CreateRenderTargetView(Texture.Get(), &viewDesc, RenderTargetView[i].GetAddressOf()); // crash here
        throwIfFailed(res);

    }

```

and here is the message I receive:

> D3D11 ERROR: ID3D11Device::CreateRenderTargetView: The Dimensions of the View are invalid due to at least one of the following conditions. MipSlice (value = 0) must be between 0 and MipLevels-1 of the Texture Resource, 0, inclusively. FirstArraySlice (value = 1) must be between 0 and ArraySize-1 of the Texture Resource, 5, inclusively. With the current FirstArraySlice, ArraySize (value = 6) must be between 1 and 5, inclusively, or -1 to default to all slices from FirstArraySlice, in order that the View fit on the Texture. \[ STATE\_CREATION ERROR #137: CREATERENDERTARGETVIEW\_INVALIDDIMENSIONS\]

I dont quite understand the error message, especially the last part about ArraySize, why does it want it to be between 1 and 5 and not 0 to 5?

# Answer
It looks like you want `viewDesc.Texture2DArray.ArraySize = 1;` instead of `6`.

This represents the number of array slices in the view you're taking, counting from the first slice.

When `i = 0`, this can be any number from 1 (since a view of 0 slices doesn't make sense) to 6 (the whole array). But when `i = 1`, this can only go up to 5 - trying to view the 6th slice starting at 1 means accessing the seventh item in a 6-item collection, throwing the error you experienced.

To render into one slice at a time, you don't need more than one slice in your view.
> 1 votes

---
Tags: textures, directx11, cubemap
---


# Question
Title: What is causing this error in rpg maker mv "Animated Sideview Enemies plugin"
I am having trouble with this plugin because when I use it to attack It gives an error. You can clearly see using magic works fine, it only seems to cause the error when attacking and only when using the "" notetags aka side-view mode.

Using Attack

Using Magic  Here is some reference links to what I am talking about. The plugin: http://yanfly.moe/2015/12/13/yep-44-animated-sideview-enemies/ rpg maker mv: https://store.steampowered.com/app/363890/RPG\_Maker\_MV/

# Answer
> 1 votes
The error you are receiving is because the plugin doesn't know how to handle what you have told it to do. Specifically doesn't know how to handle the sprite it thinks it should use. Which is why you are getting the error. I had a similar issue when I first started using RPG Maker MV with YANFLY plugins and hope the below will help. A great many developers, myself included, use this plugin without issue. This is why I recommend double checking.

Most notably, be sure you have the correct information in the notes section for your "enemy"

As an example you should have something like this in the "Note" section of the enemy

```
<Sideview Battler: Ritz>
<Scale Sprite: 66%>

```

Be ABSOLUTELY sure you have the correct name, and case in the name. If it is upper case R in "Ritz", then "ritz" will fail.

I hope this is of help and I made a comment asking for some additional information so I may be able to help further, which I will revise this answer with when, and if needed.

Hope you get it sorted and don't be discouraged by some of the quirks to configure them. YANFLY plugins are usually very good for RPG Maker MV.

---
Tags: plugin, error-management, rpg-maker-mv
---


# Question
Title: Change Unity 3d viewport shortcuts to match Blender?
The shortcuts in Unity are more similar to Maya (**Alt+Middle** for 3d orientation, **LeftClick** select, etc). I've looked into **Edit -\> Shortcuts** but couldnt find them. Is there any way to do this?

# Answer
> 1 votes
It seems that you're not the only person that wanted to make Unity more like Blender, and on the Unity forum someone has tried to script the editor to make it behave a bit more like Blender by adjusting the keyboard shortcuts. See https://forum.unity.com/threads/unity-editor-viewport-navigation-hotkeys.81673/

There's also the official documentation for adding your own menu items with keyboard shortcuts.

I'm not sure if there's a way to modify the mouse controls though. The scene navigation documentation doesn't mention any control customization options.

---
Tags: unity, 3d, blender, viewport
---


# Question
Title: How do I connect Unity to a server backend developed in .net core?
I'm currently running to a wall in my game development and I need now some discussion to clear my mind... In my mind I have a plan for some little online game (focused around clicking and idling), which I imagined could be served both on website and winapp, and in future even in mobile platforms.

I have chosen C# for it, build some server backend (join server, game server), but 'cause I want this server components be runned on linux, I have chosen .net core. Which is now my problem, because I'm building the game client in Unity, which only works in .net standard.

My main problem now is that I have build some "base network library" for communication, written in .netcore with plenty of NuGet packages, which I now have implement to Unity to get it work, but there are now conflicts (the main one is that unity is using another version of System.Threading).

Now I am wondering what steps should I choose nexts... There are some work behind now (but not so much, there are only some basic proceses for login and creating game worlds), so probably make that base network package compatible with .netstandard and .netcore.

Or I am thinking if it isn't more suitable to choose some another technology like c++ and some 2D engine in it (which to choose?).

What are you opinions? And what would you do in this situation?

# Answer
Sometimes a time and discussion is everything, what man needs!

Seperated my Message Protocol to custom library suitable for building for .net standard (unity) and .net core (server-side). Of course I get rid of native implementation of JSON in it, so it isn't dependent on some JSON library. So now it isn't pain to get it into Unity project.

Now make some nice Tcp Client usable in Unity project.
> 1 votes

---
Tags: unity, networking, multiplayer, software-engineering
---


# Question
Title: Could not establish connection with local server process when opening or making Unity project
Whenever i try to either create or open a Unity project, I get faced with this error.

Does Unity need a proxy server, because I dont have one. (If so, how do I get one?) And apparently I need to add some environment variables, (HTTP\_PROXY, HTTPS\_PROXY and UNITY\_NOPROXY=localhost,127.0.0.1) what values do i add to these?

# Unity Package Manager Diagnostics (v0.1.5)

# Ran 7 checks

1 succeeded

# 6 failed

❌ UPM registry reachable (FAIL) Make an HTTP request to the UPM package registry

> > Connection error. This could be because a proxy is misconfigured.

❌ Ping UPM registry (FAIL) Measure the latency of the UPM package registry API

> > No successful pings could be made in 0.062 seconds (30 failed)

❌ Ping UPM download (FAIL) Measure the latency of the UPM package download endpoint

> > No successful pings could be made in 0.039 seconds (30 failed)

❌ UPM registry download speed (FAIL) Test the Internet connection using the UPM package registry

> > Connection error. This could be because a proxy is misconfigured.

❌ Speedtest.net (FAIL) Test the Internet connection using Speedtest.net

> > Connection error. This could be because a proxy is misconfigured.

✅ HTTP proxy environment variables (PASS) Detect whether proxy-related environment variables are set (HTTP\_PROXY, HTTPS\_PROXY, ALL\_PROXY, NO\_PROXY, UNITY\_PROXYSERVER, UNITY\_NOPROXY)

> > Proxy support has been configured through the following environment variables: HTTPS\_PROXY = C:\Program Files\Unity Hub\Unity Hub.exe HTTP\_PROXY = C:\Program Files\Unity Hub\Unity Hub.exe UNITY\_NOPROXY = C:\Program Files\Unity Hub\Unity Hub.exe

❌ UPM health check (FAIL) Start the UPM process and call its health endpoint

> > Server started but did not respond to health requests: Error: Invalid protocol: c:

How do I fix this?

# Answer
I got the same error, checked 127.0.0.1 on my browser and got an error hence setx UNITY\_NOPROXY localhost did not work for me, so I went to my windows defender firewall with advanced security, and turned off the domain ,public and private profiles since I already have Quick Heal on, and my project started working, I suppose there was a conflict between Quick Heal and Windows Defender as both of them were turned on! I hope that helps!
> 1 votes

---
Tags: unity, error-management
---


# Question
Title: How do I play a sound after a given time is over?
I have a sound effect in my game that I want to play every time there is a collision detected, the problem is that the collisions are very frequent and the sound plays many times and gets overlapped, which doesn't sound good.

The code is simple enough, I just put a `walkSound.Play()` in the `OnCollisionEnter` method.

I also tried using a coroutine but I don't get the desired result:

```
private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            StartCoroutine(WalkSound());
        }

    }

IEnumerator WalkSound()
    {
        walkSound.Play();
        yield return new WaitForSeconds(0.41f);
    }

```

The `WaitForSeconds` could be above the playing code, but then there is an unnecessary delay that I don't need.

Basically what I want to achieve is, to have code execute the `Play()` method **only** when the previous iteration of the sound reaches `0.41f` seconds. This is similar to having an if statement that checks if the sound is already playing, but I want the sound to overlap at a given time.

Hope I was clear enough, any help appreciated. :)

# Answer
> 1 votes
One way to do it is to keep track of a state variable, like so:

```
private bool soundReady;
private void OnCollisionEnter(Collision collision)
    {
        if (soundReady && collision.gameObject.tag == "Ground")
        {
            soundReady = false;
            StartCoroutine(WalkSound());
        }

    }

IEnumerator WalkSound()
    {
        walkSound.Play();
        yield return new WaitForSeconds(0.41f);
        soundReady = true;
    }

```

# Answer
> 0 votes
When you want to avoid playing the sound while it is already playing, you can check the property `AudioSource.isPlaying` and only play the sound when it isn't already playing.

But with walk sounds, you likely want the sound to loop while a certain condition is fulfilled and stop it when that condition is no longer fulfilled. You can do that by checking the "Loop" box in the AudioSource component and then use OnCollisionEnter and OnCollisionLeave to switch it on and off using Play() and Stop().

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


# Question
Title: Calculating the bounding box of a game object based on its children
2D game with Unity. Have a parent game object, with several children objects scattered all over the scene.

I want to calculate the bounding rectangle of the parent game object.

Let the black dots be the children objects. The red rectangle is the bounding box. I am not really interested in the position - I only want the dimensions of such box.

Of course, the bounding box should also consider the bounding boxes of the children... and so on.

---

How can I achieve this? I heard that `Renderer` has a `bounds` property... but my parent object doesn't have a renderer. And when I put one, the value is `0` anyway.

# Answer
```
Bounds GetMaxBounds(GameObject g) {
   var b = new Bounds(g.transform.position, Vector3.zero);
   foreach (Renderer r in g.GetComponentsInChildren<Renderer>()) {
     b.Encapsulate(r.bounds);
   }
   return b;
}

```
> 9 votes

# Answer
The answer provided by Alex Merlin gives a false result when the children's bounding box doesn't contain the pivot (`transform.position`) of the parent.

The following should always be correct

```
Bounds GetMaxBounds(GameObject g) {
   var renderers = g.GetComponentsInChildren<Renderer>();
   if (renderers.Length == 0) return new Bounds(g.transform.position, Vector3.zero);
   var b = renderers[0].bounds;
   foreach (Renderer r in renderers) {
     b.Encapsulate(r.bounds);
   }
   return b;
}

```
> 4 votes

# Answer
if your 2D game is laying on the XY plane for example, all you have to do is to determine 4 points in Global/WorldSpace. These points will be the 4 corners of the red rectangle and their coordinates will be formed with:

* max X coordinate over all the childrens
* max Y coordinate over all the childrens
* min X coordinate over all the childrens
* min Y coordinate over all the childrens

When calculating the local edges coordinates for your children you can use their bounding box or bounding circle (center position +/- radius). All you have to do is to maintain 4 variables in which you save max and min x/y coordinates you found parsing all your children objects

Pseudocode will be something like:

```
foreach( child in parent )
{
    if ( child.min_x < min_x ) min_x = child.min_x;
    if ( child.min_y < min_y ) min_y = child.min_y;
    if ( child.max_x > max_x ) max_x = child.max_x;
    if ( child.max_y > max_y ) max_y = child.max_y;
}

```

so now you'll have these 4 values let's form the 4 points (pseudo code):

```
top_left = Point2D(min_x, max_y);
top_right = Point2D(max_x, max_y);
bottom_right = Point2D(max_x, min_y);
bottom_left = Point2D(min_x, min_y);

```

So now that you have the corners of the rectangle, calculating the dimension is straight forward because you can consider 2D Points as 2D Vectors and calculate their distance to determine the edges of the red box. So you can simple calculate a difference between the points or use the Unity built-in function Vector2.Distance like so:

```
float BaseOfRedBox = Vector2.Distance(bottom_right, bottom_left); // the base
float HeightOfRedBox = Vector2.Distance(bottom_right, top_right); // the height
float AreaOfRedBox = BaseOfRedBox * HeightOfRedBox; // the Area

```

You can do more stuff considering the 2D Points as vectors and determine 2D Normals and so...

All the calculation is made in WorldSpace if you need to transform the points back to screen space just use the Unity function camera.WorldToScreenPoint(...) where camera is your main orthographic camera.
> 2 votes

# Answer
I dont use unity but I believe all you would need to do is find the x and y value of your parent object, then the x and y value based on the bounding box being the second screen, for example
> 1 votes

---
Tags: unity
---


# Question
Title: Unity build does not launch and leaves no logs/errors
I have released my first title Audio Infection ( https://store.steampowered.com/app/911580/Audio\_Infection/ ) for a bit over a year ago. Recently 1 user has so far encountered an issue where the game does not launch. He is the only user that encounters this problem.

He has this issue on both Win 7 and Win 10. His system specs are fine and his drivers are up-to-date. The game does not leave a log file, rather it looks like it is unable to boot. There are no Windows error reports on it either. I watched it through Discord screenshare because I could not properly understand his issue.

I had asked a few other random people to test my game and demo (he has the issue with both, the demo and full version) however no one else (including me) is able to reproduce this behavior.

At this point I have tried:

1. updating Unity from 2018 to 2019 (no change in behavior)
2. added manual logging (with no results)
3. updating drivers (on his system)
4. installing Visual C++ (on his system)
5. empty project with Unity sample scene (he was able to load the sample scene!)
6. deleting crashhandler.exe (used to fix similar issue in the past based on older threads)
7. modifying files
8. deleting and downloading the files

What else can I try in order to figure out what is causing the issue? I am honestly clueless. Since the sample project was able to boot on his system there is definitely something wrong with the build on my end. However he is the first person with this issue. It doesn't even get to the point of launching on his system and it can't be found in the memory either. It is almost as if Windows is blocking it from launching, however that is not the case. But the result is very similar to that.

There is a free demo on the store page available in case you want to see if it boots on your system. It works for both VR and non VR systems. When no VR devices are detected all VR related contents are disabled. This has been thoroughly tested and worked on loads of different Windows systems with different specs, with VR and no VR.

Once again, there are no errors, no logs, the build doesn't even make it to that point, yet that exact same build works for literally everyone else on various systems. I am absolutely clueless about what to do in order to resolve this issue. Any help/advice or pointers towards the right direction are greatly appreciated!

PS: he is not a troll, I have known this guy for a long time now and he genuinely wants to support me.

# Answer
> 3 votes
It took me 3 months on and off working on this issue, but I have figured it out.

The issue lies with OpenVR/SteamVR. The head tracker of Steam has 2 camera's; head and eyes.

This is where the instability comes from, for some systems (even if VR isn't used and toggled) it prevents the build from starting. It will not throw any errors. For some systems it will be a bit slow but still stable.

The cause of this issue is the fact that the head camera has by default no background type. By setting background type to sky (or color) you fix this issue.

Hope this helps for anyone in the future that comes across this or a similar issue, good luck!

---
Tags: unity, c#, debugging, virtual-reality
---


# Question
Title: How to make planets "stay together" on collision
I working on a 2D planetary orbit simulator and I've encountered a problem regarding the collision of planets. Currently, here is what I have

```
if self._dist_between(p1.pos, p2.pos) <= p1.radius + p2.radius:
    pass

```

I detect the collisions but I don't know how to resolve them. I don't want the planets to bounce or do anything fancy, I simply want them to not pass through one another. I have tried disabling their movement completely on collision but this fails to work when more than 2 planets are active in the simulation, as when 2 planets collide they freeze in time rather than continue to be affected by the other planets.

This is the code that manages the movement

```
 def update(self):
    for p1 in self.planets:
        for p2 in self.planets:
            if p1 != p2:

                # Calculate and apply force
                temp_force_vector = [
                    self._gravitational_force(p1.mass, p2.mass, self._dist_between(p1.pos, p2.pos)),
                    self._radians_between(p1.pos, p2.pos)
                ]

                if self._dist_between(p1.pos, p2.pos) > p1.radius + p2.radius:
                    p1.apply_force(temp_force_vector)

                p1.update_pos()

```

Any suggestions?

# Answer
> 1 votes
To make 2 bodies (planets) move together naturally. you need to make it conserve momentum. In this case you need to see inelastic collision When collision happen, both object need to be merge in to single object. velocity of new object can be obtain by

```
v_x = (m1*v1_x+m2*v2_x)/(m1+m2)
v_y = (m1*v1_y+m2*v2_y)/(m1+m2)

```

Additionally you should make it conserve angular momentum as well, so it still rotate around new center of mass after collistion.

# Answer
> 0 votes
Maybe you could do something like this:

Let's say we have planet A and planet B.

When A and B collide, a function is executed, and we can use it to set some values.

1. First we decide which planet is going to be the master and which is going to be the slave. Lets say A is master and B is slave.I'll explain it later.
2. Then we find the vector between A and B
3. Then we add the newly recieved vector to the master's position, and set that as the position of the slave (`B.pos = A.pos + vector`, for example)
4. Then we set the velocity of the master to the desired value.

This will make B have the same relative position to A as at the moment of the collision and whenever A moves, B will move with it, without changing its relative pos

---
Tags: 2d, physics, python, collision-resolution, simulations
---


title: Speed after an angled collision?

text:
# Question
Title: Speed after an angled collision?
I can calculate the speed when there is no angle, but I can't calculate the speed when it is angle.

Physics paramaters:

```
Player Physics :
    radius : 15,
    bounce coefficient(coefficient of restitution) : 0.5,
    mass : 2
    damping : 0.96101

Ball Physics :
    radius : 8,
    bounce coefficient(coefficient of restitution) : 0.5,
    mass: 1,
    damping : 0.9902

```

Gif image(angled): haxball gif angled

```
Player speed on start: Vx: 5, Vy: 0

Ball speed on start: Vx: 0, Vy: 0

Player speed on collision: Vx: 3.4189778846153844, Vy: -0.9240480769230772

Ball speed on collision: Vx: 2.7721442307692317, Vy: 1.8480961538461544

```

The formula i use(this formula can calculate the speed when there is no angle): Formula image: Formula image

```
V1 = (m1*u1*k1 + m2*u2*k2 + m2*C1*C2*(u2*k2 - u1*k1)) /(m1 + m2)
V2 = (m1*u1*k1 + m2*u2*k2 + m1*C1*C2*(u1*k1 - u2*k2)) /(m1 + m2)

```

C1 and C2 bounce coefficient of player and ball.

How can i do?

# Answer
> 0 votes
The bottom of This page provide clear equation and explanation of 2D circle collision. It's might help. Note: As you see in that page, you collision equation only work in impact line (normal of contact surface) but the tangen velocity still the same cause by no serface friction. the general idea is to transform velocity to tangen and normal velocity. update normal velocity with your equation then transform back to original frame of reference.

---
Tags: 2d, collision-detection, physics, mathematics, collision-resolution
---


title: Unity 2019.3 HDRI SkyBox

text:
# Question
Title: Unity 2019.3 HDRI SkyBox
I am trying to create an HDRI SkyBox out of 6 textures but after I create the cubemap with Assets → Legacy → Cubemap and drag it in the HDRI Sky I get an all white environment. Is this a problem with the textures or maybe I am missing some setting?

# Answer
The legacy cubemap pipeline of dragging six separate textures into a cubemap asset in Unity does not support HDR.

To get HDR (and better filtering as a bonus), you need to import your cubemap as a single image, not as six separate images.

As described in the docs, you need to lay out your 6 views into one image file with one of these arrangements:

(I've omitted the Equirectangular/LatLong and SphereMap options since they'd require re-projecting your images instead of just pasting them side-by-side).

You can use any image editing software you like to do this arrangement.

Place the resulting single image into your Assets folder, and in its import settings, choose Texture Type: Default, Shape: Cube.

The result will be a Cubemap asset that you can use as your sky.
> 0 votes

---
Tags: unity, skybox, hdr
---


# Question
Title: Trouble generating a depth map (black screen)
I am having trouble generating a depth map for my scene. I tried to figure out this issue a 2 weeks ago and got nowhere after days of trying to fix it, so I took a break and tried to tackle it again today. I'm still stuck and with no ideas.

Here's the main code:

```
#Sets up the depth FBO and the texture that will be used to render to a quad
const unsigned int d_width = 1024, d_height = 1024;

    unsigned int depthFBO;
    glGenFramebuffers(1, &depthFBO);
    glBindBuffer(GL_FRAMEBUFFER, depthFBO);

    unsigned int depthMap;
    glGenTextures(1, &depthMap);
    glBindTexture(GL_TEXTURE_2D, depthMap);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, d_width, d_height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
    glDrawBuffer(GL_NONE);
    glReadBuffer(GL_NONE);

    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        std::cout << "Incomplete stuff!" << std::endl;

    glBindBuffer(GL_FRAMEBUFFER, 0);

    glm::vec3 lightPos(-2.0f, 4.0f, -1.0f);

```

Rendering loop:

```
/* Render here */
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);

        #render scene from the light's perspective
        float near_plane = 1.0f, far_plane = 8.0f;
        glm::mat4 lightProj = glm::ortho(-10.0f, 10.0f, 10.0f, 10.0f, near_plane, far_plane);
        glm::mat4 lightView = glm::lookAt(lightPos, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
        glm::mat4 lightSpaceMat = lightProj * lightView;

        depthShader.use();
        depthS.setUniformMat4("lightSpaceMat", lightSpaceMat);
        glm::mat4 model = glm::mat4(1.0f);
        depthS.setUniformMat4("model", model);

        glViewport(0, 0, d_width, d_height);
        glBindFramebuffer(GL_FRAMEBUFFER, depthFBO);
        glClear(GL_DEPTH_BUFFER_BIT);

        #render everything else
        planeVAO.bind();
        model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f));
        depthS.setUniformMat4("model", model);

        glDrawArrays(GL_TRIANGLES, 0, 6);

        cubeVAO.bind();
        model = glm::translate(model, glm::vec3(1.0f, 1.0f, -2.0f));
        model = glm::scale(model, glm::vec3(0.6f));
        depthS.setUniformMat4("model", model);
        glDrawArrays(GL_TRIANGLES, 0, 36);

        model = glm::translate(model, glm::vec3(2.0f, 1.0f, -1.0f));
        depthS.setUniformMat4("model", model);
        glDrawArrays(GL_TRIANGLES, 0, 36);

        #render to the quad now which is supposed to display the depth map
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        glViewport(0, 0, scr_width, scr_height);
        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

        quadVAO.bind();
        quadShader.use();
        glActiveTexture(GL_TEXTURE15);
        glBindTexture(GL_TEXTURE_2D, depthMap);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

```

Here are the shaders:

depth shaders:

```
#vertex
#version 330 core

layout (location = 0) in vec3 aPos;

uniform mat4 lightSpaceMat;
uniform mat4 model;

void main()
{
    gl_Position = lightSpaceMat * model * vec4(aPos, 1.0);
}

#fragment
#version 330 core

void main()
{
    gl_FragDepth = gl_FragCoord.z;
}

```

visual quad shaders:

```
#vertex
#version 330 core

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTex;

out vec2 TexCoords;

void main()
{
    TexCoords = aTex;
    gl_Position = vec4(aPos, 1.0);
}

#fragment
#version 330 core

out vec4 FragColor;

in vec2 TexCoords;

uniform sampler2D depthMap;

void main()
{
    float depthValue = texture(depthMap, TexCoords).r;
    FragColor = vec4(vec3(depthValue), 1.0);
}

```

Anyone have any idea what I might be doing wrong? I have tried debugging in every way I could think of and have made no progress.

edit: full source.cpp code:

```
#include <fstream>
#include <sstream>

#include <iostream>
#include <string>
#include <vector>
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>

#include "Shader.h"
#include "Textures.h"
#include "Camera.h"
#include "Context.h"
#include "Renderer.h"
#include "DataDefs.h"
#include "Renderer.h"
#include "StaticDataDefs.h"
#include "VertexBuffer.h"
#include "Context.h"
#include "Model.h"

#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <tuple>
#include <array>

#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include <stdio.h>
#include <map>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

float planeVertices[] = {
    // positions            // normals         // texcoords
     25.0f, -0.5f,  25.0f,  0.0f, 1.0f, 0.0f,  25.0f,  0.0f,
    -25.0f, -0.5f,  25.0f,  0.0f, 1.0f, 0.0f,   0.0f,  0.0f,
    -25.0f, -0.5f, -25.0f,  0.0f, 1.0f, 0.0f,   0.0f, 25.0f,

     25.0f, -0.5f,  25.0f,  0.0f, 1.0f, 0.0f,  25.0f,  0.0f,
    -25.0f, -0.5f, -25.0f,  0.0f, 1.0f, 0.0f,   0.0f, 25.0f,
     25.0f, -0.5f, -25.0f,  0.0f, 1.0f, 0.0f,  25.0f, 10.0f
};

const unsigned int scr_width = 800;
const unsigned int scr_height = 600;

float quadVertices[] = {
    // positions        // texture Coords
    -1.0f,  1.0f, 0.0f, 0.0f, 1.0f,
    -1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
     1.0f,  1.0f, 0.0f, 1.0f, 1.0f,
     1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
};

int main(void)
{
    //Setup all openGL stuff
    setProject init;
    GLFWwindow* window = init.returnWindow();

    Camera camera;
    camera.setInputs(window, camera);

    glEnable(GL_DEPTH_TEST);

    Shader normal;
    normal.setUpShader("Resources/Shaders/lightObject.vs", "Resources/Shaders/lightObject.fs");
    Shader depthS;
    depthS.setUpShader("Resources/Shaders/depthS.vs", "Resources/Shaders/depthS.fs");
    Shader depthR;
    depthR.setUpShader("Resources/Shaders/depthR.vs", "Resources/Shaders/depthR.fs");

    Context va;
    VertexBuffer vb(vert3d.size() * sizeof(Def3), vert3d.data(), 's', "type3a", GL_FALSE, GL_FLOAT);
    va.addBuffer(vb, "VBO");
    GLCall(va.setVBOAttribs());

    Context va2;
    VertexBuffer vb2(sizeof(quadVertices), &quadVertices[0], 's', "type2a", GL_FALSE, GL_FLOAT);
    va2.addBuffer(vb2, "VBO");
    GLCall(va2.setVBOAttribs());

    Context plane;
    VertexBuffer planevb(sizeof(planeVertices), &planeVertices[0], 's', "type3a", GL_FALSE, GL_FLOAT);
    plane.addBuffer(planevb, "VBO");
    GLCall(plane.setVBOAttribs());

    depthR.use();
    depthR.setInt("depthMap", 15);

    const unsigned int d_width = 1024, d_height = 1024;

    unsigned int depthFBO;
    glGenFramebuffers(1, &depthFBO);
    glBindBuffer(GL_FRAMEBUFFER, depthFBO);

    unsigned int depthMap;
    glGenTextures(1, &depthMap);
    glActiveTexture(GL_TEXTURE15);
    glBindTexture(GL_TEXTURE_2D, depthMap);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, d_width, d_height, 0, GL_DEPTH_ATTACHMENT, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
    glReadBuffer(GL_NONE);
    glDrawBuffer(GL_NONE);

    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        std::cout << "Incomplete stuff!" << std::endl;

    glBindBuffer(GL_FRAMEBUFFER, 0);

    glm::vec3 lightPos(2.0f, 4.0f, 1.0f);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {

        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);

        texo.textureBinder(0);

        //set up scene, draw objects, etc.

        camera.processInput(window);
        camera.calcDelta();

        float fov = camera.return_fov();

        float near_plane = 1.0f, far_plane = 8.0f;
        glm::mat4 lightProj = glm::ortho(-10.0f, 10.0f, 10.0f, 10.0f, near_plane, far_plane);
        glm::mat4 lightView = glm::lookAt(lightPos, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
        glm::mat4 lightSpaceMat = lightProj * lightView;

        depthS.use();
        depthS.setUniformMat4("lightSpaceMat", lightSpaceMat);
        glm::mat4 model = glm::mat4(1.0f);
        depthS.setUniformMat4("model", model);

        glViewport(0, 0, d_width, d_height);
        glBindFramebuffer(GL_FRAMEBUFFER, depthFBO);
        glClear(GL_DEPTH_BUFFER_BIT);

        depthS.use();

        plane.bind();
        model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f));
        depthS.setUniformMat4("model", model);

        glDrawArrays(GL_TRIANGLES, 0, 6);

        va.bind();
        model = glm::translate(model, glm::vec3(1.0f, 1.0f, -2.0f));
        model = glm::scale(model, glm::vec3(0.6f));
        depthS.setUniformMat4("model", model);
        glDrawArrays(GL_TRIANGLES, 0, 36);

        model = glm::translate(model, glm::vec3(2.0f, 1.0f, -1.0f));
        depthS.setUniformMat4("model", model);
        glDrawArrays(GL_TRIANGLES, 0, 36);

        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        glViewport(0, 0, scr_width, scr_height);
        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

        va2.bind();
        depthR.use();
        glActiveTexture(GL_TEXTURE15);
        glBindTexture(GL_TEXTURE_2D, depthMap);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

```

(the "VA" VAO holds the data for the cubes and "VAO2" for the quad)

https://github.com/julkothegu/p\_1\_test

# Answer
Sorry I cant comment yet.

I havent done shadow mapping in openGL yet, however, I cannot see that you are setting your `uniform sampler2D depthMap`. It should be set like:
`glUniform1i(glGetUniformLocation(PROGRAM_ID, "depthMap"), 15);`

Its being set to 15 because of this code:
`glActiveTexture(GL_TEXTURE15);
glBindTexture(GL_TEXTURE_2D, depthMap)`
In above code you are saying your depthMap texture is at index 15.

**Edit:** Okay I gave it a try(I am also following the learOpengl.com) and this is my render. Please note I am not doing a double pass . I am just basically changing my perspective projection to ortho and I got the following result:

This is my render with perspective:

Therefore, I would strongly recommend you to first do a normal render and then try the shadows.
> 1 votes

---
Tags: opengl, shadow-mapping
---


# Question
Title: In regards to real time turn based games, where should the turn handler be?
I'm currently developing a pool-like browser game. I'm stuck on where should I handle the turn changing, timer, etc.

Currently, turn timer (i.e. 15 seconds left to do action, then turn will change) is handled by the server. But the changing of turns itself is handled by the client (the browser itself).

Now in my current setup, whenever a player leaves window focus, the game gets out of sync. Should I migrate the turn change handling to the server instead?

# Answer
> 3 votes
The general rule of thumb for handling multiplayer games is that any game mechanics which *can* be handled on the server *should* be handled on the server. There are two reasons for that:

1. The less the client is responsible for, the easier it is to develop a new client for a different platform
2. It makes it a lot harder to cheat

The server should be the one who decides what state the game is currently in and reject any commands which aren't valid in the current state.

---
Tags: javascript, html5, browser-based-games
---


title: How to file down a fingernail mesh?

text:
# Question
Title: How to file down a fingernail mesh?
I am creating a nail salon 3D game where I need to implement nail filing mechanics. I have tried out approaches including mesh deformation but I'm concerned about performance as I am targeting mobile platforms.

How can I shape a nail efficiently for mobile devices?

# Answer
> 21 votes
Myself, I'd approach this by keeping the mesh fixed and unchanging, and using a texture to shave away the edge.

You can make a signed distance field of your nail shape, and use this in your shader to get a smooth, crisp edge on it, even if the texture you're working with is quite low-resolution.

I didn't have a nail mesh handy, so here I'm using this SDF texture on a stretched sphere to get roughly the curvature I wanted. Note how we can get an edge much smoother and more detailed than our underlying triangle mesh, even using just a 128x256 texture.

When you start a fresh nail, you'll blit your source nail SDF texture into a RenderTexture, letting you modify it frame by frame.

By blitting tool shapes into your RenderTexture with "min" blending, you can shave away from the edge of the nail. For example, blending with a linear gradient will give you a straight-line cut-off, like you'd get from a flat nail file. You could also make textures with arched gradients to simulate nail clippers, etc.

This subtractive process is super cheap - similar in cost to drawing a particle - so you can stack up lots of small modifications frame by frame to shave and sculpt the nail in realtime.

---
Tags: unity, mobile, dynamic-mesh, mesh-deformation
---


# Question
Title: How do fixed-point physics (engines) work?
I would think there should be an abundance of excellent articles answering this question, but my searches have come up completely empty.

I am developing an embedded graphics engine on a microcontroller which does not have an FPU or math co-processor.

I read somewhere before during my research that reasonably precise physics can be implemented without floating point math by using fixed point math.

How exactly does this work? What generally would be the programmatic behavior of a physics engine with some time step `dt`?

# Answer
**TL;DR** they *work* exactly the same; the difference comes from trade-offs like performance, value range and (sometimes) syntax.

It's is possible to simulate floating- or fixed-point math, you just have to write all logic yourself (or use library). The only limits are your creativity and resulting performance overhead.

Fixed-point math may be considered a subset of floating-point math, where exponent is constant. This leads to fewer instructions (no need to read exponent and do calculations on it) and smaller data types (no need to store exponent).

If your language of choice supports operator overloading, then syntax won't be too much different from floating-point universe: `x * y` is same thing in both worlds. Copy-pasting some premade physics engine and replacing data types it operates on *might* just work. In case you are less lucky with language, then I wish you patience, because turning every `b*x + a` into `add(mul(b, x), a)` is tedious task.

Next, because exponent is fixed, the possible range of fixed-point numbers is severely limited. It's not a problem for storing things like coordinates, because even in floating-point engines objects don't go too far from origin — but when they do, coordinates start to loose precision and physics becomes wonky, so game designers try to avoid that.

But for intermediate operations this loss of range matters. If numbers go out of range during fixed-point calculations, information will be lost. (Yes, you can go out of range with floating points too, but it's much harder to do so.) This issue can be mitigated by promoting values to bigger types during calculations, but it incurs further performance costs.

To avoid underflow and overflow issues, it's better to choose all units of measurements such that most variables (and constants) will be as close to `1.0` as possible. For instance, distance of `x = 0.001` units may seem not too bad for `int16` \+ `int16` fixed-point data type, but calculating area `x*x` will blow out of range.

Using very small units of measurements stored as integers (as proposed in comments) is possible as well. Integer values may be considered special case of fixed-point without fractional part. In some calculations, using pure integers will result in even faster code.

As a side note, I presume it'll be impossible to get rid of fixed-point completely, because they have nice property of shrinking values by multiplication. You'll also would need them for all sorts of unit-less multipliers that must be compatible with any other unit type — imagine scaling object's size, weight and acceleration with same curve.

At last, it may be good idea to assign and display all values via conversion functions: `meters(3)` looks more readable than `3 * 0xFFFF` and allows to easily change unit representation later, would the need arise. Again, some programming languages (C++) allow to introduce measurement units into type system to protect you from mistakes and even allow to define custom suffixes, so it will be possible to write previous example as `3m`.
> 4 votes

# Answer
I've been using FixedPoint (FxP) for last several years across multiple 8/16/32/64 bit platforms (mostly in Assembler).

The single most problematic issue with FxP is occasional overflow during multiplication. Very hard to reproduce and debug if it happens at 1 frame out of 1,000, especially in Assembler.

I would very strongly recommend doing initial prototyping in as high-level language as possible (even if you are targeting ASM). Just spend a weekend creating a reference floating-point functionality, save the ranges of all values into some global Min,Max variables and only then start refactoring it to work in FxP.

You might find you don't even need FxP - just 32-bit integer - as long as all computations are done in 32-bit integer space, then it doesn't matter.

Alternatively, a simple hack is to shift 8x (e.g. 24.8) - for most purposes it gives sufficient precision - but you must confirm your dataset will be fine with it (or adjust environment).

For things like Global Illumination (Radiosity Form Factors) - it's even possible to use 32-bit Integer approximation to form factors (double fp precision originally).

Can you double check if your target platform doesn't accidentally support intermediate results in higher precision ? Meaning while you can't access full 24-bit intermediate result (for 16-bit ops), internally the ALU will work with more bits than you have access to (via registers).
> 1 votes

---
Tags: physics-engine, fixed-timestep, fixed-point
---


title: What is SpriteStudio?

text:
# Question
Title: What is SpriteStudio?
In the game, I've seen asset types for animations that are of SpriteStudio. I have searched the documentation and cannot find any information on what this is.

I looked at the template project that purportedly covers SpriteStudio, but I don't see anything that really explains how to use it. There are various entities of type "SpriteStudio" that reference assets called SpriteStudio Animations. These assets show their source to be files with a ".ssae" extension. I assume these entities, assets, and resources are purposed to create the 2D animations within the demo.

I don't see how to generate ".ssae" files, nor is there any editor that I could find for the SpriteStudio Animation assets.

Is SpriteStudio separate software? Is it a sub-editor of the Game Studio? How do I create ".ssae" files?

# Answer
> 2 votes
SpriteStudio is an external software for 2d animation that Xenko supports back, I believe when it's own by Silicon Studio (I think it does make sense since Xenko is originally a Japanese game engine, and SpriteStudio is of Japan, too). I also know that fact from the documentation site, but can't find it anymore now (maybe Stride won't support it anymore?).

You can see the website here

---
Tags: 2d, animation, stride
---


# Question
Title: How to generate a multiplier map for radiosity
I am following this tutorial: here I am at the part where you are creating a hemicube. I have got the code to render the scene into a texture and therfore an array.

Now how can I generate a so-called "multiplier map" for use given these parameters: width, height, camera location, camera direction/normal.

I want the multiplier map to be stored in an array like this:

```
unsigned char* mult0 = new unsigned char[width*height];

```

I will have 5 of these maps for each side of the hemicube.

# Answer
```
multiplier = new GLfloat[SCREEN_WIDTH*SCREEN_HEIGHT];// calc multiplier map
GLfloat* row = new GLfloat[SCREEN_WIDTH];
float factor = 90/SCREEN_WIDTH;
for (int i = 0;i < SCREEN_WIDTH;i++)
  row[i] = cos(DEG_TO_RAD(i*factor));

for (int i =0;i < SCREEN_HEIGHT;i++)
  std::copy(row, row + SCREEN_WIDTH, multiplier + (i*SCREEN_WIDTH));
delete row;

normalise(multiplier,SCREEN_WIDTH*SCREEN_HEIGHT);

```

Check your tutorial to normalize the map
> 0 votes

# Answer
I would strongly recommend against using that particular tutorial for direct implementation, from personal experience.

Rather, implement a progressive refinement approach, where in each pass you select a Shooter with highest unsent radiance (initially all lights), and compute form factors from that shooter against every other patch.

This way you will have a generic CPU solution that can be used off-line (at loading time or by other tool).
> 0 votes

---
Tags: opengl, c++, 3d, lighting
---


title: Constant Buffer Alignment issues

text:
# Question
Title: Constant Buffer Alignment issues
I have issues with constant buffer member alignments. I have the following C++ struct:

```
namespace Renderer {
    using DirectX::SimpleMath::Matrix;
    using DirectX::SimpleMath::Vector3;
    using DirectX::SimpleMath::Vector2;
    struct alignas(16) CCameraMatrixBuffer
    {
        Matrix ViewProjection;
        //--
        Matrix View;
        //--
        Matrix Projection;
        //--
        Vector3 CamPositionWS;
        int CameraUnderwater;
        //--
        Vector3 CamDirectionWS;
        unsigned int RoomNumber;
        //--
        Vector2 ViewSize;
        Vector2 InvViewSize;
        //--
        unsigned int Frame;
        //--

    };
}

```

and this HLSL counterpart:

```
    cbuffer CameraMatrixBuffer : register(b0)
{
    float4x4 ViewProjection;
    float4x4 View;
    float4x4 Projection;
    float3 CamPositionWS;
    int CameraUnderwater;
    float3 CamDirectionWS;
    unsigned int RoomNumber;
    float2 ViewSize;
    float2 InvViewSize;
    unsigned int Frame;
};

```

however, when i debug the shader, CamDirectionWS shows the following:

The `1024.000f` is part of the ViewSize (the resolution). Can someone tell me whats wrong with it?

# Answer
Review the HLSL cbuffer packing rules here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-packing-rules

> HLSL packing rules are similar to performing a #pragma pack 4 with Visual Studio, which packs data into 4-byte boundaries. Additionally, HLSL packs data so that it does not cross a 16-byte boundary. Variables are packed into a given four-component vector until the variable will straddle a 4-vector boundary; the next variables will be bounced to the next four-component vector.
>
> Each structure forces the next variable to start on the next four-component vector. This sometimes generates padding for arrays of structures. The resulting size of any structure will always be evenly divisible by sizeof(four-component vector).

So, for example, your float3s are actually being padded-out to float4 size in your HLSL.

To resolve, either pad out your C++ struct to match, or use packoffset in your HLSL.

An example of using packoffset:

```
cbuffer test0 {
    float3 this : packoffset(c0.x);
    float that: packoffset(c0.w);
};

```

This will pack the cbuffer as you probably expect.
> 3 votes

---
Tags: c++, shaders, directx11, hlsl
---


# Question
Title: Smooth player input direction when changing camera
I'm working on an exercise using fixed cameras like how they work in the PSX final fantasy games. I have the camera scripts working fine but it's an aspect of the character control that I'm struggling with.

My character moves relative to the cameras facing position, but when the camera suddenly changes to another angle, my running direction instantly and abruptly changes too. In the final fantasy games it sort of keeps going roughly in the same direction you were briefly.

```
input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
input = Vector2.ClampMagnitude(input, 1);

// get camera direction
// need to add something here for in between camera switches!
camF = Camera.main.transform.forward;
camR = Camera.main.transform.right;
camF.y = 0;
camR.y = 0;
camF = camF.normalized;
camR = camR.normalized;

transform.position += (camF * input.y + camR * input.x) * Time.deltaTime * 8;

```

I saw someone with a similar game comment on an article with his solution, but I don't quite know how to put it into code. The quote;

> "Player just gets a rotation based on where the camera is looking and multiplies the character’s motor force by that .forward and .right. I only update that rotation after a big delta in input so you can smoothly move between shots."

This is his small (online) game which he's talking about, I'm trying to mimic the movement basically; https://ocias.com/games/foggy-shore/

Can anyone give me some pointers?

---

Updated:

It doesn't quite play how it does in the demo game, but it's getting there.

```
    input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
    input = Vector2.ClampMagnitude(input, 1);

    if (!cameraChanged) {
        _lastCameraInput = input;
        camF = Camera.main.transform.forward;
        camR = Camera.main.transform.right;
        camF.y = 0;
        camR.y = 0;
        camF = camF.normalized;
        camR = camR.normalized;

    } else if (Vector3.Dot(input, _lastCameraInput) <= -0f) {
        cameraChanged = false;
        }

    transform.position += (camF * input.y + camR * input.x) * Time.deltaTime * 8;

```

# Answer
> 0 votes
Here's one potential implementation of this behaviour:

```
Quaternion _lastCameraFacing;
Vector2 _lastCameraInput;

void Start() {
    _lastCameraFacing = Camera.main.transform.rotation;
}

void Update() {
    var input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
    input = Vector2.ClampMagnitude(input, 1);

    var cameraFacing = Camera.main.transform.rotation;
    // If our camera angle has changed abruptly,
    // store our current input to compare against in future frames.
    if (Quaternion.Angle(cameraFacing, _lastCameraFacing) > 30f) {
        _lastCameraInput = input;
    } else if (Vector3.Dot(input, _lastCameraInput) <= 0f) {
        // If we let go of the stick, or turn 90+ degrees,
        // switch to using the latest camera angle.
        _lastCameraFacing = cameraFacing;
    }

    // Keep using the saved camera angle for movement.
    var camF = _lastCameraFacing * Vector3.forward;
    var camR = _lastCameraFacing * Vector3.right;
    camF.y = 0;
    camR.y = 0;

    camF = camF.normalized;
    camR = camR.normalized;

    transform.position += (camF * input.y + camR * input.x) * Time.deltaTime * 8;
}

```

---
Tags: unity, camera, input
---