# Question
Title: How can I dissolve using dynamic mask objects?
I want to Implement dissolve shader like this youtube video

as you can see minions projected light on house to burning it out.

I like to know how to make a similar effect.

# Answer
you can make this effect by dissolve in world space.

(I explained the world space in this post)

let's Implement this shader:

# Masking Objects by World Space

you can make array of positions and sizes in shader and use world space to fade them.

> we also have to signal to the shader that these variables will be modified from outside, hence the uniform qualifier. As it happens in C, there is an extra variable which indicates how many points are actually used.
>
> https://www.alanzucconi.com/2016/01/27/arrays-shaders-heatmaps-in-unity3d/

```
Shader "Smkgames/worldSpaceFade" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _NormalMap("Normal Map",2D) = "bump" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader {
    Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
         Pass {
            ZWrite On
            ColorMask 0
        }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows alpha:fade

        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _NormalMap;

        struct Input {
            float2 uv_MainTex;
            float3 worldPos: TEXCOORD2; // using world position
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        void vert (inout appdata_full v, out Input o){
            UNITY_INITIALIZE_OUTPUT(Input,o);
            o.worldPos = mul(unity_ObjectToWorld, v.vertex); // calculating world position in vertex shader
        }

        uniform float4 _arrayPosition [5]; // declare array position
        uniform float _arraySize [5]; // declare array size

        UNITY_INSTANCING_BUFFER_START(Props)
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;

         float4 color = float4(0,0,0,0); // temp color for using in alpha

         for(int i = 0; i < 5;i++){
             float dist = distance(IN.worldPos,
               float4(_arrayPosition[i].xyz, 1.0)); // calculate distance in world position

            if (dist < _arraySize[i]) // if distance is smaller than size of each object result is white in mask
            {
               color += float4(1.0, 1.0, 1.0, 1.0); // sum result of dynamic masks
            }
            }

            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha =  saturate(1-color); // saturate to make sure is between 0 and 1 that is equivalent of clamp(value,0,1)
            o.Normal = UnpackNormal(tex2D(_NormalMap,IN.uv_MainTex));
        }
        ENDCG
    }
    FallBack "Diffuse"
    }

```

then you should initialize the positions and sizes of objects in shader:

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

[ExecuteInEditMode]
public class WorldMask : MonoBehaviour
{
    public Transform[] arrayTransform;
    public Vector4[] arrayPosition;
    public float[] arraySize;
    public Material material;

    private void Awake()
    {
        arrayPosition = new Vector4[arrayTransform.Length];
        arraySize = new float[arrayTransform.Length];
    }

    private void Update()
    {
        for (int i = 0; i < arrayTransform.Length; i++)
        {
            arrayPosition[i]= arrayTransform[i].position;
            arraySize[i]= arrayTransform[i].localScale.x;

        }

        material.SetVectorArray("_arrayPosition",arrayPosition);
        material.SetFloatArray("_arraySize",arraySize);
    }
}

```

# Making World Position Dissolve Shader

I found a good tutorial that explained how to Dissolving Objects in the world:

Dissolving the world Part 1

Dissolving the world Part 2

Dissolving the world Chris Chen

**Final Result:**

```
Shader "Smkgames/WorldDissolve" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _NormalMap("Normal Map",2D) = "bump" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0

        _DissolvePoint("Dissolve point", Vector) = (0,0,0,0)
        _DissolveAmount("Disolve amount", Range(0,1)) = 1
        _MaxDistance("Max distance", float) = 1
        _Intensity("Intensity", Range(1,5)) = 1
        _NoiseFreq("Noise frequency", float) = 1
        _Border("Border size", float) = 0.1
        [HDR]_BorderColor("Border color", Color) = (1,0,0,1)
        [HDR]_BorderEmission("Border emission", Color) = (1,0,0,1)
    }
    SubShader {
        Tags {
            "RenderType"="TransparentCutout"
            "Queue"="AlphaTest"
        }
        Cull Off

        CGPROGRAM
        #pragma target 3.0
        #pragma surface surf Standard fullforwardshadows addshadow
        #include "UnityCG.cginc"
        #include "noiseSimplex.cginc"

        sampler2D _MainTex;
        sampler2D _NormalMap;
        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        fixed _NoiseFreq;
        fixed _Border;
        fixed4 _BorderColor;
        fixed4 _BorderEmission;

        uniform fixed _DissolveAmount;
        uniform fixed _MaxDistance;
        uniform fixed _Intensity;
        uniform float3 _DissolvePoint;

        struct Input {
            float2 uv_MainTex;
            float3 worldPos;
        };

        uniform float4 _arrayPosition [5];
        uniform float _arraySize [5];

        void surf (Input IN, inout SurfaceOutputStandard o) {

            // texture and color
            fixed4 color = tex2D(_MainTex, IN.uv_MainTex) * _Color;

         fixed isBorder = 0;
         for(int i = 0; i < 5;i++){

            // calculate distance between current position and dissolve point
            float dist = distance(IN.worldPos, _arrayPosition[i].xyz);

            // get gradient by distance
            float gradient = clamp(dist / _arraySize[i], 0, 2);

            // calculate final value
            float finalValue = (_DissolveAmount - gradient) * _Intensity;

            // snoise is expensive
            // do not call it if we are sure the final value is large enough
            if (finalValue > _Border + 1) {
                discard;
            }

            // get noise by world position, snoise return -1~1
            // make the noise 0~1
            float ns = snoise(IN.worldPos * _NoiseFreq) / 2 + 0.5f;

            if (ns + _Border < finalValue) {
                discard;
            }

            // after clip, ns should be finalValue ~ (finalValue - _Border)
            // if (finalValue >= ns)
            //      isBorder
            // else
            //      !isBorder
             isBorder += step(ns, finalValue);

            o.Albedo = lerp(color, _BorderColor, isBorder);
            o.Emission = lerp(fixed4(0, 0, 0, 0), _BorderEmission, isBorder);
            }

            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Normal = UnpackNormal(tex2D(_NormalMap,IN.uv_MainTex));
        }

        ENDCG
    }
    FallBack "Diffuse"
}

```

# Github

source is Available in my github
> 3 votes

---
Tags: unity, shaders, special-effects
---


title: Update vs events

text:
# Question
Title: Update vs events
i would like your opinion on two different coding styles to solve the same problem, namely, react to user input actions.

To do this, two solutions.

* Subscribe to events (usually "when").
* Real time verification (usually "while").

**Event pros:**

* Optimized
* Easy to read.

**Event cons:**

* Disperse logic to many places (other events, update loop, etc ...)
* Not so flexible than update way.

**Update pros:**

* Concentrate all logic in one place.
* Very useful to group logic like you want (not only by input state).
* Sequential processing.

**Update cons:**

* Hard to optimize when code complexity increase, bad performance.

*Sample following the event-driven way:*

```
void CollisionPolygon2DTool::HandleSceneUpdate(StringHash, VariantMap& eventData)
{
    if (!IsEnabled() || !checkBox_->IsChecked())
    {
        return;
    }

    if (mode_ == Mode::INSERTION)
    {
        ShowShadowVertex();
        shadowVertexNode_->SetWorldPosition2D(sceneView_->GetMouseWorldPosition());
    }
    else
    {
        HideShadowVertex();
    }
}

void CollisionPolygon2DTool::HandleShortcutsKeyDown()
{
    if (!IsEnabled() || !checkBox_->IsChecked())
    {
        return;
    }

    if (input->GetKeyDown(KEY_I))
    {
        mode_ = Mode::INSERTION;
    }
    else if (input->GetKeyDown(KEY_S))
    {
        mode_ = Mode::SELECTION;
    }
    else if (input->GetKeyDown(KEY_DELETE) && mode_ == Mode::SELECTION && selectedVertexIndex_ != -1)
    {
        DeleteVertex(selectedVertexIndex_);
    }
}

void CollisionPolygon2DTool::HandleSceneViewClick(StringHash, VariantMap&)
{
    if (!IsEnabled() || !checkBox_->IsChecked())
    {
        return;
    }

    if (mode_ == Mode::SELECTION && button == MOUSEB_LEFT)
    {
        selectedVertexIndex_ = GetVertexIndexAt(sceneView_->GetMouseWorldPosition());
    }

    if (mode_ == Mode::INSERTION && button == MOUSEB_LEFT)
    {
        auto mouseWorldPosition = eventData["Position"].GetVector2();
        AddVertex(mouseWorldPosition.x_, mouseWorldPosition.y_);
    }
}

void CollisionPolygon2DTool::HandleSceneViewDragBegin(StringHash, VariantMap&)
{
    if (!IsEnabled() || !checkBox_->IsChecked())
    {
        return;
    }

    if (mode_ == Mode::SELECTION && selectedVertexIndex != -1)
    {
        beginSelectedVertexPosition_ = vertices[selectedVertexIndex];
    }
}

void CollisionPolygon2DTool::HandleSceneViewDragMove(StringHash, VariantMap& eventData)
{
    if (!IsEnabled() || !checkBox_->IsChecked())
    {
        return;
    }

    if (mode_ == Mode::SELECTION && selectedVertexIndex != -1)
    {
        auto delta = eventData["Delta"].GetVector2();
        MoveVertex(selectedVertexIndex, beginSelectedVertexPosition_ + delta);
    }
}

```

*Sample following the update-driven way:*

```
void CollisionPolygon2DTool::Update()
{
    selectedCollisionPolygon2D_ = GetSelectedCollisionPolygon2DComponent();

    if (selectedCollisionPolygon2D_ == nullptr)
    {
        SetEnabled(false);
    }
    else
    {
        SetEnabled(true);
    }

    if (!IsEnabled() || !checkBox_->IsChecked())
    {
        return;
    }

    auto input = GetSubsystem<Input>();

    if (input->GetKeyDown(KEY_S))
    {
        mode_ = Mode::SELECTION;
    }
    else if (input->GetKeyDown(KEY_I))
    {
        mode_ = Mode::INSERTION;
    }

    if (mode_ == Mode::SELECTION)
    {
        auto input = GetSubsystem<Input>();

        if (sceneView_->GetMouseButtonPress(MOUSEB_LEFT))
        {
            auto vertexIndex = GetVertexIndexAt(sceneView_->GetMouseWorldPosition());

            if (vertexIndex != -1)
            {
                SelectVertex(vertexIndex);
            }
            else
            {
                UnselectVertex();
            }
        }

        if (input->GetKeyPress(KEY_DELETE) && selectedVertexIndex_ != -1)
        {
            DeleteVertex(selectedVertexIndex_);
        }

        if (!isMoving_ && sceneView_->GetMouseButtonDown(MOUSEB_LEFT) && selectedVertexIndex_ != -1)
        {
            beginSelectedVertexPosition_ = vertices_[selectedVertexIndex_];
            isMoving_ = true;
        }

        if (isMoving_ && sceneView_->GetMouseButtonDown(MOUSEB_LEFT) && selectedVertexIndex_ != -1)
        {
            auto newPos = vertices_[selectedVertexIndex_] + sceneView_->GetMouseMove();
            MoveVertex(selectedVertexIndex_, newPos.x_, newPos.y_);
        }

        if (isMoving_ && !sceneView_->GetMouseButtonDown(MOUSEB_LEFT))
        {
            isMoving_ = false;
        }
    }

    if (mode_ == Mode::INSERTION)
    {
        auto mouseWorldPosition = sceneView_->GetMouseWorldPosition();

        ShowShadowVertex();
        shadowVertexNode_->SetWorldPosition2D(mouseWorldPosition);

        if (sceneView_->GetMouseButtonPress(MOUSEB_LEFT))
        {
            AddVertex(mouseWorldPosition.x_, mouseWorldPosition.y_);
        }
    }
    else
    {
        HideShadowVertex();
    }
}

```

Seriously, maybe i think too much but i do not know which one to choose.

# Answer
Please keep in mind that asking for opinions on Gamdev.se is considered off-topic here. With this answer, I will try to help you make your mind.

---

This kind of decision generally integrates within the broader style of your architecture. You'll want to use repeating patterns for similar contexts. If you define an event architecture for a specific context, you'll most likely want to reuse it for *other* contexts of your software, where it would apply. If you make an event system just for *one* part of your game, maybe you're wasting your time and energy.

Now I'd like to add something about the concept of 'Optimized'. Did you profile your example in an actual context? Was the 'optimized' approach actually faster? If so, by what percentage?

In a game, the time and resource taken by management of the input is generally *nothing* compared to other aspects like physics simulation and graphics rendering. This would make the arguments "more optimized" or "less optimized" weight very little in the balance.

This leaves you with these questions:

* Did I hate myself in the past because I used approach X?
* Am I likely to thank myself in the future because I used approach X?
* Since code will be read more often than modified, which approach seems the clearest and understandable (because I'll have to work with again in 8 months and I'll have to understand what I did *fast*)?

I generally suggest to go with the cleanest solution first, then optimize what's actually a bottleneck (found by profiling).
> 1 votes

---
Tags: c++, algorithm, patterns
---


# Question
Title: Model gets distorted when rotating the camera
I'm currently developing my own 3d graphics engine and I'm having a hard time figuring out why my 3D models gets distorted when rotating the camera around.

This is my projection matrix. I'm following the OpenGL's Model.

```
def get_projection_mat(aspect_ratio, camera):
    fov = camera.fov
    z_near = camera.z_near
    z_far = camera.z_far
    top = math.tan(fov * 0.5) * z_near
    bottom = -top
    right = top * aspect_ratio
    left = -right
    projection_mat = np.identity(4, dtype=float)
    projection_mat[0, 0] = 2 * z_near / (right - left)
    projection_mat[0, 2] = (right + left) / (right - left)
    projection_mat[1, 1] = 2 * z_near / (top - bottom)
    projection_mat[1, 2] = (top + bottom) / (top - bottom)
    projection_mat[2, 2] = -(z_far + z_near) / (z_far - z_near)
    projection_mat[2, 3] = -2 * z_far * z_near / (z_far - z_near)
    projection_mat[3, 2] = -1
    projection_mat[3, 3] = 0

    return projection_mat

```

This is my view matrix:

```
def camera_matrix(self):
    camera_matrix = np.identity(4, dtype=float)
    camera_matrix[:3, 0] = self.left[:]
    camera_matrix[:3, 1] = self.up[:]
    camera_matrix[:3, 2] = self.forward[:]
    camera_matrix[:3, 3] = self.pos[:]

    return camera_matrix

```

This is how I get the ViewProjection matrix:

```
    projection_mat = get_projection_mat(self.aspect_ratio, self.camera)
    view_mat = self.camera.camera_matrix()
    view_mat = np.linalg.inv(view_mat)
    self.view_projection_mat = np.dot(projection_mat, view_mat)

```

And, finally, this is the ViewProjectionModel matrix:

```
    view_projection_model_mat = np.dot(model.transform_mat.T, self.view_projection_mat)

```

This is the method that I use to rotate the camera:

```
def rotate(self, yaw, pitch, degress=True):
    rotation_mat_y = helper.rotate_matrix_y(yaw, degrees)
    rotation_mat_x = helper.rotate_matrix_x(pitch, degrees)
    rotation_mat = np.dot(rotation_mat_y, rotation_mat_x)
    self.forward = np.dot(np.insert(self.forward, 3, 1), rotation_mat)
    self.forward = helper.normalized((self.forward / self.forward[3])[:3])
    self.up = np.dot(np.insert(self.up, 3, 1), rotation_mat)
    self.up = helper.normalized((self.up / self.up[3])[:3])
    self.left = np.dot(np.insert(self.left, 3, 1), rotation_mat)
    self.left = helper.normalized((self.left / self.left[3])[:3])

```

A video demo, showing the problem

To summarize, the order of multiplication is ProjectionMat X ViewMat x ModelMat x ModelFaces. If it isn't clear by now, I'm using Python for this project. Any help would be greatly appreciated.

With best regards, João Pedro

**EDIT**: Like this?

```
    directions, r = np.linalg.qr(np.array([self.forward, self.up, self.left]))
    self.forward = directions[0]
    self.up = directions[1]
    self.left = directions[2]

```

# Answer
> 1 votes
I see two potential errors here:

1. You're transforming directions like they're points.

`np.insert(self.forward, 3, 1)` says "Add a homogenouse coordinate of 1 to this direction vector so that matrix translation affects it" - but you absolutely *do not* want translation to affect your directions! Turning 30 degrees is turning 30 degrees, no matter whether I do it at the origin or 50 km away from the origin.

Your translation is already tracked by the `pos` variable, so don't let it leak into your directions this way. Instead, your 4th component / "w" of a direction vector should be zero, to ensure you factor in only the rotation of the vector.

This also makes the division by w unnecessary, though you were already obliterating its result by normalizing it anyway.
2. You're allowing rounding errors to accumulate

`forward`, `up`, and `left` are used as inputs to compute their own successors, meaning that any error in the input gets replicated in the output, along with any new rounding errors from the latest multiplication / normalization. So each small incremental error adds up and gradually snowballs up to a perceptible scale.

You're re-normalizing the vectors, so you're correcting any errors in their lengths, but not their directions. So as the errors build up, the three basis vectors drift from being fully orthogonal, causing the skewing artifacts you're seeing.

To fix this, you'll want to orthonormalise your basis to correct both magnitude and directional errors and stop them from building up. One way to do this is using the Gram-Schmidt process. You can compute the `left` vector from the cross product of `up` and `forward` to get a mutually-perpendicular unit vector by construction with a bit less work.

---
Tags: opengl, 3d, graphics, python, 3d-meshes
---


# Question
Title: How to make a gameObject Transform Position move in a circle while making its Transform Position move forward?
```
 // I'm using Unity2D =)

 // I'm trying to move the Transform.Position in a circle pattern and also move it forward.
 // I'm not trying to move transform.rotation at all just the transform.position.

 // This one moves in a circle pattern but unfortunately shakes violently which I don't want.
 // Also it does not move forward which I do want it to do.

 // Most importantly, I don't want it to immediately move on Start. I want it to move after something is true. When I put it on FixedUpdate it moved too quickly.

 // Thank you for any help! =)

     void Start()
     {
         StartCoroutine(MoveCircularly());
         StartCoroutine(MoveForward());
     }

     IEnumerator MoveForward()
     {
         while ( condition )
         {
             g.transform.Translate(Vector2.right);
             yield return new WaitForEndOfFrame();
         }
     }

     IEnumerator MoveCircularly()
     {
         while ( condition )
         {
             //move in a circle
             yield return new WaitForEndOfFrame();
         }
     }

```

# Answer
It sounds like you're describing a curve called a helix:

(Animation via Gyre & Gimbal)

You can do this in a single function:

```
IEnumerator MoveInHelix(Matrix4x4 space, float radius, float frequency, float linearSpeed) {
    space = space * Matrix4x4.Scale(new Vector3(radius, radius, linearSpeed));

    float progress = 0;

    while(true) {
        progress += Time.deltaTime;
        float angle = progress * frequency * Mathf.PI * 2f;
        transform.position = space * new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), progress);
    }
}

```
> 1 votes

# Answer
what you are looking for is polar coordinates in 2d and variable z. maybe its called cylinder coordinates.

in polar or circular coordinates, position is defined by radius and angle. as unity and other simulation systems use cartesian coordinates, then you have to do a change coordinate to show it in unity.

```
 private void FixedUpdate()
    {
        foreach (var item in PolarElements)
        {

            float x = item.radius * Mathf.Cos(item.myAngle);
            float y = item.radius * Mathf.Sin(item.myAngle);

            item.position = new Vector3(transform.position.x+  x,transform.position.y+y,transform.position.z);
            item.myAngle += item.speed;
        }
    }

```

you can replace `**transform.position.z**` with any z value you want
> 1 votes

# Answer
I solved it by having one Game Object move in a circle and add a Game Object into the Game Object moving in a circle and have it move forward. That's the best I can do since IEnumerator wasn't working both functions at the same time for me.
> 0 votes

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


# Question
Title: Rotating a spaceship around 2 axes rotates it around 3
I am developing a 3D space shooter and I've found that when trying to rotate the ship using X and Y axes, it also rotates on the Z axis.

The answer here helped me a lot, but now when I try to rotate on 3 axes I have the same problem on the 2 axes sharing local space.

The code I have right now is this:

```
    float rotZ = 1;
    float rotLeftRight = Input.GetAxis("Mouse X") * mouseSensitivity;
    float rotUpDown = Input.GetAxis("Mouse Y") * mouseSensitivity;
    transform.Rotate(0, rotLeftRight, 0, Space.World);
    transform.Rotate(-rotUpDown, 0, 0, Space.Self);
    transform.Rotate(0, 0, -rotZ, Space.Self);

```

Does anyone know how to make all 3 rotations independent from each other?

# Answer
> 1 votes
As I mention in the linked answer, for full 6 DoF controls like spaceflight or swimming, it often works well to think of a corrective twist that you gradually apply to reassert your desired horizontal plane.

Here's one way we can do this:

First, we'll track a normal for the plane we want the ship to orient to when the player is not deliberately rolling.

```
Vector3 _planeNormal;

void Start() {
    _planeNormal = transform.up;
    // ...
}

```

Next, we'll think of our yaw and pitch controls as rotating only our forward vector. We'll play with the up vector next so we can control the twist:

```
float rotLeftRight = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float rotUpDown = -Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

Quaternion yawPitch = transform.rotation * Quaternion.Euler(rotUpDown, rotLeftRight, 0f);
Vector3 newForward = yawPitch * Vector3.forward;

```

Next we're going to look at how we're currently oriented toward our reference plane.

```
float alignment = Vector3.Dot(transform.up, _planeNormal);
Vector3 referenceUp = Mathf.Sign(alignment) * _planeNormal;

```

This gives us the perpendicular to our reference plane that's closest to our current vertical direction (to avoid a nasty flip/lurch if we fly in a loop-de-loop - we'd rather tolerate flying upside-down than doing a sudden snap upright)

If we snap straight to this up vector, we can still get a nasty lurch when we're flying nearly perpendicular to our plane - its projection on our view can swing from pointing up to sideways to down and back from just small wiggles in our heading. So instead, we'll blend toward it gradually, with a strength that falls off to zero when we're perpendicular to the reference plane:

```
Vector3 targetUp = Vector3.Lerp(transform.up, referenceUp, alignment * alignment);

```

(Note that you'll want to do this at a consistent framerate, or adjust the above for deltaTime if your framerate is variable)

Now we're ready to set our new rotation based on our yawed/pitched forward vector and our calculated up vector:

```
Quaternion newOrientation = Quaternion.LookRotation(newForward, targetUp);

```

Before you apply this, you can add in your roll:

```
float roll = Input.GetAxis("Roll");
if(Mathf.Approximately(roll, 0) == false) {
    newOrientation = newOrientation * Quaternion.Euler(0f, 0f, roll * rollSpeed * Time.deltaTime);

    // Save our new reference plane, according to the player's input.
    _planeNormal = newOrientation * Vector3.up;
}

transform.rotation = newOrientation;

```

At this moment, the player has told you "I want my horizon to be rotated like this," so we save that information into our reference plane normal. Wherever possible, we'll try to level-out the ship's orientation to align with this newly-twisted plane, until the player manually twists it back.

(Of course, you can also add a "twist decay" over time, if you want the roll to unroll itself if the player doesn't touch the roll controls for a while).

All together, this lets the player's local yaw/pitch/roll win in the short term, so the player immediately sees consistent response to their controls, and it's always correct relative to their current orientation - even if it introduces an unwanted twist globally. Then as we can, we gradually hint the ship back toward the last horizontal plane the player told us was good for them by deliberately rolling toward it.

---
Tags: unity, rotation, geometry, transformation
---


title: Calculate size of hexagonal map libgdx

text:
# Question
Title: Calculate size of hexagonal map libgdx
I have a staggered hexagonal map created with "tiled" map editor and I want to calculate the height of this map in pixels, the example map below should be `MAP_WIDTH_IN_PX = 1056` and `MAP_HEIGHT_IN_PX = 303;`

```
MAP_WIDTH = map.getProperties().get("width",Integer.class); //16 tiles
MAP_HEIGHT = map.getProperties().get("height",Integer.class); //5 tiles
TILE_WIDTH = map.getProperties().get("tilewidth",Integer.class); //64px
TILE_HEIGHT = map.getProperties().get("tileheight",Integer.class); //84px
TILE_SIDE_LENGTH = 27; //this value is set in the map editor

MAP_HEIGHT_IN_PX = ?;
MAP_WIDTH_IN_PX = MAP_WIDTH * TILE_WIDTH + TILE_WIDTH * 0.5f;

```

# Answer
1. The height of each individual hexagon is 84px *including shadow* but the shadow only matters for the last row. So we need to know the size without shadows. I believe the height of the hexagon without shadow is 73px.
2. For all rows except the last row, there is overlap in heights by 1/4 of the hexagon height. The second row starts at 3/4 of the hexagon height. (diagram from my page)

3. This means for all rows except the last row, we want to count only 3/4 of the hexagon height without shadows: 3/4 * 73px * 4 rows = 219px. Then we need to add the last row, which will be full height including the shadow: 84px. The sum of these is 219px + 84px = 303px.
> 2 votes

# Answer
Just check even and odd number of tiles in column, than half of them take tile height space and half tile width space. In case of odd number take care of last one.

```
if (MAP_HEIGHT%2==0)
  MAP_HEIGHT_IN_PX = MAP_HEIGHT/2*TILE_SIDE_LENGTH +MAP_HEIGHT/2*TILE_HEIGHT;
else
  MAP_HEIGHT_IN_PX = (MAP_HEIGHT-1)/2*TILE_SIDE_LENGTH +(MAP_HEIGHT+1)/2*TILE_HEIGHT;

```

Also we need to subtract part of tile shadow for long (for example 1px).

```
if (MAP_HEIGHT%2==0)
  MAP_HEIGHT_IN_PX = MAP_HEIGHT/2*TILE_SIDE_LENGTH +MAP_HEIGHT/2*(TILE_HEIGHT-1);
else
  MAP_HEIGHT_IN_PX = (MAP_HEIGHT-1)/2*TILE_SIDE_LENGTH +(MAP_HEIGHT+1)/2*(TILE_HEIGHT-1);

```
> 0 votes

---
Tags: java, libgdx, hexagonal-grid
---


# Question
Title: Styles of games that work at low-resolution
I'm taking a class on compilers, and the goal is to write a compiler for Meggy Jr devices (Arduino). The goal is just to make a simple compilers with loops and variables and stuff.

Obviously, that's lame, so the "real goal" is to make an impressive game on the device. The problem is that it only has 64 pixels to work with (technically 72, but the top 8 are single-color and not part of the main display, so they're really only useful for displaying things like money).

My problem is thinking of something to do on a device that small. It doesn't really matter if it's original, but it can't be something that's already available. My first idea was "snake", but that comes with the SDK. Same with a side-scrolling shooter.

Remaining ideas include a tower defense game (hard to write, hard to control), an RPG (same), tetris (lame)..

The problem is that all of the games I like require a high-resolution screen because they have a lot of text. Even a really simple game like nethack would be hard because each creature would be a single color.

tl;dr What styles of games require a. No text; and b. Few enough objects that representing them each with a single color is acceptable?

EDIT: To clarify, the display is 8x8 for a total of 64 pixels, not 64x64.

# Answer
> 9 votes
Low-resolution constraints was the premise of the Gamma 256 \[archive\] design challenge. Their mandatory constraint was quite a bit higher than 64x64, but many of the submissions used far less than the maximum.

Darius Kazemi has done (in my opinion), one of the best games on the Meggy Jr. device.\[archive\] You might look at his work for inspiration.

# Answer
> 7 votes
Strikes me that a basic Rogue-like top-down corridor shooter could be possible. At 8x8 you obviously wouldn't have space to show a full room, but you would be able to show a small section of the map. A white pixel could be you (fade to black as you lose health), gold for treasure, red for enemies, green for healing, etc. 1-pixel wide walls, 2, 3 or 4 pixel wide corridors, and it might just work.

# Answer
> 6 votes
You could write something akin to a tomagatchi or other virtual pet. The original ones were done on very low resolution screens.

Pong is another game that comes to mind for a low resolution display. While it may seem basic, it covers most of the important bits in many games: collisions, physics (albeit simple), game-loop, etc. On such a limited platform, you may be forced to "roll your own" for many of those tasks which may take up more time that you anticipated.

# Answer
> 5 votes
That makes me think about board games, like Go or Checkers, and puzzley things involving pentaminos or other interesting configurations of uniform parts. I'd stay away from heavily spatial games as well as the text-heavy. Your game pretty much has to be abstract. With 8x8 rez, you might be able to do something as spatial as Sakoban, but I have my doubts.

To be clear here: none of the games named above will work very well. You'll need to create your own game and rules, but I'd suggest keeping the above games in mind when you do so. Simple world states that display easily, but more complex mechanics behind-the-scenes. Your game won't be able to have much metaphor, so I'd stay abstract.

# Answer
> 4 votes
You could write a little ray-casting 3D engine, like this fellow is working on. Wouldn't require too much color; although your screen is smaller than the one he's got, it might be workable.

# Answer
> 4 votes
Game of Life can be a good example for such low-res devices. I have seen the video where this game was made on a LED cube.

# Answer
> 3 votes
A lot of puzzle designs would work fine in that format. Slider puzzles leap instantly to mind.

# Answer
> 3 votes
How about Chess? An 8x8 grid with different colours should be fine for some chess.

# Answer
> 3 votes
What about a reflex game? Kind of like 2player reactor for Android phones.

You could also look to the Wario Ware games for inspiration.

# Answer
> 3 votes
Wolfenstein 1-D

While it uses 1px height, its width is way longer than 8px, so you'd probably have to come up with something.

# Answer
> 3 votes
Another idea could be Mastermind.

# Answer
> 3 votes
I have a playfield with similar restrictions. Mine is 10x20. However, it is still possible to implement many games, although you have to be a bit creative and change the rules of some games. A cool thing is if you have sound.

This is my hardware:

Here are my "screenshots":

# Tetris

# Snake

Snake (green) eats food (blue) with its head (red). Be aware of obstacles (grey)

# Guitar hero

Notes falling from top. Press the button (bright) and hold (dark)

# Drums

Drums animate and make sound when a button is pressed.

# Melody memory

Recall a sequence of tones plus light

# Game of life

Editing first, then simulating

# Boulder dash

Player (yellow) must collect diamonds (blue) before he exits (red). Be aware of falling rocks (grey)

# Space invaders

The only one monster loses single pixels when shot.

# Skyfall

Similar to guitar hero. Player (yellow) can collect items (green), must collect items (blue) and must not collect dangerous items (red)

# Driver

Player (red) drives on a road and must overtake cars on his side while watching cars on the opposite side.

# Pacman

Player (yellow) collects coins (brown) and food (violet) while running through a maze with walls (grey). Be aware of ghosts (blue) unless they are eadible (green).

# Sokoban

Player (white) needs to move pieces (bright) onto their destination (dark). Use Tetris bricks here, since I already had them.

# Flappy bird

I hope that's known.

# Pong

# Others

While not a game, it may still be fun. On the 10x20 display it's possible to display weather or use it as a torch.

# Answer
> 0 votes
Many of the classics would render well with such limited screen space, such as: Tetris, Pacman and Asteroids. You could also try board games such as Checkers, Chess and Backgammon. Also, Helicopter is one of my favorite, simple games.

# Answer
> 0 votes
You could create breakout and make the camera follow the ball for larger levels (only vertically) and maybe the pad horizontally making for a larger play area.

The idea of moving the camera is probably necessary for anything on such a small screen.

---
Tags: game-design
---


# Question
Title: Save object transform values in play mode for editor mode?
Many times I need to adjust the position or rotation angle of object in play mode but when I got back to editor mode I found all my work is gone! I looking on InterNet for a solution and I found this scrip. Where using tags to identify the object that I need to adjust it In "play mode". What ever I do with transform values of this object is saved when exit from "playMode".

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

public class saveobjectPositions : MonoBehaviour
{

     // Made by Filmstorm - Author: Kieren Hovasapian
     // Object Minder - Keeps In-Game Object Changes in Sync with Editor

    [Header("State of Play")]

    public bool InEditor;
    public bool InGame;

    [Header("Controls")]

    public bool setValuesToLastSave;
    public string tagToSave;

    public GameObject[] FoundObjectsInGame;
    public List<GameObject> InGameObjects;

    string savePath;

    private void Awake()
    {
        InGameObjects = new List<GameObject>();

        //Setup save path
        savePath = Path.Combine(Application.persistentDataPath, "saveFile");
    }

    //Save our data from the scenes objects
    void Save()
    {
        using (var writer = new BinaryWriter(File.Open(savePath, FileMode.Create)))
        {
            for (int i = 0; i < InGameObjects.Count; i++)
            {
                Transform t = InGameObjects[i].transform;
                writer.Write(t.localPosition.x);
                writer.Write(t.localPosition.y);
                writer.Write(t.localPosition.z);
                writer.Write(t.localRotation.w);
                writer.Write(t.localRotation.x);
                writer.Write(t.localRotation.y);
                writer.Write(t.localRotation.z);
                writer.Write(t.localScale.x);
                writer.Write(t.localScale.y);
                writer.Write(t.localScale.z);

            }
        }

        //Debug.Log("I tried to save!");
    }

    //Load specific data we saved previously
    void Load()
    {

        using (var reader = new BinaryReader(File.Open(savePath, FileMode.Open)))
        {
            for (int i = 0; i < InGameObjects.Count; i++)
            {
                Vector3 p;
                Quaternion r;
                Vector3 s;
                p.x = reader.ReadSingle();
                p.y = reader.ReadSingle();
                p.z = reader.ReadSingle();
                r.w = reader.ReadSingle();
                r.x = reader.ReadSingle();
                r.y = reader.ReadSingle();
                r.z = reader.ReadSingle();
                s.x = reader.ReadSingle();
                s.y = reader.ReadSingle();
                s.z = reader.ReadSingle();

                //set position from load data
                InGameObjects[i].transform.localPosition = p;
                InGameObjects[i].transform.localRotation = r;
                InGameObjects[i].transform.localScale = s;

                if (i == InGameObjects.Count - 1)
                {
                    //Last operation now we break
                    setValuesToLastSave = false;
                }

            }
        }
    }
    // Use this for initialization
    void Start()
    {

        //Check if the game is in play or in editor mode
        if (Application.isPlaying)
        {
            //Debug.Log("Running in play mode");
            InEditor = false;
            InGame = true;
            setValuesToLastSave = true;
        }
        else
        {
            //Debug.Log("In editor");
            InEditor = true;
            InGame = false;
            setValuesToLastSave = true;
        }

    }

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

        //If in game -- find all objects and store their transforms
        if (tagToSave != null)
        {
            FoundObjectsInGame = GameObject.FindGameObjectsWithTag(tagToSave);
            foreach (GameObject go in FoundObjectsInGame)
            {
                if (go.activeInHierarchy)
                {
                    if (!InGameObjects.Contains(go))
                        //Save Gameobject to List?
                        InGameObjects.Add(go);

                }
            }

            //If in editor run the updated loader
            if (InEditor)
            {
                if (setValuesToLastSave == true)
                {
                    Load();

                }
            }

        }
    }

    //When we stop playing save object locations
    private void OnApplicationQuit()
    {
        Save();
    }

}

```

Here is the issue, When I get back to "Editor mode" I can't get these values. To get them, I have to run again "play mode" and click on "InEditor" bool to get them. Is there a way to change this and get the transform values that saved in play mode into Editor mode ?

# Answer
> 2 votes
The only way to save the values I know of is to go to the transform component, press the gear icon and copy the component, then after leaving play mode you can paste the values back using "paste" button in the same menu

# Answer
> 1 votes
You can use console window to record values in playMode and then copy it. This script will help you to get last details of XYZ axises. Just try to tag these objects that you want to record there values.

```
    public GameObject[] Objects_List;

// Update is called once per frame
void Update()
{
    Objects_List = GameObject.FindGameObjectsWithTag("changer");

    foreach (GameObject Objects in Objects_List)
    {
        print(Objects.transform.parent.name + " , " + Objects.name + "( " + Objects.transform.localPosition.x + " )*( " + Objects.transform.localPosition.y + " )*( " + Objects.transform.localPosition.z + " )");
    }
}

```

Here you will get first parent object name. then the object that you tagged with his values. You can delete the parent part if you want. It's simple and helpful.

# Answer
> 1 votes
I have a heavy solution, but it is working very good. For serialization use mem.cs. This is a scriptable object and a new one must be created from the asset menu in the projects area. It is used like a memory card, name it and insert it into any script to store specific data. \**You must call mem?.Load() \** from any script you are using it in to load up the data, it is not done by default.

---

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[CreateAssetMenu(menuName ="mem")]
public class mem : ScriptableObject {

    public string recordID;
    Dictionary<string, object> items = new Dictionary<string, object>();
    Dictionary<string, object> loadedItems = new Dictionary<string, object>();
    bool loadCalled;
    //must call Load() before use
    public void Load()
    {
        try
        {
            byte[] g = File.ReadAllBytes(Application.persistentDataPath + "/" + recordID);
           items = (Dictionary<string,object>) ByteArrayToObject(g);
            Debug.Log("MEMORY LOADED: "+items.Count);
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }

        loadCalled = true;
    }

    public object GetFromMem(string nm)
    {
        if(!loadCalled)
        {
            Debug.LogWarning("Load Not Called " + nm);
        }
        object o;
        if (items.TryGetValue(nm, out o))
        {
              Debug.Log(nm+ " got " + o);
              if (!loadedItems.ContainsKey(nm))
              loadedItems.Add(nm,o);
            return o;
        }
        else
            return default(object);

    }

    public bool AddToMem(object o,string nm)
    {
        try
        {
            if (!items.ContainsKey(nm))
                items.Add(nm, o);
            else
                items[nm] = o;
     //      Debug.Log("Add "+ nm+" vl:"+o);
            File.WriteAllBytes(Application.persistentDataPath + "/" + recordID, ObjectToByteArray(items));
            return true;
        }
        catch(Exception e) { Debug.Log(e.ToString()); }

        return false;

    }

    public void ClearUnused()
    {
        items.Clear();
        items=loadedItems;
     File.WriteAllBytes(Application.persistentDataPath + "/" + recordID, ObjectToByteArray(items));
    }

    // Convert a byte array to an Object
    public static object ByteArrayToObject(byte[] arrBytes)
    {
        using (var memStream = new MemoryStream())
        {
            var binForm = new BinaryFormatter();
            memStream.Write(arrBytes, 0, arrBytes.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            var obj = binForm.Deserialize(memStream);
            return obj;
        }
    }

    // Convert an object to a byte array
    public static byte[] ObjectToByteArray(object obj)
    {
        BinaryFormatter bf = new BinaryFormatter();
        using (var ms = new MemoryStream())
        {
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }
    }
}

```

This next one is Unitmon.cs, it uses mem.cs to store and retrieve all data, and monitors everything on load and start. Add it to a solo gameobject and toggle run to update manually. Run executes automatically on the editor loading and on play mode loading. The refreshed buffer allows the script to run a few times after play mode is exited. I have noticed it takes a few frames to begin updating edit mode scripts again.

```
//THE BIG WORKHORSE TO MANAGE ALL UNITS.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[InitializeOnLoad]
[ExecuteInEditMode]
public class Unitmon : MonoBehaviour
{
    internal static Unitmon M;
    public mem storage;
    public bool run;
    public List<Unit> collected;
    static int refreshed=5;

    void OnEnable()
    {
        Awake();
        Start();
    }

    void Awake()
    {
        if(M && M.gameObject && M !=this)
            Destroy(gameObject);

        M=this;
    }

    // Start is called before the first frame update
    void Start()
    {
        if(storage)
        {
            storage.Load();
        }
        run=true;
        Update();
    }

    // Update is called once per frame
    void Update()
    {
        if(Application.isPlaying)
            refreshed=5;//PLAY -> EDIT MODE 2 FRAME SKIP BUFFER
        else
            if(refreshed>0)
            {
                run=true;
                refreshed--;
            }

        if(run)
        {
            collected.Clear();

            collected.AddRange(FindObjectsOfType<Unit>());

            foreach(Unit u in collected)
            {
                Unit.UnitData ud  = (Unit.UnitData)storage.GetFromMem(u.uData.hash.ToString());
                if(ud!=null)
                    u.Setup(ud);
            }
            storage.ClearUnused();

            run=false;
        }
    }

    internal static void UpdateUnit(Unit u)
    {
        if(M.collected.Contains(u))
        {
            M.storage.AddToMem(u.uData,u.uData.hash.ToString());
        }
    }
}

```

This final component is the Unit.cs, managed by Unitmon. Attach the Unit to any gameobject to save its properties both during runtime and edit mode. The UnitData class is used and can be extended to include any type of data other than rotation and position. Enjoy!

```
//THE UNIT OF THE UNITY GAME ENGINE
using UnityEngine;

[ExecuteInEditMode]
public class Unit : MonoBehaviour
{
    [System.Serializable]
    public class UnitData
    {
        public int hash;
        public float[] pos=new float[3];
        public float[] rot=new float[3];
        public Vector3 position
        {
            get{return new Vector3(pos[0],pos[1],pos[2]);}
            set{pos[0]=value.x; pos[1]=value.y; pos[2]=value.z;}
        }
            public Vector3 rotation
        {
            get{return new Vector3(rot[0],rot[1],rot[2]);}
            set{rot[0]=value.x; rot[1]=value.y; rot[2]=value.z;}
        }
    }

    internal UnitData uData=new UnitData();
    bool somethingChanged;

    internal void Setup(UnitData ud)
    {
        if(ud !=null)
        {
            print(ud.hash+" setup");
            uData=ud;
            if(uData.position != Vector3.zero)//SET ONLY IF UPDATED FROM DEFAULT
                transform.position =uData.position;
            if(uData.rotation != Vector3.zero)//SET ONLY IF UPDATED FROM DEFAULT
                transform.rotation = Quaternion.Euler(uData.rotation);
        }

    }

    void Awake()
    {

    }

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        uData.hash=GetInstanceID();
        if(Application.isPlaying)
        {
            if(uData.position!= transform.position)
            {
                uData.position=transform.position;

                somethingChanged=true;
            }
            if(uData.rotation!= transform.rotation.eulerAngles)
            {
                uData.rotation=transform.rotation.eulerAngles;

                somethingChanged=true;
            }

        }
        if(somethingChanged)
        {
            Unitmon.UpdateUnit(this);
            somethingChanged=false;
        }

    }
}

```

---
Tags: unity, transformation
---


# Question
Title: Make an arrow to point at a direction from UI
I want to have a guiding arrow on the left side of UI. The arrow is child of the player's camera and it's rendered from another camera into render texture. The render texture is displayed on the screen. The arrow is rotated via `transform.LookAt(targetPosition)` The problem I'm having is that although it does point in the right direction, form player's point of view it looks like the arrow is pointing somewhere else.  I want that arrow to point from the point where it's placed on the UI. It should look something like this:  I tried to do this:
`Vector3 direction = targetPosition - _arrowRawImage.rectTransform.position;
_transform.LookAt(direction);` but it didn't work.

# Answer
You are using the `_arrowRawImage.rectTransform.position`, which is getting the *vector* of the raw image and not the arrow itself. Try working with the position of the arrow transform.

```
Vector3 direction = (targetPosition - _arrowTransform.position);
_arrowTransform.LookAt(direction);

```
> 0 votes

---
Tags: unity
---


# Question
Title: uniform matrix not being assigned to shader
im trying to apply a rotation matrix to my shader and when i try to set it and mult it in the shader my triangle doesn't render

my drawing code:

```
        var rotmat = Matrix4d.CreateRotationZ(45);

        shader.SetMatrix("transform", rotmat);

        shader.Use();
        mesh.Draw();

```

shader.SetMatrix:

```
    public void SetMatrix(string name,Matrix4d mat)
    {
        int index = GL.GetUniformLocation(Program, name);
        GL.UniformMatrix4(index, false,ref mat);
    }

```

vertex shader code:

```
#version 440 core
layout (location = 0) in vec3 position;
layout(location = 1) in vec4 color;
layout(location = 20)uniform mat4 transform;

out vec4 fragcolor;

void main(void)
{
  gl_Position = transform * vec4(position,1.0);
  fragcolor = color;
}

```

# Answer
This is happening because in OpenGL uniform values (set by glUniform calls) are part of program object state, i.e. specific to the currently bound program.

If you wish to change a uniform value you must bind the program first (via `glUseProgram`); in your code that means calling shader.Use *before* shader.SetMatrix.

Depending on your GL version you may alternately be able to call `glProgramUniformMatrix4fv` which doesn't require the program to be bound first.
> 2 votes

---
Tags: c#, opentk
---


title: How do game engines export projects?

text:
# Question
Title: How do game engines export projects?
I've been wanting to make a small game engine (relatively. basic features, predefined shaders) to learn that side of game development and I was wondering how game engines export projects to create executables.

I would imagine that they copy over all the necessary code and remove the editor from the code base. Or perhaps they are engineered in a way that completely abstracts the game code and the editor code?

If someone could explain the pipeline of how they export the game, I can do the rest of the research and experimentation myself.

# Answer
The details vary widely, especially with the style of language (compiles versus interpreted, for example) and runtimes (native versus, say, browser-based).

However the basic strokes are generally what you surmised. The editor executable for an engine generally knows how to recompile/repackage/et cetera the engine code to exclude the editor bits and alter the code flow so the user’s game is loaded at startup instead of the editor. Unreal, for example, can do this by running the platform specific compiler tools to rebuild the engine without WITH\_EDITOR defined, making all the editor code compile out.

You can also distribute your engine as a sort of stub executable that just loads modules from DLLs, have it load the editor DLL by default, but when exporting a game make a copy of the executable (and data files), exclude the editor DLL, and include a config file that tells the executable to load to game DLL instead.
> 0 votes

---
Tags: unity, unreal, export
---


# Question
Title: LibGDX HexagonalTiledMapRenderer wrong stagger index?
Im using Tiled map editor, Hexagonal(staggered) map, libgdx version `1.9.9`

If I set `staggeredIndex = even` in tiled map editor, libgdx seems to render `odd`

If I set it to `odd` in map editor, libgdx renders `even`

**Screen Shots:**

Here's the code:

```
@Override
public void create () {
    map = new TmxMapLoader().load("mapa.tmx");
    cam = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    mapRenderer = new HexagonalTiledMapRenderer(map);

}

@Override
public void render () {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    cam.update();
    mapRenderer.setView(cam);
    mapRenderer.render();
}

```

# Answer
> 1 votes
Since I found the problem ima go ahead an answer my own question.

The tile(0,0) in Tiled is in top-left corner while in libgdx tile(0,0) is down-left corner.

This is why staggeredY axis causes problem in a map where the height is even like 10 tiles, in the map editor the first row is `even` and the last row is `odd` in libgdx the last row is actually the first row, so its `even`.

Solution: Make the map height odd, instead of 10 tiles I made it 11. You could make small changes to `HexagonalTiledMapRenderer` like

```
if(mapHeight % 2 === 0)
  staggerIndex = !staggerIndex

```

I just didn't mind adding an extra row.

I personally think they should correct this in libgdx

---
Tags: libgdx, tiled
---


# Question
Title: What do I provide to SDL_LockTexture **pixels?
All I'm trying to do is write random data to an array, then display that array to a window. But I can't get SDL\_LockTexture to cooperate, it keeps complaining that I'm using the wrong argument. I've tried `&pixels`, `**pixels`, and now this weird proxy void construction. None of it works, of course. What is the correct way of doing this?

<pre><code>// gcc C11

#include <stdio.h>
#include <omp.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
    if (argc != 3){
        printf("Wrong amount of args given: expected width, height.\n");
        return 1;
    }

    int w = atoi(argv[1]);
    int h = atoi(argv[2]);

    int pixels[w][h];

    uint8_t r,g,b;

    int pitch = w*4;

    void * pixelpointer = &pixels;

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }

    SDL_Window *window;
    SDL_Renderer *renderer;
    SDL_CreateWindowAndRenderer(w, h, 0, &window, &renderer);

    SDL_Texture* buffer = SDL_CreateTexture(renderer,
                          SDL_PIXELFORMAT_RGBA8888,
                          SDL_TEXTUREACCESS_STREAMING,
                          w,
                          h);

    SDL_LockTexture(buffer,
                    NULL,      // NULL means the *whole texture* here.
                    *pixelpointer,
                    &pitch);

    printf("\nStarting render...\n\nWidth:  %d\nHeight: %d\n", w, h);

    #pragma omp parallel for
    for (int y = 0; y < h; ++y){
        for (int x = 0; x < w; ++x){
            r = rand();
            g = rand();
            b = rand();
            pixels[x][y] = r & g>>8 & b>>16 & 0x000000FF;
        }
    }

    printf("parallel for ends.\n");

    SDL_UnlockTexture(buffer);
    SDL_RenderCopy(renderer, buffer, NULL, NULL);

    SDL_Delay(2000);

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
```
</code></pre>

# Answer
> 3 votes
`void **pixels` is a pointer-to-a-pointer; these are typically used (in this kind of context) where the data is of a pointer type but memory management is handled by the function you call.

The correct usage is therefore:

```
int *pixels = NULL;
SDL_LockTexture (buffer, NULL, (void **) &pixels, &pitch);

```

After this call your `int *pixels` pointer will be accessible for writing, and when you call SDL\_UnlockTexture the pointer will no longer be valid for use.

---
Tags: sdl2, c
---


# Question
Title: WebGL-HTML5 canvas in two blogger blog posts show individually but not together?
In my blogger blog: https://cglabprojects.blogspot.com

I have a newer blog post with

```
<canvas width = "570" height = "570" id = "my_Canvas1"></canvas>

```

and a document.getElementById() stmt

```
var canvaspmet = document.getElementById('my_Canvas1');

```

Another older post has two canvases:

```
<canvas height="200" id="mycanvas" width="600"></canvas>
var canvastemp = document.getElementById('mycanvas');

```

and

```
<canvas height="300" id="my_Canvas" width="300"></canvas>
var canvas = document.getElementById('my_Canvas');

```

Now the problem is if the two blog posts are viewed in one page the WebGL which does the rotation of the cube stops working(interaction). If I open individual posts they work fine and I get the images rendered perfectly.

What might be the issue? I have used unique Id for each canvas in each posts.

# Answer
If you look at the browser error console (`F12`) you will notice a lot of errors:

```
WebGL: INVALID_OPERATION: uniformMatrix4fv: location is not from current program
WebGL: INVALID_OPERATION: bindBuffer: object does not belong to this context

```

It appears that one WebGL application tries to access stuff which belongs to a different WebGL application. How is that possible?

You just discovered one of the reasons why global variables are evil.

You have two scripts on the website which both try to use the global variable `gl` to store their respective webgl context. So the two scripts are actually referring to the same global variable while they are programmed under the assumption that they have that variable to themselves. So you get a lot of chaos.

How can you solve that problem?

Wrap all your scripts in unnamed functions which you execute immediately. That way all variables you declare are local to that function. Other scripts can use the same variable names in their respective functions and there won't be any interference.

```
<script>
(function(){
     // variables local to this function
     var canvas = document.getElementById('my_Canvas1');
     var gl = canvas.getContext('webgl');
      // write your code here as usual
})();
</script>

<!-- Lots of HTML code -->

<script>
(function(){
     // these variables here are different than the variables
     // with the same names in the other script, because each
     // variable is local to the unnamed function its declared in
     var canvas = document.getElementById('my_Canvas2');
     var gl = canvas.getContext('webgl');
})();
</script>

```

Also make sure that you declare all variables with `var` (or more modern `let`) before you use them. If you use an undeclared variable, you are creating a global even if you are in a function. You can disable this by enabling strict mode. Using an undeclared variable will then throw an error.
> 2 votes

---
Tags: html-canvas, webgl
---


title: Monogame sprite rotation issue

text:
# Question
Title: Monogame sprite rotation issue
I'm having interesting problem with rotating a sprite in MonoGame. Here is how origin, destination rectangle and scale are created:

```
  Vector2 origin = new Vector2(tx.Width / 2, tx.Height / 2);

  Rectangle dstRectangle = new Rectangle((int)e.Xpos, (int)e.Ypos, (int)(tx.Width), (int)(tx.Height));
        dstRectangle.X += (tx.Width / 2);
        dstRectangle.Y += (tx.Height / 2);

  Vector2 scale = new Vector2(tx.Width * (float)TxScaleFactor, tx.Height * (float)TxScaleFactor);

```

And here is the draw function:

```
 Editor.spriteBatch.Draw(texture: GlowWhite, destinationRectangle: dstRectangle, color: Tint * (Alpha * 0.6f), rotation: rotation, scale: scale, origin: origin);

```

Now, with angle 0.0f, everything is fine but any additional rotations become weird:

1. Zero rotation, white background is WinForms picturebox, below is MonoGame
2. 90 deg

3. And 180 deg

Its like there is some kind of offset - I've tried to change 0 to 90, and back 0 and next to 180 - result is always the same (apparently, there is no adding). I'm guessing that problem is related to origin, destination rectangle or scale. Sprites are rotated in place as you can see (no issues with that) but something with rotation isn't right. Any ideas?

# Answer
> 3 votes
Nevermind, my (poor) experience in graphics is problem - rotation has to be in radians, not degrees. Solution is `MathHelper.ToRadians(rotationInDeg)`...

---
Tags: c#, monogame, windows-forms
---


title: NavMesh going in the ground

text:
# Question
Title: NavMesh going in the ground
I'm trying to do a navmesh. Everything seems to work fine exept that my character in almost completely under the ground. The ground is a plane with a mesh collider. I have baked it and checked my heigth mesh. My character has a rigidbody and a collider. What could be the problem ?

# Answer
make your rigidBody **Kinematic** as navmesh and navmesh-Agent does not need physics to navigate your agent. make sure you object is grounded and be near of navigation mesh surface.
> 1 votes

---
Tags: unity, 3d-meshes, navmesh
---


# Question
Title: AI Behaviour design pattern which handles lots of diverse behaviours and mechanics?
I'm working on an **2D overhead topdown game** in **Unity3D** and I want the enemies to have **lots of diverse behaviours**.

**How should I design the architecture with this in mind?**

**For example I want:**

* A simple walking monster, which can move on walkable tilemaps, attack the player on sight.
* A spider like creature, which jumps from wall tile to wall tile, and approaches the player in this manner.
* I want a snail which walks on a route, and makes a trail (ie by flagging the tiles) behind itself, apart from this, it's unresponsive (like doesn't care if the player attacks itself)
* A werewolf, which can smell the player from X tile away. (Like there is a walkable path to the player)
* 50 more unique behaviours...

Needless to say, I'm not talking about how to implement this, but how **could I design a system** which will be **robust enough for this many behaviours**, not really error-prone, low amount of code duplication, etc.

Thanks in advance!

# Answer
> 4 votes
i think you are looking for a generic way to make an script that works for big range of NPC's.

for making these types of behaviours, there are some techniques. you can research for each of them and think which one works for you.

1)FSM(finite state machine) -\> HFSM(Hierarchical FSM), FSM with stack very easy to implement. simply a Switch-case programming or using action delegates can make this happen. the problem is state connections are hard-coded so you cant extend it easily.

2) GOAP(goal oriented action planning) its like FSM but connection are not hard-coded. there is a planner algorithm that calculates best way to achieve goal state from current state.

3) behavioural Tree its a tree that leafs are actions. simple left to right parsing is performed to find right action for current conditions. unity and unreal have great visual designing plugins for this. problem is you need change design of tree for wanted behaviour.

4)Utility Theory its latest approach for designing character AI. it uses game theory and fuzzy logic. i dont think there are so many games that used this. but there are good learning references in the internet. in every condition you only have too feed Utility System condition variables to a fuzzy based system to select action with best utility. in this techniques utility is best based in condition. for example when hungry, eating is best action but when you arent, eating is not the best action. its good because you simply can change behaviour with changing condition variables and fuzzy rules.

if you want to go generic as much as possible, number 4 is your best choice.

# Answer
> 2 votes
You could implement most of the low level functionalities which are shared by many creatures as service-components which don't do much on their own but provide functionality to be used by the creature-specific behaviours.

For example, if a lot of your entities should be able to follow a route of waypoints, create a `WaypointFollow` MonoBehaviour with methods like `FollowRouteTo(Vector3 destination)`. If multiple creatures should be able to detect the player, create a `PlayerDetector` MonoBehaviour which exposes properties like `bool seesPlayer` or `Vector3 lastKnownPlayerLocation`. If the monster has a melee attack, give it a component `MeleeAttacker` with properties like range, damage, speed, animation and so on.

Then you create a behaviour for each enemy which describes the high-level functionality of that creature. But in order to keep the code simple and concise, it should depend on other components for the implementation details.

The behaviour of the monster which attacks on sight could look like this:

```
 // references to service components
 private PlayerDetector playerDetector;
 private WaypointFollow waypointFollow;
 private MeleeAttacker meleeAttacker;

 Start() {
     playerDetector = GetComponent<PlayerDetector>();
     waypointFollow = GetComponent<WaypointFollow>();
     meleeAttacker = GetComponent<MeleeAttacker>();
 }

 Update() {
     // the actual behavior
     if (playerDetector.seesPlayer) {
         if (meleeAttacker.CanAttack(playerDetector.detectedPlayer) {
            meleeAttacker.Attack(playerDetector.detectedPlayer);
         } else {
            waypointFollow.FollowRouteTo(playerDetector.lastKnownPlayerLocation);
         }
     }
 }

```

Concise and readable.

All the nitty gritty details, like how to find out which player is the closest player, if they are visible, if something is within attack range or how to find the route to the player are hidden in the service components.

---
Tags: unity, architecture, ai, design-patterns
---


# Question
Title: Set the start orientation of the gyroscope to initial phone orientation
I am making a mobile VR project in Unity, and I have a 360-degree video that starts playing where I can look around using a VR headset.

I am trying to set the start rotation of the video to the same rotation as my phone. So no matter where I look when I start the video, that should be my start rotation. I used `Input.gyro.attitude` in the start but that did not fix my problem. I think I am using it wrong.

This is my code (on the camera inside the sphere):

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

public class Gyroscope : MonoBehaviour
{
    private bool gyroEnabled;
    private Gyroscope gyro;
    private GameObject cameraContainer; //A camera container for my main camera
    private GameObject videoSphere; //The sphere my video is in
    private Quaternion rot;

    private void Start()
    {
        videoSphere = GameObject.FindGameObjectWithTag("Video");
        cameraContainer = new GameObject("Camera Container");

        gyroEnabled = EnableGyro();

        cameraContainer.transform.position = transform.position; // put the cameracontainer into the sphere
        cameraContainer.transform.rotation = Input.gyro.attitude; // here I want to set the cameracontainer to the rotation of my phones gyroscope
        transform.SetParent(cameraContainer.transform); // make my main camera a child of the camera Container

        videoSphere.transform.localRotation = cameraContainer.transform.rotation; // Here I wanted to set my sphere rotation to the camera rotation
        Debug.Log(videoSphere.transform.localRotation);
    }

    private bool EnableGyro()
    {
        if (SystemInfo.supportsGyroscope)
        {
            Input.gyro.enabled = true; // turn on my gyroscope

            cameraContainer.transform.rotation = new Quaternion(0, 90, -90, 0); // rotate my camera container so the video shows good
            rot = new Quaternion(0, 0, 1, 0); // set the variable rot so that you can turn your device
            return true;
        }
        return false;
    }

    private void Update()
    {
        if (gyroEnabled)
        {
            transform.localRotation = Input.gyro.attitude * rot; //this makes you turn the device and it recognizes the input of the phones gyroscope
        }
    }
}

```

# Answer
If you want to rotate the video sphere counter to the head's rotation (to make it look like the head is rotating within a stationary sphere), then you want something like this on the sphere:

```
// Track the sphere's starting orientation in your scene.
Quaternion _startingOrientation;

void Start() {
    _startingOrientation = transform.rotation;
}

// Re-orient the sphere to reflect the head's attitude.
public void CounterRotate(Quaternion headAttitude) {
    transform.rotation = Quaternion.Inverse(headAttitude) * _startingOrientation;
}

```

Now, if you want to "neutralize" the player's starting orientation (so they're always looking at a standard "North" to begin with), you can store their starting orientation as a correction.

You'll probably want to ignore pitch and roll here (the player can feel the tilt of their head relative to the horizon — if the horizon they see doesn't match, it can cause simulation sickness)

```
// Since the phone is mounted sideways in the VR device, we'll need to account for that.
// Store the angle of your sensor here in the inspector.
public Vector3 sensorAngleInHeadset = new Vector3(0, 0, 90);

// Store a correction to neutralize the starting orientation of the head.
Quaternion _neutralizer = Quaternion.identity;

// Compute the attitude of an upright sensor, from the phone's tilted mounting.
Quaternion GetUprightAttitude() {
    return Input.gyro.attitude * Quaternion.Euler(-sensorAngleInHeadset);
}

// Call this when initializing, or when the player chooses to "re-center"
public void Neutralize() {
    // Look at only the forward vector to ignore roll.
    Vector3 forward = GetUprightAttitude() * Vector3.forward;

    // Flatten the forward to the horizon to ignore pitch.
    forward.y = 0;

    // Form a view orientation looking in this direction.
    var neutral = Quaternion.LookRotation(forward);

    // Form a correction that undoes this orientation,
    // bringing its "forward" back to world Z+
    _neutralizer = Quaternion.Inverse(neutral);
}

// Each frame, rotate our video sphere according to the corrected orientation.
void Update() {
     var corrected = _neutralizer * GetUprightAttitude();
     videoSphere.CounterRotate(corrected);
}

```

Or, if you want to keep your sphere stationary and rotate the camera inside, then change that last line to:

```
camera.transform.rotation = corrected;

```

Either way, make sure you're rotating either just the camera or just the video screen, not both at once, or you'll get a very confusing outcome.
> 1 votes

---
Tags: unity, android, virtual-reality, gyroscope
---


# Question
Title: How can I read a value from a file accessed via the Internet?
I have made text file and I put it on Dropbox, I have in this text file a *value*. From my code, I want to check if this *value* is 1.

I have tried this code, inspired by the Unity example, but it looks like I'm not able to reach the file.

```
void Start()
{
    StartCoroutine(GetText());
}

IEnumerator GetText()
{

    UnityWebRequest www = UnityWebRequest.Get("https://www.dropbox.com/s/6jkhtnpskzsi5pj/TestTXT.txt?dl=0");
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log(www.error);
    }
    else
    {
        // Show results as text
        Debug.Log(www.downloadHandler.text);
        // Or retrieve results as binary data
        byte[] results = www.downloadHandler.data;
    }
}

```

# Answer
> 1 votes
It looks like Unity was not able to *download* the file. To fix this, I set the `dl=1` in the Dropbox URL, instead of `dl=0`.

Here is the code that made it work for me:

```
public class DMROnline : MonoBehaviour
{
    public string Active;
    public string Disable;

    public TextAsset textFile;
    void Start()
    {
        StartCoroutine(GetText());
    }

    IEnumerator GetText()
    {
        UnityWebRequest www = UnityWebRequest.Get("https://ucc4b7b1ad9c37a497d7fda64ed6.dl.dropboxusercontent.com/cd/0/get/AoPqwsZg_TSmt1UXQMastDHIcrmf3T5GMlbzHmcj4P0ppWKsKA1qWlRtDM5p-6wCBKMxbuacBGzYaLzUwSg30UekYJ4ntqa0-Oxrg6mG6BImz7wfRzon9OAz2IBTTd1VF5g/file?dl=1#");
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            // Show results as text
            Debug.Log(www.downloadHandler.text);
            // Or retrieve results as binary data
            byte[] results = www.downloadHandler.data;

            string pathTxt = www.downloadHandler.text;
            Console.WriteLine(pathTxt);
            Debug.Log(pathTxt);
        }
    }
}

```

I also had to make sure that the folder holding the file is public, not private.

# Answer
> 0 votes
i think dropBox is all about downloading. you have no access to serverside logic so for reading a file you have to download it

im not sure about dropBox but requesting from A server of cloud from an app is different from browsers as you dont have sessions and cookies for app requests. certainly you need some authentication headers. try to send a request. if you receive 4XX specially 403 it means you need authentication.

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


title: OpenGL strange depth test behavior

text:
# Question
Title: OpenGL strange depth test behavior
I have a simple OpenGL program that renders terrain with a texture. It exhibits some strange behaviors (see video) that look similar to depth test issues. However, I have already enabled depth test. Where else can I look to solve this problem?

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

This is the relevant setup code

```
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

... VBO and texture setup ..

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

projectionMatrix = glm::frustum(-2.0, 2.0, -2.0, 2.0, 1.0, 10000.0);

... rendering stuff ...

glFlush();
swapEGLBuffers();

```

# Answer
> 1 votes
The problem was that I did not request a depth buffer in my EGL config. The solution was to add EGL\_DEPTH\_SIZE to my requested EGL configuration:

So this:

```
EGLint attrib_list[]= { EGL_RED_SIZE,        8,
                        EGL_GREEN_SIZE,      8,
                        EGL_BLUE_SIZE,       8,
                        EGL_SURFACE_TYPE,    EGL_WINDOW_BIT,
                        EGL_RENDERABLE_TYPE, 0,
                        EGL_NONE};

```

Became this:

```
EGLint attrib_list[]= { EGL_RED_SIZE,        8,
                        EGL_GREEN_SIZE,      8,
                        EGL_BLUE_SIZE,       8,
                        EGL_SURFACE_TYPE,    EGL_WINDOW_BIT,
                        EGL_RENDERABLE_TYPE, 0,
                        EGL_DEPTH_SIZE, 24,
                        EGL_NONE};

```

This answer on stackoverflow helped: https://stackoverflow.com/questions/13349714/messed-up-opengl-depth-buffer

---
Tags: opengl, opengl-es2, egl
---


# Question
Title: Should my game's entities use global variables?
I have a base class called `Entity` and several sub classes like `Player` and `Goblin`. They all have the method `update(delta)`, but that's not enough to update `Goblin` for example, which also requires `setTargetPosition(vec2)` to get updated properly.

All sub classes are stored together in a single vector `vector<Entity*> entities`.

**Solution 1** is to use some C++ version of JavaScript's `instanceof` and depending on class call methods like `update()` and `setTargetPosition()`.

**Solution 2** is to have a source file with global variables like `Goblin`'s target position and thus only `update()` is necessary because all the data that's needed is in the file with global variables.

What solution is better than those above?

# Answer
Your design is at odds with reality, and you need to bring the two into alignment.

The thesis of your design seems to be, essentially, that "everything is an entity" and "everything is in one big list" because you can just `update()` that whole list. That's fine, up until the point where it isn't, which is the point you've reached now.

Your interface for `Entity` is not rich enough to actually express reality: some `Entity` implementations require extra information to fully update themselves, information that is not present in `Entity`. You can address this in a few ways.

One way is to give `Entity` that information; this means storing the target position or target entity in `Entity` itself instead of `Goblin`, which now let's `Entity` have the requisite interface to manage and update the target position. If most subclasses won't use this information, however, this is somewhat wasteful.

What I'd argue is the better way is to simply treat the entities that need special handling (goblins) differently. Store them in a separate `std::vector<Goblin*>` so you *know* everything in that vector is a goblin and can use the goblin-specific APIs. Then you can both `update()` them and set their target positions all in a loop.

This avoids complicating the base class with data and methods that aren't universal to all child types. It also gives you a much stronger locality of reference with respect to the update of the goblin instances: you can know when all the goblins start and stop the update work because there's an explicit loop for it, rather than a loop over the big entity "master list" that is potentially processing entity types in an effectively-random order.

This can be a huge win when when you end up having other logic that really wants to depend on the goblin update being "done," as well as for finding places where your work can be data-parallel and benefit from concurrency.

And of course it doesn't involve `dynamic_cast` or the stashing of information in well-known globals, as requested.
> 8 votes

# Answer
Preface: I've designed several game engines in C and C++ by hand and have plenty of experience with game engine architectural patterns and theory

It appears you're designing a game from scratch. Let me first say, **no**, you should *not* use global variables for this purpose. They are stored in what's called the BSS or Data segment and while you may not notice the performance hit from cache misses right away, I can guarantee that once you have your game in a more developed state, you will be kicking yourself in the butt for not outlining the design of your custom engine before embarking on the design journey.

In simple terms, a cache miss happens when a program tries to accesses memory which is "far away" from the memory being frequently or currently accessed, which in a game is primarily going to be stack memory. A professor once told me "Cache is king" when it comes to performance.

Aside from that, you may want to read through a common architectural pattern called Entity-Component-System architecture which is easy to understand and simple to implement. Since, in a custom engine, you will have a graphics implementation, a serializing implementation for saving loading, potentially a reflection system, audio or the like, your program will be moving through different segments of memory quite often and it is important to begin compartmentalizing your data **now** as it may get quite cluttered quite fast.

Like all tools in the game-dev toolbox, global variables have their time and place. They can be quite useful in reflection with regards to entity-factories when using static initializers, or for singleton classes. However, for storing the objects which make up the "meat-and-potatoes" of your game, you should certainly plan on a different strategy other than global variables.

For more complete information regarding memory management, this is an excellent overview of pitfalls and strategies and may provide a more complete picture to help you plan.
> 5 votes

---
Tags: c++
---


# Question
Title: Saving predesigned tilemap "rooms" and access them in script in Unity3D?
I'm working on a top-down rogue-like in Unity3D, and I already have some kind of dungeon generation.

The next feature I'd like to implement, is to predesign some kind of "event rooms" (i.e. boss fight rooms), so my algorithm could place them at random locations.

Is there some kind of Unity feature for this, or I have to implement an editor script which could save and load tilemaps into and from scriptable objects?

# Answer
You can design each event room on a separate tilemap and then save that tilemap as a prefab. Those prefabs can then be referenced by ScriptableObject's or directly by the script which does your dungeon generation.

If your architecture allows for more than one tilemap, then you could simply instantiate the event rooms. This would have the advantage that the room prefab can actually contain more than just a tilemap. You can put literally anything you want in there.

But if your architecture assumes that there will only ever be one tilemap in the scene, then you need to copy the tiles from the prefab into the actual game tilemap. You should be able to do that with `prefabTilemap.GetTilesBlock` and `mainTilemap.SetTilesBlock`.
> 1 votes

---
Tags: unity, procedural-generation, tilemap, random
---


# Question
Title: What is the intended usage of FDetachmentTransformRules in Unreal
There seems to be little to no documentation on this part of Unreal functionality and I was wondering whether anyone here had any examples to share with the community or information regarding potential usages/applications for this.

FDetachmentTransformRules Unreal Documentation page.

# Answer
Components in Unreal have transformation information that is relative to their parent component. When you attach a component to a new parent, or detach one from its current parent, Unreal will update the transformation stored in the component.

The attachment and detachment transform rules let you specify how that update occurs. You can ask Unreal to keep the relative transform as-is or update the transform so that the world space transform of the component is preserved.
> 1 votes

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


# Question
Title: How to handle objects at the edges of spatial partition cells?
A lot of games store object positions as floats and have a closed ball for the game area (eg. a rectangle and objects are allowed to have position coordinates on all 4 edges).

However, this becomes problematic when partitioning the game area (eg. gridding/quadtrees). The edge cases would have to be added in so that 2 edges of the game area are included in rectangles that touch them or objects on 2 edges would have to be missed out in the partition.

---

Is there another solution to this or do games (and other programs this applies to) usually go with one of the above 2?

(One solution is to use integer coordinates, but what if using floats is unavoidable?)

# Answer
> 2 votes
The simple answer would be to add the object's pointer to both cells. As it exists in both cells, to not include it in both cells would be to circumvent the purpose of having the tree to begin with.

The more complicated answer would be to reexamine the purpose for which you're using the spatial partitioning. If this is for graphics and culling, the answer could go both ways. If you don't cull the object, it's not that big of a deal. If this is for broadphase collision detection, obviously not including the object in both cells will almost certainly produce missed collisions.

The best answer would be to use something like a dynamic AABB tree such as an R-tree or R\*-tree in which the cells are not limited to simple volume-based binary subdivision.

---

I run my school's physics club, and I recently spoke with Erin Catto when he came to give his 2019 GDC presentation on dynamic bounding-volume hierarchies to our club. The main takeaway is that the data structure you use and the heuristics employed will be dependent on the scale and purpose of the implementation. I suggest visiting the GDC vault and watching his presentation as he delivers excellent anecdotal information that you may be able to relate to your current problem.

# Answer
> 0 votes
Another way to slice this is to modify your collision checks so you check each object against everything after it in its own cell *and also* everything in the cells bellow or to the left but not above. (This pattern ensures that each pair is still checked only once: for the remaining neighbouring cells we didn't check, this current cell will be one of their checked neighbours)

Handling it this way, each object can "belong" to only one cell, even if it touches or straddles the border between two cells. You can make your cells smaller to keep the overall number of pairs checked similar, as long as the largest single object is less than two cells wide (so its center can be just on the edge of one cell, without reaching past its immediate neighbouring cell).

---
Tags: collision-detection, grid, quadtree, spatial-partitioning
---


# Question
Title: Best strategy when player left the online multiplayer game
I have developed a online multiplayer HTML5 card game. This game can be played by four players.

Now I am having this confusion on what to do when a player left the game in the middle.

**Possible strategies**

1. If player left the game intentionally(like pressing 'quit' button)
    1. Notify other players about this event and stop the game(This will be hated by other players as they have invested their time in this round of game)
    2. Notify other players about this event and assign bot to the position of this player. Penalize the player who left the game.(I think, this step will also decrease interest level of other players about the idea of playing with the bot)
2. If player left the game unintentionally due to network glitch and he may reconnect to game.
    1. Wait for that player indefinitely(not a good strategy)
    2. Wait for that player for finite duration, if he/she is not reconnected then kick out that player and assign bot in his/her place.

Also, from technical point of view, it will difficult to know on server end that if player left due to network issue or simply he close his browser(or switch off his network)

Any suggestion on how I can handle this scenario ?

# Answer
> 4 votes
It's just a matter of time until the players notice that they can avoid the rage-quit penalty by killing their web browser through the task manager. So you shouldn't try to differentiate between these cases.

Replacing the player with a bot is a good idea. It allows the other players to resolve the game in a satisfying manner.

# Answer
> 4 votes
Intentionally and unintentionally leaving should be treated the same, as it's impossible to be sure which scenario happened in every case (e.g. a user plugging out their network cable versus the connection dropping). The only exception is to not wait for them if they were to explicitly select a "concede" option (but otherwise treat this option the same).

Apart from that, I would say **there isn't really a "right" answer to this**. Some options just may not make sense for some specific game. Other than that, different games treat this differently for different reasons, and they may also have special cases (e.g. allow players to concede in tournaments, but not in regular play). Even games that are *very* similar treat this differently (e.g. League of Legends allows conceding most of the time while Dota 2 only allows this in some tournaments).

*Note: Some of the below may be specific to 2-player (or 2-team) games, where one player losing automatically means the other wins, or was at least framed in terms of such games.*

## The main options I see (which aren't exclusive)

* **If a player disconnects**:

+ Allow them to return indefinitely, for some time (after which you can go with one of the below options) or not at all.
    + Either pause (for a few minutes) or keep the game going while waiting for them to return, or give remaining players the option to pause (even when no-one disconnected, perhaps).

    *Note: It should not be possible for a player to start a new game if they are being waited for in another game.*
* **Allow a player to concede**, after which they cannot return (and they can start a new game).
* **Replace the player who left with a bot** (possibly without telling the players, which can be seen as deceptive and players may despise this if they find out or it's obvious). You may or may not want to give them a win either way.
* **Just end the game.**
* **Allow players to choose** whether they want to play with a bot or stop playing (with the game recorded as a win either way, even if they end up losing against the bot).
* **Just let the player who left either idle or "die"** while keeping the game going.

## To decide between the options, there are a few factors to consider

**Note:** A number of the factors listed below may indicate another problem with your game which would be best address directly instead of treating this one effect of that problem.

* **How much fun and how fast is ending a game (for each player)?**

If ending the game is the most enjoyable part of winning (which it often is, for a lot of people), you want to allow them to continue until the end.

But an option to end the game (from either the losing players in the form of conceding, or the remaining players) may be useful if:

+ Ending the game is mostly a chore for both players.
    + A losing player is able to easily significantly delay the end of a game without really giving themselves a better chance of winning.
    + A winning player can indefinitely keep control of the game without ending it (which would be frustrating for the losing player).
* **How long are the games? How far along is this game?**

Players may prefer finishing games if they've already committed a lot of time to the game and it's almost done.

They may prefer ending it if the disconnect happens after they barely started.

If the games only take a few minutes, you probably don't want to wait for disconnected players nor give remaining players a choice in terms of what happens (in order to keep the pace going). But either replacing them with a bot or just ending the game could make sense.
* **How many other players are there?**

When there are multiple players in the game that needs to agree on something (whether it's the decision to concede or wait or continue with a bot), this could make things complicated and make players angry at other players or you. So one should be careful when implementing things like that.
* **How often do players leave? At which point in the game do they leave?**

*Why* they leave could depend on a number of factors, including which device they're playing on, which country they're in, what penalties there might be for leaving and a number of other things specific to the game. But the bottom line is how often they end up leaving. You'll probably need to look at the data of your game, or at least your target audience, to determine this.

If the average player leaves often, anything other than silently replacing them with bots is likely going to be a huge irritation for the remaining players.

If players very rarely leave, you could make a good argument for waiting for them.
* **The effect on the game, and teammates**

If there are just 2 players in the game, just ending the game could be a good option. But this is significantly worse when there are more than 2 players.

You really, **REALLY** want to avoid having a tie any time a player leaves or telling players they lost while the game is still ongoing (in case of team games or if you just pick the leading player as the winner).

If it's a team game, this would heavily favour a waiting option. Also, players may prefer to have their disconnected teammate just idle or die instead of being replaced by a bot which does "dumb" things.
* **Can players join a game as a team?**

If players can form a team with friends, you'd almost certainly want to at least give the *option* to wait for disconnected players, and you probably don't want to replace them with a bot.
* **What's the penalty for losing versus simply leaving a game?**

You may or may not want to treat these differently.

If simply leaving is heavily punished (either in terms of bans or just significant ranking changes), that would make a good case for giving a disconnected player some time to return to the game.
* **Is the game "casual" or "serious"?**

In a "casual" game, it could make more sense to replace disconnected players with bots, whether silently or by asking the player first. You probably don't really want to do this with a game people are extremely passionate about, where they spend a lot of time trying to improve and there are tournaments and rankings and so on. For the latter, waiting for players would also make more sense.
* **What do your players think of playing with bots?**

If players choose to play with other players, it stands to reason they prefer this above playing with bots (obviously).

How strong of a preference this is, however, and how this compares to other factors, would depend on the individual player, so this is something you could potentially A/B test.
* **How good are the bots?**

This is especially important to ranked play, where players would have a certain expectation for the skill level of their opponents and you almost certainly don't want to replace players with bots, or at least this should be recorded as a win regardless of the actual result. But this may also be applicable to unranked play.

Having a bot that plays reasonably at all skill levels would likely be really difficult to achieve for a heavily skill-based game.

The bot should ideally be *slightly worse* than the player who left, and preferably play *somewhat* similar to how a human plays.

If they're better, this could suddenly make the game a lot harder, which will frustrate remaining players. If they're much worse, the game might become trivial to win, which may also frustrate players.

If they don't "act human", the switch between a human player and a bot may be rather jarring for the remaining players.

If they're either much worse or they don't "act human", silently replacing players with bots probably isn't a good idea.
* **What happens if players idle or "die"?**

If a player can idle, die or have anything they control be removed from the game entirely without it making extreme changes to how the game is played for the remaining players, this might be a good option.

If the player has teammates, it might make sense to give any resources they might have or get to the other players instead, or allow their teammates to control their units.

# Answer
> 1 votes
we have standards for this. for both conditions there are solutions.

for intended disconnect, you can make any scenario based on your theme or game-play. for example in head ball 2 when a opponent exits, you receive the message that opponent was afraid of you and quit. or you can give winning score to opponent.

for un intended disconnect, most fair scenario is to give time to return. for example about 20 seconds to return. if that did'nt happen, just run the intended scenario.

# Answer
> 0 votes
If player quit intentionally: -assign a bot but don't notify other players, penalize the player. If player quit due to network: -assign a bot but don't notify other players, don't penalize the player, but allow him to rejoin if he get back online. And philipp said that the players could just close browser to avoid penalty, but what if you check if a player left the game from the other players ? I mean a script always run to detect if one of the player is a bot, if so find the player who left and give penalty.

# Answer
> 0 votes
**This is actually the same problem as what you do if the player chooses not to act**

Good game design in an online multiplayer turn based game will time out the player if they do not take their turn in a timely fashion, because otherwise a losing player can simply walk away from the game and force their opponents to wait it out or concede. You will have to decide what to do when this happens. In games based on traditional card games there is usually a requirement to act, so you will need to choose an action for the player anyway when they time out. If they don't need to act, you simply pass their turn.

All you need to do for the missing player is repeat this action each round, probably with a sharply reduced time out after the first missed round.

If they resume their connection while the game continues, they can be re-introduced into the game and take their action. If not, the game finishes without them and they take whatever penalty results from losing. If you think this can be abused, you can apply an additional penalty if they repeatedly disconnect during active games.

This model is successfully used in online 2-player games such as Hearthstone, but there's no inherent reason it cannot scale to more than 2 players.

---
Tags: game-design, multiplayer, card-game, strategy
---