# Question
Title: How to simulate destruction/damage of household objects?
I'm looking for a method to simulate various objects' damage and destruction.

As far as I can see, Unreal Engine 4's Chaos can only simulate buildings, but I'm more interested in other type of objects. I found DestroyIt for Unity, but the author must manually create all destructions which is not really a simulation.

For example, if I had a TV sitting on a table, how could I simulate both the TV's and table's realistic destruction if something heavy falls on top of them?

# Answer
> 1 votes
As DMGregory said, realistic destruction effects are *hard*. You have to weigh realism against practicality when designing a game with high levels of destructibility. You can write an algorithm that can dynamically split a wooden table into several chunks of wooden debris, but you can't write an algorithm that knows what the inside of a TV looks like or which parts of a model are metal and which are plastic.

There are two approaches that immediately come to mind when I think about practical destructible objects and what I've seen in commercial games:

1. A "gibs"-style approach, where when you smash something, it explodes into little bits of materials. The term "gibs" usually refers to organic gore that explodes from enemies when they are killed, such as bits of bone or chunks of flesh; however, the same principle can be applied to any object. For example, if you smash a table, it could explode into random chunks of wood. If you smash a modern TV, it could explode into chunks of metal, glass, plastic, and circuit boards. A large object should have more gibs and/or larger gibs than a small object. This isn't super realistic, but it's also a reasonably easy system to implement. You would just need to add a little bit of data to each destructible model indicating what kinds of gibs should come out of it, and in what proportion.
2. When an object is smashed, it turns into several premade pieces of debris. For example, when the player smashes the table, the table model is removed and replaced with a ragdoll table-top and four ragdoll legs. If you smash a PC, maybe it's replaced with a ragdoll case, a ragdoll side panel, and a couple of ragdoll hard drives. You can see the problem here - if you want the ragdoll debris to match the object that was smashed, you have to create several separate ragdoll models for *every single* destructible object in your game.

One compromise is to use premade ragdoll debris for certain objects that are likely to be smashed/be more noticeable when they are smashed, and use the "gibs" approach for other objects.

---
Tags: physics, procedural-destruction
---


# Question
Title: How can I lerp between two numbers setting the lerp time each 0.3f seconds?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BlendShapesController : MonoBehaviour
{
    private SkinnedMeshRenderer bodySkinnedMeshRenderer;
    private bool randomizeNumbers = true;

    // Start is called before the first frame update
    void Start()
    {
        bodySkinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();
        StartCoroutine(RandomNumbers());
    }

    // Update is called once per frame
    void Update()
    {
        if(randomizeNumbers == true)
        {
            StartCoroutine(RandomNumbers());

            randomizeNumbers = false;
        }
    }

    IEnumerator RandomNumbers()
    {
        int rand = Random.Range(0, 23);
        bodySkinnedMeshRenderer.SetBlendShapeWeight(0, rand);

        yield return new WaitForSeconds(0.3f);

        randomizeNumbers = true;
    }
}

```

Now I'm using a random number betwen 0 and 23 every 0.3f seconds. I want to change it so it will lerp in the SetBlendShapeWeight at index 0 but instead rand it will lerp from 0 to 23 then from 23 to 0 when done stop waiting seconds.

So the time or speed should be set for the lerp and according to that how much time to wait. For example if the lerp will take 5 seconds from 0 to 23 and then back from 23 to 0 then after 5 seconds start the Coroutine again.

The idea is to make some kind of mouth talk fake/cheat. So I want to mouth to be open/close smooth between 0 and 23 and then 23 to 0 before starting the new Coroutine and to be able to decide how much time it will take to make the lerp from 0 to 23 and 23 to 0.

In the screenshot when the blendshape of the mouth is set to 0 the mouth is open at 23 or 27 the mouth is closed. So I want to simulate mouth talking between this range of numbers for example each 0.3f make the mouth close/open then after 0.3f again mouth close/open and so on.

# Answer
```
//Lerp between startValue and endValue over 'duration' seconds
private IEnumerator LerpShape(float startValue, float endValue, float duration) {
    float elapsed = 0;
    while (elapsed  < duration) {
        elapsed += Time.deltaTime;
        float value = Mathf.Lerp(startValue, endValue, elapsed / duration);
        bodySkinnedMeshRenderer.SetBlendShapeWeight(0, value);
        yield return null;
    }
}

private bool talking = true;
//animate open and closed, then repeat
private IEnumerator AnimateMouth() {
    while (talking) {
        //yield return StartCoroutine waits for that coroutine to finish before continuing
        yield return StartCoroutine(LerpShape(0, 23, .5f));
        yield return StartCoroutine(LerpShape(23, 0, .5f));
    }
}

```
> 1 votes

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


title: Functions in the game loop

text:
# Question
Title: Functions in the game loop
I'm learning about the game development. No i'm on the total basics - writting a proper `game loop`. As i've searched over the Web i'v found that simple but good working pattern using so called fixed time step:

```
double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previous;
  previous = current;
  lag += elapsed;

  processInput();

  while (lag >= MS_PER_UPDATE)
  {
    update();
    lag -= MS_PER_UPDATE;
  }

  render();
}

```

I roughly understand the logic behind this piece of code but i have the question regarding the game composition. What exactly the update function do and what the render function. What's their responsibility? Am i assuming right that in the super simple 2D game the update function can for e.g. calculate the distance in pixels the object (e.g. a Car) should move in the next frame and the render function in such a case just takes this calculated position and draws the Car on the screen? Correct me if i'm wrong and please provide some example/s.

Thx.

PS. Sorry for such a basic question but i'm really beginner.

# Answer
> 1 votes
What this simple pattern is still missing is the **game state**. The game state is a data structure which contains all the information about the current state of the game. All the entities in the game, their type, their positions and every other information about them.

The purpose of the update-function is to update the game state. For example, if every entity in your game has a velocity, then the update-function would be responsible for changing the position of each entity by its velocity. It would then compare their new positions and see if there are any collisions. And when there are, it would do whatever is supposed to happen in case of a collision.

The purpose of the render-function is then to visualize the game state to the player by drawing it onto the screen.

---
Tags: c++, architecture, game-loop
---


# Question
Title: How can I render a font in C with OpenGL?
# What I tried:

I was testing some things in order to render text with stb\_truetype.h and OpenGL in C.

I took as a reference the example that appears here. Basically, this example, loads a .ttf file and returns the raw information in bytes, that can be used to generate a texture in OpenGL.

I adapted the example, mentioned before, into modern OpenGL, because, the example uses OpenGL deprecated functions, like `glVertex2f`. The only thing I get to output on screen was this kind of noise of strange colors:

# The code I use:

```
texture_t fnt_texture;
GLuint fnt_shader;

unsigned char ttf_buffer[1 << 20];
unsigned char temp_bitmap[512 * 512];

stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs

#define FONT_VS\
    "#version 330 core\n"\
    "layout(location = 0) in vec3 m_Position;"\
    "layout(location = 1) in vec2 m_TexCoords;"\
    "out vec2 TexCoords;\n"\
    "void main() {\n"\
    "TexCoords = m_TexCoords;\n"\
    "gl_Position = vec4(m_Position, 1.0);\n"\
    "}\n"\

#define FONT_FS\
    "#version 330 core\n"\
    "in vec2 TexCoords;\n"\
    "uniform sampler2D Texture;\n"\
    "void main() {\n"\
    "gl_FragColor = texture(Texture, TexCoords);\n"\
    "}\n"\

void font_init(void)
{
    fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
    stbtt_BakeFontBitmap(ttf_buffer, 0, 32.0, temp_bitmap, 512, 512, 32, 96, cdata); // no guarantee this fits!

    glGenTextures(1, &fnt_texture[3]); // My texture type, is an array that saves the texture on the 3rd position.
    glBindTexture(GL_TEXTURE_2D, fnt_texture[3]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 512, 512, 0, GL_RGBA, GL_UNSIGNED_BYTE, temp_bitmap);
    glGenerateMipmap(GL_TEXTURE_2D);

    // can free temp_bitmap at this point
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glBindTexture(GL_TEXTURE_2D, 0);

    fnt_shader = shader_init(FONT_VS, FONT_FS);
}

void font_render(model_t model)
{
    shader_bind(fnt_shader);
    texture_bind(fnt_texture, 0);

    model_begin(model);
    model_draw(model, GL_TRIANGLES); // The model (vao, vbo, ibo) is rendering the whole buffer, not individual glyphs
    model_end();

    texture_unbind();
    shader_unbind();
}

```

Can someone tell me what I'm doing wrong, and, how I'm suposed to render correctly text, with modern OpenGL, with textures and buffers, in order to read the .ttf file and create the necessary information with stb\_truetype.h and, then, render the text?

# Answer
> 0 votes
I'm not an OpenGL expert and since you didn't give us a working example I can't say much about your code but here is an example with a little game library (noengine) that I'm working on. and here is my draw function and here is my shader. I hope it helps.

/*
# run me with 'bash stbttHello.c build'
if [ "$1" == "xterm-send" ]; then xterm-send bash $0 $2 ; exit 1 ; fi
echo -ne "\033c"

sdir=`dirname $0`
odir=${sdir}/../bin
ofilename=`basename $0 .${0##*.}`
ofilepath=${odir}/${ofilename}

mkdir -p $odir
cd $odir

build="gcc $0 -o $ofilepath -I$sdir/../src -I/home/raoof/git/stb -lm -lSDL2 -lGL  -fmax-errors=5"
build="tcc $0 -o $ofilepath -I$sdir/../src -I/home/raoof/git/stb -lm -lSDL2 -lGL  -fmax-errors=5 -DSDL_DISABLE_IMMINTRIN_H"

cmd=$1
echo $cmd...
if [ "$cmd" == "build" ]; then
time $build &&
$ofilepath ; echo $?
elif [ "$cmd" == "debug_build" ]; then
time $build -g &&
gdb -ex r -ex="bt" -ex="set confirm off" -ex=quit $ofilepath
fi
exit 1
*/

#define NOENGINE_IMPLEMENTATION
#include "noengine.h"
#define STB_TRUETYPE_IMPLEMENTATION
#include "stb_truetype.h"

unsigned char ttf_buffer[1<<20];
unsigned char temp_bitmap[40][199];
unsigned char textureData[4*40*199];
int textureWidth = 199;
int textureHeight = 40;
int fontSize = 32;

stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
GLuint ftex;

ObjectT image;
float vertexData[12] = {0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1};
stbtt_fontinfo font;

void init() {}

void ginit() {
  fread(ttf_buffer, 1, 1<<20, fopen("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", "rb"));
  stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));

  int i,j,ascent,baseline,ch=0;
  float scale, xpos=2; // leave a little padding in case the character extends left
  char *text = "Hello world!"; // intentionally misspelled to show 'lj' brokenness

  scale = stbtt_ScaleForPixelHeight(&font, fontSize);
  stbtt_GetFontVMetrics(&font, &ascent,0,0);
  baseline = (int) (ascent*scale);

  while (text[ch]) {
     int advance,lsb,x0,y0,x1,y1;
     float x_shift = xpos - (float) floor(xpos);
     stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
     stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
     stbtt_MakeCodepointBitmapSubpixel(&font, &temp_bitmap[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, textureWidth, scale,scale,x_shift,0, text[ch]);
     xpos += (advance * scale);
     ++ch;
  }

  for(size_t i = 0 ; i < textureWidth ; i += 1) {
    for(size_t j = 0 ; j < textureHeight ; j += 1) {
      textureData[4 * (j * textureWidth + i) + 0] = 255;
      textureData[4 * (j * textureWidth + i) + 1] = 255;
      textureData[4 * (j * textureWidth + i) + 2] = 255;
      textureData[4 * (j * textureWidth + i) + 3] = temp_bitmap[j][i];
    }
  }
  ObjectT_init(&image);
  image.textureWidth = textureWidth;
  image.textureHeight = textureHeight;
  image.textureBytesPerPixel = 4;
  image.vertexData = vertexData;
  image.vertexDataLength = sizeof(vertexData) / sizeof(float);
  image.textureCoordinateData = vertexData;
  image.textureCoordinateDataLength = image.vertexDataLength;
  image.textureData = textureData;
  image.transform.size = (Vector) { textureWidth, textureHeight, 0 };
  ObjectT_update(&image);
}

void output() {
  ObjectT_draw(&image);
}

void input() {
}
```

---
Tags: opengl, graphics, c, fonts, ui-design
---


# Question
Title: OOP architecture problem between Camera, Player, Weapon
I am making an FPS game in Unity, trying to keep myself to OOP principles as much as I can but I found dead-end.

I want to add recoil to my game, now logically thinking the amount of recoil should be stored in the Weapon instances, but the recoil itself should be done by the Camera. The problem here, it doesn't make sense for the weapon to have a dependency towards the Camera, I think this could cause trouble down the line. I thought of making an Action (observer pattern), where the Weapon is a broadcaster while the Camera is an observer.

The problem here is there will be multiple players, so the Camera instance shall know if it's their Player who made the shot (the weapon would broadcast it's Player reference as well), so in order to do this, every Camera should store a reference to their own Player which again brings the problem I described with the gun. The Camera shouldn't have a reference to its player, for example, if I later want to add the ability to spectate a game, this would cause problems.

* So the Player can have a Camera dependency
* The Camera shouldn't have any dependencies
* The Weapon can have a Player dependency

How would one go about implementing this recoil, how could I avoid the problems I've described?

# Answer
One simple method is to add a `UnityEvent`. Here I've chosen to put it on the character controller, so I don't need to rewire it each time the player picks up a new weapon.

```
public class FPSController : MonoBehaviour {
    [System.Serializable]
    public class RecoilEvent : UnityEvent<Vector3> {}

    public RecoilEvent onRecoil;

    // In Unity 2020+, you can skip the class definition and just write:
    // public UnityEvent<Vector3> onRecoil;

    Weapon _currentWeapon;

    // Code for handling player input and movement goes here...

    void Fire() {
        Vector3 recoil = _currentWeapon.Fire();

        // Pass the recoil information along to anything that needs to react.
        // (Could include camera, reticle UI, character animation, even health!)
        if(onRecoil != null)
            onRecoil.Invoke(recoil);
    }
}

```

Now weapons just have to honour a contract that, when fired, they report back the recoil that results from that firing. I'm using a simple `Vector3` here, but it could be a struct with more sophisticated recoil parameters, or even a reference to a `ScriptableObject` asset that you use to tune your various recoil profiles.

```
public class Weapon : MonoBehaviour {

    // Do ammo/cooldown management
    // (or delegate that responsibility to its own component)...

    public Vector3 Fire() {
        // Do the shooty bits...

        // Compute the appropriate recoil effect as needed.
        Vector3 recoil = GetRecoilVector();

        return recoil;
    }
}

```

Now your camera controller can expose a public method to anything that wants to apply a jerk to the camera:

```
public class CameraControl : MonoBehaviour {

    public void ApplyImpulse(Vector3 impulse) {
        // I'm agnostic as to the source of this impulse,
        // this method will just push the camera around.
        // So now you can re-use it for explosions, melee hits, etc.
    }
}

```

Note that there's no coupling here between the weapon and anything else. The weapon doesn't know who uses its recoil, and the camera doesn't know where the impulse came from, or even what "recoil" is. Neither the weapon nor camera need to know about `RecoilEvent` \- as long as they both speak a common language (here, `Vector3`), they can communicate.

You can wire up this connection in data at design time, say if you have a "local player avatar" prefab that has the character, weapon, and camera all together.

Or it can be wired up at runtime by the code that spawns the local player avatar and their camera:

```
FPSController avatar = Instantiate(localPlayerAvatarPrefab, spawnPosition, spawnOrientation);
FPSCamera camera = Instantiate(cameraPrefab);

camera.AttachToCharacter(avatar);
avatar.onRecoil.AddListener(camera.ApplyImpulse);

// This can of course include multiple listeners, if you have multiple systems that
// care about recoil, but don't all live inside the same prefab.
avatar.onRecoil.AddListener(fpsHUD.OnShoot);

```
> 1 votes

---
Tags: unity, architecture, oop
---


# Question
Title: Is there a way to normalize for both ways in Unity?
I have a building, built in blender, that has been imported to Unity. And I flipped every necessary piece and calculated the normals inside in blender. However, since I made the rooms inside the building with just a single cube, it's only visible from one side like they're not visible until I go the way around. Is there a way to solve this?

# Answer
> 1 votes
You usually do not want your polygons to draw from both sides in a game.

If you're standing outside a building, you want to see the outside faces that point toward you. You don't want to waste time and GPU resources drawing the back side of the building.

Similarly when you're standing inside a building, you want to see the faces of the interior walls. You don't want to waste time drawing the outside of the building that's not visible from where you're standing.

This lets us cut down the GPU workload by almost a factor of 2 - a huge savings! (Imagine being able to take a game and double its fps rate without sacrificing visual quality on any visible surface)

If you configure your polygons to be drawn from both sides, you lose this optimization, so the GPU has to spend time drawing the inner faces of things only to draw over them with the outer face later.

Also, the mesh still has only one shading normal, so your shader needs to detect when it's drawing the "wrong" side of the polygon and flip the normal for lighting, slightly increasing the complexity of your shader.

For all of these reasons, I would strongly recommend that you keep your material single-sided. Interior rooms should have their own polygons, separate from the outer shell of the building (real walls have thickness, after all), that face inward. If you make these interiors a separate mesh, they can be culled entirely when not visible from the outside, if you set up your scene appropriately.

That said, if you want a dual-sided material, here's how you can modify the default new Surface Shader to accomplish it:

1. Add `Cull Off` to the top of the shader, just before `CGPROGRAM`. This says not to cull triangles based on their facing direction, so both the fronts and backs of triangles will be draw.
2. Add `fixed facing : VFACE;` to your `Input` structure. This is a special shader semantic that the GPU pipeline will populate with a negative value when drawing the back of a triangle, and a positive value for the front.
3. Inside your `surf` function, add `o.Normal = o.Normal * IN.facing;` to flip the normal for back faces.

Here's the full shader:

```
Shader "Custom/DoubleSidedLit"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        Cull Off

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input
        {
            float2 uv_MainTex;
            fixed facing : VFACE;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
        // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
        // #pragma instancing_options assumeuniformscaling
        UNITY_INSTANCING_BUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            o.Normal = o.Normal * IN.facing;

            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

---
Tags: unity, rendering, blender, 3d-meshes, normals
---


# Question
Title: Taking advantage of multithreading between game loop and openGL
Talking in context of a game based on openGL renderer :

Let's assume there are two threads :

1. Updates the game logic and physics etc. for the in game objects
2. Makes openGL draw calls for each game object based on data in the game objects (that thread 1 keeps updating)

Unless you have two copies of each game object in the current state of the game you'll have to pause Thread 1 while Thread 2 makes the draw calls otherwise the game objects will get updated in the middle of a draw call for that object, which is undesirable!

But stopping thread 1 to safely make draw calls from thread 2 kills the whole purpose of multithreading/concurrency

Is there a better approach for this other than using hundreds or thousands or sync objects/fences so that the multicore architecture can be exploited for performance?

I know I can still use multithreading for loading texture and compiling shaders for the objects which are yet to be the part of the current game state but how do I do it for the active/visible objects without causing conflict with draw and update?

What if I use separate sync lock in each of the game object? This way any thread would only block on one object (ideal case) rather than for the whole update/draw cycle! But how costly is taking locks on each object (game may have a thousand objects)?

# Answer
> 13 votes
The approach you've described, using locks, would be very inefficient and most likely slower than using a single thread. The other approach of keeping copies of data in each thread would probably work well "speed-wise", but with a prohibitive memory cost and code complexity to keep the copies in sync.

There are several alternative approaches to this, one popular solution for multi-threaded rendering is by using a double-buffer of commands. This consists of running the renderer back-end in a separate thread, where all draw calls and communication with the rendering API are performed. The front-end thread that runs the game logic communicates with the back-end renderer via a **command buffer (double-buffered)**. With this setup, you only have one synchronazation point at the completion of a frame. While the front-end is filling one buffer with render commands, the back-end is consuming the other. If both threads are well balanced, none should starve. This approach is suboptimal however, since it introduces latency in the frames rendered, plus, the OpenGL driver is likely to be already doing this in its own process, so performance gains would have to be carefully measured. It also only uses two cores, at best. This approach has been used in several successful games though, such as Doom 3 and Quake 3

More scalable approaches that make better use of multi-core CPUs are the ones based on independent tasks, where you fire an asynchronous request that gets serviced in a secondary thread, while the thread that fired the request continues with some other work. The task should ideally have no dependencies with the other threads, to avoid locks (also avoid shared/global data like the plague!). A task-based architectures is more usable in localized parts of a game, such as computing animations, AI pathfinding, procedural generation, dynamic loading of scene props, etc. Games are naturally event-full, most kinds of events are async, so it is easy to make them run in separate threads.

Finally, I recommend reading:

# Answer
> 0 votes
https://github.com/quartermeat/aeonExMachina

I'm using Go routines to give every object it's own update thread and it's own draw thread. I'm drawing 400 sprites at 30 fps, but adding collision detection is going to be interesting.

---
Tags: opengl, c++, android, opengl-es2
---


# Question
Title: Unity highlight/outline mesh edges/border (make them visible)
Let's say I create a cube using mesh triangles similar to the graph below. I would like to make those 12 edges visible in play mode so user/player can see them too (but without the diagonals).

What would be the best way to approach this problem in unity? Hundreds of cubes will be created in run time using mesh/triangles and the vertices position (vector3 value) will change at some point, so I am wondering if there's a way that allows those edges to change/move along when the mesh/triangles change and the edges still remain visible the whole time.

The desired outcome should be similar to the shaded wireframe in the scene view. Any help would be appreciated.

# Answer
> 1 votes
Wireframe without Diagonal Combine this shader code with any shader code/file using mutiple pass solved the problem. It's also possible to use multiple materials but that may slow performance.

Note: Unfortunately, this solution uses geometry shader which is not supported in mobile devices.

---
Tags: unity
---


title: Gradient Input in Game view

text:
# Question
Title: Gradient Input in Game view
I want to develop a little tool to help visualize fireworks before using them in a show in Unity where the user can set several parameters and gets a preview of the firework effect in a preview window. To allow the user to customize color over time like I can currently statically do in the visual effects graph, I wanted to add a Gradient input field to my UI.

After fiddling around with manually trying to make things work, I stumbled upon the new UIElements / UI Toolkit and following this Medium post was able to render a simple text UI in a Panel Renderer. However the Gradient Field I added won't show up (which is quite reasonable because in the UI Builder it said something about "Editor only").

Just to make sure, the box on the left is what I mean:

I was strolling around in the Asset Store for a while but couldn't find anything like what I was looking for (just shaders and stuff to apply a gradient to UI elements amongst other things). Other searches led to tutorials on how to completely custom build a single color selection tool which both seemed like a larger effort and didn't allow creating a full gradient.

The question is: Is there some sort of library, package or tool I could use to add an input like that to my "game"? Or am I taking a completely wrong approach with this?

# Answer
It turns out that I am utterly bad at googling things! While "unity gradient input" and several attempts at going at it from UIElements and UI Toolkit didn't yield result, a brainfart reminded me that the thing you select a color in is called a color picker and look at that, there actually *is* an implementation of both a color and gradient picker available for free in the Easy Color & Gradient Picker.

It comes with a handy PDF telling you how to set up things and while intensity is not part of the input, building the gradient comes very close to the editor built in controls:
> 1 votes

---
Tags: unity, gui, input, unity-ui
---


title: Devkitpro msys errors

text:
# Question
Title: Devkitpro msys errors
Whenever I try to install devkitPro, I get these command prompt windows for short periods of time with the following errors:

```
error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
:: Synchronizing package databases...
 msys                                           206.2 KiB   729K/s 00:00 [#######################################] 100%
 msys.sig                                       438.0   B   214K/s 00:00 [#######################################] 100%
error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
error: failed to update msys (invalid or corrupted database (PGP signature))
 dkp-libs is up to date
 dkp-windows is up to date
error: failed to synchronize all databases

```

```
error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
error: database 'msys' is not valid (invalid or corrupted database (PGP signature))

```

```
error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
error: database 'msys' is not valid (invalid or corrupted database (PGP signature))

```

```
error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
error: database 'msys' is not valid (invalid or corrupted database (PGP signature))

```

Interestingly enough, when I go to the C:/devkitPro folder, I find that I have no devkitpro related files in there whatsoever - just an msys2 folder. I did manage to find a repository online with the files that would have been installed... but when I try to build a project, it says that it can't find the appropriate .specs file.

I would like to know if there is any way I can properly install devkitPro on my windows 10 device. Thanks in advance

# Answer
The msys2 issue could be solved by updating your key stores:

```
curl -O http://repo.msys2.org/msys/x86_64/msys2-keyring-r21.b39fb11-1-any.pkg.tar.xz
curl -O http://repo.msys2.org/msys/x86_64/msys2-keyring-r21.b39fb11-1-any.pkg.tar.xz
pacman-key --verify msys2-keyring-r21.b39fb11-1-any.pkg.tar.xz.sig

```

Then, re-run `pacman -Syu`. By default, msys2 will not install devkitPro to `C:\devkitpro`, but to somewhere like `/opt/devkitpro` within msys2.
> 1 votes

---
Tags: nintendo
---


# Question
Title: Find grid cells in 2D grid based on object size and rotation
I am working on a game that uses a grid system that allows the player to place buildings in the world. Each cell in the grid is 64x64. All buildings will be a multiple of 64x64, so everything will evenly fit in the the grid.

Below shows an example of a building that is 128x64 and placed at grid position 64x64. The client sends the server the "base" cell, which in this case is 1,1 (@64x64), and knows the building that is being build is 128x64 so it sets both cells to the "occupied" state which means a building is placed in those 2 grids.

The problem I am having is allowing the client to rotate the building either 90, 180, or 270 degrees.

For example, if the client wanted to place the same building, but rotated 90 degrees, it would look like this:

Basically what I am asking is: Given the client sends to server the location to build 64x64, and sends 90 for the rotation, how can I (on the server) figure out which cells are going to be build on?

Currently I am using this code to get the grids, but it doesn't allow for rotation since I have no idea.

https://pastebin.com/UaaUa7jZ

Any help would be appreciated.

# Answer
I have previously implemented something similar for determining placement of items within a 2D grid and hope that sharing my ideas with you will provide some guidance.

It helps to normalise the coordinates for the items being placed into an offset around the origin as well as considering rotations as a fixed step rather than an angle (which you could convert to/from later if needed).

As an example, consider the following shape rotated in 4 different orientations:

The footprint of the object is defined by the offsets from the origin where `0,0` is the "base" cell as you described. To calculate the neighbouring cells for a given rotation, we can use a simple formula to convert from the original, non rotated footprint to the footprint of the rotated object.

For the original rotation (rot = 0), we simply do nothing and the footprint coordinates remain as is.

For each subsequent rotation we can follow these rules:

```
Rot = 1: First invert the x coordinate, then flip both the x and y coordinates.
Rot = 2: Invert both the x and y coordinates
Rot = 3: First invert the y coordinate, then flip both the x and y coordinates.

```

Here is an example for the footprints of the above shapes with the appropriate rotation:

To work through an example of this, given the footprint with `rot = 1`, we would convert the coordinates as such:

```
Rot = 1: First invert the x coordinate, then flip both the x and y coordinates.

0, 0 -> 0, -0
0, 1 -> 1, -0
1, 1 -> 1, -1

```

Hopefully this should be enough information to infer the remaining rotations with the aforementioned formulas.

Once you have calculated the new footprint coordinates for your given rotation, these can then be added to your world grid coordinates to determine which neighbouring cells need to be checked in relation to your base cell.
> 1 votes

# Answer
The server has to have the same knowledge of building types that the client has, and needs to know the current rotation and dimension(s).

To keep this information concise in your packets sent up to server, you can use 1 byte for the direction (this is really just an `enum` type that both client and server code have access to):

```
0=0 degrees
1=90 degrees
2=180 degrees
3=270 degrees

```

You can actually fit these 4 values into 2 bits i.e. 2^2=4, rather than 1 byte or 8 bits. But keeping it as a byte keeps it simple to start with.

Building shape could be either just length (say 1 unit wide x n units long), or length and width, both of which get sent to the server - you can use 1 byte for each of width and height, and later on, use fewer bits to save on bandwidth.

So your simplified packet layout might be e.g.:

`[1 byte rotation factor|1 byte width| 1 byte height| other stuff you need to send]`

When this arrives on the server, you multiple the rotation factor by 90 degrees or the equivalent radians, then figure out the direction the body length is going to go, and then check whether this collides with existing buildings on the server.

I would suggest for a more compressed layout (optimise only once the basic logic is working):

`[2 bits rotation factor|3 bits width|3 bits height] totalling 8 bits or 1 byte`
> 0 votes

---
Tags: c#, 2d, grid
---


# Question
Title: Serializing game information over TCP connection
I'm trying to write a Unity client with C++ game server with TCP socket. When I'm sending game data back and forth with client and server, I'd want to serialize it in someway that can be deserialized on both ends.

Is xml appropriate for this or is there a better method of doing this?

# Answer
> 0 votes
XML has the advantage that it is a well-structured format which is both machine-readable and human readable.

But what makes it bad for use in game protocols is that it contains a lot of boilerplate. It will use a large number of bytes to encode relatively little information. Especially considering that game protocols usually consist of mostly numbers being passed around, which XML encodes in ASCII digits.

Which is why most games use binary protocols. That allows to squeeze a lot more information into the same numbers of bytes.

But while binary protocols are efficient, they also have their drawbacks during development. When the meaning of a byte depends on its position in a message, then a small bug can screw up the alignment of all following bytes, make the receiver interpret it completely wrong and cause very weird bugs. Such errors are hard to troubleshoot, because binary messages are difficult to read for human developers. And it is pretty easy to create such bugs, because serialization and deserialization will usually have to be completely self-developed code, and not use a library.

A compromise between the readability and structure of XML and the conciseness of binary protocols can be JSON, by the way. It still encodes everything in ASCII, but it has a lot less boilerplate than XML. It also writes out the key for every value (like XML), which makes it fail more gracefully when there is a bug in the serialization / deserialization.

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


title: Enemy script of Unity with c#

text:
# Question
Title: Enemy script of Unity with c#
I have created a simple game and there are **zombies** as my enemies.If the distance of The player(Which is me) and the zombie less than 10,The zombie starts walking towards me.and there is a Cylinder object around me.I have turned off the Mesh Renderer of that cylinder so that it is invisible. And also there is a mesh collider in the Cylinder. If the zombie reaches the cylinder , it starts to attack me and stops walking.But walking animation is still working.

How can I fix this, I need to stop walking animation of the zombie when it reaches the cylinder.Here is my code,

```
using UnityEngine;
using System.Collections;

public class ZombieFollow : MonoBehaviour
{

    public GameObject ThePlayer;
    public float TargetDistance;
    public float AllowedRange = 10;
    public GameObject TheEnemy;
    public float EnemySpeed;
    public int AttackTrigger;
    public RaycastHit Shot;

    void Update()
    {
        transform.LookAt(ThePlayer.transform);
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot))
        {
            TargetDistance = Shot.distance;
            if (TargetDistance < AllowedRange)
            {
                EnemySpeed = 0.01f;
                if (AttackTrigger == 0)
                {
                    TheEnemy.GetComponent<Animation>().Play("Walking");
                    transform.position = Vector3.MoveTowards(transform.position, ThePlayer.transform.position, EnemySpeed);
                }
            }
            else
            {
                EnemySpeed = 0;
                TheEnemy.GetComponent<Animation>().Play("Idle");
            }
        }

        if (AttackTrigger == 1)
        {
            EnemySpeed = 0;
            TheEnemy.GetComponent<Animation>().Play("Attacking");
        }
    }

    void OnTriggerEnter()
    {
        AttackTrigger = 1;
    }

    void OnTriggerExit()
    {
        AttackTrigger = 0;
    }

}

```

Here **ThePlayer** Gameobject is me and **TheEnemy** is the zombie.*Walking*, *Idle* and *Attacking* are the animations.

# Answer
> 1 votes
Why use animation.play??

Why don't you use transition to animation, add parameters and play your animation according to the parameters? It's much smoother that way

Never the least you could try animation.stop()

# Answer
> 0 votes
Is the zombie colliding with the trigger? If it isn't registering the collision then it will never change the attack value.

Another user also posted about using animation transitions. In unity you can set up a kind of state machine in the animator component and control that with variables. It will be cleaner and more optimized than calling PlayAnimation in Update.

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


# Question
Title: Networking gampeplay - Sending controller inputs vs. sending game actions
I'm reading about techniques for implementing game networking.

Some of the resources i've read state that it is a common practice (at least for some games) to send the actual controller input across the network, to be fed into the remote game's loop for processing.

This seems a bit odd to me and i'd like to know what are the benefits of using such a method?

To me, it seems that controller input is merely a way to gather data to be fed into the game, which in turn determines how to translate these into specific game actions.

Why would i want to send the control data and not the game actions themselves?

# Answer
# Sending Input to the Game Server

**Pros**

* The computation for all players is done at once on one machine.
* Each player receives the same game state.

**Cons**

* The player has to wait for the server's response to his/her input.

# Sending Game Actions to the Game Server

**Pros**

* The player will not experience any latency relating to his/her own actions.

**Cons**

* The server has to stitch together and arrange multiple events from multiple players to be sent back out to the players.

## Summary

It takes more work for a server to listen to multiple players' actions than it is to just take their input, calculate the result, and return a game state for all players.
> 4 votes

# Answer
In general, yes, you send desired actions, not raw inputs. Sanity-check on the server, though (otherwise players could run at twice the max speed, etc).

I've written a series of articles detailing how all this works, some people have found it useful: http://www.gabrielgambetta.com/fpm2.html.
> 3 votes

# Answer
The problem comes from cheaters. You might want to read some about the so called authoritative game server. It is very well explained in this article by Gabriel Gambetta.

But lets think about the following example.

You have an online shooter game, which can be either ammo or cooldown based. Your client is a nasty hacker. By accepting game actions (events) from the client, the client can feed the server with new bullets fired, even when he is out of ammo, or his weapon on cooldown. By collecting user input, you need to do the maths and all the checkings on the server side but in return your game is kinda cheat safe. Using an aimbot also gets a lot easier for hackers if you simply accept game events on server side.

You could of course validate the events sent by the client, but sending game events can be heavier on bandwidth.

Have fun implementing your game.
> 2 votes

# Answer
Depends on your game more specific...

**Action/Event based System**

* Strategy Game
* Turn based games
* ...

you need to send the actions which the players do because the server don't care about the realtime informations

**Live/Streamed System**

* Realtime games

the server need to know as fast as possible what the input of each user is to update gameworld objects.

For example if i hold the forward button of a racer game the client should send on every network tick the state of all buttons so the server can simulate the world in realtime.

You could also realisize this with an event based system, but you need more bits to encode the event for a button change which is not that good.
> 0 votes

# Answer
I know this thread is 7 years old but for anyone looking in here and wondering one big advantage is that its practicaly hacker safe. Online game hacking happens when a player can moddify the packets sent to the server in ways you shouldnt but if you only send key inputs there cant be any combination of input controlls that are concidered cheating. but if you send for example the player movements you can modify them so that the player for example is flying even if he isnt allowed to, wich isnt possible if all the math is done by the actuall server.
> 0 votes

---
Tags: architecture, software-engineering, networking, multiplayer, input
---


# Question
Title: Unity Cinemachine+URP : 2D pixelPerfect zoom issue?
There are many PixelPerfect component that exists and it confuses me. The CM PixelPerfect component doesn't work in my 2D Tilebased game.

So I use the Camera component named "Pixel Perfect Camera (Experimental)".

I feel that the right PixelPerfect component because it seems that it's the only one working for my project ahah. (note : I'm aware there's another PixelPerfect component in the "2D pixel perfect" package, but it's only compatible with LWRP projects if I'm right.)

The camera :

The hierarchy :

CM vcam1 and CM vcam2 are used to make transitions between Areas.

Now, I need to make a zoom on the player. To achieve that, I have added a 3rd "CM vcamZOOM".

But nope, it's not working at all. I mean, everything else works, the rotation, etc, everything but the zoom. Even if it's the only vcam enabled, it's not zooming. I found out that **disabling the "Pixel Perfect Camera (Experimental)" component on the Camera solved the problem**. That's not a real solution since I need to use a PixelPerfect component (with the ability to Zoom).

Am I using the right PixelPerfect component for my needs? Is this a compatibility bug between URP camera pixelperfect component and CM zoom ? Thanks for reading and for your answers.

# Answer
And voilà. I had to use BOTH pixelPerfect components :

On my Camera : URP-pixelPerfect (experimental)

On my VCams : Cinemachine-pixelPerfect

Answer is here
> 0 votes

---
Tags: unity, camera, cinemachine
---


# Question
Title: How can I scroll/animate up lines reading from a string to ui text?
This is the reading lines code :

```
if (primaryTarget != null)
            {
                var lines = primaryTarget.description.Split('\n');
                text.text = "Item found: " + primaryTarget.description;
            }
            else
            {
                text.text = "";
            }

```

And this is the script of the description : The script is attached to each interactable target(item) :

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

public class InteractableItem : MonoBehaviour
{
    public enum InteractableMode // your custom enumeration
    {
        Description,
        Action
    };

    public InteractableMode interactableMode = InteractableMode.Description;

    public float distance;

    private bool action = true;

    [TextArea(1, 10)]
    public string description = "";

    public void ActionOnItem()
    {
        if(interactableMode == InteractableMode.Action && distance <= 5f && action == true)
        {

            action = false;
        }
    }
}

```

Depending on the amount of text in the string I want to show it in the ui Text. If there is one line then just show the text or even if there are two lines. but if there is a lot of text then split the lines and scroll the lines smooth up so the first line will be disappear or pushed up and bottom lines will come up.

In the screenshot you can see on the left the text that show in the ui text on the right the text of the description. The ui text can't show all the text and I don't want the text to overlap other ui's or objects so the idea is to make the text slowly smooth scrolling up.

# Answer
Use a coroutine:

void OnEnable() {
    StartCoroutine(DisplayText(primaryTarget.description, 2f));
}

private IEnumerator DisplayText(string originalText, float lineDisplayTime) {
    //split the text into separate strings
    var lines = originalText.Split('\n');
    //display each line for the given number of seconds, then advance to the
    //next line
    foreach (var line in lines) {
        text.text = line;
        yield return new WaitForSeconds(lineDisplayTime);
    }
}
```

> 0 votes

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


# Question
Title: Mathf.Clamp not Working Properly to clamp a rotation between -90° and 90°
I want to clamp the vertical rotation of the first person controller I was making. I want to restrict the vertical rotation of the main camera between -90 and 90 degrees. The code is as follows:

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

public class MouseY : MonoBehaviour
{
    [SerializeField]
    private float _sensitivity = 5.0f;
    private float _verticalInput;

    // Update is called once per frame
    void Update()
    {
        _verticalInput = Input.GetAxis("Mouse Y") * _sensitivity;
        Vector3 lookDirectionY = transform.localEulerAngles;
        lookDirectionY.x -= _verticalInput;
        lookDirectionY.x = Mathf.Clamp(lookDirectionY.x, -90f, 90f);
        transform.localEulerAngles = lookDirectionY;
    }
}

```

In the above code, Mathf.Clamp does not work for -90. On reaching 0 degrees, it reels back to the +90 degrees. What could be the reason for this and how to resolve it?

# Answer
This example shows how you can convert any angle into the range -180 to 180.

```
Vector3 lookDirection = transform.localEulerAngles;
float x = lookDirection.x;
x -= _verticalInput;
//convert `x` into the range -180 to 180
x = x % 360;
if (x > 180) x -= 360;
else if (x < -180) x += 360;
//clamp and apply
x = Mathf.Clamp(x, -90f, 90f);
lookDirection.x = x;
transform.localEulerAngles = lookDirection;

```
> 1 votes

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


# Question
Title: Approaches on 2D top-down track racing visualisation
I'm considering writing a very simple management style game with the theme being motorsport racing.

I've got a good idea how to do the 'management side', but the issue I'm having is how to visually render cars and move on a track (something a bit like):

**The key points (keeping it simple):**

* the user won't control the vehicle directly, they are the 'manager' (think football manager) - they can decide on a strategy but cannot control the vehicle
* the car should stay on track (visually) - they may 'crash' (along with other events) though
* the speed it goes around the track is determined by vehicle performance
* a car will be aware of other near-by cars around the track - for example, if they're about to be overtaken, they may actually do a slower lap as they are defending - they may collide, along with other events

My initial thoughts are there are two key design elements here, the track and the car.

**The track:**

* a track is composed of many segments
* each segment is stored in an array
* a segment (I'm not entirely sure here) but one thing it might contain is a 2D array:

```

(From [this](https://gamedev.stackexchange.com/questions/149966/approaches-on-2d-top-view-racing-game-track-design) answer gave an approach of using multi-dimensional arrays)
_ _ _ _ _ _ _ _ _ _
| d d x x x d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d e e e d d d |
| _ _ _ _ _ _ _ _ |

_ _ _ _ _ _ _ _ _ _
| d d x x x d d d |
| d d r r r d d d |
| d d d r r r d d |
| d d d d r r r e |
| d d d d r r r e |
| d d d d d d r e |
| d d d d d d d d |
| d d d d d d d d |
| _ _ _ _ _ _ _ _ |

```

Above is a straight and a 90 degree corner - `x` exit, `e` entry, `r` racetrack and `d` dirt. Maybe I could create a bunch of these and create a track.

Or maybe a simpler version where I define just an entry and exit:

```
_ _ _ _ _
| d e d |
| d r d |
| d e d |
| _ _ _ |

_ _ _ _ _
| d x d |
| d r e |
| d d d |
| _ _ _ |

```

The simplified version where I define an entry `e` and exit `x`. I can add additional points `r` and then construct a curve/straight-line based on the `x`, `e` and `r` coordinates?

My idea is that the vehicle will then move across each segment and I can calculate the time it takes to complete that segment. I can then add up all segments which will give me the lap time. With this approach, I can also check the previous/current/next segment to determine if there are other vehicles it needs to defend/attack against.

**The car:**

* store all vehicles in an array
* each vehicle will always be in a segment
* speed it completes the segment is determined by its performance (and segment characteristics)
* vehicle can 'see' if there are other vehicles in previous/current/next segment and decide whether to overtake/defend.

I think I could make this work, but I'd be really interested to know if there are better/simpler approach - bearing in mind it's mostly a visualization and the speed and events are determined by my program.

# Answer
> 0 votes
Defining the track segments in some type of data structure may be necessary if you are using procedurally generated tracks that are built at runtime from assorted segments.

If you *don't* need the tracks to be procedurally generated, the solution is probably much simpler:

1. Create each track as a single 2D image
2. Define waypoints around the track that the vehicles will follow. These can be simple x-y pairs. If you're using an engine that has a visual editor, you might be able to place the waypoints in the visual editor (even if not, you'd probably want to build a simple visual interface for this purpose).
3. Animate the cars from waypoint to waypoint. You may need to do a bit of path interpolation around turns to keep the motion smooth, but if this is a simple top-down representation then you might find that the extra smoothness from interpolation isn't necessary.

---
Tags: game-design, architecture
---


# Question
Title: How can I display a 3d object and my player on a canvas?
The main goal is to animate my player with animator on a canvas. The problem is that any 3d object (my player, a cube) I drag over the canvas is transparent/not seen.

The main camera is set to Clear Flags : Depth Only and Culling Mask to Everything.

The Main Menu Canvas is set render mode to Screen Space Camera and I selected the main camera.

The Main Menu Background Material is set to New Material I created and on the new material I added a shader I created that make this image to be blur.

The main camera settings screenshot :

And the Canvas settings :

And the Main Menu Background settings :

You can see in all the screenshots in the scene view top left that my player and the cube both are transparent on the canvas.

Now if I change the Main Camera Clear Flags to SkyBox then I see my player and the cube but also they are not looking like they should be with the texture/materials and also I don't want the Main Camera to be the clear flags on SkyBox I want the objects to be over the blur image so the Main Camera should be clear flags depth only.

The main goal again is to put my player on the canvas with the blur image and animate my player. This is for my main menu.

* The canvas that will display the player if the player will be on his own canvas should be transparent and only display the player so the canvas will not overlap the other cnavas with the blur image.
* I want to animate using animator the player not only to display it as static object.

This is a screenshot of what I mean I used paint to cut my player and put it on but the player canvas should be transparent or without a canvas the player should be on like the ui button on the left :

Another screenshot. On the top it's the scene view window the player the ui button and the blur image.

On the bottom the game view window the ui button is on the blur image. I want the player to be the same as the ui button on the blur image and then to animate the player. Not like in my other screenshot the player should not have a skybox background or something it should be like the ui button on the blur image:

# Answer
> 1 votes
You have 2 options:

1. Make your canvas (with buttons and UI elements) transparent, and put your blurred background as a texture on a plane pointed at the camera, with your animated character in front.
2. Setup a second camera which renders only the character to a RenderTexture and use the RenderTexture as a RawImage in your GUI.

The first option is pretty self-explanatory, but will take some tweaking to avoid unrealistic shadows. The second option is a bit more complicated:

1. Set up a new Layer, lets call it "characterRender".
2. Assign your character to this layer.
3. Remove this layer from your main/GUI camera culling mask so that it does not get rendered.
4. Create a new camera, and set its culling mask to only "characterRender" layer.
5. Set its clear flags to Color only, and its color alpha to 0.
6. Place your character in front of the second camera (with gizmos enabled and the second camera selected in the hierarchy you can tweak the positioning with the camera preview)
7. Create a RenderTexture, and assign it as the Target Texture of the second camera.
8. Add that texture as a RawImage element to the GUI on your first camera.
9. Animate your character normally

I hope that makes sense. If not, let me know and I will get some screenshots when I get home from work.

# Answer
> 1 votes
After so many tries I finally got it.

1. Created a new scene Main Menu
2. Deleted the Main Camera and created a new Camera.
3. Created a Canvas named it Main Menu Canvas.
4. Created a Rawimage named it Main Menu Background and made it child of the Main Menu Canvas.

This is a screenshot of my Hierarchy :

Now screenshots to show the settings :

The first screenshot is of the Canvas : Very important is to look at the Order In Layer I set it to -1

Next the Rawimage settings, To get this blur image I used a shader and added the shader to a new material and then dragged the new material to the Rawimage :

Last screenshot the Camera settings : Look at the Clear Flags set to Don't Clear and Culling Mask is set to Everything.

In the end I used one Camera not the Main Camera it didn't work with the Main Camera. but since it's a new scene and only for the main menu you don't need the main camera at least not for this.

Very easy and working great.

Later I will add also a short video clip to show the player animation.

---
Tags: unity, rendering, camera
---


title: Unity disable SteamVR

text:
# Question
Title: Unity disable SteamVR
I'm making a game which is playable with VR and without VR. The `SteamVR` plugin is inside my project folders, but no `CameraRig` or other `SteamVR` object is inside my scene.

When I start the game, `SteamVR` starts.

How can I only activate `SteamVR` when I need it? (When it is checked in the settings).

# Answer
> 2 votes
You can disable VR support in Unity. This will disable SteamVR from starting. This can be done via code by using the `VRSettings` class. Specifically, the `enabled` value.

So, if you have two different scenes, the VR scene could set `VRSettings.enabled = true;` and the non-VR scene would use `VRSettings.enabled = false;`

Additionally, you can switch VR platforms by using something like `VRSettings.LoadDeviceByName("OpenVR");`.

# Answer
> 3 votes
For those looking in 2019, make sure that `Automatically Enable VR` in `Edit > Preferences > SteamVR` is **off** if you need to build also non-VR scenes

# Answer
> 3 votes
The only way I've found to work is to both uncheck 'Auto Enable VR' on Assets/SteamVR\_Resources/Resources/SteamVR\_Settings.asset and also uncheck Virtual Reality Supported on the Player Settings.

# Answer
> 2 votes
You should have a **CameraRig** object for your SteamVR or a normal **Character controller** for your Normal game mode (non-VR mode). You only require the on/off these two game-objects and need to on one game-object at a time.\[more\]

# Answer
> 2 votes
For those looking in 2018, here is the solution for 2018.2.6f1

```
using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.XR;

public class test : MonoBehaviour {

    void Start () {
        XRSettings.enabled = false;
    }
}

```

# Answer
> 2 votes
Solved

First go to Assets/SteamVR\_Resources/Resources/SteamVR\_Settings.asset

disable auto enable VR

then go to project settings, Player, XR Settings and disable VR Support

# Answer
> 1 votes
None of these suggestions work in December 2019.

The only fix I found is that you have two cameras in two different game objects, one for VR and one for non VR. Inside the Camera settings for your Non VR Object in your Inspector you just change the Target Eye to "None (Main Display)."

This should work. It did for me. I have the same game in both standard First Person and with the HTC Vive headset. You just Instantiate the Game Object with the First Person Non VR Camera settings instead of the Game Object with the VR Camera Settings when you don't want VR in the game.

# Answer
> 1 votes
In newer versions,

1. Open **SteamVR\_Settings**, which can be done by clicking **Window -\> SteamVR Input -\> Advanced Settings -\> SteamVR Settings**.
2. Close the **SteamVR Input** window and Uncheck **Auto Enable VR** in the inspector.
3. Go to **Project Settings -\> Player** and uncheck **Virtual Reality Support**.

# Answer
> -1 votes
my oh my looks like this setting keeps moving.

Using the SteamVR Asset 2.5.0 in Unity 2019.3, the 'Auto Enable VR' setting can be found in the following Scriptable Object:

Assets/SteamVR\_Resources/Resources/SteamVR\_Settings.asset

---
Tags: unity, virtual-reality, steam
---


# Question
Title: JNI multidimensional array as return value
I have some C++ code that I wrote to generate voxel terrain and would like to access it in JAVA. you pass it three integers; the seed and the coordinates of the chunk that it is generating (represented as `int x` and `int y`). It returns to you a 3D array of integers representing the value of each block in that chunk. In java I have:

`private native static int [ ][ ][ ] genTerrain ( int seed , int x , int y );`

And in the generated header I have:

```
#ifndef _Included_co_lambdas_koc_server_Terrain
#define _Included_co_lambdas_koc_server_Terrain
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     co_lambdas_koc_server_Terrain
 * Method:    genTerrain
 * Signature: (III)[[[I
 */
JNIEXPORT jobjectArray JNICALL Java_co_lambdas_koc_server_Terrain_genTerrain
  (JNIEnv *, jclass, jint, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

```

And for the Class file I have tried:

```
JNIEXPORT jobjectArray JNICALL
Java_co_lambdas_koc_server_Terrain_genTerrain ( JNIEnv * env , jclass , jint seed , jint xCord , jint yCord )
{
    jclass intClass = env->FindClass("[I");

    jintArray x = env->NewIntArray ( 32 ) ;
    jintArray y = env->NewIntArray ( 32 ) ;
    jintArray z = env->NewIntArray ( 512 ) ;

    jobjectArray terrain = env->NewObjectArray(3, intClass, NULL);
    env->SetObjectArrayElement(terrain, 0, x);
    env->SetObjectArrayElement(terrain, 1, y);
    env->SetObjectArrayElement(terrain, 2, z);

    return ( terrain ) ;
}

```

Of-course this may be completely invalid as I have found little JNI documentation and haven't been able to understand much of what I have read. Could anyone show me how to generate a 3D JAVA int array (`jint[][][]`) in C++ through JNI?

# Answer
> 3 votes
It's a bit inconvenient: You have to create each array manually, along each dimension:

* Create an object array with size `sizeX`, with element type `[[I` (a **2D** `int` array)
* At each entry of this array:
    + Create an object array, with size `sizeY`, with element type `[I` (a **1D** `int` array)
    + At each entry of this array:
        - Create an int array, with size `sizeZ`

Here is an example:

```
#include "TestNativeArray3D.h"

JNIEXPORT jobjectArray JNICALL Java_TestNativeArray3D_genTerrain
    (JNIEnv *env, jclass cls, jint seed, jint xCoord, jint yCoord)
{
    jclass intArray1DClass = env->FindClass("[I");
    jclass intArray2DClass = env->FindClass("[[I");

    jint sizeX = 4;
    jint sizeY = 5;
    jint sizeZ = 6;

    jobjectArray array3D = env->NewObjectArray(
        sizeX, intArray2DClass, NULL);
    for (jint x = 0; x < sizeX; x++)
    {
        jobjectArray array2D = env->NewObjectArray(
            sizeY, intArray1DClass, NULL);
        for (jint y = 0; y < sizeY; y++)
        {
            jintArray array1D = env->NewIntArray(sizeZ);
            env->SetObjectArrayElement(array2D, y, array1D);
        }
        env->SetObjectArrayElement(array3D, x, array2D);
    }
    return array3D;
}

```

(Note: In "real" code, you should *diligently* check for error conditions, and exit the method as soon as possible. For example, the allocations may fail due to an `OutOfMemoryError`, and will return `NULL` in this case).

> EDIT In response to the comment

Actually *accessing* or *filling* the innermost arrays is again a different story. There are several functions and approaches for this:

* GetIntArrayRegion and SetIntArrayRegion, as the names suggest, are intended for reading/writing parts (regions) of an array to/from a data buffer that was allocated separately
* GetIntArrayElements and ReleaseIntArrayElements: The `Get` function tries to obtain a *pointer* to the actual array contents, that can then be accessed and modified, and later be "committed" back to the array by calling the `Release` function. (See the documentation about the cases where it might not return a pointer, but a *copy* of the data instead!)
* GetPrimitiveArrayCritical/ReleasePrimitiveArrayCritical: This also tries to obtain a pointer to the array contents, but ... it tries even harder ;-) Again, refer to the documentation for details (it may disable garbage collection, for example, so should be used with some care)

So depending on how the actual process of filling the arrays looks like, you'd employ different techniques.

Which of the first functions (`Get*ArrayElements` vs. `Get*ArrayRegion`) is faster heavily depends on the *size* of the region that you're interested in. If you have an array with 10000 elements, but only want to read/write a few elements, the `...Region` based functions are likely to be faster. If you have to access the whole array anyhow, the `...Elements` based functions should be more appropriate. But admittedly, I have not (yet) made detailed, dedicated performance comparisons here (these would depend on *many* factors - array size, region size, JVM version, ...). The `...Critical` method is likely to be the fastest for nearly all cases, but should only be used when there is a dedicated point where you can quickly acquire+use+release the data, and don't have any other JNI calls in between.

---

Based on your description, it sounds like you could fill the arrays **during** their creation (assuming that you create the native data before actually creating the Java arrays). You don't have many choices in terms of granularity: The innermost `int[]` arrays are the largest possible block that you can use here. So you could do something like this after creating the innermost `array1D`:

```
jint *a = (jint*)env->GetPrimitiveArrayCritical(array1D, NULL);

// Use `a` here (But don't do more than just accessing the
// array - particularly, don't to any time-consuming
// computations, and don't call other JNI functions!)
for (jint z = 0; z < sizeZ; z++)
{
    a[z] = z; // Fill with actual (pre-computed) data
}
env->ReleasePrimitiveArrayCritical(array1D, a, NULL);

```

---

A general hint: As you might have noticed, the handling of 3D arrays is not something that flows easily from your fingertips in JNI. Many libraries that are concerned with handling large data blocks try to "flatten" multidimensional arrays into 1D array. This is something you should consider as well, if it is possible based on your existing C implementation and depending on how the data will be used on the Java side.

<sub>(BTW: I hope you're not doing this in C for the sake of performance. Porting the terrain generation code to Java might be a viable option, too ;-))</sub>

# Answer
> 0 votes
```
std::vector<std::vector<std::vector<int>>> filter_boxes;

jclass intArray1DClass = env->FindClass("[I");
jclass intArray2DClass = env->FindClass("[[I");

jint sizeX = filter_boxes.size();
jint sizeY = 4;
jint sizeZ = 2;

jobjectArray  array3D = env->NewObjectArray(sizeX, intArray2DClass, NULL);
for (jint x = 0; x < sizeX; x++)
{
    jobjectArray array2D = env->NewObjectArray(sizeY, intArray1DClass, NULL);
    for (jint y = 0; y < sizeY; y++)
    {
        jintArray array1D = env->NewIntArray(sizeZ);
         jint *buf = new jint[2];
         for (int i = 0; i < 2; i++){
             buf[i] = (jint) filter_boxes[x][y][i];
         }
        env->SetIntArrayRegion(array1D, 0, 2, buf);
        env->SetObjectArrayElement(array2D, y, array1D);
        delete[] buf;
    }
    env->SetObjectArrayElement(array3D, x, array2D);
}

```

---
Tags: c++, java, jni
---


# Question
Title: How can I destroy trees when placing a building in an RTS?
I am developing RTS game. When I build buildings on the Terrain, any trees that were in that location end up intersecting with the building.

I want to remove all trees from the building's footprint when placing.

Can I use the building's OnTriggerStay to detect tree colliders with a particular tag and destroy the trees? Or is there a better way to clear out these trees?

# Answer
Here is my solution:

```
void Update()
{

    TerrainData terrain = Terrain.activeTerrain.terrainData;
    ArrayList instances = new ArrayList();

    foreach (TreeInstance tree in terrain.treeInstances)
    {
        distanceG = Vector3.Distance(gameObject.transform.position, tree.position);

        distance = Vector3.Distance(Vector3.Scale(tree.position, terrain.size) + Terrain.activeTerrain.transform.position, transform.position);

        if (distance < closeRange)
        {
            // the tree is in range - destroy it
            print("1");
        }
        else
        {
            // tree is out of range - keep it
            instances.Add(tree);

        }
    }
    terrain.treeInstances = (TreeInstance[])instances.ToArray(typeof(TreeInstance));

}

```
> 1 votes

# Answer
When you place the building you could search for any tree object in a certain radius around it and if it's less than a certain distance delete them. That way you wouldn't need collision.

You would need a reference to the trees in the scene to access their position information.
> 0 votes

# Answer
Assuming your buildings have a rectangular base, you can use `Physics.OverlapBox` / `Physics2D.OverlapBox` to get all the colliders which overlap the area where you want to put down the building and decide what to do with them depending on object type.
> 0 votes

---
Tags: unity, c#, terrain, collider, tree
---


title: Jump script using AddForce not working

text:
# Question
Title: Jump script using AddForce not working
I am making a simple jump script by adding a separate script to the character.

I got the character from the Asset Store and I have left it untouched. I have searched the solution and similar problems to this, and I changed the force or JumpHeight to a pretty high value. But it is still nothing. The logs are printed out just fine.

```
public class JumpScript : MonoBehaviour {
public Rigidbody rb;
public float JumpHeight = 7.0f;

// Update is called once per frame
void Update () {
    if (Input.GetKeyDown (KeyCode.Space)) {
        Debug.Log ("PRESSSED");
        GetComponent<Rigidbody> ().AddForce (Vector3.up * JumpHeight);
        Debug.Log (GetComponent<Rigidbody> ());
    }
}

```

# Answer
> 1 votes
1. Be sure your character has a Rigidbody attached, and no Character Controller (if you're intending to move this character with physics)
2. Ensure the character's Rigidbody is set to dynamic, and its constraints allow movement on the y axis
3. Disallow rotation on the Rigidbody, to keep your character from tipping over accidentally
4. Verify that the character's collider is not interpenetrating with any scenery that might trap them in place
5. Use velocity changes or impulses to set velocity, not forces

---

Here's a simple jump script that helps fix a couple of these:

```
// This tells the editor to enforce "only use this script on objects with Rigidbodies".
[RequireComponent(typeof(Rigidbody))]
public class Jump : MonoBehaviour {

    public float jumpHeight

    [SerializeField, HideInInspector]
    float _jumpVelocity;
    [SerializeField, HideInInspector]
    Rigidbody _body;

    // When you tune the jump height in the inspector, automatically
    // calculate the physics values that will get you to that height.
    void OnValidate() {
        // Cache a reference to our body so we don't have to search at runtime.
        _body = GetComponent<Rigidbody>();

        // Solve v(t) = v(0) + a * t for v(t) = 0.
        float secondsToJumpApex = Mathf.Sqrt(-2f * jumpHeight / Physics.gravity.y);

        // Substitute into h(t) = h(0) + v(0) * t + (a/2) * t^2 and solve for v(0).
        _jumpVelocity = Physics.gravity.y * secondsToJumpApex;
    }

    void Update() {
        // Use a named input set up in the Input Manager, not a hard-coded key.
        if (Input.GetButtonDown("Jump")) {
            // Jumps are instantaneous, so use VelocityChange instead of a gradual push.
            _body.AddForce(jumpVelocity * Vector3.up, ForceMode.VelocityChange);
        }
    }
}

```

---
Tags: unity, vector, rigidbody, jumping
---


# Question
Title: LibGDX How to adjust mouse aim angle calculation when screen is resized
I'm starting with a screen resolution of `1280 x 960` and that is the default resolution where mouse aiming is calculated thus:

```
angleRad = (float) (Math.atan2(screenX - (screenWidth / 2), screenY - (screenHeight / 2)));
angle = (float) Math.toDegrees(angleRad - Math.PI / 2);
angle = Math.round(angle) <= 0 ? angle += 360 : angle;
if (Math.round(angle) == 360)
    angle = 0;

```

Which all works fine. But when the game is resized to some resolution with a vastly different ratio to the default, like for example `2560 x 1440` at full screen in my case, the aiming is off. The resize method is like this:

```
@Override
public void resize(int width, int height) {
    game.getViewport().update(width, height);
    control.screenWidth = width;
    control.screenHeight = height;
}

```

Where `control.screenWidth` and `control.screenHeight` are used in the above angle calculation and as the set resolution in other areas. The angle calculation when resized is roughly correct but tends to get further and further off course the further the aim is away from the player.

If the player aims straight up, down, left or right (N, S, W or E basically) then the aim is dead on, but veers off as aiming goes away from the player towards a screen edge - no doubt due to the resolution ratio difference.

We have these ratio differences which no doubt affect the angle calculation:

```
1280x960 1.33 ratio
2560x1440 1.77 ratio

```

But I'm not sure how to take into account these ratios to adjust the angle calculation accordingly in my code?

The crosshair and bullets are both off position. In the screenshot below the crosshair position in comparison with the mouse pointer can be seen. This is for resolution `2560x1440`. The code for the crosshair is this:

```
point = angleToVector((float) (angleRad + Math.PI)).scl(10000);
gs.getWorld().rayCast(callBack, pos, point);

```

`angleRad` is the mouse angle in radians, `pos` is the vector position of the player and `point` is the vector target position. This is the raycast callback

```
private RayCastCallback callBack = new RayCastCallback() {
    @Override
    public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
            collision.set(point);
        return fraction;
};

```

# Answer
> 0 votes
Here "point" is actually an offset vector (a relative shift in space, with a direction and distance).

```
point = angleToVector((float) (angleRad + Math.PI)).scl(10000);

```

Here "point" is being used as a position (an absolute location in space).

```
gs.getWorld().rayCast(callBack, pos, point);

```

So you're drawing your ray from the player position, `pos`, to a point 10000 units in your aiming direction *measured from the world origin*.

It looks to me like you want:

```
point = pos.cpy().add(angleToVector((float) (angleRad + Math.PI)).scl(10000));

```

to aim from the player position, not from the world origin.

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


# Question
Title: Rotating camera in 3D without yawing diagonally
I'm programming a C raytracer. I'm having trouble getting the camera to rotate the way I intend.

I would like the camera to rotate by pressing keys:

* `F` & `H` rotate left & right around the world's vertical axis (Y)
* `T` & `G` rotate up & down around an axis that is always horizontal and perpendicular to the view axis.
* `R` & `Y` rotate around the camera's viewing axis (local Z)

But with my current code, rotating up and then left rotates on a diagonal, instead of going around the world Y axis:

How can I make this rotation control more intuitive?

---

This is how the camera axes are initialized at the beginning of the program (I do this once) :

```
void    init_camera_vecs(t_camera *cam)
{
    t_vec3  forward;

    forward = get_normalised(invert(cam->vec));
    cam->up = (t_vec3){0, 0, 0};
    if (fabs(cam->vec.y) > 0.7)
        cam->right = vec_cross((t_vec3){0, 0, -1}, forward);
    else
        cam->right = vec_cross((t_vec3){0, 1, 0}, forward);
    cam->up = vec_cross(forward, cam->right);
}

```

This is my get\_ray\_dir() function which gives the direction of the ray from camera space to world space:

```
static t_vec3   lookat(t_camera *cam, t_vec3 ray_coord)
{
    t_vec3  forward;
    t_vec3  ray_dir;

    forward = get_normalised(invert(cam->vec));
    ray_dir.x = ray_coord.x * cam->right.x + ray_coord.y * cam->up.x
            + ray_coord.z * forward.x;
    ray_dir.y = ray_coord.x * cam->right.y + ray_coord.y * cam->up.y
            + ray_coord.z * forward.y;
    ray_dir.z = ray_coord.x * cam->right.z + ray_coord.y * cam->up.z
            + ray_coord.z * forward.z;
    return (ray_dir);
}

static t_vec3   get_ray_dir(int i, int j, t_resolution res, t_camera *cam)
{
    t_ray ray;
    float scale;
    float point_x;
    float point_y;
    float ratio;

    ratio = res.x / (float)res.y;
    scale = tan(cam->fov / 2 * M_PI / 180);
    point_x = (2 * (j + 0.5) / (float)res.x - 1) * ratio * scale;
    point_y = (1 - 2 * (i + 0.5) / res.y) * scale;
    ray.coord = (t_vec3){point_x, point_y, -1};
    ray.dir = lookat(cam, ray.coord);
    normalize(&ray.dir);
    return (ray.dir);
}

```

I tried this :

```
void    make_rotation_x(t_vec3 *rot_x, float angle)
{
    float   c;
    float   s;

    c = cos(angle);
    s = sin(angle);
    rot_x[0] = (t_vec3){1, 0, 0};
    rot_x[1] = (t_vec3){0, c, -s};
    rot_x[2] = (t_vec3){0, s, c};
}

void    make_rotation_y(t_vec3 *rot_y, float angle)
{
    float   c;
    float   s;

    c = cos(angle);
    s = sin(angle);
    rot_y[0] = (t_vec3){c, 0, s};
    rot_y[1] = (t_vec3){0, 1, 0};
    rot_y[2] = (t_vec3){-s, 0, c};
}

void    make_rotation_z(t_vec3 *rot_z, float angle)
{
    float   c;
    float   s;

    c = cos(angle);
    s = sin(angle);
    rot_z[0] = (t_vec3){c, -s, 0};
    rot_z[1] = (t_vec3){s, c, 0};
    rot_z[2] = (t_vec3){0, 0, 1};
}

void    mult_matrix(t_vec3 *res, t_vec3 *lhs, t_vec3 *rhs)
{
    res[0] = rotate_vector(lhs, rhs[0]);
    res[1] = rotate_vector(lhs, rhs[1]);
    res[2] = rotate_vector(lhs, rhs[2]);
}

void    cpy_matrix(t_vec3 *dst, t_vec3 *src)
{
    dst[0] = src[0];
    dst[1] = src[1];
    dst[2] = src[2];
}

void    apply_rotation_x(t_vec3 *orientation, float angle)
{
    t_vec3  matrix[3];
    t_vec3  res[3];

    make_rotation_x(matrix, angle);
    mult_matrix(res, orientation, matrix);
    cpy_matrix(orientation, res);
}

void    apply_rotation_y(t_vec3 *orientation, float angle)
{
    t_vec3  matrix[3];
    t_vec3  res[3];

    make_rotation_y(matrix, angle);
    mult_matrix(res, orientation, matrix);
    cpy_matrix(orientation, res);
}

void    apply_rotation_z(t_vec3 *orientation, float angle)
{
    t_vec3  matrix[3];
    t_vec3  res[3];

    make_rotation_z(matrix, angle);
    mult_matrix(res, orientation, matrix);
    cpy_matrix(orientation, res);
}

void        move_cam(t_specs *s, int key)
{
    t_camera    *cam;
    t_vec3      orientation[3];
    float       angle;

    angle = 4.5 * (M_PI / 180);
    cam = s->current_cam;
    orientation[0] = cam->right;
    orientation[1] = cam->up;
    orientation[2] = cam->vec;
    if (key == KEY_W)
        cam->coord = vec_add(cam->coord, cam->up);
    else if (key == KEY_S)
        cam->coord = vec_sub(cam->coord, cam->up);
    else if (key == KEY_A)
        cam->coord = vec_sub(cam->coord, cam->right);
    else if (key == KEY_D)
        cam->coord = vec_add(cam->coord, cam->right);
    else if (key == KEY_Q)
        cam->coord = vec_sub(cam->coord, cam->vec);
    else if (key == KEY_E)
        cam->coord = vec_add(cam->coord, cam->vec);
    else if (key == KEY_H)
        apply_rotation_y(orientation, -angle);
    else if (key == KEY_F)
        apply_rotation_y(orientation, angle);
    else if (key == KEY_G)
        apply_rotation_x(orientation, -angle);
    else if (key == KEY_T)
        apply_rotation_x(orientation, angle);
    else if (key == KEY_R)
        apply_rotation_z(orientation, -angle);
    else if (key == KEY_Y)
        apply_rotation_z(orientation, angle);
    s->current_cam->right = orientation[0];
    s->current_cam->up = orientation[1];
    s->current_cam->vec = orientation[2];
    normalize(&s->current_cam->right);
    normalize(&s->current_cam->up);
    normalize(&s->current_cam->vec);
}

```

I use this function now for rotation.

```
void        move_cam(t_specs *s, int key)
{
t_camera    *cam;
t_vec3      orientation[3];

cam = s->current_cam;
orientation[0] = cam->right;
orientation[1] = cam->up;
orientation[2] = cam->forward;

if (key == KEY_W)
    cam->coord = vec_add(cam->coord, cam->up);
else if (key == KEY_S)
    cam->coord = vec_sub(cam->coord, cam->up);
else if (key == KEY_A)
    cam->coord = vec_sub(cam->coord, cam->right);
else if (key == KEY_D)
    cam->coord = vec_add(cam->coord, cam->right);
else if (key == KEY_Q)
    cam->coord = vec_sub(cam->coord, cam->vec);
else if (key == KEY_E)
    cam->coord = vec_add(cam->coord, cam->vec);
else if (key == KEY_H)
    cam->yaw += 0.1;
else if (key == KEY_F)
    cam->yaw -= 0.1;
else if (key == KEY_T)
    cam->pitch -= 0.1;
else if (key == KEY_G)
    cam->pitch += 0.1;
else if (key == KEY_R)
    cam->roll += 0.1;
else if (key == KEY_Y)
    cam->roll -= 0.1;

make_rotation_z(orientation, cam->roll);
make_rotation_x(rotation, cam->pitch);
mult_matrix(orientation, rotation, orientation);
make_rotation_y(rotation, cam->yaw);
mult_matrix(orientation, rotation, orientation);

s->current_cam->right = orientation[0];
s->current_cam->up = orientation[1];
s->current_cam->forward = orientation[2];
normalize(&s->current_cam->right);
normalize(&s->current_cam->up);
normalize(&s->current_cam->forward);
}

```

I increment/decrement the angles by pressing keys on the keyboard and then I reconstruct the matrix.

The problem is that this method assumes that the camera has direction (0, 0, -1), right (1, 0, 0, 0) and up (0, 1, 0).

When another camera is not initialized like this one but with a random orientation, as soon as I press a key it rotates from the camera directed to (0, 0, -1). (Because all three angles are initialized to 0). I can't figure out how to initialize my angles with my camera.

I tried to calculate the angles this way:

```
float my_atan(float y, float x)
{
    float res;

    res = 0;
    if (x > 0)
        res = atan(y / x);
    else if (y >= 0 && x < 0)
        res = M_PI + atan(y / x);
    else if (y < 0 && x < 0)
        res = -M_PI + atan(y / x);
    else if (y > 0 && x == 0)
        res = M_PI / 2;
    else if (y < 0 && x == 0)
        res = -M_PI / 2;
    else if (y == 0 && x == 0)
        res = 0;
    else if (y == 0 && x < 0)
        res = res = 2 * M_PI;
    if (res < 0)
        res += 2 * M_PI;
    return (res);
}

float phi = my_atan(cam->vec.y, cam->vec.x);
float theta = atan(sqrt(cam->vec.x * cam->vec.x + cam->vec.y * cam->vec.y) / cam->vec.z);

cam->yaw = theta;
cam->pitch = phi;
cam->roll = 0;

```

**\[EDIT\]** I use this function to initialise my angles :

```
void    init_camera_angles(t_camera *cam)
{
    cam->yaw = atan2(cam->vec.x, -cam->vec.z);
    cam->pitch = asin(cam->vec.y / -sqrt(get_norm_2(cam->vec)));
    cam->roll = 0;
}

```

And I use this function to wrap the angles :

```
float           wrap_angle(float angle)
{
    float two_pi;

    two_pi = 2 * M_PI;
    return (angle - two_pi * floor((angle + M_PI) / two_pi));
}

```

I have a problem at the beginning of the programme when I initialise the three vectors of my camera. I use this function to initialise these three vectors:

```
void    init_camera_axis(t_camera *cam)
{
    t_vec3 up_tmp;

    cam->forward = get_normalised(invert(cam->vec));
    if (fabs(cam->vec.y) > 0.7)
    {
        if (cam->vec.z <= 0)
        up_tmp = (t_vec3){0, 0, 1};
        else
            up_tmp = (t_vec3){0, 0, -1};
    }
    else
        up_tmp = (t_vec3){0, 1, 0};
    cam->right = vec_cross(up_tmp, cam->forward);
    cam->up = vec_cross(cam->forward, cam->right);
}

```

The problem is that I get a right equal to (0.85, 0, 0) instead of (1, 0, 0), which produces the effect of a different zoom on the first image compared to the others generated with move\_cam().

Maybe I'm doing the initialization of the three vectors wrong or I need to use another method?

# Answer
> 1 votes
You can store three float variables, `pitch`, `yaw`, and `roll` (or equivalently, package them together into a 3-vector), representing the orientation of your camera as Tait-Bryan angles (often called Euler angles in gamedev, though their formal mathematical definition is different).

When you press a key, increment/decrement the corresponding angle, and wrap it into the range \\$\[ -\pi, \pi\]\\$ to keep it well-behaved. (You may want to clamp pitch or roll into a narrower range to avoid gimbal lock when looking straight up, or confusing controls if you roll upside-down)

Then after any angle has changed, rebuild your camera matrix from scratch:

```
t_vec3  rotation[3];

// Roll about Z is "most local", so we'll apply it first.
make_rotation_z(orientation, roll);

// Pitch about X is "in-between", so we'll apply it second.
make_rotation_x(rotation, pitch);
mult_matrix(orientation, rotation, orientation);

// Yaw about Y is "most global", so we'll apply it last.
make_rotation_y(rotation, yaw);
mult_matrix(orientation, rotation, orientation);

```

Note that we completely stomp the old value of the camera orientation each time we update the angles. So the angles are the source of truth here, and the matrix is just an "unpacking" of those angles into a usable form.

Your look-at method, or other ways to initialize the camera orientation, should then set these angles (say, transforming a look-at vector into spherical coordinates, and using those angles as your `pitch` and `yaw`), to ensure the source of truth is updated accordingly.

Here's an example of how to do that:

```
void SetCameraAnglesToFace(t_vec3 direction) {

    yaw = atan2(-direction.x, -direction.z)
    pitch = asin(diretion.y/magnitude(direction));

    // Not enough information in a single direction vector
    // to specify a twist around the roll axis.
    roll = 0;
}

```

# Answer
> 0 votes
Note that *camfwd* is solely defined by (yaw,pitch) so calculate that first.

Given *fwd* / *left* / *up* of the null-rotation (right-handed system)...

```
// yaw the forward vector.
vec3 projectedcamfwd = fwd * cosf(yaw) + left * sinf(yaw);
// pitch the forward vector.
vec3 camfwd = projectedcamfwd * cosf(pitch) + up * sinf(pitch);

```

If you never want camera roll, then camleft is always horizontal, so:

```
vec3 camleft = cross( up, camfwd ).normalized();
vec3 camup = cross( camfwd, camleft );

```

With that, you have all axes (rows) of the camera matrix. Just group them along with a translation vector, and you are done!

If you do want camera roll, we need more work:

```
camup = camup * cosf( roll ) + camleft * sinf( roll );
camleft = cross( camup, camfwd );

```

Let me stress, that this will compute your camera transformation matrix. If you were to render with that in e.g. OpenGL, you still need to get the view matrix from the camera matrix, but that is easy, as *viewmat* is simply the inverse of the *cammat*.

I recommend that you limit pitch in the range \[ -0.4999 π, 0.4999 π \] as it will cause issues when looking straight up.

---
Tags: 3d, camera, rotation, c, raytracing
---


# Question
Title: How to calculate the dot product between the input direction and a character with root motion?
I need to calculate the dot product between my character movement direction and the input being pressed by the player. When the character movement was being controlled only by code, I was using something like this:

```
movementInputVector = new Vector3(inputDirection.y, 0, inputDirection.x) * Time.fixedDeltaTime;
rigidbody.MovePosition(transform.position + movementInputVector);

```

With this movement code, it was possible to calculate the dot product using the character's tansform.forward and the movement input vector.

It happens that I discovered that my movement needs to use root motion and after this change, I can't find a way to generate a consistent dot product anymore. Already did some attempts, but none of them worked.

Firstly, I tried to use the transform.forward, as it did worked before:

```
MovementDirectionDot = Vector3.Dot(transform.forward, movementInputVector);

```

But the result was 0, no matter the direction I pressed as input.

Then I tried to use the root bone of the character as reference:

```
MovementDirectionDot = Vector3.Dot(rootBoneTransform.forward, movementVector);

```

This attempt generated inconsistent values from ~-0,07 to ~9.

Taking a look at the transform.forward values, I've noticed it doesn't change as the character moves, remaining as a vector3(0,0,1) the whole time. Also, I tried to normalize all vectors involved and the same results happened.

So I have no clue what to do now, I don't know what vector should be used in this method in order to get back the correct dot product ranging from -1 to 1. Does anyone have an insight on this?

# Answer
> 0 votes
So after revise everything again and again I stopped to take a closer look on two vectors I was using to generate the dot. It happens that the "movementVector" is a vector2 and the "transford.forward" is a vector3, as the movement in a 3D ground happens in the X and Z axis, the results never would be right. So my solution was to create a vector3 using the movementVector as base, inverting the value on X axis(for some reason the original value is opposed of the transform.forward one), so I solved the problem using this 2 lines:

```
var convertedMovementVector = new Vector3(movementVector.y, 0, -movementVector.x);
    MovementDirectionDot = Vector3.Dot(convertedMovementVector, transform.forward);

```

The results are consistent now, so I believe this is a good solution for my case, even looking like an improvisation.

---
Tags: unity, vector, transformation
---


# Question
Title: SDL2 - Why use `SDL_Window* win` and not `SDL_Window win`?
Is there a reason to allocate the window on the heap and not the stack?

# Answer
`SDL_Window win;` will not compile.

`SDL_Window` is a so-called *opaque struct*. Somewhere in SDL headers, it's declared as `struct SDL_Window;` or something similar (without the body, as opposed to `struct SDL_Window {...};`). Since you don't know what members are inside, or even how large the struct is, you can't create an instance of it.

Somewhere inside of SDL sources (not in the headers accessible to you) there might be a proper definition: `struct SDL_Window {...};`, which allows SDL itself to create instances of this struct and access its members. But since *your* code doesn't see this definition, *you* can't do that.

(Disclaimer: I didn't actually look in the headers. `SDL_Window` might be `typedef`ed to something like `void *`, then SDL would have to cast it to a proper struct type before accessing the members, but it's effectively the same thing.)

This accomplishes several things:

1. You can't mess with the the members of this struct, `win->foo = bar;` won't compile.

Technically you could cast the pointer to `char *` and read/write some bytes to it, but nothing in C/C++ can protect against that.
2. If you link dynamically, your application is supposed to work with different versions of `SDL2.dll`. If SDL always handles the \[de\]allocation of its structs, it's able to change the size/members of the struct between versions, without your app noticing it.
> 6 votes

# Answer
Pointers to stack allocated and static memory exist, FYI. The fact that you are throwing around a pointer implies nothing about the lifetime / owner / origin of the memory you are pointing to.

This is why C++ Core Guidelines insist raw pointers are bad design and concepts such as views, ownership and smart pointers were created.
> 0 votes

---
Tags: sdl2
---


# Question
Title: Unity: Will a 2D animator controller load all sprites for all animations into memory?
I've got a massive animator controller for my main character in my 2D game. I want to know if my animator controller will load every animation for my main character all at once since all of his animation clips are in the controller. That would represent a huge number of sprites. The game uses sprite animation.

# Answer
> 2 votes
For posterity, all sprites in all animation clips used in an Animator Controller will be pre-loaded into memory.

In other words, it's not a good idea to have all of your animations for a character handled by one Animator Controller if you have lots of animations for that character.

In my case, (2D point and click adventure game), I'm going to have to either break my controllers apart, or start using the Playables API (probably via some third party library like Animancer).

I wish this were documented somewhere, so here's my wish being granted! Hope this helps someone else.

---
Tags: unity
---


# Question
Title: How do I import a Spine animation project into DragonBones when DB cannot read the atlas file?
I found 2 interesting Spine projects that I would like to import into DragonBones, but their texture atlas is in `.atlas` format, which cannot be read by DragonBones. I don't know how to convert `.atlas` files to `.json` files that DragonBones understands.

How should I proceed?

# Answer
> 1 votes
So, after hours of hit and trials, here are my **OBSERVATIONS** when importing spine project in DragonBones.

**(1)** You cannot import `.atlas` file and its sprite sheet from the assets option. It takes only `.json` and `.xml` is general So, if you have multiple `.atlas` sprite sheets of spine animation, do it at the time of **Creating a new project from spine**, otherwise, it won't give option to read `.atlas` file later.

**(2)** Even after importing Spine animation, it didn't put images in respective slots for me and in one case, the scale of some images were not correct. However, it shows the correct name of images in the slot but no sprite was actually present even if the assets are correct available in DragonBones library. The author of dragonbones told that DragonBones doesn't support some features of spine.

**(3)** If multiple `.atlas` files are in the same folder then it picks the first `.atlas` file. Ideally, it should pick the one with the same name. So, you have to manually browse the correct file. However, .png, it picks automatically corresponding to the name of `.atlas`

**(4)** There is some meta in the starting of animation file of spine(you can easily find it). If that meta is not correct or missing then it won't be read by DragonBones. So, if correct file is not working for you, find if that's missing.

**(5)** Don't use random texture data file, example, don't generate it by script which converts json to atlas, or vice versa, etc. Because that might not always work. DragonBones reads atlas file and converts into correct `.json` texture data file which is readable to DragonBones itself. So, you must see that if the texture data finally matches with what is given in the default examples of DragonBones software.

**FINALLY**, simple steps to import are if your `.atlas` `.json` and `.png` files are correct are:

**1)** Click on import(not import assets), form the toolbar

**2)** It opens the popup and asks you to select "Animation" data file which is your spine animation file. When you select that .json animation file, DragonBones automatically selects "Spine Animation Data" in the next window popup.

**3)** So, now, you just select the corresponding texture `.atlas` data and `.png` texture. (In my case it was `png`. I am not sure if Spine exports other format as well. So, whatever it exported from spine should work, I guess)

I've given a little pause to animation. So, above steps can look vague to you but assured, they are correct observations.

I Hope some of it is helpful as there is probably nothing out there which could seriously help, AFAIK.

# Answer
> 0 votes
I think it's not possible at the moment.

If you select Spine's *JSON* export option with *Create atlas*, it exports the following files:

* `.json` files describing skeletons and their animations,
* `.png` or `.jpg` files containing the images used, and
* `.atlas` files describing what images belong to which parts of the skeleton.

If DragonBones cannot read `.atlas` files, it cannot put the images where they should be, and so cannot import the project.

Some options for you:

# Answer
> 0 votes
DragonBones offical tools for converting to and from popular formats

Installation: `npm install dragonbones-tools --global`

Convert Spine json format files to DragonBones json format files in current path.

```
$ 2db -t spine

```

After running above command, you will get three files of Dragon Bones, e.g.:

* `xxx_ske.json` (the skeleton file)
* `xxx_tex.png` (the texture image)
* `xxx_tex.json` (the atlas file).

---
Tags: skeletal-animation, texture-atlas, spine
---


title: What's wrong with my planar reflection?

text:
# Question
Title: What's wrong with my planar reflection?
At some angle my mirror with planar reflection shows this result. Looks like it mix with the sphere reflection capture.

How to fix it?

# Answer
Sometimes the worst result arises like this Which the reflection is totally(sometimes half) white or black.

I accidentally set the **planar reflection scale** back to default, the artifacts went away. Couldn't explain why, but it worked:D

*(Special thanks to @DMGregory)*
> 1 votes

---
Tags: rendering, unreal-4
---