# Question
Title: Clip a 2D sprite within a bounding box without masking
In Unity, working on a 2D game, I have a platform game where the platforms can "sink" when jumped on. The platforms are 32x32 sprites, and when sinking, the desired effect is to push the sprite down and avoid drawing the portion of the sprite outside the original 32x32 box:

I currently do this by placing a sprite mask below the platform. It works very well, but the problem begins when I have several such platforms directly below one another:

I can't get this effect using mask since the mask will also partially cover the **upper** side of the platform below. An ad-hoc solution is assigning the sprites to different sorting layers, but I sometimes have **many** such platforms, and they're all conceptually the same, so I'm looking for a cleaner solution.

**TL;DR**: I want to define a "bounding box" for a **specific** sprite such that parts of the sprite outside the box will not be drawn.

Note that this is a 2D problem concerning sprites; I've seen solution based on 3D components which are not relevant here.

# Answer
> 1 votes
I prefer to use a simple shader to handle this:

Set a parameter `MinY`, Any fragment with uv.y less than this value will be discarded.

```
Shader "Custom/NewShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _MinY("MinY", Range (0, 1)) = 0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

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

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float _MinY;

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

            fixed4 frag (v2f i) : SV_Target
            {
                float2 uv = i.uv;
                if (uv.y<_MinY){
                    discard;
                }

                fixed4 col = tex2D(_MainTex, uv);
                if(col.a==0){
                    discard;
                }
                return col;
            }
            ENDCG
        }
    }
}

```

And a c# script to control the material parameters:

Cache the original position of the sprite, compare the position every frame and calculate the value of `MinY`.

```
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    private Vector3 pos;
    private Material material;
    private float sizeY;
    void Start()
    {
        pos = transform.position;
        var spriteRenderer = GetComponent<SpriteRenderer>();
        material = spriteRenderer.material;
        sizeY = spriteRenderer.size.y;
    }

    void Update()
    {
        var offsetY = (pos - transform.position).y;
        material.SetFloat("_MinY", offsetY / sizeY);

    }
}

```

This is a rough prototype, there is a lot of room for optimization, maybe you can think of some strategies to reduce computation. :)

Result:

---
Tags: unity, 2d, sprites, masking
---


# Question
Title: "Attach socket" with Oculus Interaction SDK
I'm trying to recreate the "attach socket" (XRSocketInteractor) from Unity's XR Interaction Toolkit.

Has anyone had any success? I've read through the documentation but can't come up with a simple way to do this. I've even tried writing my own script with an `OnTriggerEnter()` using both

`grabInteractable.AddSelectingInteractor(grabInteractor);` and `grabInteractor.Select();`

but still haven't got a complete snap attach..

I've gotten the grabbable object to turn green (be Selected) seen with the "Interactable Debug Visual" script but the object doesn't "auto move" to the transform point and I'd rather see if there is indeed a proper way to do it.

Any ideas?

# Answer
There is now the "Snap Interaction" (or "drop zone") included in the SDK https://developer.oculus.com/documentation/unity/unity-isdk-drop-zone-interaction/
> 0 votes

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


# Question
Title: Use one collider for Rigidbody2D.Cast, and another for a hurtbox
I'd like to do the following:

* Characters (player, enemies) have a collider for collision with the world (= other characters/obstacles/etc)
* Characters have another collider acting as a hurtbox (most likely larger than the collision)

Now what I tried is a layout is like roughly this:

```
Character root GameObject [layer is "default"]
  - Rigidbody2D (kinematic, full kinematic collision)
  - BoxCollider2D (rather small, just the feet of the sprite)
  - `MovementController` script with collision detection using `rigidbody.Cast` and MovementFilter set to layer "default"
  * `Hurtbox` child object [layer is "hurtbox"]
    - BoxCollider2D (covers most of the sprite (or more to make some enemies easy to hit))

```

LayerMatrix: Two user defined layers: Hitbox, Hurtbox. There's no interaction with the predefined layers and the only interactions among these is

```
Hitbox - Hurtbox [used for damage, etc: when a hitbox collides with a hurtbox, things happen]

```

Now the problem seems to be that all the Colliders in the child objects attach themselves to the ribidbody in the parent even though they're on different layers. And so the `rigidbody.Cast` uses the combined shape of both the "collision" box collider AND the "hurtbox" box collider.

How can I fix this?

# Answer
Here's the solution as proposed by @DMGregory.

The key is to use the collider itself for the `.Cast` instead of the rigidbody

Old code - irrelevant parts omitted

```
private Rigidbody2D rb;

void Start()
{
  rb = GetComponent<Rigidbody2D>();
}

private bool HasCollision(Vector2 direction)
{
  int count = rb.Cast(
    direction,
    movementFilter,
    collisions,
    collisionOffset
  );

  return count > 0;
}

```

New code - irrelevant parts omitted:

```
private Rigidbody2D rb;
private Collider2D collider;

void Start()
{
  rb = GetComponent<Rigidbody2D>();
  collider = GetComponent<Collider2D>();
}

private bool HasCollision(Vector2 direction)
{
  // Here's the key change!
  int count = collider.Cast(
    direction,
    movementFilter,
    collisions,
    collisionOffset
  );

  return count > 0;
}

```

This works, but it'd be still great to hear about a solution solely based on nested objects and layers. The use case would be to allow for composite colission shapes without resorting to something like a `foreach` where every step in the iteration does a `.Cast`.
> 2 votes

---
Tags: unity, 2d, collision-detection, rigidbody
---


# Question
Title: Implementing a pinball flipper without tunnelling
I'm trying to create a pinball and flipper system in Unity.

Unity has documentation specifically on a spinning body and a ball.

I am using rigid bodies for both the ball and flipper. I've set the ball to continuous dynamic and the flipper to continuous speculative but there are still cases where the ball passes through the flipper:

I am using the basic sphere and box colliders. The flipper is using a hinge joint with 28000 force and a script that sets it to either 18000 or -18000 velocity depending on if space bar is pressed. Gravity is set to -300 Y. The ball and table have 0.01 dynamic and static friction. The ball is rolling down an inclined plane with a rotation of -8 Z. I am using Unity 2021.3.10f1.

I have tried changing default contact offset, default solver iterations, and default solver velocity iterations in the project settings but these have not fixed the issue.

# Answer
The problem you're having is generally called tunnelling.

There are a few ways that you can try to solve it:

* Instead of simulating the physics in discrete steps, use some sort of continuous collision detection system. For general purpose physics, continuous collision detection can be rather expensive, and I don't know if Unity has a built in implementation.
* Use a smaller time step, which you can do in Unity in the project settings (Edit -\> Project Settings -\> Time). This will make the physics simulation more expensive, as it will need to calculate more steps.
* Try to avoid the problem by avoiding small / thin fast moving objects. For example, that pinball looks a bit on the small side in your image. Do you need it to be that small?
> 1 votes

---
Tags: unity, collision-detection, physics
---


# Question
Title: Unity Shader - Moving one texture around and on top of another texture
I have a shader that applies a texture to a sphere with lighting, making it look like a nicely lit planet:

The code for my shader is here:

```
Shader "Custom/CloudedSurface"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Clouds ("Clouds", 2D) = "white" {}
    }
    SubShader
    {
        Pass {
            Tags { "LightMode" = "ForwardBase" }
            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                #include "UnityCG.cginc"

                struct appdata
                {
                    float4 vertex : POSITION;
                    float2 uv : TEXCOORD0;
                    float3 normal : NORMAL;
                };
                struct v2f
                {
                    float4 pos : SV_POSITION;
                    float2 uv : TEXCOORD0;
                    float3 normal : NORMAL;
                    float3 worldPos : TEXCOORD1;
                };
                sampler2D _MainTex;
                sampler2D _Clouds;
                float4 _MainTex_ST;
                float4 _Clouds_ST;
                v2f vert(appdata v)
                {
                    v2f o;
                    o.pos = UnityObjectToClipPos(v.vertex);
                    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                    o.normal = normalize(mul(v.normal, unity_WorldToObject).xyz);
                    return o;
                }
                fixed4 _LightColor0;
                fixed4 frag(v2f i) : SV_Target
                {
                    float dif = max(0.05, dot(i.normal, normalize(_WorldSpaceLightPos0.xyz)));
                    fixed4 col = tex2D(_MainTex, i.uv);
                    fixed4 result = fixed4(col.rgb * dif * _LightColor0.rgb, 1);
                    return result;
                }
            ENDCG
        }
    }
}

```

It is quite simple as it just applies a texture to a sphere with some basic lighting. It needs to run on a mobile so I want to keep it simple for high performance. No need for complex effects or details etc.

The issue is that I need to apply a second texture (called "Clouds" above) and move this around the sphere, whilst keeping it under the influence of lighting. This will make it look like clouds are moving around the planet. Please can someone help me to do this?

I don't think it should be hard, but whenever I try it combines the two textures together and moves them simultaneously. I don't know how to move the clouds independently and "on top" of the main texture to create the illusion. Maybe I need a second pass? I have tried to no luck.

Any help would be really appreciated.

# Answer
The code that works is:

Shader "Custom/CloudedSurface"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Clouds ("Clouds", 2D) = "white" {}
    }

    SubShader
    {
        Pass {
            Tags { "LightMode" = "ForwardBase" }

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

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

                struct v2f
                {
                    float4 pos : SV_POSITION;
                    float2 uv : TEXCOORD0;
                    float3 normal : NORMAL;
                    float2 cloudUV : TEXCOORD2;
                };

                sampler2D _MainTex;
                sampler2D _Clouds;
                float4 _MainTex_ST;
                float4 _Clouds_ST;

                v2f vert(appdata v)
                {
                    v2f o;
                    o.pos = UnityObjectToClipPos(v.vertex);
                    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                    o.normal = normalize(mul(v.normal, unity_WorldToObject).xyz);
                    o.cloudUV = TRANSFORM_TEX(v.uv, _Clouds);
                    return o;
                }

                fixed4 _LightColor0;

                fixed4 frag(v2f i) : SV_Target
                {
                    float dif = max(0.05, dot(i.normal, normalize(_WorldSpaceLightPos0.xyz)));

                    fixed4 col = tex2D(_MainTex, i.uv);
                    fixed4 clouds = tex2D(_Clouds, i.cloudUV);
                    col = lerp(col, clouds, clouds.a);

                    fixed4 result = fixed4(col.rgb * dif * _LightColor0.rgb, 1);
                    return result;
                }
            ENDCG
        }

    }
}
```

> 0 votes

---
Tags: unity, shaders, graphics, graphics-programming
---


title: Game Maker Studio 2 Camera Jitter

text:
# Question
Title: Game Maker Studio 2 Camera Jitter
I am trying to follow an RPG tutorial. I used the code for the camera following from there, but in my case for some reason all sprites jitter every time the camera moves, and also when some NPCs move.

Maybe there's something new in GameMaker that I should be implementing, as the tutorial I'm following is 5 years old. I tried using `round()` as some solutions said it might help, but it didn't.

Here is my code for the camera following in `obj_camera` in its *Create* event:

```
following = obj_player;
h_border = 60;
v_border = 30;

```

Here is my code for the camera following in `obj_camera` in its *Step* event:

```
    x = round(clamp(x,(following.x) - h_border, (following.x) + h_border));
    y = round(clamp(y,(following.y) - v_border, (following.y) + v_border));

```

And in the Room's Viewports, I enabled the object following and set it to `obj_camera`:

And here are my settings for the graphics; I have 60 FPS:

I know I should probably use another camera setup, but this one was shown in the tutorial by FriendlyCosmonaut and I just thought I might use it as it was working for her. Also, I use a Mac computer, maybe it has something to do with that.

I would really appreciate any help, thanks.

# Answer
> 1 votes
After trying to open the same project on Windows I figured out that the jitter had something to do with Mac OS and M1 as there was no camera jitter on PC. So there was nothing wrong with the code or settings, Game Maker just works like that on M1 in my experience.

# Answer
> 0 votes
The subtle jitter movement of your camera could be due to different reasons:

* **Rounding:** since you force integers when updating the camera position, it results in a non-uniform displacement at each frame, e.g. moving `2.5`-`2.5`-`2.5`-`2.5` pixels vs. moving `3`-`2`-`3`-`2` pixels over time. *Fix*: force your character (and camera) movement to integer increments, and use no decimals in your movement logic; this will let you get rid of `round()` functions.
* **Interpolation:** you aren't using interpolation for rendering, I guess because you want to achieve a pixel-perfect look for your game. However, it works best with very low resolutions (e.g. 320x240, 160x120), so scaling up the application surface to the screen size will show very few artefacts. *Fix*: enable interpolation to smooth pixels during rendering. This is very effective if you don't `round()` your character/camera position during movement, and interpolation will smooth pixels when rendering at the current position.
* **V-sync:** lack of vertical synchronisation may lead to screen tearing. It happens because the OS tries to render new frames as fast as possible, without trying to stick to a constant flow rate. *Fix*: enable synchronisation and check if the final result improves the visual quality of your game.
* **Fixed timestep/game loop decoupling:** while `room_speed` defines how many updates the game performs each second, this quantity doesn't necessarily synchronise well with the screen refresh rate. It may occur to skip a render frame once in a while because the game update cycle tries to keep up with the real-time; on the other hand, the same render frame may be drawn multiple times on the screen because the screen refresh has occasionally run faster than the game loop.
GameMaker Studio uses a game loop where rendering is strictly coupled with game logic: each update step implies a new frame to draw. You can disable drawing, but you can't actually tell GMS to "use `room_speed` 30, but render at 60 FPS". It just doesn't support that. *Fix*: there's nothing simple I can think of. You may implement a new game loop yourself and nest its logic beneath the three Step Events, but it's going to be quite a convoluted code and I believe you just want to develop your actual game rather than some boilerplate logic for it.

---
Tags: camera, game-maker, game-maker-studio-2
---


# Question
Title: How to check if a Vector3 or Quaternion are unassigned?
How can I check whether `Vector3` and `Quaternion` are not "null"?

I have a saving system and didn't have a vector and quaternion value before.

Now I've added a `Vector3` and `Quaternion` value into the saving system, so the new save file should have a `Vector3` and `Quaternion` value.

I need to check whether the vector and quaternion values are present in the save file, but I can't use `!= null`, cause it's a struct, so it can't be null.

So how can I check whether the value exists or not?

```
position != Vector3.zero , Rotation != Quaternion.identity

```

Is this the right way to do it?

# Answer
> 2 votes
If a `struct` type has not been given any particular value, it will usually default to a special value helpfully called `default`. (Though it's possible the file loading code you use does something different — you haven't shown us, so I'm assuming it's following standard C# convention).

The members of `default` will each hold the value corresponding to the `default` of their respective types: 0 for numbers, `false` for booleans, `null` for reference types, etc.

So you can check:

```
if (!position.Equals(default)) {/*...*/}

if (rotation != default) {/*...*/}

```

For a `Vector3`, the default value is the same as `Vector3.zero`, ie. (0, 0, 0), just less typing, and a bit more explicit that you're checking if it's a default value not looking for a deliberately-set value of zero.

But that highlights a bit of an issue with this code: it won't distinguish between loading an item for which no `position` was set, versus loading an item that was set to `(0, 0, 0)` deliberately.

If that distinction is important for your loading logic, then as others have suggested, you may want to change the declaration of your variable to:

```
[SerializeField]
Vector3? position;

```

This makes it a "nullable" struct — it's still a value type, but it gains an extra flag that tracks whether a value has been set.

You can check this with:

```
if (!position.HasValue) {/*...*/}

```

or, for convenience, `position == null` translates to this for nullable types.

Then, to access the `Vector3` contents, you'd write `position.Value`.

You'll note that I used the `.Equals()` method instead of `==` above. That's because the equality operator for `Vector3` has a built-in tolerance, so a vector very close to zero but not *actually* zero will return `true` if you compare it to a zero vector with `==`. The `.Equals()` method only returns `true` for an exact match.

For quaternions, you have a somewhat easier time, in that any valid quaternion will have a non-zero value. ie. `Quaternion.Dot(rotation, rotation)` should be close to 1.0 — even for `Quaternion.identity`, which is (0, 0, 0, 1) (in x, y, z, w order).

So if you ever read an all-zero quaternion (like `default`), you can be sure that was not a deliberately set value, and needs to be overridden.

The difference between an all-zero quaternion and a valid one is much larger than the tolerance used in the `==` operator, so you don't strictly need the `.Equals()` method in this case.

# Answer
> 0 votes
You can use

Quaternion? rotation = null; Vector3? position = null;

then you can check if the value exit in savefile

---
Tags: unity, c#, savegame, serialization
---


# Question
Title: How to make a 3-Color Noise texture in Substance Designer?
I am trying to make a seamless leafy texture in Substance Designer procedurally.

Basically I want 3 colored noise from scratch. Even two color would be ok but not just black and white.

In the following image I have the effect I want, (I do note its not JUST black n white, it is greyscale). I want greens and yellows in there and NO black or white at all in there. Essentially I just want to change the black value to be green, and white to be yellowish brown. Then it would be the exact effect I need for the texture.

# Answer
To change greyscale to colors simple use Gradient Map node and specify colors you want there (i.e. green and yellow). You can add any other colors in between too.
> 2 votes

---
Tags: textures
---


# Question
Title: Add and Removing Elements on the Circumference of a Circle
I am trying to spawn entities on the circumference of a circle.

These entities may be removed at any time, including all of them being removed.

Periodically I would like to add an element on the circle at the furthest distance from all other entities, but I cannot figure out the math.

The basics is to add an entity at the midpoint between the two neighbors that have the greatest distance between them.

My pseudo code is -

```
positions = []
radius = 40
max_angle = 0
if positions.size() == 0:
  positions.append( {x: radius, y: 0} )
elif positions.size() == 1:
  positions.append( {x: -positions[0].x, y: -positions[0].y })
elif positions.size() > 1:
  for i in [0 to positions.size()]:
    p1 = positions[i]
    p2 = positions[i + 1 % positions.size()]
    angle = atan2(p2.y - p1.y, p2.x - p1.x)
    if angle > max_angle:
      temp = {x: cos(angle/2) * radius, y: sin(angle/2) * radius}
  positions.append(temp)

```

Everything breaks down in my for loop when trying to calculate the third point. This is because the angle after 2 iterations is 0, and results in a bad spawn.

My knowledge of geometry is not really good enough for me to figure out what I should be doing here.

I have some work arounds which would involve adding static points on the circle, or redistributing points along the circle on a new spawn, but it would be pretty cool if I could get this function able to automatically find the correct mid point.

Any help or direction is appreciated.

# Answer
> 4 votes
Firstly, atan2(p2.y - p1.y, p2.x - p1.x) isn't what you want, as that just gives the direction between the two points, not the distance, so comparing atan2(p2.y,p2.x) and atan2(p1.y,p1.x) is closer to what you want.

That still leaves an annoying edge case at the discontinuity when the atan2 jumps between -pi and pi, so I'd suggest calculating the biggest gap in a different way. You don't need the actual size of the gaps, you just need to compare relative sizes, so you could just use the direct square of the distance between the points instead of an angle: (p2.y-p1.y) * (p2.y-p1.y) + (p2.x-p1.x) * (p2.x-p1.x). This is faster to calculate, and completely avoids the discontinuity.

Even simpler would be a dot product: dot(p1,p2) = p1.x * p2.x + p1.y * p2.y, although in that case you need to reverse the comparison order: the dot product gets bigger when the points get closer together.

BTW, these solutions only work for points on the circumference - if you were wanting to compare general angles between points at varying distances from the center, you could use the dot product, but would have to normalize by dividing by distances from the center.

---
Tags: geometry
---


# Question
Title: How to do color post processing in WebGL, when you can not read the color of the current pixel?
In a WebGL 2 GLSL fragment shader, one can not access the pre-existing color value of the current pixel, i.e. the color that is already there in the framebuffer before the pixel that is currently calculated. I am woundering how one can get around this limitation?

For instance, let's say that I want to do some color post processing by running a fragment shader on a quad covering the whole screen. I'll use gamma correction as an example, but it could be any arbitrary function that takes a color for and return a new color. I would like to write code like this:

```
#version 300 es
precision highp float;

in vec2 uv;
out vec4 outColor;

void main() {
  vec4 currentColor = readPixel(uv)
  outColor = pow(currentColor, vec3(1.0, 1.0, 1.0) / 2.2);
}

```

However, there is no such function as `readPixel`, so I do not know what color I am trying to gamma correct. I can think of a few approaches to tackle the problem:

* **Leverage the blend modes.** However, they are quite limited (all are linear, I think), and I don't think they will help me here.
* **Include the post processing in all fragment shaders.** If all fragment shaders that put pixels on the screen has the same post processing built in at the end, I don't need to do it in a separate pass. But this complicates my code, since every single fragment shader is suddenly dependant upon my post processing needs. It's not so much *post* any more.
* **Use ping pong buffers.** Render to one framebuffer, and read the pixels from a texture belonging to another framebuffer. The non-existing `readPixel` can then be replaced with the very much existing `texture` function. However, this can't be great for performance since I am basically copying the full frame each frame.

What is the best path forward here? Is there a fourth option that I am missing? Is there some established best practice in a situation like this?

# Answer
This is not a WebGL 2 restriction. This is fundamentally how GPUs and their 3D rendering APIs all work.

Because they're designed to render many triangles and fragments in parallel, they structurally eliminate data dependencies between these operations. A particular chunk of memory is either read-only (texture) or write-only (frame buffer / render target) for the full rendering pass.

If you want to change to read some memory, all pending writes to it need to finish first (a full pipeline flush). This would be unimaginably slow if it had to happen for every pixel — your super fast parallel processor would effectively become serial. So the APIs are designed so you can't write code that could incur such a serial penalty.

(There are some exceptions involving compute shaders, unordered access views, etc., but they're more specialized, and generally not a performant way to do a big bulk operation like a full-screen post effect where you know you want to write one value for every screen pixel)

Every post-processing system you've ever seen — yes, even that one that ran at ridiculously high frame rates — works using the "ping pong" approach you describe. **You render the scene to one buffer, then read that buffer to apply post effects and write them to a second buffer, which is ultimately shown to the screen.**

Your assumption that this would be unreasonably slow due to "copying" is not quite right. Whether writing to a new buffer or overwriting the value in-place, we still have to do the same work:

1. Sampling a buffer
2. Calculating a new colour based on the value read
3. Writing that colour to a buffer

The only difference is whether the write destination is the same as the read destination. These are cached separately on GPUs so you don't incur a performance penalty from writing to a different spot of memory — in fact you gain performance because there's no need to interleave loads and stores from the same memory chunk.

In fact, this can even give you more control over performance by allowing you to render your scene at a reduced resolution when needed, then apply a post-process resolve to map it to a full-res buffer to present to the screen, in a more sophisticated way than a bilinear upscale. "Dynamic resolution", checkerboard rendering, DLSS, and other strategies for getting high framerates at high resolutions work in roughly this way.

Modern games will often have many of these off-screen buffers, used for things like deferred rendering G-buffers, previous frames' output for motion blur, screenspace reflection, or temporal antialiasing, downsampling the frame buffer for fast bloom blurs, and all sorts of other effects.

It's not free, but generally fill rate (the number of times you write a value out — whether to the same place or a new one) is more likely to be a bottleneck on modern GPUs than the amount of memory used for render targets.
> 41 votes

---
Tags: shaders, glsl, fragment-shader, webgl, post-processing
---


# Question
Title: Canvas scaler does not work when the UI is Instantiated at runtime
My canvas scaler does not work when the UI is instantiated dynamically.

It does work well in iPhone 6.5 inch simulator:

The problem is when I use 5.5 inch or smaller simulator:

It does not follow the Canvas scaler to resize.

How can I fix this problem?

# Answer
set worldPositionStays to false as a second parameter to SetParent.

YourUI.transform.SetParent(canvas.transform, false);
> 1 votes

---
Tags: unity, mobile, scale, unity-ui
---


# Question
Title: Should the state object be defined inside the actual object? For Save/Load purpose
I have a class Furniture with a subclass of FurnitureState where all the "live" data will be stored. During gameplay when the furniture will be turned off or relocated (Player action) it will change the fields of this state class.

The idea is that i can easily serialize all the states during the save operation by just iterating over all furnitures, items, enemies.

```
public class Furniture
{
    [System.Serializable]
    public class FurnitureState
    {
        public string furnitureType;
        public int x;
        public int y;
        public int enabled;
    }

    public FurnitureState state;
}

```

Is this a good approach or should i keep the state classes in separate files with all other states for player, items, enemies?

Is it good practice to have the state class to be serializable or should i use another class which will extract the properties that sould be saved/loaded?

# Answer
This is mostly a matter of coding style, and different teams will have different style guidelines. It looks fine to me, according to my personal style preferences.

There's nothing wrong with using a serialized type to gather the save/load properties of an object. In fact, I'd consider that a distinct positive, since it means less boilerplate code to write/modify when adding new properties, reducing the surface area where you can accidentally introduce bugs.

One thing I would change is to make your nested type a `struct` instead of a `class`. This way you don't pay for an extra garbage collector memory allocation when deserializing it, and no extra pointer indirection when accessing it.

Mutable structs can be dangerous in some circumstances (leading to excess copying, or accidental modification of a copy instead of the original), but when all this type is doing is acting as a serializable container for member variables to save/load, those risks are unlikely to bite you for your use cases.

I'd move it out to its own file if it gets cumbersome to maintain the `Furniture` file with `FurnitureState` mixed in. But as long as it's just using a dozen or so lines, I don't see it as causing undue clutter.
> 0 votes

---
Tags: data-structure, savegame
---


# Question
Title: How to make equipment of unique characters relevant in a turn-based RPG with large armies?
I'm developing a turn-based RPG with Pygame as a hobby to better learn Python. I am inspired by NEO Scavenger, Fallout and Mount & Blade. I like the idea of equiping the character with the stuff you loot anywhere but I don't know how I could handle the impact of equipment in combat since in the game you can recruit some guys to fight with you. In NEO Scavenger, you are alone so turn based fights are easy to manage and in M&B, the real time battles allow the equipment to directly impacts your character while giving orders to your party.

But, in a turn-based game with hundreds of units on the battlefield, how can I deal with the impact of equipment on the player's character ?

I thought of auto-resolution battles a bit like in Paradox games or tactical battles like Heroes of M&M or some traditional wargames, or even of the player commanding units like in Total War and one units is the general (so it would be the player's one) but these different systems don't solve the problem of the equipment impact.

# Answer
Assumption: A typical battle in your game is between armies that consist of about 1000 "soldiers" (nameless soldiers who are not more than a unit type) and one "commander" (with name, face, complex stats and an inventory).

How do we make the inventory of the commander matter?

* Make the commander a unit that is extremely strong compared to the regular soldiers. When a commander with bad equipment is as powerful as 200 soldiers and one with good equipment as powerful as 400 soldiers, then their equipment can decide a battle. In a more simulationist game, such a huge power discrepancy between named heroes and unnamed soldiers can strain the suspension of disbelief. But in a game that goes for more of a heroic fantasy atmosphere, it can feel far more believable for individual heroes to be just that powerful on the battlefield. Compare the heroes during the battle scenes in *Lord of the Rings* and the TVTropes article Authority Equals Asskicking.
* Make the commander the leader of a regiment, and make the equipment of the leader representive for the equipment of the units they lead. That means when the commander of a 100 soldier regiment gets equipped with a flame sword and adamantine armor, then **all** the soldiers in their regiment now carry flame swords and wear adamantine armor, and become accordingly more powerful.
* Make the equipment of the commander confer passive bonuses to the whole army. Like equipping the commander with an awesome sword gives 10% more attack for the whole army.

Yes, I am aware that neither of these options is particularly plausible. But plausibility in game design is often overrated. Most players will gladly accept any contrivances as long as they aren't completely counter-intuitive and the result is an enjoyable game experience.
> 2 votes

---
Tags: game-design, game-mechanics, combat
---


# Question
Title: How do I do a dash damage using this method?
```
[SerializeField]float dashingSpeed = 25f;
[SerializeField]float dashingTime = 0.2f;
float dashingCoolDown = 1f;
bool candash = true;
bool IsDashing;
[SerializeField]float MovingSpeed = 10f;
Rigidbody rb;

 void dashing()
{
    if (Input.GetKeyDown(KeyCode.W) && candash)
    {
        StartCoroutine(Dashing());
    }
}

   IEnumerator Dashing()
    {
        candash = false;
        IsDashing = true;
        rb.velocity = transform.right * dashingSpeed;
        transform.gameObject.tag = "dashes";
        yield return new WaitForSeconds(dashingTime);
        IsDashing = false;
        transform.gameObject.tag = "Player";
        yield return new WaitForSeconds(dashingCoolDown);
        candash = true;
    }

```

Hi, i was thinking of changing a gameobject tag during the dash but sometimes it didn't work, like my game object remains under "Player" instead of changing sometimes. Which is weird. why? oh i do this because like once it change during that "dashing" duration, the other game object will take damage when got hit by that tag. So it will feel like that object take damage during the dashes

# Answer
> 7 votes
Using tags is a very messy way to do this. Unity is designed around the concept of reusable components. Let's create and use a reusable component instead.

First, we need a component to represent health. You might already have something like this, but here's a simple example:

```
[System.Serializable] public class HealthEvent : UnityEvent<Health>{}

//Attach to objects that should have HP
[RequireComponent(typeof(Collider))]
public class Health : MonoBehaviour {
    [SerializeField] private float maxHP;
    [SerializeField] private float currentHP;
    [SerializeField] private HealthEvent healthChangedEvent = new HealthEvent();
    [SerializeField] private HealthEvent diedEvent = new HealthEvent();

    public float CurrentHP {
        get => currentHP;
        set {
            currentHP = Mathf.Clamp(value, 0, maxHP);
            healthChangedEvent.Invoke(this);
            if (currentHP == 0) {
                diedEvent.Invoke(this);
            }
        }
    }

    public HealthEvent HealthChangedEvent => healthChangedEvent;
    public HealthEvent DiedEvent => diedEvent;

}

```

Then we need a component to deal damage. This is a very simple example of a damage trigger, which applies damage to any object with a `Health` that enters the trigger. We would attach this component to a GameObject with a Collider with the "Trigger" box checked:

```
//Attach to objects that should deal damage.
//This example only works with trigger colliders, but you can modify it to work with
//regular colliders by adding the OnCollisionEnter() event
[RequireComponent(typeof(Collider))]
public class DamageTrigger : MonoBehaviour {
    [SerializeField] private float damage;

    private void Awake() {
        Collider collider = GetComponent<Collider>();
        Assert.IsNotNull(collider);
        Assert.IsTrue(collider.isTrigger, "Damage Trigger only works with Trigger colliders");
    }

    private void OnTriggerEnter(Collider other) {
        Health health = other.GetComponent<Health>();
        if (health != null) health.CurrentHP -= damage;
    }
}

```

This is a great example of a highly reusable component. We can put `DamageTrigger` on projectiles, environmental hazards (e.g. fire, spikes), AOE effects, or anything else that deals damage to any objects within its volume.

Finally, we reference a damage trigger from our Dasher component. Rather than messing with tags, we turn the damage trigger on when we start dashing and off when we stop dashing:

```
public class Dasher : MonoBehaviour {
    [SerializeField] private DamageTrigger dashDamageTrigger;
    [SerializeField] float dashingSpeed = 25f;
    [SerializeField] float dashingTime = 0.2f;
    float dashingCoolDown = 1f;
    bool canDash = true;
    bool isDashing;
    [SerializeField]float movingSpeed = 10f;
    Rigidbody rb;

    void Awake() {
        rb = GetComponent<Rigidbody>();
        Assert.IsNotNull(dashDamageTrigger);
        dashDamageTrigger.gameObject.SetActive(false);
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.W) && canDash && !isDashing) {
            StartCoroutine(Dashing());
        }
    }

    IEnumerator Dashing() {
        Assert.IsTrue(canDash, "Started dashing while dashing is disabled!");
        canDash = false;
        isDashing = true;
        rb.velocity = transform.right * dashingSpeed;
        dashDamageTrigger.gameObject.SetActive(true);
        yield return new WaitForSeconds(dashingTime);
        isDashing = false;
        dashDamageTrigger.gameObject.SetActive(false);
        yield return new WaitForSeconds(dashingCoolDown);
        canDash = true;
    }
}

```
1. Add a new GameObject as a child of the Player and give it a Collider with "Trigger" checked and the `DamageTrigger` component. Make sure it's on the same Layer as the player, and make sure that layer can't collide with itself in the project Physics settings' layer collision matrix. Otherwise, the player may be hurt by the damage trigger when performing a dash.
2. In the Inspector for the Dasher component, find the "Dash Damage Trigger" field and select the Damage Trigger from step 1.
3. Add a Health component to the object that you want to damage.

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


# Question
Title: Design reasons against directly cancelling draft building
I am developing an RTS right now and this topic came up in discussion about the UI design and patterns in Starcraft 2:

When you issue a building command in any race, it will create a "draft" transparent model of the building that will be seen until the worker arrives at the location and the construction begins.

Once you deselect/lose track of the worker, though, there's no easy way to cancel such a building. One needs to manually locate the unit tasked with it and stop it.

Is there any design reason or implication of why the building drafts themselves aren't clickable? The only thing I can think of is that it would potentially allow modifying the action queue in the middle by cancelling a specific building - which isn't possible elsewhere.

I know that I can do whatever I want, but I was interested in potential design implications I might not be aware of.

# Answer
Adding friction to cancelling a build as described increases the 'cost' of changing strategies with respect to the player's time & attention. Put another way, it draws the focus away from others things & may represent a bit of risk reward. The player wants to change their mind about a course of action (building the structure that they now wish to cancel), but there may be varying degrees of certainty as to how long that will take. The worker needs to be located in order to cancel.

If the worker is on screen, the time required to cancel is probably negligible, but it may take slightly more time to click a moving worker as opposed to the static draft structure. If the worker is not on screen, there's the added time of locating the worker before it can be clicked.

Whether or not this aspect is relevant to your game depends on how meaningful this friction is to your design. In a single player game, a more casually paced game or a game based around fluidity of tactics, the friction might be a design liability. For games at the other ends of those spectrums, the friction might be desirable.
> 2 votes

# Answer
DMGregory brought up a good point in a comment on another answer: When the player cancels the build command, what happens to the worker unit? It would then have no order and just stand around. So unless the player wants to waste that worker, they need to find it and give it a new command anyway. That means canceling the build process at the location of the building would be a redundant action.

And then there is also an argument to be made about consistency. When the player wants to cancel an attack order, do they interact with the target? When the player wants to cancel a move order, do they interact with the destination? No, they interact with the unit they gave the command to. Why should building be any different?
> 2 votes

---
Tags: game-design, ui-design
---


title: Move object on World's XYZ axes

text:
# Question
Title: Move object on World's XYZ axes
I'm trying to move my Character on the world's XYZ Axes, but how do I get them?

I'm trying to do this because my Player is sort of a Sphere and is rolling around, so its xyz directions are rotating.

I thought I can fix this if I make it move with the world's xyz.

Does someone know how to do this, or another way to fix this problem?

This is my current code to move my olayer object:

```
    public float playerSpeed = 20;

    public float verticalInput;
    public float horizontalInput;
// Update is called once per frame
void Update()
{
    verticalInput = Input.GetAxis("Vertical");
    transform.Translate(Vector3.forward * Time.deltaTime * playerSpeed * verticalInput);

    horizontalInput = Input.GetAxis("Horizontal");
    transform.Translate(Vector3.right * Time.deltaTime * playerSpeed * horizontalInput);
}

```

# Answer
This question does not demonstrate research effort.

Just visiting the documentation page for the method you're using, Transform.Translate, would show you that you can pass a `Space.World` argument to apply the transformation in world space, like so:

```
transform.Translate(
    Vector3.forward * Time.deltaTime
    * playerSpeed * verticalInput,
    Space.World
);

```

Please be sure to read the documentation for the methods you're using, and you'll be able to find your own answers faster next time.
> 1 votes

---
Tags: unity, c#, movement, vector, linear-algebra
---


# Question
Title: Difficulties in converting RGBA to float and back
I can't get my colors back.

What I'm using to encode/decode:

```
static const float Scale = 255.0f;//or 256 not working either
static const float Scale2 = Scale*Scale;
static const float Scale3 = Scale2*Scale;
static const float Scale4 = Scale3*Scale;
static const float4 bitSh = float4( 1.0f, Scale, Scale2, Scale3);
static const float4 bitMsk = float4(1.0f/Scale, 1.0f/Scale, 1.0f/Scale, 0);
static const float4 bitShifts = float4(1.0, 1.0/Scale, 1.0/Scale2, 1.0/Scale3);

```

RGBA to Float to be stored as R16\_FLOAT or UNORM (I've tried both none works fine)

```
float C16 = dot(Color, bitShifts);
Output.Color = C16;

```

float to RGBA

```
float4 C16 = txDiffuse.Load(int3(960*Input.Tex.x, 540*Input.Tex.y, 0)).r*bitSh;
float4 rgba = frac(C16);
rgba -=rgba.yzww*bitMsk;
float4 Color = rgba;

```

As explained here some additional modifications can be used to take care about preсision. What I have when manipulating the rgb is either a full red or full blue scene. There is also a problem with the frac result that gives flickering random colors.

The bitXXX data can be reversed (e.g. xyzw values are in wzyx order) but the results are the same.

# Answer
> 0 votes
Finally I got it working as follow:

First solution

Using a rendertarget/shaderresource R16\_UINT, with the restriction of using texture.Load when used as SRV.

take benefit of bitshifting in SM5. Can be replace by appropriate multiplication/division with power of 2 as shown in the second solution

```
 Encode RGB to R16,
 uint3 C16 = uint3(min(Color.rgb*255.0,float3(255.0,255.0,255.0)));
 //using min to ensure the color is in the range 0..255 otherwise if value > 255 black color can be obtained
 uint OutColor  = (C16.r & 0xf8)>>3 | (C16.g & 0xfc)<<3 |(C16.b & 0xf8)<<8;

 Decode R16 to R5G6B5
 uint C16 = txDiffuse.Load(int3(Input.Tex.xy*float2(myresolutionXY),0)).r;
 uint3 i3C16 = uint3(C16 & 0x001F, (C16 & 0x07E0)>>5,(C16 & 0xF800)>>11);
 float4 Color = float4(float3(1.0/31.0,1.0/63.0,1.0/31.0)*i3C16,1);

```

Second solution

the f\_f4 and f4\_f functions are inspired from there

Using a rendertarget/shaderresource R16\_UNORM

Encode RGB to R16\_UNORM

```
Output.Color0  = f4_f(min(float4(Color,Flag & dwReflexPlane), float4(1,1,1,1)));
//using min to ensure the color is in the range 0..1 otherwise if value > 1 black color can be obtained

```

With

```
float f4_f(float4 f4Value)
{
    uint r, g, b, a;
    r = uint(f4Value.r * 31.0f);
    g = uint(f4Value.g * 63.0f)*32;//bitshit version uint(f4Value.g * 63.0f)<<5;
    b = uint(f4Value.b * 31.0f)*2048;//bitshit version uint(f4Value.b * 31.0f)<<11;
    a = 0;//;
    return = float((r | g | b | a)/65535.0);

```

}

Decode R16\_UNORM to R5G6B5

```
 float4 ColorTx = f_f4(txDiffuse.SampleLevel(samPoint, Input.Tex, 0));

```

with f\_f4

```
 float4 f_f4(float fValue)
 {
     uint uiValue = uint(fValue*65535);
     float4 f4Value;
     f4Value.r = (uiValue & 0x001F) / 31.0f;
     f4Value.g = ((uiValue & 0x07E0) /32) / 63.0f;//bitshift version ((uiValue & 0x07E0) >> 5) / 63.0f;
     f4Value.b = ((uiValue & 0xF800) /2048) / 31.0f;//bitshift version ((uiValue & 0xF800) >> 11) / 31.0f;
     f4Value.a = 1;

     return f4Value;

 }

```

Should be adapted to R5G5B5A1 if 1bit alpha is need

Finally these previous packing solutions were not totally satisfactory for my needs.

My multitarget deferred pipeline requires an alpha channel for blending with at least 1 bit to work properly, not possible with these previous solutions. Also UINT did not accept blending.

The other problem to solve was the maximum of 8 simultaneous render target in my card. The problem here was that my current screen space reflection was using 3 layers to show occluded parts using the 8 RTVs, all rendered in one pass. It appears that a 4th layer may be needed in some cases. Each layer requires 3 information’s : color, normal depth. So at least 12 render targets.

The only way to solve this is to pack the color and its normal in one render target and accept some loss of quality. In addition my card is sensitive to bandwith pressure and using format like R16G16B16A16 is more demanding and the highest RTV format available is R32G32. So I selected R10B10G10A2 as the most convenient format for me and find how to pack color and normal in R10G10B10

Packing Color.rgb as R55G5 and Normal.xyz as G5B55 with 2 bits Alpha

```
 float4 f331_R10G10B10A2(float3 Color, float3 Normal, float Alpha)
 {
     float4 Out;
     //min ensures that the value is in the range [0..31] otherwise incorrect colors will be obtained when unpaking
     uint3 uColor = uint3(min(Color*31.0,   float3(31, 31, 31)));
     uint3 uNormal = uint3(min(Normal*31.0,   float3(31, 31, 31)));
    Out = float4((uColor.r | (uColor.g<<5)),
                (uColor.b | (uNormal.r<<5)),
                (uNormal.g | (uNormal.b<<5)), Alpha*1023.0);
     return Out/1023.0;
 }

```

Unpack R10B10G10A2 to Color, Normal and Alpha

```
 void R10G10B10A2_f331(float4 Pack, inout float3 Color, inout float3 Normal, inout float Alpha)
 {
     uint4 iPack = uint4(Pack*1023.0);
     Color = float3( iPack.r&0x1F, (iPack.r>>5)&0x1F,iPack.g&0x1F)/31.0f;
     Normal = float3((iPack.g>>5)&0x1F, iPack.b&0x1F, (iPack.b>>5)&0x1F)/31.0f;
     Alpha = Pack.a!=0;//in my app alpha is used only as 0/1 value
 }

```

Now my pipeline as 4 RTVs for the 4 layers and 1 RTV to store the corresponding depths in R16B16G16A16. Next step : produce a texture for bumpiness (SSR works very slow with bump) and maybe pack normal as 2 8 bits for better quality. Various methods are explained here . 555 normals format is not precise enough for screen space reflection.

---
Tags: hlsl
---


# Question
Title: How to shift focus of RTS gameplay from manual dexterity to strategy?
I am doing an exercise where I have to make a board game where the win condition relates to area control. I decided to make a real-time game where players have to control certain key points at the end of each round.

The player gets a large amount of pawns as troops that they can move around to capture territory with. A big problem that I encountered was that players felt that dexterity played too much of a role in the game, and wanted to focus more on the strategic aspect. I agree with this sentiment.

I am looking for a solution to this problem in RTS games, since these games also deal with a large amount of troops that move around a big map.

I understand that it's incredibly difficult to provide an immediate solution without all the details, so I am looking for books and articles that break down troop control in RTS games.

# Answer
> 1 votes
The game Eufloria (called Dyson during development) had an interesting solution to this.

A Eufloria game map is a graph of circular nodes connected by traversable edges. Each node controlled by a player (by planting a tree on it) passively produces "seedling" units at some rate, which orbit that node until given an order.

The player cannot issue commands to individual seedlings, only plant them in bulk to make a new tree, or send *all* seedlings from one node to a neighbouring node.

This coarse granularity of commands, combined with the relatively slow movement of the seedlings, effectively removes high-dexterity "micro" play from the game, and all decision-making focuses on the broad-scale distribution of troops across the nodes of your territory and its immediate frontier.

Of course, this is easier in a video game where you can have a computer that can move all the little units to follow the high-level command, without the player needing to do it manually. But I think it has lessons you can apply:

* Focus on groups of units. Rather than moving large numbers of pawns, could you use a die or a token with a spinning counter to represent a group of units? Turn the die/spinner to account for the size of the group changing, and move it as a single object, rather than needing to manipulate many pieces.

Your combat rules then hinge on the sizes of the group tokens involved, rather than pairwise interactions between every opposed unit.
* Discretize your space. Moving from one strategic position to another should involve just one or a few distinct hops, so the physical labour of moving pieces from one to the next is minimized.

I think the real-time nature of your game may also be a risk here. As long as the player who moves the fastest has an advantage, that will always push players to the limit of their dexterity to try to capitalize on that potential.

If you don't want to go full turn-based, consider making the game play out in rounds, where each round is still real-time, but players have a limited number of actions they can perform (and some mechanism to help them track this in the heat of the moment). If I know I can do just three things in the next interval, I'm encouraged to deliberate more, rather than rushing to act as fast as I can and course-correct by squeezing in more actions through pure dexterity. It also gives moments of rest so players aren't constantly running full-tilt, and can take in the strategic landscape, or talk a new player through the next step of learning the game.

---
Tags: game-design, rts, strategy, board-game
---


# Question
Title: How to rotate two transforms to touch at a point, while preserving forward direction?
I have a transform which I need to point one of its axes in the direction of another game object, without disturbing or rotating the other axes in any way.

Consider the way your hips move around on a horizontal plane, while both your upper and lower body rotate to face the hip bone's position, without turning left or right.

How do I achieve the above using Unity transforms in C#?

In this image, both T1 and T2 need to face the controller anywhere it moves without spinning on their Up axis, meaning their forward axis must always remain forward.

While reviewing my question I see Billboarding as a suggestion. I am asking how to billboard both T1 and T2 to the controller without turning their forward directions.

The problem I am facing comes down to the three axes. If I apply LookAt() to the controller, even if setting the x, y, or z, or both xz or xy or zy to 0, there is no way that LookAt() can point T1 in the right direction along the Z and X axes while ignoring the Y. It is always Z rotation only or X rotation only or undesired Y turning as the result. LookAt is causing the front of the body to face away from the front when the controller moves, I need to lock it to face forward, but tilt side to side and back and forth.

# Answer
I get a lot of mileage out of this helper function:

```
static Quaternion TurretLookRotation(Vector3 exactUp, Vector3 approximateForward) {
    return Quaternion.LookRotation(exactUp, -approximateForward) * Quaternion.Euler(90, 0, 0);
}

```

This gives you a quaternion that points the local up axis exactly in the direction specified by `exactUp`, then twists to keep the local forward axis as close as possible to `approximateForward`.

So you might want to use it something like this:

```
torso.rotation = TurretLookRotation(torso.position - hips.position, camera.forward);
legs.rotation = TurretLookRotation(hips.position - legs.position, camera.forward);

```

(Though you may want to negate `camera.forward` if you want to point the forward axis *at* the camera)

To keep a point of contact with the hip object, you'll also need to shift the positions of the leg/torso objects, something like:

```
torso.position = hips.position + torso.rotation * (new Vector3(0, torsoPivotHeight, 0));

```
> 1 votes

---
Tags: unity, rotation, transformation, quaternion
---


# Question
Title: Given a quad in 3D space with two diagonally opposite points and normal, how would I find the other two points?
Image attached below for clarification:

So here we have a plane with a random rotation in 3D space, and we have the values for P1, P2, and the plane normal. How do I find the points X1 and X2?

This quad can have any width/height, any position, and any rotation.

# Answer
As discussed in the comments, to make this align with the texture displayed on your touch screen object, you'll also need a tangent vector. With that in hand (and assuming your tangent has unit length), we just do vector projection:

```
Vector3 diagonal = p2 - p1;
float width = Vector3.Dot(diagonal, tangent);
Vector3 side = tangent * width;

x2 = p1 + side;
x1 = p2 - side;

```
> 1 votes

---
Tags: vector, geometry, linear-algebra, normals
---


# Question
Title: How to change sprites for multiple child object from a parent?
I am not much of an expert, tried to look up for solutions but I never found any that I could use.

I have a parent object, and I want to change it's child objects randomly. This is the hierarcy:

I want to change both the "Roof" and the "Building" sprites randomly. This is how my code looks like right now:

```
public Sprite[] sprites;

void Update()
{
    RandomizeSprites();
}

public void RandomizeSprites()
{
    random = Random.Range(0, sprites.Length);
    GetComponentInChildren<SpriteRenderer>().sprite = sprites[random];
}

```

This currently only works for the first child object.

Can anyone help me how to do it for both? Thank you in advance!

# Answer
In the Start() function, store all of your child object building and roofs into a SpriteRenderer Array with

```
SpriteRenderer[] renderers;

void Start(){

    renderers=GetComponentsInChildren<SpriteRenderer>();
    //GetComponents with an S collects all  children of that type.
    //Now loop through the array and apply a random sprite

    foreach (SpriteRenderer ren in renderers) {
        //Sprite ransomsprite = select random sprite however
        ren.sprite = randomsprite;
    }
}

```

No need to use the update function if you are doing this when they spawn.

You can have a separate list of sprites for buildings and one for roof if needed and draw a random one accordingly for each.

You can differentiate between roof and building by checking

```
if(ren.name == "Roof")
ren.sprite = roofsprites[random];

```
> 1 votes

---
Tags: unity, c#, 2d, sprites, visual-studio
---


# Question
Title: Unity UI Toolkit | Select Background Image and Position of a VisualElement
I am searching now for almost an hour and I cannot figure out how correctly to select the background image and position of a visual element.

The query docu is really poor, there is literally nothing:

UQuery is a set of extension methods allowing you to select individual or collection of visualElements inside a complex hierarchy.

All the youtube guys show the same example with a Button.

I have this structure:

Each "Layer" contains a background image:

Here is my code:

```
    public class ParallaxController : MonoBehaviour {

    public VisualElement layer_0;
    public Image layer_0_0;
    public Image layer_1;
    public Image layer_1_1;
    public Image layer_2;
    public Image layer_2_2;
    public Image layer_3;
    public Image layer_3_3;
    public Image layer_4;
    public Image layer_4_4;

    // Start is called before the first frame update
    void Start() {
        var root = GetComponent<UIDocument>().rootVisualElement;

        layer_0 = root.Q<VisualElement>("Layer_0");
        Debug.Log(layer_0.style.backgroundImage);
        Debug.Log(layer_0.style.backgroundImage.value.sprite);
        Debug.Log(layer_0.style.backgroundImage.value.texture);
        Debug.Log(layer_0.style.position);
        //Debug.Log(layer_0.Q.<Image>());
        //Debug.Log(layer_0.Q.<Background>());
    }

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

    }
}

```

Its always `Null`

# Answer
> 1 votes
You can change the background image in this way:

```
public Texture2D ExampleTexture;

void Start()
{
    var layer_0 = root.Q<VisualElement>("Layer_0");
    layer_0.style.backgroundImage = ExampleTexture;
}

```

---
Tags: unity, unity-ui
---


title: How is depth buffer written to?

text:
# Question
Title: How is depth buffer written to?
As far as I know you normally can't read and write to the same render target in the same shader pass. But if I understand correctly, depth tests rely on depth writes of things being drawn in the same pass (otherwise it'd always be the depth of the last fragment drawn which don't have to be ordered) so how is that being done exactly?

I think this should have many answers but for some reason I could find no articles about depth writing. So I'm hoping someone could share where I can learn about this information.

---

One other thing I wonder: Is it possible to write to the depth buffer in a custom way? For example, I think the depth buffer is normally written to the same way the geometry is drawn as specified by depth testing comparison (e.g. only closest objects, "Less" depth comparison). But could I instead choose to write the depth of furthest fragments (e.g. "Greater" depth comparison), and draw color as closest as usual.

I guess the answer is no because you would need two depth buffers and I assume the tools don't exist to write shaders (without using multiple passes).

I'll tag this as Unity since that is what I'm most familiar with but I assume the answers will generalize to other graphic frameworks too.

# Answer
> 3 votes
> so how is that being done exactly?

There is one part of the pipeline that's allowed to both read and write from the render target: the blending unit at the final stage. This has specialized hardware that's only configurable in a fixed function fashion, so it can read the colour to blend with, blend, and write the result atomically, in a correctly ordered sequence with all other fragments in flight.

Naturally, this serialized access can be a bottleneck, which is part of the reason why transparent blending is more expensive, and why fill rate is often our limiting factor in GPU rendering. There's a limit to how fast we can force all our writes through even this specialized and very fast hardware unit.

A similar thing happens with the depth value, where depending on your depth testing and writing settings the depth value is compared and possibly overwritten in a single operation.

Because this unit is so performance-critical, in shader models to date it's stayed on a fixed function model, unavailable for you to customize programmatically beyond turning depth testing and writes on/off, or changing the comparison used. That keeps the circuitry simple and fast, with exactly predictable execution time for scheduling — all stuff that gets more complicated if we were to inject customized programs into this stage.

You may object that the depth buffer can also be read earlier in the pipeline, for "early z rejection" to skip executing the fragment shader for fragments that are going to fail the depth test later anyway. This optimization can use a conservative depth estimate though — possibly not yet taking into account writes that are still in flight. If a few fragments leak through because the read was out of date, the depth test at the end still ensures we get the correct result. If the rendering configuration does not allow such a conservative z test (ie. a write in flight might make an occluded fragment no longer occluded) then the early z rejection is disabled.

> could I instead choose to write the depth of furthest fragments (e.g. "Greater" depth comparison), and draw color as closest as usual.

No. There are not really two separate writes happening here, just one. Either the depth test passes, and both colour and depth are written (if colour and depth writes are enabled, respectively), or the depth test fails, and neither are written.

So while you can change the direction of the depth test to less-than or greater-than, the same test is always used for the whole fragment, both colour and depth components.

You can control what depth to output in the fragment shader by writing a value to the special `DEPTH` semantic, but doing so disables that early z rejection optimization. The hardware pipeline can no longer determine whether the fragment will be occluded until the fragment shader has been run, so it has to run the full shader even for fragments which will never be seen.

You could achieve something similar to this with multiple passes, rendering your content once with a "Less" test and saving the resulting depths to one buffer, then rendering your content a second time with a "Greater" test, and reading the buffer you previously saved to do whatever computations you want that rely on knowing both the greatest and least depth values at a point.

You may also want to look into the technique of "depth peeling" which is used in some order-independent transparency approaches.

# Answer
> 1 votes
If you want to write custom values to the depth buffer, one option is to render the appropriate geometry while disabling writes to the colour buffer, but enabling writes to the depth buffer.

For example, if you want to render a transparent mesh while hiding all of the internal polygons then you can render it twice. The first time you want to render it with colour writes disabled, and depth writes enabled. The second render wants colour writes enabled, depth writes disabled, and the depth test set to equal. Note that for that process to work, you need to make sure that the depth only rendering happens immediately before the transparent rendering or it won't look right.

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


# Question
Title: Template projects missing after updating to Unreal Engine 5.0.3
I just recently upgraded to Unreal Engine 5.0.3 and I cannot find different templates on the start window:

Previously there were many templates, like for a third person project, top-down, hand held etc. I was just starting to learn Unreal and they were pretty useful. How may I get them back? Are there any solutions to this?

# Answer
> 2 votes
It happened to me also, I solved it by accessing the engine options using the arrow down button as shown in the following image:

From this menu I've selected the checkbox to add templates.

---
Tags: unreal-5
---


# Question
Title: Blender exported model is giving better FPS than creating the meshes in Unity
I am experimenting with Hex grid layouts and testing the most efficient way of building a hex map.

I tried 2 things:

1. Build my own hex mesh using 6 triangles and 7 vertices
2. Use blender to create a Hex and import it

For 1. The mesh renderer I created is attached to an object prefab and I instantiate one for each Hex in my grid. 2 is almost similar but I imported the .fbx model from blender and I created a prefab from it. Then instantiate one per hex in my grid.

**Question:** Why is the Blender approach giving me better performance then when I create the meshes myself?

When I use the first approach with the meshes I created, I'm getting around 44FPS

But when I use the Blender approach I get around 60 FPS

**Info on how I'm creating my meshes.** I create 7 vertices, Marked on this screenshot from 0 to 6

Then my triangles will be:

```
List<int> triangles = new List<int>() {
            0, 2, 1,
            0, 3, 2,
            0, 4, 3,
            0, 5, 4,
            0, 6, 5,
            0, 1, 6,
        };

 //Create the Mesh
 m_mesh = new Mesh();
 m_mesh.name = "Hex";
 m_mesh.vertices = vertices.ToArray();
 m_mesh.triangles = triangles.ToArray();
 m_mesh.uv = uvs.ToArray();
 m_mesh.RecalculateNormals();

```

# Answer
> 1 votes
Let me share an insight in the form of a meme:

The way you've chosen to generate your hexagon mesh in Unity is like the one on the left, with 7 vertices and 6 triangles per hex.

I'd bet that Blender has chosen to triangulate it without adding an extra vertex in the center, which lets it use only 6 vertices and 4 triangles, like the example on the right.

Checking your rendering stats backs this up:

|  | Unity Mesh | Blender Mesh | Ratio |
| --- | --- | --- | --- |
| Tris | 121.7 k | 81.7 k | ~6:4 |
| Verts | 145.1 k | 125.1 k | ~7:6 |

So, no special magic, the Blender version just has less data to push down the graphics pipe, so it can be drawn in fewer batches. If you use the 4-triangle split in your Unity code, I'd expect you'd see the difference disappear.

---
Tags: unity, performance, blender, mesh
---


# Question
Title: Formula to assign star rating based on cooking time over/under target
I'm making a cooking game and one of the minigames in the game is to put ingredients on a barbeque. As it's being cooked, a progress bar is displayed, with a range between 0-1.

The goal is to take it off the barbeque at the "perfect point", which would give you a score between 1-5, in the form of a star rating. The "perfect point" in my example image is 0.5, but could vary between ingredients, so it can for example be closer to 1, when the ingredient is burned/destroyed.

Also depending on the difficulty of the ingredient, the slope to get a 5 star rating can be narrower (red line) which makes it harder or broader (green line) which makes it easier. This is currently set as the **factor** variable in the code below.

What mathematical function can I use to get a shape more like the image? Also, can you recommend an online tool to visualize the curve and how the values change it?

I'm currently using the code below, but I don't like that much how it works:

```
// The result is then capped between 0-1 and remapped to 1-5 stars,
// but that's not important for this question. :)

// Varies based on user input
float progress = 0.4f;

// Set per ingredient
float perfectPosition = 0.5f;
float factor = 1.3f;

// Calculation
float distFromPerfectPosition = Mathf.Abs(perfectPosition - progress);
float result = 1 - Mathf.Pow(distFromPerfectPosition, factor);

```

Thank you in advance!

# Answer
Myself, I like to hop into a spreadsheet to play with formulas like these.

Check the "Cooking Stars" tab of this workbook for one way we could tackle it.
You can download it or make a copy so you can edit it and play with the numbers to see how it behaves.

Here's a walkthrough of my process:

First, I wanted to make the two sides of the curve behave the same for our math. So I make a "normalized" value that rises from 0 at time zero to 1 at the "perfect point" (called `TargetValue` in my spreadsheet), and then sinks from 1 to 0 again by the end of the interval at time one:

$$\text {normalized} = \begin{cases} \frac x {\text {target value}}, & x \le \text{target value}\\ \frac {1 - x} {1 - \text {target value}}, & x \> \text{target value}\\ \end{cases}$$

That gives us a "curve" that's really just peaked roof, with two straight sides meeting at a sharp corner at (target value, 1), then sloping down to (0, 0) and (1, 0) on either side. That's the blue dashed line in the graph above.

We can turn a linear ramp between 0 and 1 like this into a smooth sigmoid curve using the smoothstep function:

$$\text{smooth}(x) = 3 x ^2 - 2 x^3$$

Applying this to our normalized value between 0 and 1 gives us the red dashed curve in the graph. This has the rough shape we want, but the peak is too broad, and not symmetrical: if we have a target value on the high side like 0.8, the long interval on the left has a much more gentle ramp-up than the short interval on the right. We also might like to be able to shape how tight the peak is.

So let's add another variable, "strictness", and warp our normalized value from earlier into a "strictified" value like so:

$$\text{strictified} = \begin{cases} \text{normalized}^{\text {strictness} \times \text{target value}}, & x \le \text{target value}\\ \text{normalized}^{\text {strictness} \times \left( 1 - \text{target value} \right)}, & x \> \text{target value}\\ \end{cases}$$

Raising a number in \[0, 1\] to a power \> 1 like this bends it into a curve, shrinking most of the values toward zero and making the rise to 1 at the end steeper. That makes our 5⭐ range narrower. By applying a higher power on the side with the wider interval, we squeeze that side of the peak correspondingly more aggressively, while going gentler on the side with the narrower gap to fill, overall making the peak in our score function more symmetrical in shape.

FInally we can apply smoothstep to *that* strictified value to get a final score. We can multiply the value by 4, add one, and round to an integer to get our star count.

You can make the strictness number higher to make the peak of the curve narrower, or lower to make the peak wider.
> 6 votes

# Answer
Try this:

float result = Mathf.Exp(-factor * (perfectPosition - progress) * (perfectPosition - progress));

then you would have what is essentially a normal distribution, which is the sort of shape that would make sense here.

As for visualizing curves, I'm sure there are better options, but for a general set of tools I use https://www.wolframalpha.com/ . It does that and a whole lot more.
> 2 votes

---
Tags: mathematics, game-mechanics
---


# Question
Title: How does Discord get Overwatch 2 player status from battle.net APIs?
Discord uses battle.net integration and displays player status such as "Playing Overwatch 2". I looked through battle.net API documentation and couldn't find an API that would provide such data.

Is it using some private APIs?

# Answer
> 2 votes
First, as indicated in the comments, the "Playing \[game name\]" status is not unique to Overwatch 2. Discord can look at the client side processes, match them against a database & update the reported status accordingly.

Second, it is possible for an application to integrate with Discord. They provide a dedicated GameSDK in their developer documentation.

So it isn't that Discord is using the various APIs of various games, but that games are able to use the Discord API to make use of Discord's features.

---
Tags: api, discord
---


# Question
Title: How do I stop my gun from pointing at the player?
I'm making a game where you shoot enemies in Unity, but I can't figure out how to stop the player from pointing the gun at himself.

I've tried detecting if the gun is on the left side of the player and if it's rotation on the z-axis is less than 0, but no luck

Here's the code for the gun:

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

public class GunController : MonoBehaviour
{
    public bool testbool;

    public Transform player;
    public CharacterController2D playercontroller;
    public float smoothness = 0.125f;
    public float winglength = 2;
    private Vector2 difference;
    bool facingright = false;

    public GameObject bullet;
    public int maxammo;
    private int ammo;
    private bool firing;
    public Vector3 bulletspawnpos;

    private SpriteRenderer sprite;
    public Texture2D normalGun;
    public Texture2D emptyGun;
    public GameObject emptyBottle;
    // Start is called before the first frame update
    void Start()
    {
        sprite = GetComponent<SpriteRenderer>();
        player = transform.parent.transform;
        ammo = maxammo;
    }

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

    }
    private void FixedUpdate()
    {
        firing = false;
        bool wasfacingright = facingright;
        if (Input.GetMouseButton(0) & ammo !>= 0 & !firing )
        {
            firing = true;
            Instantiate(bullet, transform.position+bulletspawnpos, transform.rotation);
        }
        if (player.transform.position.x - transform.position.x < 0)
        {
            facingright = false;
            sprite.flipY = false;
        }
        if (player.transform.position.x - transform.position.x > 0)
        {
            facingright = true;
            sprite.flipY = true;
        }
        if (wasfacingright != facingright) { playercontroller.Flip(); }

        difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float rot = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;

        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition) - player.position;
        pos.z = 0;
        Vector3 desiredpos = player.position + (winglength * pos.normalized);
        Vector3 smoothpos = Vector3.Lerp(transform.position, desiredpos, smoothness);
        transform.position = smoothpos;
        transform.rotation = Quaternion.Euler(0, 0, rot);

    }
}

```

Before you point out that the ammo doesn't go down, just know I didn't add that for testing purposes.

# Answer
> -1 votes
I'm pretty sure that it is pointing to the camera, and not the player. It happened to me.

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


# Question
Title: Order of interface used for GetComponent
I'm trying to make a dynamic buff system, where each component is manipulating the base value of the skill. Those components should be executed in a certain order but the order within the same type does not matter.

All modifiers have the same basis.

```
public interface IBaseMod {
    float ApplyModifier(float original);
}

```

There exists for now three different layers that are build on this.

```
public interface IPlusMod: IBaseMod {}
public interface IPMultMod: IBaseMod {}
public interface IPCapMod: IBaseMod {}

```

Those are used for the actual implementation, namely

```
public class Add35: MonoBehaviour, IPlusMod {

   public float ApplyModifier(float original) {
       return original + 35;
   }

}

public class Mult2: MonoBehaviour, IMultMod {

   public float ApplyModifier(float original) {
       return original * 2;
   }

}

public class Cap50: MonoBehaviour, ICapMod {

   public float ApplyModifier(float original) {
       return original <= 50 ? original : 50;
   }

}

```

I have a test skill that has those three components

Now within the skill I would like the access the implementation of the modifier in a defined way.

```
public class TestSkill: MonoBehaviour {

    public void Start() {
        Test1();
        Test2();
        Test3();
    }

    private void Test1() {
        float baseValue = 5f;
        foreach (var mod in GetComponents<IBaseMod>()) {
            baseValue = mod.ApplyModifier(baseValue);
        }
        Debug.LogFormat("Test1 returns {0}", baseValue);
    }

    private void Test2() {
        float baseValue = 5f;
        foreach (var mod in GetComponents<IPlusMod>()) {
            baseValue = mod.ApplyModifier(baseValue);
        }
        foreach (var mod in GetComponents<IMultMod>()) {
            baseValue = mod.ApplyModifier(baseValue);
        }
        foreach (var mod in GetComponents<ICapMod>()) {
            baseValue = mod.ApplyModifier(baseValue);
        }
        Debug.LogFormat("Test2 returns {0}", baseValue);
    }

    public interface[] order3 = new interface[]{IPlusMod, IMultMod, ICapMod};

    private void Test3() {
        float baseValue = 5f;
        foreach (var modType in order3) {
            foreach (var mod in GetComponents<modType>()) {
                baseValue = mod.ApplyModifier(baseValue);
            }
        }
        Debug.LogFormat("Test3 returns {0}", baseValue);
    }

    enum MODTYP {CAP, MULT, ADD};
    private MODTYP[] order4 = new MODTYP[3] {MODTYP.ADD, MODTYP.MULT, MODTYP.CAP};
    private IBaseMod[] helper(MODTYP modtyp) {
        switch (modtyp) {
            case MODTYP.ADD: {
                return GetComponents<IPlusMod>();
            }
            case MODTYP.MULT: {
                return GetComponents<IMultMod>();
            }
            case MODTYP.CAP: {
                return GetComponents<ICapMod>();
            }
        }
        return null;
    }

    private void Test4() {
        float baseValue = 5;
        foreach (var modType in order4) {
            foreach (var mod in helper(modType)) {
                baseValue = mod.ApplyModifier(baseValue);
            }
        }
        Debug.LogFormat("Test4 returns {0}", baseValue);
    }

    public Type[] order5 = {typeof(IPlusMod), typeof(IMultMod), typeof(ICapMod)};
    private void Test5() {
        float baseValue = 5f;
        foreach (var modType in order5) {
            foreach (var mod in GetComponents(modType)) {
                baseValue = ((IBaseMod) mod).ApplyModifier(baseValue);
            }
        }
        Debug.LogFormat("Test5 returns {0}", baseValue);
    }
}

```

The return value for `Test1()` is 45 and for `Test2()` is 50. I would like to have the result of `Test2()` in a way that is not hard coded (those 3 interfaces are for now only an example, I would like to be able to change the order dynamically at runtime and not always have all of them). With `Test4()` the order can be changed at runtime with the help of an enum that defines the order and a helper class that has a case for each of the enum and a corresponding GetComponents. That still feels a bit off.

If possible I would like to have a logic similar to `Test3()` where I can store the order in an array or list, iterate over it and use that as the type for `GetComponents`. When possible I would like to avoid that the interface itself has the order hardcoded.

`Test3()` would be the solution I would like to have but it fails in placing the interfaces into an array and/ or using the stored interface from the array as an option to place as type for `GetComponents<InterfaceFromArray>`. Test3() does not compile as is.

The latest Test5() is using the cast with typeOf on the interface to store it and using it to get the component. The only last leftover drawback is, that the return value from the inner foreach is returning a component and it needs to be cast back to the interface.

# Answer
You can't do this in C#

```
public interface[] order = new interface[]{IPlusMod, IMultMod, ICapMod};

private void Test3() {
    float baseValue = 5f;
    foreach (var modType in order) {
        foreach (var mod in GetComponents<modType>()) {
            baseValue = mod.ApplyModifier(baseValue);
        }
    }
    Debug.LogFormat("Test3 returns {0}", baseValue);
}

```

But you should be able to do something like this:

```
// This defines the order of "component getters".
// It's just an array of lambdas - inline functions of the form
// (parameter list) => function_body
//
// Func<IBaseMod[]> just means: a function that takes
// no params, and returns an array of IBaseMod objects.
// Func<IBaseMod[]>[] is an array of such functions.
private Func<IBaseMod[]>[] modGetters = new Func<IBaseMod[]>[] {
    () => (IBaseMod[])GetComponents<IPlusMod>(),
    () => (IBaseMod[])GetComponents<IMultMod>(),
    () => (IBaseMod[])GetComponents<ICapMod>()
};

// So, to summarize, you're just sticking some functions in
// an array, so that you can iterate through it later, and
// invoke (call) those functions dynamically based on some game logic.
// For more info, look up Func and Action delegates.

private void Test3() {
    float baseValue = 5f;

    foreach (var getMods in modGetters) {
        foreach (var mod in getMods()) {
            baseValue = mod.ApplyModifier(baseValue);
        }
    }

    Debug.LogFormat("Test3 returns {0}", baseValue);
}

```
> 0 votes

---
Tags: unity, effect-modifier
---


# Question
Title: Yaw rotation not translating to Quaternion
I'm trying to implement the gimbal lock fix described in this question, but I end up getting weird behavior where when I rotate on the X axis (or try to at least) it rotates on both the X and Y axis at the same time, but when i try and rotate on the Y axis nothing happens at all.

I'm keeping total orientation in a quaternion and (trying to) update it with a rotation matrix constructed by forward, right, and up vectors. I'm deriving these vectors like so:

```
// From https://learnopengl.com/Getting-started/Camera

_forward.X = (float) (MathHelper.Cos(MathHelper.DegreesToRadians(_rotation.Y)) *
                      MathHelper.Cos(MathHelper.DegreesToRadians(_rotation.X)));

_forward.Y = (float)  MathHelper.Sin(MathHelper.DegreesToRadians(_rotation.X));

_forward.Z = (float) (MathHelper.Sin(MathHelper.DegreesToRadians(_rotation.Y)) *
                      MathHelper.Cos(MathHelper.DegreesToRadians(_rotation.X)));

_forward.Normalize();
_right = Vector3.Cross(_forward, _worldUp).Normalized();
_up    = Vector3.Cross(_right, _forward)

```

and updating the \_rotation values like this:

```
public void RotateX(float rotation) {
    _rotation.X += rotation * _sens;
}

public void RotateY(float rotation) {
    _rotation.Y += rotation * _sens;
}

```

To get the rotation matrix I'm just putting the 3 vectors into a Matrix3 object:

```
var r1 = new Vector3(_right.X, _up.X, _forward.X);
var r2 = new Vector3(_right.Y, _up.Y, _forward.Y);
var r3 = new Vector3(_right.Z, _up.Z, _forward.Z);

var mat = new Matrix3(r1, r2, r3);

if (mat != _check) {
    _orientation = Quaternion.FromMatrix(mat) * _orientation;
}

_orientation.Normalize();

```

and then I update the orientation quaternion.

The `_check` property is just a matrix that represents what *should* be created if there is no change in rotation so `_orientation` isn't changed when it doesn't have to be.

This is a gif of what happens when I just use the RotateX function, so it just rotates on some weird axis. Any clue what I'm doing wrong? Am I initializing the rotation matrix wrong or is it something else entirely?

\[edit\]

Camera pitch now works without affecting Yaw and Roll:

```
public void Update() {
        _forward.X = (float) (MathHelper.Cos(MathHelper.DegreesToRadians(_rotation.Y)) *
                              MathHelper.Cos(MathHelper.DegreesToRadians(_rotation.X)));

        _forward.Y = (float) MathHelper.Sin(MathHelper.DegreesToRadians(_rotation.X));

        _forward.Z = (float) (MathHelper.Sin(MathHelper.DegreesToRadians(_rotation.Y)) *
                              MathHelper.Cos(MathHelper.DegreesToRadians(_rotation.X)));

        // _forward.Normalize();
        _right = Vector3.Cross(_forward.Normalized(), _worldUp);
        _up    = Vector3.Cross(_right.Normalized(), _forward.Normalized());

        Console.Out.WriteLine("forward: {0}", _forward);
        Console.Out.WriteLine("right: {0}", _right);
        Console.Out.WriteLine("up: {0}", _up);

        var r1 = new Vector3(_right.X, _up.X * _worldUp.X, _forward.X);
        var r2 = new Vector3(_right.Y, _up.Y * _worldUp.Y, _forward.Y);
        var r3 = new Vector3(_right.Z, _up.Z * _worldUp.Z, _forward.Z);

        var mat = new Matrix3(r1, r2, r3);

        if (mat != _check) { // Change in orientation.
            _orientation = Quaternion.FromMatrix(mat) * _orientation;
            Console.Out.WriteLine(_orientation.ToEulerAngles());
        }

        _orientation.Normalize();

        Console.Out.WriteLine("Position: {0}", _position);

        _rotation = Vector3.Zero;
}

```

But no rotation occurs when trying to rotate about Y axis.

# Answer
Thanks to DMGregory for correcting my quaternion understanding. All is working fine now. I just make a quaternion for pitch and yaw then multiply them with my existing oreientation quaternion like so:

```
// Values in _rotation are already converted to Radians.
var pitchQuat = new Quaternion((float) MathHelper.Sin(_rotation.X / 2f), 0f, 0f,
                               (float) MathHelper.Cos(_rotation.X / 2f));

var yawQuat = new Quaternion(0f, (float) MathHelper.Sin(_rotation.Y / 2f), 0f,
                                 (float) MathHelper.Cos(_rotation.Y / 2f));

_orientation = pitchQuat * _orientation * yawQuat;

```

This replaces the whole Matrix thing I was going with and actually makes the camera work like I wanted. Thanks again to DMGregory for just being cool.

Result(idk why the colors are freaking out it wasn't actually doing that it's just recording artifact i guess):
> 1 votes

---
Tags: c#, opengl, rotation, quaternion, opentk
---


# Question
Title: What makes the network coding for MUDs different from that of MMORPGs?
(I understand this is a bit broad, but I'm not a game developer, so I don't have a particular problem that I'm trying to solve.)

I can understand why the network coding for MMORPGs is so complicated and difficult to get right considering the enormous number of messages that need to be dealt with non-stop. However, I'm not sure I understand why MUDs (as far as I can tell) are so much simpler to get right. Naturally, MUDs have no graphics to deal with, but is it really just that?

An example I've seen for what makes MMOs difficult to code is that something as simple as a player placing an item on the ground can lead to an enormous number of messages being sent. In MUDs, players may also place items on the ground, so while there's no graphical representation, there's still an item being left there and potentially thousands of players logged in that may or may not need to be told about that item being there. Does this not snowball in ways similar to MMORPGs?

# Answer
> 5 votes
I'm going to put forward the opinion that there is actually no netcode at all in a MUD server.

I've seen the phrase 'netcode' thrown about quite a bit in multiplayer gaming - usually as a criticism of how poor it is in a particular game. What this means is in respect of multiplayer shooters; that the other players 'rubber band' a lot, or shots placed on target on your screen don't land on the server. This is an artefact of latency - your local view of the game is different to the server's, and 200ms is a *lot* of time (in server frames, at least). The games where the netcode is praised usually use a combination of interpolation or extrapolation of other player's positions, as well as an amount of forgiveness about how actions are resolved.

A MUD server is different. Unlike graphical games, there is no client. Sure, you *use* a client to access it, but that client is just your favourite flavour of `telnet`. And that's literally all a MUD server is; a port you connect to and type commands into. The server *is* the game, and has no code at all about communicating with the client. As a response to a command, it just spits more text out of that port. On the other end could be a `telnet` client, or a Braille display, or a TTS interpreter or a line printer. The server doesn't care.

Some more modern specialist MUD clients offer local functionality; like mapping, scripting, triggers, etc, but they all just connect to the server and submit text commands. The clients don't know anything about character 'position' like graphical game clients need to (other than they are in your room / not in your room).

Unlike MMORPGs, a MUD is also highly likely to be single-instanced; holding the same view of the world for all players at once. Commands are reacted to by the server in the order they arrive and are *usually\** executed completely (as in one command from one user needs to end before another starts).

And yes, latency is also present on MUDs (and can be quite a problem sometimes), but not in the same way as I described for graphical games. Also, due to the speed at which we type and submit commands, it is a lot slower process in general than moving your crosshair over the head of an enemy and clicking.

An example of latency in a MUD might look like;

```
> look

You are in a maze of twisty passages, all alike

Steve is here

> kill steve

Steve leaves to the east

You cannot see a 'steve' to attack

```

In this example, you saw that Steve was in the room, but between you pressing `[enter]` on your command and the server reacting to it, it had already reacted to Steve's command to move out of the room.

To answer your question directly;

> An example I've seen for what makes MMOs difficult to code is that something as simple as a player placing an item on the ground can lead to an enormous number of messages being sent.

Yes, and no. In this example a player drops an item on the floor. The MUD server knows which room you are in, so it scans the player list for other player characters that are in the same room. To each one, it might send the message

```
joshisanonymous has dropped the McGuffin on the floor

```

That's one message sent out to each connected player that is in the same room as you. The server can achieve this in less than a millisecond, if its data structures are set up correctly.

And the message is just that - a simple string of text. In an MMO the 'message' is likely to be a complex serialised object containing; the action (something was dropped), the position (in world coordinates), what it was (an item ID, its world graphic (ID), its icon (ID), what sound to play, how damaged it is, whether it is a special version of this item, etc). A lot of that info is also being tracked and known by the MUD server, but the message to the players is nothing more than a string. They need to interact with the item in order to know more about it.

\*I say 'usually' as I'm not aware of the internals of most MUD servers. However even if they are multi-threaded, the world view needs to be consistent - only one person can pick up that item off the floor so if two players try to go for it, only one can get it.

Footnote: if you are considering writing a MUD server for this day and age, make sure that you either build in TLS encryption to the server itself, or pipe it through something like `stunnel`.

---
Tags: networking, multiplayer, client-server, mmo, mud
---