# Question
Title: Understanding how to use Quaternion to rotate object
I m having hard time to understand Quaternions and to use them in my engine for rotating object. I m looking for step by step explanation, actually a correction of my view of Quaternions.

Here is how I understand they work.

q = cos(40\*) + sin(40)(i+j+k)

-\>what I understand is that i+j+k represents the axis of rotation. Basically if i = 1 that means we rotate object around X-axis.

Formula q * point * p-1, is what I dont quite understand. Lets for the sake say I understand why forumla goes like this. What I dont seems to get how would I apply this to my engine to rotate object.

What I tried is to create 3dVector with object position, example (0,0,-5). I would use quaternion that would rotate this vector around y axis, so q * ThisVector * q(conjugate), and then result I would put in translate matrix. But no work. I cant seem to find a way to implement them. I saw some articles on quaternion to matrices, But what do I put in that matrix, a result from q*ThisVector*q(conjugate) or it is just q that is transfromed in matrix?

EDIT What I want is to rotate object on Y-axis using quaternion. So far,because of lack of my understanding, I m failing to rotate. I created a class 3dVector -\>three dimensional vector, and instantiate a new position (0,0,-5). This position I sent as translate matrix to opengl and multiplied with glPosition.

When I tried to rotate that object using quaternion. I just took that position (0,0,-5) and used it in formula q = q * p * q(conjugate). I manually calculated that but result I get didnt make object rotate on Y-axis around itself. Now I m not sure, but I think it actually rotated object but not around him self,he was moved to the right, so he was not in the same position anymore

EDIT\_2:

I have cube that is on position \[0,0,-5\] and I want to rotate it around y-axis by some angle.

I tried to write code in python

```
poinToRotate = Quaternion(w=0,x=0,y=0,z=-5)

angle =45

sinus = math.sin(math.radians(angle));
q=Quaternion(
w=math.cos(math.radians(angle)),
x=sinus*0,
y=sinus*1,
z=sinus*)

newPoint = q.rotate(poinToRotate)

```

Rotation is somewhere good but it cube does not rotate around it self but around some point. But when

```
   p = Quaternion(w=0,x=0,y=0,z=0)

```

to make it to the center, result is all zeros.

# Answer
> 5 votes
Explaining why quaternions work the way they do and their relation to mainstream linear transformation rotations would require some more advanced mathematics knowledge regarding group theory and how it applies to complex numbers and matrices. For your needs however what you need to know is the following:

* Quaternions are 4-dimensional (w,x,y,z) objects with some interesting properties which we can *abuse* in order to do rotations in 3-dimensional space (x,y,z).
* A 3-dimensional vector or point in space can be represented as a quaternion if we create a quaternion where \\$w=0\\$ and we set the rest of \\$x,y,z\\$ to the point/vector coordinates
* The above *hacky* quaternions have the following property: if a quaternion \\$p\\$, that represents a point in 3D space, is multiplied by another quaternion and its conjugate in a sandwich \\$q\*p\*q^{\*}\\$ a **new** quaternion results from this operation that **also** represents a point in 3D space, **specifically** one that has been rotated by using the following linear transformation matrix $$R=\begin{pmatrix} 1-2y^2-2z^2 & 2xy-2zw & 2xz+2yw \\ 2xy+2zw & 1-2x^2-2z^2 & 2yz-2xw \\ 2xz-2yw & 2yz+2xw & 1-2x^2-2y^2 \end{pmatrix}$$ where the \\$w,x,y,z\\$ values represent the values of the \\$q\\$ quaternion.
* The above *rotation* transformation matrix represents a rotation **around** the **axis** represented by \\$x,y,z\\$ with **angle** \\$2\*cos^{-1}(w)\\$

To summarize, if you have a 3D point \\$x,y,z\\$ that you want to rotate by angle \\$θ\\$ **around** the axis represented by vector \\$\[a,b,c\]\\$ using quaternions, what you need to do is:

* Create a quaternion \\$p=0 + xi + yj + zk\\$
* Create a quaternion \\$q=cos(θ/2) + ai + bj + ck\\$ where \\$cos(θ/2)^2 + a^2 + b^2 + c^2 = 1\\$ i.e. a **unit** quaternion. If your axis vector \\$\[a,b,c\]\\$ is a unit vector then it is easier to do \\$q=cos(θ/2) + sin(θ/2) * (ai + bj + ck)\\$
* Do the sandwich multiplication \\$p'=q\*p\*q^{\*}\\$
* Extract \\$x',y'\\$ and \\$z'\\$ from \\$p'\\$ and you now have the rotated 3D point \\$(x', y', z')\\$

---
Tags: opengl, quaternion
---


# Question
Title: Cannot change main camera's inital position in Unity inspector
I modify the Unity Platformer Minigame and want the main camera to display less of the lower part of the view. The Y coordinate in the inspector of the main camera is always -0.2777786 and I cannot change it.

I think what I want to is very simple so it should not take several hours of confusion.

# Answer
> 2 votes
After 11 hours of RT\*M I found the correct answer on the Unity Forum:

> "You won't be able to drag the camera in the scene view because it's locked with the object/sprite that it's following, BUT instead you can change the positions of the VM Cam inside the Inspector;'s cinemachine component:
>
> Inspector \> CinemachineVirtualCamera \> Body \> Screen X (or Screen Y)
>
> Adjust the X and Y settings there and it will move the position of the camera. "

It worked.

---
Tags: unity, camera
---


# Question
Title: How do I create a prefabs when a button is clicked(Unity)
So I want to be able to spawn prefabs when a button is pressed

Shop script -

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

public class Shop : MonoBehaviour
{
    public static string Item01;
    public static string Item02;
    public static string Item03;
    public static string Item04;

    public static int ShopNum;
    // Update is called once per frame
    void Update()
    {
        if(ShopNum == 1) {
            Item01 = "Cannon";
            Item02 = "Tower";
            Item03 = "army Camp";
            Item04 = "Baracks";
        }
        if(ShopNum == 2) {
            Item01 = "Archer";
            Item02 = "Barbarian";
            Item03 = "Goblin";
            Item04 = "Wizard";
        }
    }
}

```

And then my Shop Access script -

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Shop01Access : MonoBehaviour
{
    public GameObject ShopInventory;
    public GameObject Item01Text;
    public GameObject Item02Text;
    public GameObject Item03Text;
    public GameObject Item04Text;
    public GameObject ItemCompletion;
    public GameObject CompleteText;

    void OnTriggerEnter() {
        ShopInventory.SetActive(true);
        Screen.lockCursor = false;
        Shop.ShopNum = 1;
        Item01Text.GetComponent<Text>().text = "" + Shop.Item01;
        Item02Text.GetComponent<Text>().text = "" + Shop.Item02;
        Item03Text.GetComponent<Text>().text = "" + Shop.Item03;
        Item04Text.GetComponent<Text>().text = "" + Shop.Item04;
    }

    public void Item01(){
        ItemCompletion.SetActive(true);
        CompleteText.GetComponent<Text>().text = "Are you sure you want to buy" + Shop.Item01 + "?";
    }
    public void Item02(){
        ItemCompletion.SetActive(true);
        CompleteText.GetComponent<Text>().text = "Are you sure you want to buy" + Shop.Item02 + "?";
    }
    public void Item03(){
        ItemCompletion.SetActive(true);
        CompleteText.GetComponent<Text>().text = "Are you sure you want to buy" + Shop.Item03 + "?";
    }
    public void Item04(){
        ItemCompletion.SetActive(true);
        CompleteText.GetComponent<Text>().text = "Are you sure you want to buy" + Shop.Item04 + "?";
    }

    public void Cancel(){
        ItemCompletion.SetActive(false);

    }
}

```

How could I spawn a cannon when button item01 is pressed into my 3d scene

# Answer
First, in your `Shop` you do not need to spam the assignment of `Item01-04` in the `Update()`. If the value does not change, doing once in `Start()` is enough. If your Shop can change the sortiment, you can assign the new values when you assign the new `ShopNum`.

There is another problem with your reference to Shop. First your class is not static. Second it makes not much sense to just change it each time you try to access the text. You probably want to reference to the actual object of your Item to access more of it stats/ images/ prices besides the name.

What you are looking for is Instantiate. Now if I read your `Shop01Access` correctly, you want to have a small dialog to confirm the action. (Besides the need to check if the Player has enough funds to actually be able to afford the item). There is as well the problem, where do you want to spawn the Object? Just spawning it `Instantiate(prefab);`. But that is not really helpful as it is, usually you need to provide the location and rotation. It helps as well with organizing if you parent it to another GameObject in the scene to have all your spawned objects together.

Another thing you might want to take a look at are Arrays. You repeat a lot of things that are exactly the same besides the name. Instead of

```
public GameObject Item01Text;
public GameObject Item02Text;
public GameObject Item03Text;
public GameObject Item04Text;

```

You can write

```
public GameObject[] ItemText;

```

And access it with the number

```
CompleteText.GetComponent<Text>().text = "Are you sure you want to buy" + ItemText[0] + "?";

```
> 1 votes

# Answer
You could create a something like this and link it to the button in the OnClick window in properties:

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

public class NewBehaviourScript : MonoBehaviour
{
    // GameObject to be instantiated on click
    public GameObject instantiatedGameObject;

    // Function to be called on button click
    public void SpawnItem()
    {
        Instantiate(instantiatedGameObject, new Vector3(0, 0, 0), Quaternion.identity);
    }
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Integration of gravitational interaction
I don't know if this question get her place in physics.stackoverflow forum. I prefer post here, with code etc.

So, I want simulate 2D movements (no rotation) of an asteroid in space affected by a planet's gravity, the problem is how integrate that ? Any better integration for performance ?

Here is the code in C:

```
struct vec2
{
  float x;
  float y;
};

struct body
{
  double mass; //kg
  struct vec2 prev_pos; //for semi-implicit euler method
  struct vec2 pos; //position
  struct vec2 v; //velocity
};

void move_asteroid(float dt) {
  //semi-implicit euler integration #1 -moving the object
  asteroid.pos.x += asteroid.v.x * dt;
  asteroid.pos.y += asteroid.v.y * dt;

  //START
  float x = planet.pos.x - asteroid.pos.x;
  float y = planet.pos.y - asteroid.pos.y;
  float d = x * x + y * y; //distance^2 between asteroid and center of planet

  //acceleration
  float ah = G * ((planet.mass * asteroid.mass) / d); //gravity

  //get components of gravity
  float rad = atan2(y, x);
  float ax = ah * cos(rad);
  float ay = ah * sin(rad);

  //semi-implicit euler integration #2 -update velocity
  asteroid.v.x += ax * dt;
  asteroid.v.y += ay * dt;
}

```

*this is for 'fun' and sadly my knowledge is quite not good, I try to find with my vocabulary (not native english), if you have directions, ideas for better implementation (like study RK4 for correctness etc), it's welcome*

# Answer
> 2 votes
Following correction from @Keelhaul's comment and performance improvement from @DMGregory's comment.
Here is the right code:

```
struct vec2
{
  float x;
  float y;
};

struct body
{
  double mass; //kg
  struct vec2 prev_pos; //for semi-implicit euler method
  struct vec2 pos; //position
  struct vec2 v; //velocity
};

void move_asteroid(float dt) {
  //semi-implicit euler integration #1 -moving the object
  asteroid.pos.x += asteroid.v.x * dt;
  asteroid.pos.y += asteroid.v.y * dt;

  //START
  float x = planet.pos.x - asteroid.pos.x;
  float y = planet.pos.y - asteroid.pos.y;
  float d = x * x + y * y; //distance^2 between asteroid and center of planet

  //acceleration
  /*
    F = G * ((objectA.mass * objectB.mass)/d^2) //gravitational force
    a_objectA = F/objectA.mass //acceleration applied to objectA
  */

  float ah = G * (planet.mass / d); //acceleration applied to asteroid

  //get x,y components of acceleration
  float norm = ah / sqrt(d);
  float ax = x * norm;
  float ay = y * norm;

  //semi-implicit euler integration #2 -update velocity
  asteroid.v.x += ax * dt;
  asteroid.v.y += ay * dt;
}

```

---
Tags: physics
---


# Question
Title: Some of the model's vertices are incorrectly positioned in skeletal animation
Everything is almost ready . I do not understand what the problem is.

The animation works, but some vertices are not where they should be.

I am using an SMD file from Half Life. I found that these vertices have a parent bone at index 2. "Bip01 Pelvis" This bone is in the right place - at the height of the pelvis.

```
version 1
nodes
  0 "Bip01"  -1
  1 "Bip01 Footsteps"   0
  2 "Bip01 Pelvis"   0
  3 "Bip01 L Leg"   2
  4 "Bip01 L Leg1"   3

```

Here is my code:

Animation:

```
// void modelUpdate()...
Mat4 TranslationM;
TranslationM[3] = objJoint.m_position;
TranslationM[3].w = 1.f;

Mat4 RotationM;
RotationM.setRotation(objJoint.m_rotation);

Mat4 NodeTransformation = TranslationM * RotationM;

if (mdlJoint->m_parentIndex != -1)
{
    objJoint.m_globalTransformation =
        m_joints[mdlJoint->m_parentIndex].m_globalTransformation
        * NodeTransformation;
}
else
{
    objJoint.m_globalTransformation = NodeTransformation;
}

objJoint.m_finalTransformation = objJoint.m_globalTransformation * mdlJoint->m_matrixOffset;

```

`objJoint.m_finalTransformation` \- matrix for shader

Here how I read bind pose:

```
Mat4 R;
SMDAngleMatrix(v3f(nt.m_rotation.y, nt.m_rotation.z, nt.m_rotation.x), R);

Mat4 T;
T[3] = nt.m_position;
T[3].w = 1.f;

joint->m_matrixBind = T * R;

if(node.m_parentID != -1)
{
    joint->m_matrixBind = object->m_mdl->m_joints[node.m_parentID]->m_matrixBind * joint->m_matrixBind;
}
joint->m_matrixOffset = joint->m_matrixBind;
joint->m_matrixOffset.invert();

```

I have no experience with skeletal animation. Perhaps someone has encountered a similar problem and knows the solution.

**UPDATE**

I disabled animation (for testing)

```
Mat4 NodeTransformation = mdlJoint->m_matrixBindNoParent;

if (mdlJoint->m_parentIndex != -1)
{
    objJoint.m_globalTransformation =
        m_joints[mdlJoint->m_parentIndex].m_globalTransformation
        * NodeTransformation;
}
else
{
    objJoint.m_globalTransformation = NodeTransformation;
}

objJoint.m_finalTransformation = objJoint.m_globalTransformation * mdlJoint->m_matrixOffset;

```

maybe problem with m\_matrixOffset

How I create matrix from Tait–Bryan angles (ZYX)

```
// up / down
#define PITCH   0
// left / right
#define YAW     1
// fall over
#define ROLL    2
void SMDAngleMatrix(v3f& angles, Mat4& matrix)
{
    float       angle;
    float       sr, sp, sy, cr, cp, cy;

    angle = angles[YAW];// *(math::PI * 2 / 360);
    sy = sin(angle);
    cy = cos(angle);
    angle = angles[PITCH];// * (math::PI * 2 / 360);
    sp = sin(angle);
    cp = cos(angle);
    angle = angles[ROLL];// * (math::PI * 2 / 360);
    sr = sin(angle);
    cr = cos(angle);

    // matrix = (YAW * PITCH) * ROLL
    matrix[0][0] = cp*cy;
    matrix[0][1] = cp*sy;
    matrix[0][2] = -sp;
    matrix[1][0] = sr*sp*cy + cr*-sy;
    matrix[1][1] = sr*sp*sy + cr*cy;
    matrix[1][2] = sr*cp;
    matrix[2][0] = (cr*sp*cy + -sr*-sy);
    matrix[2][1] = (cr*sp*sy + -sr*cy);
    matrix[2][2] = cr*cp;
    matrix[0][3] = 0.0;
    matrix[1][3] = 0.0;
    matrix[2][3] = 0.0;
}

```

OpenGL shader:

```
"void main(){\n"
    "   mat4 BoneTransform = Bones[inputBones.x] * inputWeights.x;\n"
    "   BoneTransform     += Bones[inputBones.y] * inputWeights.y;\n"
    "   BoneTransform     += Bones[inputBones.z] * inputWeights.z;\n"
    "   BoneTransform     += Bones[inputBones.w] * inputWeights.w;\n"
    "   vec4 vertexPosition = BoneTransform * vec4(inputPosition.xyz,1.0f);\n"
    "   gl_Position = WVP * vertexPosition;\n"
    "   texCoord.x = inputTexCoord.x;\n"
    "   texCoord.y = inputTexCoord.y;\n"
"}\n";

```

My matrices:

```
class Mat4{
    ....
    vec4 m_data[4];
}

```

Where m\_data\[3\] - position;

That's all I have.

I will try to use quaternions instead of function SMDAngleMatrix...no same result...

# Answer
This article helped me: https://veeenu.github.io/blog/implementing-skeletal-animation/

But, in my case, I needed to make some additional actions

```
Mat4 localMatrix = T * R;

if (node.m_parentID == -1)
{
    joint->m_matrixWorld = localMatrix;
}
else
{
    joint->m_matrixWorld =
        object->m_mdl->m_joints[node.m_parentID]->m_matrixWorld *
        localMatrix;
}

joint->m_matrixBindInverse = joint->m_matrixWorld;
joint->m_matrixBindInverse.invert();
joint->m_matrixOffset = joint->m_matrixBindInverse * joint->m_matrixWorld;
joint->m_matrixOffset.invert();   // invert here

```

And final shader matrix:

```
Mat4 NodeTransformation = TranslationM * RotationM;

if (mdlJoint->m_parentIndex != -1)
{
    objJoint.m_globalTransformation =
        m_joints[mdlJoint->m_parentIndex].m_globalTransformation
        * NodeTransformation;
}
else
{
    objJoint.m_globalTransformation = NodeTransformation;
}

objJoint.m_finalTransformation =

    objJoint.m_globalTransformation *  mdlJoint->m_matrixOffset *  mdlJoint->m_matrixBindInverse;

```

Result:

Perhaps someone will write a more complete answer. My question is why do I need 2 inverted matrices? What do I need to do to have only one?
> 0 votes

---
Tags: skeletal-animation
---


# Question
Title: Timers: check in game loop, or run independently?
Specifically talking in the context of JavaScript game development.

For example, I can use the language specific timeout mechanism:

```
// Timeout is not tied to game loop at all, tied to language specific timer loop
setTimeout(() => player.age += 1, 1000);

```

Or I can create some custom game timer

```
game.createFixedDelayTimer(() => player.age += 1, 1000);

// In update loop
let lastTimerCheckTime = Date.now();
function update(game) {
  checkTimers(game, lastTimerCheckTime); // Fire timer if specified delay has passed.
  lastTimerCheckTime = Date.now();
}

```

The disadvantage to approach 2 is that the checks are less granular... but maybe it's still desirable so that game behavior is deterministic?

# Answer
It's your choice to make, quite honestly. You can do research to see if you find setTimeout to be more or less efficient than your custom timer. Personally, I don't like to create timers using the browser's api when I already made a game loop I can keep track of time with.

The 'less granular' checks - as you put it - isn't a disadvantage since the check is happening in your update loop. Checking if a timer has expired more often than you update isn't more helpful :)
> 1 votes

---
Tags: javascript, html5, game-loop, timer
---


# Question
Title: Is there a simpler way to simplify the if statement?
The code below generate angle and radius based brightness gradient. As you can see I need to use 3 if statement to define 3 circle, wonder is there a single code that can create nth circle corresponding to brightness gradient, imagine I want to create 20 circle, using 20 if statement is very unpractical.

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

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

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

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

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

        sampler2D _MainTex;
        float4 _MainTex_ST;

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

        fixed4 frag (v2f i) : SV_Target
        {
            //Define boundary value for radius
            float radius=length(i.uv);
            if(radius>0&radius<0.5)
            radius=0.5;
            if(radius<1&radius>=0.6)
            radius=1;

            if(radius<1.5&radius>=1.01)
            radius=1.5;

            if(radius<2&radius>=1.51)
            radius=2;

            //convert to polar coordinates
            float angle=atan2(i.uv.y,i.uv.x);
            float angle1=frac(angle/(2*3.142f));
            float result=-4*radius+angle1+13*frac(_Time.x);
            return result;

        }
        ENDCG
    }
}

```

}

# Answer
You can shorten the conditions with the modulus operator. All if conditions can be reduced to

```
 radius = radius - (radius % 0.5) + 0.5;

```

The `%` returns the reminder of the calculation.

```
0.4 % 0.5 = 0.4
0.6 % 0.5 = 0.1
0.8 % 0.5 = 0.3
  1 % 0.5 = 0

```

We substract the result from our original radius to get into the correct interval. The last + 0.5 is for shifting the result.

Your original code though has some undefined areas for the radius if for example the value is `0.55`.
> 1 votes

# Answer
Repetitive actions very very often means a loop. If you don't know how many repetitions, that almost always **forces** a loop.
To keep the code clean, I suggest a function with the radius as parameters, and 2 more parameters describing your data: the step increment and the number of steps (you could also use the step increment and the maximum radius if you wanted).
The function returns the rounded radius.

```
float getRoundedRadius(float radius, flot stepIncrement, int nbSteps)
{
    for (int i = 0 ; i < nbSteps ; i++)
    {
        if (radius >= i*stepIncrement && radius <= (i+1)*stepIncrement)
            return i*stepIncrement;
    }
}

```

Your function `frag` becomes:

```
fixed4 frag (v2f i) : SV_Target
{
    //Define boundary value for radius
    float radius= getRoundedRadius(length(i.uv), 0.5, 4);

    //convert to polar coordinates
    float angle=atan2(i.uv.y,i.uv.x);
    float angle1=frac(angle/(2*3.142f));
    float result=-4*radius+angle1+13*frac(_Time.x);
    return result;

}

```
> 1 votes

---
Tags: mathematics, shaders, hlsl, graphic-effects
---


title: How to Implement Trap Damage Unity

text:
# Question
Title: How to Implement Trap Damage Unity
Currently, I have a 2D platformer game, and I want to implement a function that can make the player die and go back to the start or a checkpoint when he interacts with a weapon or trap.

What I have in my scene is a sprite with a `Rigidbody` on it and a trap sprite with a `BoxCollider2D` on it which is set to trigger.

How can I make my player go back to the start when he hits the trap?

# Answer
> 1 votes
Since you do not need to reset the scene, all you need to do is

* Save the transform of the last checkpoint when you reach it.
* Destroy the current player.
* Instantiate the current player around the saved transform.
* Move the camera back to the player if it not done already.

# Answer
> 0 votes
Add this script into your enemy. It will reset the scene which in theory will bring the player back to start. Remember to call the `UnityEngine` and `UnityEngine.SceneManagement` API services at the start. Also, make sure to have the player tag on the player, so the scene won’t restart if **any** GameObject collides with the enemy.

```
  // Initiates when something collides with enemy
        void OnTriggerEnter2D(Collider2D collider) {

        if (collider.gameObject.CompareTag(“Player”))
           {
              SceneManager.LoadScene(SceneManager.getActiveScene().buildIndex);
           }
        }

```

---
Tags: unity, c#, 2d, platformer
---


# Question
Title: Convert Global Space 3D Location to Local object space?
I'm trying to find a formula that could convert my 3D global coordinates into local object space.

Here are the inputs I have

```
A Location

B Location
B Rotation
B Scale

```

I need a Location output, corresponding to my A Location in B Space, according to B Location, Rotation, and Scale. I'm working in a 3D Space

So far I didn't found any formulas online, anyone can point me in the right direction? Bests

If possible, i'd need a formula that doesn't use any matrix calculation, it's not supported by the nodal system of my engine (I'm using blender geometry node, but my problem is more generic as you can see)

# Answer
> 1 votes
You'll have to unpeel the transformations applied to B one by one, in reverse order. Typically we'll apply transformations in the sequence...

1. Scale
2. Euler Roll
3. Euler Pitch
4. Euler Yaw
5. Translate

So going backwards from 5 back to 1 (and assuming the {yaw, pitch, roll} axes are {z, x, y} - I'm not super familiar with Blender's conventions so you might need to swap some):

```
Untranslated = A.Location - B.Location

Unyawed = Yaw(Untranslated, -B.Rotation.z)

Unpitched = Pitch(Unyawed, -B.Rotation.x)

Unrolled = Roll(Unpitched, -B.Rotation.y)

Unscaled = Scale(Unrolled, (1/B.Scale.x, 1/B.Scale.y, 1/B.Scale.z) )

```

Now `Unscaled` is the point in B's local coordinate space that corresponds to the point A in the global coordinate space.

Here's how we can implement those rotation and scale functions:

(If your sine and cosine functions take their input in radians, be sure to convert your degree inputs to radians first)

```
Yaw(point, angle) {
    s = sin(angle)
    c = cos(angle)

    return (point.x * c - point.y * s,
            point.y * c + point.x * s,
            point.z)
}

Pitch(point, angle) {
    s = sin(angle)
    c = cos(angle)

    return (point.x,
            point.y * c - point.z * s,
            point.z * c + point.y * s)
}

Roll(point, angle) {
    s = sin(angle)
    c = cos(angle)

    return (point.x * c + point.z * s,
            point.y,
            point.z * c - point.x * s)
}

Scale(point, scaleTriplet) {
    return (point.x * scaleTriplet.x,
            point.y * scaleTriplet.y,
            point.z * scaleTriplet.z)
}

```

---
Tags: matrix, coordinates, projection, spaces
---


# Question
Title: Unity Physics collision metrix doesn't work on ParticleCollisions
I have this Physics collision metrix(1). I have *Player* layer on the ship and *PlayerShells* on Particles whitch's my shooting.

The problem: When I shoot, `OnParticleCollision` on my *shells* collides with *player*, but as you can see on the picture it shouldn't happen.

Proofing my theory, I testet it: (2) and (3) screenshoots;

My "collision" code:

```
private void OnParticleCollision(GameObject other)
        {
            SetDamage(other.GetComponent<ISetDamage>());

            //Creating hit effect
            _mainParticles.GetCollisionEvents(other, _collEvent);
            Vector3 pos = _collEvent[0].intersection;   //hit posotion
            Quaternion newRot =
               Quaternion.Euler(transform.rotation.x, -transform.rotation.y, transform.rotation.z);
               //Tryed to rotate effect like opposite from bullet, but it doesn't work for now

            switch (other.GetComponent<Stats>().GetMatter)
            {
                case Matter.Steel:
                    Instantiate(_hitSteel, pos, newRot);
                    break;
                case Matter.Wood:
                    Instantiate(_hitWood, pos, newRot);
                    break;
                case Matter.Flesh:
                    Instantiate(_hitFlesh, pos, newRot);
                    break;
                case Matter.Dirt:
                    Instantiate(_hitDirt, pos, newRot);
                    break;
                case Matter.Stone:
                    Instantiate(_hitStone, pos, newRot);
                    break;
            }
        }

```

What am I doing wrong?? :(

# Answer
Here's the answer :D Simple as a pie. Thank you again, my friend @DMGregory
> 0 votes

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


# Question
Title: Rect transform stretch of a child object is set to 0 after instantiation
I have the following hierarchy of my prefab:

```
-PopupParent
--Popup
---ScreenDim

```

They all have `Rect Transform` set to `Stretch`. `Anchor mins` are set to `0` and `Anchor maxes` to `1`. `Left`, `top`, `right` and `bottom` are set to `0`. When I pull this prefab to a `Canvas` manually, all works as expected.

When I instantiate the prefab the problem I am encountering is, that the `PopupParent` is stretched as expected, to the full screen, but all its children are not.

`PopupParent` looks like this:

Children `Popup` and `ScreenDim` look like this:

The instantiation I am doing using the `Spawn Prefab Node` in the `Event editor` provided by the `ORK Framework`. I am `Mounting` the `PopupParent` to my `UICanvas`.

It could be, that the issue is caused by some Framework settings, but it might very well be related to how Unity works in general. I am not sure and can't find a way to figure it out.

**SOLUTION**: I got ORK support to reply and solve the issue for me: http://forum.orkframework.com/discussion/6465/spawning-a-prefab-with-a-stretch-property#latest

**TL;DR:** Regular mounting and UI mounting works slightly different.

# Answer
> 2 votes
I got ORK support to reply and solve the issue for me: http://forum.orkframework.com/discussion/6465/spawning-a-prefab-with-a-stretch-property#latest

TL;DR: Regular mounting and UI mounting works slightly different.

This is the code that I got together to make the mounting (and stretching) work properly:

```
public string GVKey_ORKUICanvasTag = "UICanvasTag";
private string UICanvasTag;
private GameObject UICanvas;
// Start is called before the first frame update
void Start()
{
    UICanvasTag =  ORK.Game.Variables.GetString(GVKey_ORKUICanvasTag);
    UICanvas = GameObject.FindGameObjectWithTag(UICanvasTag);
    resetTransformOffset();
    SetParent(UICanvas);
}

private void resetTransformOffset()
{
    RectTransform rectTransform = GetComponent<RectTransform>();
    rectTransform.offsetMin = new Vector2(0,0);
    rectTransform.offsetMax = new Vector2(0, 0);
}

private void SetParent(GameObject parent)
{
    transform.SetParent(parent.transform, false);
}

```

---
Tags: unity
---


# Question
Title: Reference counting with resource handles
I have implemented a resource handle and resource cache class. The handle stores an integer id. The cache stores a vector of objects e.g., Textures. The handle id acts as an index into the cache asset vector.

I then have a third class which provides methods to get the object(Texture) associated with a given handle. The class also stores a map of filename, handle for previously loaded objects.

I am trying to add reference counting to the system. At the moment I store a `std::size_t* ref_count` in `Resource_handle` and have the following constructor/destructor/assignment operators:

```
Resource_handle() : id(0), verifier(0), ref_count(new std::size_t(1)) {}

Resource_handle(const Resource_handle<T>& handle)
: id(handle.id), verifier(handle.verifier), ref_count(handle.ref_count) { ++*ref_count; }

template<typename T>
Resource_handle<T>& Resource_handle<T>::operator=(const Resource_handle<T>& rhs)
{
    ++*rhs.ref_count;
    if (--*ref_count == 0) {
        delete ref_count;
        // reset handle
    }
    id = rhs.id;
    verifier = rhs.verifier;
    return *this;
}

template<typename T>
Resource_handle<T>::~Resource_handle() // reference handling 515 C++ Primer
{
    if (--*ref_count == 0) {
        delete ref_count;
        // unload resource in handle
        // reset handle?
        reset();
    }
}

```

The above code is not complete but I have two problems I'm aware of so far.

1. The objects in the `Resource_cache` vector are not allocated on the heap and `Resource_handle` has no pointer to them to delete them.
2. The reference count `ref_count` is actually counting copies of a particular handle rather than of objects in the cache vector.

How can I resolve these two issues? I'm wondering if the reference handling should be done in the cache class instead? However the cache would have no knowledge of how many handles refer to a particular object in its object vector.

Many thanks.

Edit: I did consider `std::shared_ptr<T>` however research lead me to using handles for the ability to reload resources, easier serialisation and the more lightweight approach.

# Answer
> 1 votes
Before answering your other questions one thing that could break your design. If you delete an asset in the middle of the vector all other asset indices will move and effectively ruin your cache ids since now all handles point to the wrong asset. You probably want to use something else for identifier. Either a key or switching the vector to a map could be enough.

I think your overall design goes to the correct direction, decoupling the actual asset from the handler that holds all the metadata for it. The handle doesn't need a pointer to the actual asset. As long as you have a unique identifier that can be used to pinpoint to a single asset you are ok. *( But having a pointer is probably going to make things simpler.)*

What I would probably suggest is to not have the responsibility of the freeing of assets on the handle. You can have a struct like this stored in the cache vector ( or `cache_hashmap`; one thing to be very careful here is that vector may move things in memory if it reallocates. Holding pointers to vector elements will break. Prefer to either allocate them in heap or use a hashmap or a list):

```
struct cache_entry
{
    int ref_count;
    Texture* actual_asset;
    //other data
    std::string filename;
}

```

And the handle instead of holding a pointer to the ref count can have a pointer to the `cache_entry`. The handle then instead of increasing the ref count, it notifies the cache that it's acquiring/releasing the resource. `Resource_cache::Free(entry_ptr)`

This way :

* You can iterate over your assets for debug reasons and see how many refs are still alive.
* You can lock assets that you may not want to release even if they don't have any references.
* You can decide when to react to a asset being freed whenever you want. Maybe you want o wait for the next frame or there is a chance someone will try to request the asset immediately. The cache can make that decision without making the handle more complicated.

---
Tags: c++, architecture, resource-management
---


title: How do Nethack frontends work?

text:
# Question
Title: How do Nethack frontends work?
I have been trying to learn about GUI frontends for Nethack, but I have been unable to determine how do they get the game information (map, inventory, player info, enemy locations, etc) from Nethack? As in, is there some API that allows these frontends to query these information? If so, how are they used?

I have looked up everywhere but unable to find any documentation that describes how to do so.

# Answer
> 0 votes
There are a couple of options for building a NetHack front end. Some graphical versions of NetHack are true front ends meaning they are only additions and do not modify NetHack. Others are more correctly referred to as graphical variants, they are modifications of NetHack that include changes to the source code for rendering graphics. Even though the later are not technically front ends, the differences are largely invisible to the player, so I've included information regarding both.

A note for those less familiar with older roguelike development: 'console' refers to the command line interface.

## Direct Source Code Development

NetHack is open source and has been ported to a variety of languages and platforms. The most direct way to build a front end is to use the source code directly. This option provides the most flexibility as you have full access to the internal workings of the game. It's also probably the most complex, as you will need to develop a good working understanding of the source code. Essentially you:

* determine the layout for conveying the game information to the user
* develop your graphics
* replace the output calls with graphical equivalents

From what I understand, this is how the Nintendo DS version works as it was ported the source was modified to support sprite output.

Note: sometimes instead of replacing the output, it is actual supplemented. That is graphics are added, but the console output is left in place as it can be useful for debugging and can reduce the number of changes (and thus opportunities for bugs) in the source. The ASCII output window can be minimized or redirected to `/dev/null` if needed.

## Interpret NetHack's Output

It is possible to translate the console output from NetHack into graphics. This is the approach used by Necklace of the Eye (NotEye in short) - it uses a Lua script to interpret NetHack's console output and determine how to replace the ASCII text with a graphical interface. While this may be conceptually simpler than understanding the source code for the game, it still requires a complete understanding of the game itself & the possible output. Generally speaking, the steps would be something like this:

* determine the layout for conveying the game information to the user
* develop your graphics
* intercept the console output
* interpret the console output
* display graphics
* pass user input back into the console game

There are at least a couple of ways to implement this approach - to the best of my knowledge, they are OS family specific. At one end of the spectrum, you could use something like command line pipes. More complex solutions (like those in Necklace of the Eye) rely OS APIs, using things like `getstdhandle` or `posix_openpt`.

## Modify an existing front end or variant

Instead of starting from the original source, you could modify an existing graphical variant or front end. Some are open source and can be directly changed. Others can be changed via scripts or config files. The exact steps for this route will vary greatly depending on which particular variant / front end you are attempting to change & the types of changes you are making.

## Modify a tileset

The easiest, but also least flexible option is to start with a graphical version of NetHack that uses a tileset (sometimes just called tiles or sprites) and change just the graphics. Using this approach you are limited to graphical substitutions. You likely won't be able to change the location for displaying health for instance, but you could replace the sprite for an item or enemy with a different sprite.

The RogueBasin NetHack page is a good resource for NetHack variants & front ends. There's also a variety resources posted on the NetHack Wiki.

---
Tags: gui
---


# Question
Title: How can I play a audio clip only when the volume slider value changed?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
using TMPro;
using System;
using UnityEngine.Events;
using System.Linq;

public class Settings : MonoBehaviour
{
    [SerializeField] private AudioSource[] audioSources;
    public AudioMixer audioMixer;
    public TMP_Dropdown resolutionDropdown;
    public TMP_Dropdown qualityDropdown;
    public Text musicText;
    public Text sfxText;
    public Slider[] audioSliders;
    public Toggle fullScreenToggle;

    private Resolution[] resolutions;

    private void Awake()
    {
        audioSources = GetComponents<AudioSource>();

        resolutionDropdown.onValueChanged.AddListener(new UnityAction<int>(index =>
        {
            PlayerPrefs.SetInt("resolutionvalue", resolutionDropdown.value);
            PlayerPrefs.Save();

        }));

        qualityDropdown.onValueChanged.AddListener(new UnityAction<int>(index =>
        {
            PlayerPrefs.SetInt("qualityvalue", qualityDropdown.value);
            PlayerPrefs.Save();

        }));

        fullScreenToggle.onValueChanged.AddListener(new UnityAction<bool>(index =>
        {
            PlayerPrefs.SetInt("fullscreen", boolToInt(fullScreenToggle.isOn));
            PlayerPrefs.Save();

        }));
    }

    private void Start()
    {
        qualityDropdown.value = PlayerPrefs.GetInt("qualityvalue");

        var resolutions = Screen.resolutions.Where(resolution => resolution.refreshRate == 60).ToArray();
        resolutionDropdown.ClearOptions();

        List<string> options = new List<string>();

        int currentResolutionIndex = 0;
        for(int i = 0; i < resolutions.Length; i++)
        {
            string option = resolutions[i].width + " x " + resolutions[i].height;
            options.Add(option);

            if(resolutions[i].width == Screen.currentResolution.width &&
                resolutions[i].height == Screen.currentResolution.height)
            {
                currentResolutionIndex = i;
            }
        }

        resolutionDropdown.AddOptions(options);
        resolutionDropdown.value = PlayerPrefs.GetInt("resolutionvalue", currentResolutionIndex);
        resolutionDropdown.RefreshShownValue();

        float musicvolume = PlayerPrefs.GetFloat("mainmenumusicvolume");
        float sfxvolume = PlayerPrefs.GetFloat("mainmenusfxvolume");

        musicText.text = musicvolume.ToString();
        sfxText.text = sfxvolume.ToString();
        audioSliders[0].value = musicvolume / 100f;
        audioSliders[1].value = sfxvolume / 100f;

        fullScreenToggle.isOn = intToBool(PlayerPrefs.GetInt("fullscreen", 0));

    }

    public void SetResolution(int resolutionIndex)
    {
        if (resolutions != null)
        {
            Resolution resolution = resolutions[resolutionIndex];
            Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
        }
    }

    public void SetMusicVolume(float volume)
    {
        audioMixer.SetFloat("mainmenumusicvolume", Mathf.Log10(volume) * 20);
        musicText.text = Math.Round(volume * 100, MidpointRounding.AwayFromZero).ToString();

        PlayerPrefs.SetFloat("mainmenumusicvolume", (float)Math.Round(volume * 100, MidpointRounding.AwayFromZero));

        //audioMixer.SetFloat("gamemusicvolume", Mathf.Log10(volume) * 20);
        //PlayerPrefs.SetFloat("gamemusicvolume", (float)Math.Round(volume * 100, MidpointRounding.AwayFromZero));
    }

    public void SetSfxVolume(float volume)
    {
        audioMixer.SetFloat("mainmenusfxvolume", Mathf.Log10(volume) * 20);
        sfxText.text = Math.Round(volume * 100, MidpointRounding.AwayFromZero).ToString();

        PlayerPrefs.SetFloat("mainmenusfxvolume", (float)Math.Round(volume * 100, MidpointRounding.AwayFromZero));

        if (!audioSources[1].isPlaying)
            audioSources[1].Play();
    }

    public void SetQuality(int qualityIndex)
    {
        QualitySettings.SetQualityLevel(qualityIndex);
    }

    public void SetFullscreen(bool isFullscreen)
    {
        Screen.fullScreen = isFullscreen;
    }

    int boolToInt(bool val)
    {
        if (val)
            return 1;
        else
            return 0;
    }

    bool intToBool(int val)
    {
        if (val != 0)
            return true;
        else
            return false;
    }
}

```

I'm calling this method from ui slider from On Value Changed (single) event in the editor :

```
public void SetSfxVolume(float volume)
    {
        audioMixer.SetFloat("mainmenusfxvolume", Mathf.Log10(volume) * 20);
        sfxText.text = Math.Round(volume * 100, MidpointRounding.AwayFromZero).ToString();

        PlayerPrefs.SetFloat("mainmenusfxvolume", (float)Math.Round(volume * 100, MidpointRounding.AwayFromZero));

        if (!audioSources[1].isPlaying)
            audioSources[1].Play();
    }

```

Screenshot :

The problem is that when I'm running the game first time and it's starting with the main menu it's playing once the sfx effect audio because this two lines :

```
if (!audioSources[1].isPlaying)
    audioSources[1].Play();

```

The audio source play on awake in the editor is disabled unchecked. but in the script it's playing it once when the game is running.

What can I do and where to make that it will not play the sfx audio when running the game only when changing the sfx slider volume value ?

# Answer
In your start function, you change the value of the sliders:

```
audioSliders[0].value = musicvolume / 100f;
audioSliders[1].value = sfxvolume / 100f;

```

Because the value was changed, the sliders fire the `OnValueChanged` event and call the function you told that event to call.

If you don't want to fire the event, you should use SetValueWithoutNotify.
> 1 votes

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


# Question
Title: How to communicate success/failure within an abstract hint system without using sound or words
I am designing a hint system for a "game".

The game is an interactive art simulation for multi-touch and although it is rather intuitive to figure out the basics of how to run that simulation there are some more complicated things to it that I would like to help the user discover.

My design rules are that it needs to be abstract and mostly transparent. There can be no sounds or words to this hint system. I am hesitant to use symbols as well. I realize this makes it quite difficult to effectively communicate with the user but that is sort of the point. It is supposed to be a bit of a puzzle so it is rewarding to solve and in this case it is completely fine if the user does not.

These hints will show up when the user is close to figuring out a new aspect of the simulation. The goal of it is to communicate what the missing piece is for them to get there.

For example on one of the hints I need to get the user to hold a new finger down for more than 1 second under certain conditions.

In order to communicate this I want to show some sort of indicator. When the user puts their finger on the indicator it reacts communicating that that was a good choice but there is still more to do. If the user lifts their finger before 1 second I want to show some sort of "failure animation" however if the user lifts their finger longer than 1 second I want to show some sort of "success animation". The user would also notice that the behavior of the simulation changed.

I have chosen a ring/circle as the core shape for the indicator. This makes sense because generally a hint appears somewhere they are not touching and they begin being "in progress" once their finger is on the indicator. I am good with shaders so I will make it look better later.

So far the hint has been reading but I am concerned about how clear it is whether they failed or were successful at executing whatever the hint was hinting about. I have thought about having the indicator turn "green" for good or "red" for bad but the problem here is that color scheme isn't universal. AND most critically it begs the question of what a "neutral" color is/should be for the indicator before the user has started on the hint and while they are doing it and the indicator is following their finger. Teal was my gut instinct but that color is already pretty close to green. I am worried about the use of just color and specifically the colors red/green so I am looking for other ideas on how I might be able to get this indicator to communicate success or failure following the rules at the top.

Are there other ways I could communicate success/failure?

In addition does anyone know of any other games/projects that use a non-verbal/written hint system communicating more abstractly/with colors? Would be good to have some reference. Any related articles are great too.

Here is sort of a state diagram of the indicator if that helps. I have included a simple/mockup of the indicator with very simple shapes but obviously to give you an idea it will look better. In the holding example the hint would start by being in the state "hint start" somewhere on screen and when the user touches it would transition to "hint in progress". If the user releases before 1 second it would then go to "failure" and turn red but if the user releases after 1 second it would go to "green" for success.

# Answer
> 1 votes
I would consider using an icon of some kind. For example, a smiley / emoticon system:

* :) good
* :| neutral
* :( bad

If desired, you could also couple the icon with color, but I wouldn't use color as the only means to convey information. As you noted, color meaning isn't universal. Additionally, it presents a challenge for users that are color blind & red-green color blindness is the most common form. In my experience grey is a common neutral color.

# Answer
> 1 votes
I'm fairly sure red = bad / incorrect / stop, and green = good / go, is fairly universal, mainly I think because of how stoplights use the 2 colors. So your should be fine just using those colors, at least that's what I think coming from the cultures / locations I represent, which would be the US and Japan.

This would depend on the style and feel of your game, but for the neutral color, you can have something like a yin and yang of green and red, and when the player is getting closer / further from the hint, you can have the green / red portion "overtake" the other side.

If you're really worried about the color scheme, perhaps get rid of it and add a meter / slider that goes up when something is being done right, and down when the player strays from the hint.

Another idea I have is to have the player start off the game with a relatively dark screen, or a black tunnel effect, and the more hints they clear, the brighter the screen gets, or the less of a tunnel effect there is.

Another consideration is to have a meter that does not go below the neutral / starting point. Using your color indicator as an example, instead of an indicator that goes from neutral to green or red, you'll have an indicator that starts at the neutral color, and only goes toward green. If the player gets closer to the hint, the color will turn greener. The "failure animation" can be sudden drop from the green to the neutral color, and the :success animation" could be the green circle turning different shades of green, or colors in a "fun" sort of way. This way, you won't have to worry about universal colors, as the players will eventually figure out what the change in color means.

---
Tags: game-design
---


# Question
Title: Code is skipped after await call and returns to the calling method
I'm developing a roguelike game in Unity using the RogueSharp library. Currently I'm stuck on realizing the turn-based combat aspect of the game (inspired by this tutorial), which is made up of a scheduling system that keeps track of the actors (i.e., the player and monsters) and handles the order of actions they can perform.

```
private async void ActivateMonsters()
{
    var scheduleable = SchedulingSystem.NextActor;
    UnityEngine.Debug.Log($"Turn of {scheduleable}!");

    if (scheduleable is Player)
    {
        IsPlayerTurn = true;
        SchedulingSystem.Add(Player);
    }
    else
    {
        if (IsPlayerDead)
        {
            return;
        }
        if (scheduleable is Monster monster)
        {
            UnityEngine.Debug.Log("Start monster turn!");

            if (await monster.PerformAction(InputCommand.None))
            {
                UnityEngine.Debug.Log("Monster action done!");

                SchedulingSystem.Add(monster);
            }
        }

        ActivateMonsters();
    }
}

```

At the bottom of the method, there is a recursive call to `ActivateMonsters()` for ensuring that all monsters perform their actions until the player has a turn again.

Since my roguelike game is graphical and not text-based, the monsters have animations for attacking, walking, etc., that should be displayed on every turn. Therefore, the game should wait for each monster to perform its attack including playing the corresponding animation, before moving on to the next monster's turn. To achieve that, I've made the `ActivateMonsters()` method `async` and wait for `monster.PerformAction()` to end (the `InputCommand.None` input enum can be ignored).

`ActivateMonsters()` is initially called in this event handler method invoked in Unity's Update() method:

```
private void UpdateGame(object sender, EventArgs e)
{
    if (IsPlayerTurn)
    {
        HandleKeyboardInput();
    }
    else
    {
        UnityEngine.Debug.Log("First ActivateMonsters() call!");
        ActivateMonsters();
        RenderRequired = true;
    }
}

```

`monster.PerformAction()` first calculates the next position of the monster via pathfinding in an async method, which then calls the following method:

```
public static async Task<bool> Move(Actor actor, Loc location)
{
    EnsurePropertiesAreSet();
    var previousActorPosition = actor.Loc;

    // Return true if moving the actor to the given location was successful.
    if (DungeonMap.SetActorPosition(actor, location))
    {
        if (actor is Monster monster)
        {
            var moveDirection = location - previousActorPosition;

            await Task.Delay(3000);

            // Move the monster on the map.
            Game.SetMonsterMoveDirection(monster, moveDirection);
        }

        return true;
    }

    return false;
}

```

For testing purposes, I put in the `await Task.Delay(3000)` before the monster moves to the next tile.

With this I get:

```
First ActivateMonsters() call!
Turn of BrainHero.RogueLike.Actors.Goblin!
Start monster turn!
First ActivateMonsters() call!
Turn of BrainHero.RogueLike.Actors.Player!
[3 second pause]
Monster action done!
Turn of BrainHero.RogueLike.Actors.Player!

```

However, what I want to get is:

```
First ActivateMonsters() call!
Turn of BrainHero.RogueLike.Actors.Goblin!
Start monster turn!
[3 second pause]
Monster action done!
Turn of BrainHero.RogueLike.Actors.Player!

```

The `await Task.Delay(3000)` part does work, but it seems like that the `if (await monster.PerformAction(InputCommand.None))` is skipped and the code execution returns to `UpdateGame()` for some reason. How can I modify the code so that I can achieve the latter execution sequence?

Thanks in advance for any help in solving this issue!

# Answer
> 1 votes
Because `UpdateGame()`, is not an asynchronous function, it will not wait for the `ActivateMonsters();` call to complete before executing its subsequent commands. The `ActivateMonsters();` path of execution will happen independently of `UpdateGame`.

I'm not entirely sure how your code is architected, but if possible, I would make `UpdateGame()` `async`, and `await ActivateMonsters();`.

```
private async void UpdateGame(object sender, EventArgs e)
{
    if (IsPlayerTurn)
    {
        HandleKeyboardInput();
    }
    else
    {
        UnityEngine.Debug.Log("First ActivateMonsters() call!");
        await ActivateMonsters();
        RenderRequired = true;
    }
}

```

Also, for integrating async/await with Unity, I've found the UniTask library to be very helpful. It looks like it has interoperability with standard C# Tasks as well.

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


# Question
Title: How to make MathNet.Numerics work with Unity?
I have installed the latest version of MathNet on Visual Studio using the NuGet Package Manager. I've also, copied the `MathNet.Numerics.dll` to an Plugins folder in the Unity editor. Yet it still gives a compiler error: `error CS0234: The type or namespace name 'Distributions' does not exist in the namespace 'MathNet.Numerics' (are you missing an assembly reference?)`

Does anyone know how to solve this or knows a similar package that works with Unity?

# Answer
> 5 votes
I've been able to install NuGet packages (and in particular MathNet.Numerics) for Unity using this Plugin: https://github.com/GlitchEnzo/NuGetForUnity

The instructions are in the repo's README, but the following steps should work:

1. add the NugetForUnity.unitypackage to your Unity Project.
2. Open the NuGet \> Manage NuGet Packages Window
3. Search the MathNet.Numerics and install

---
Tags: unity, probability, assembly
---


# Question
Title: How is it possible that I make my player die in unity
So what I have is a 2 platform game where I want my player to die when it hits a trap and go back to the last checkpoint it when past

Currently I use this script:

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

public class Respawn : MonoBehaviour
{
    public Transform PlayerPrefab;
    public Transform SpawnPoint;

    void OnCollisionEnter2D(Collision col)
     {
         if (col.gameObject.tag == "Trap")
         {
             respawn();
         }
    }

    void respawn()
    {
        Instantiate(PlayerPrefab, SpawnPoint.position, SpawnPoint.rotation);
    }
}

```

but When i hit the trap I go through it The trap does have a 2 collider on it with ontrigger Selected

How could I implement a checkpoint system and then death

# Answer
The Collision action matrix section of this page is always a great reference to look at. It shows what collision detection/trigger messages are sent when two objects collide.

I would ensure that the player has a `RigidBody2D` (shouldn't matter if it's kinematic or not) and a `Collider2D` (with Trigger selected), and that the trap has a `Collider2D` (with trigger selected as well).

And the callback you should use for trigger messages is `OnTriggerEnter2D(Collider2D other)`, not `OnCollisionEnter2D(Collision col)`.
> 1 votes

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


# Question
Title: How can I maintain a contiguous area when generating a tilemap using Wave Function Collapse?
I'm using Wave Function Collapse to generate a tilemap, and I'm trying to come up with a way to maintain a contiguous area during generation. As an example: ensuring all "walkable" tiles are contiguous such that no "walkable" tile is blocked off from another. An acceptable outcome would also be ensuring there is a contiguous path between two (or more) designated tiles. I'm thinking there may be some way to determine how likely any given tile is to bisect a contiguous area and integrate that into the entropy calculation, but I'm not sure how I would determine that.

# Answer
> 2 votes
This is something that Wave Function Collapse as an algorithm is notoriously bad at doing. Because it's always making local decisions based on immediate neighbours, it's difficult to make any global guarantees.

At the level of individual tile neighbours, the tiles in the middle or at the edge of one giant open area look pretty much the same as the tiles in the middle or at the edge of two small open areas that don't connect together.

Oskar Stålberg talks about how he solved this problem in Bad North about halfway through this video. He associates with each tile some connectivity information about which neighbouring tiles can be walked to from its center point. As new tiles are collapsed, he adds them to a "navigable island" based on these connections to already-collapsed tiles. When choosing which of several tile options to collapse to, he favours options that would expand the navigable island.

This can work, especially for small maps like Bad North's islands that are expected to be mostly walkable, just at different heights, with a possibly serpentine path between them.

But if you want a map where the walkable area is more restricted, you might find this heuristic pushes too hard toward big walkable areas and not enough other stuff. Or, if your generator ever starts to collapse from two separate places (say if you have a map entrance and exit), then this heuristic might not be enough to ensure the two get connected to each other. It might grow a walkable island around each at such different altitudes/materials such that there's no tile that can join them where they meet. There's not much you can do about that kind of contradiction other than restart.

Another approach is to seed your map with a different algorithm that guarantees connectivity, then fill in the rest with WFC.

For example, you could choose a set of points on your map and generate paths between them. You could use say A\* with randomized costs so that it takes a more organic wander between them, rather than always a straight line. For each grid cell in the A\* paths, mark which neighbouring cells it needs to connect with.

Then run your WFC pass. For each marked cell, exclude from its initial superposition of options any tile that doesn't connect to the neighbours marked in the A\* pass. Then proceed with the collapse. You've now guaranteed that any successful collapse from this starting state will have at least the A\* paths you chose as walkable connections between your chosen points — though it could also have additional paths beyond these.

You can then forbid selection of walkable tiles for any cell that has other options and is not adjacent to an already collapsed walkable tile, to prevent other islands of walkability from sprouting up randomly, away from the connected network.

---
Tags: path-finding, procedural-generation, tilemap, grid
---


# Question
Title: Turning around an enemy when hitting a wall or after x time
I have an enemy that is supposed to go in one direction and after **hitting the wall** or if a **certain amount of time passes**, it should turn around and go back. After hitting another wall, it should turn around again and keep doing this in a loop.

# Answer
As mentioned in my comment, I would look at what exactly you need and make steps that you can work on.

*"An enemy has to move in a direction until conditions are met, then turn around."*

So you can **start by looking up how to move an object** (either by transform.position or by physics with rigidbodies, etc.). Instead of going to position x or y, you can let it move indefinitly.

**You can add a boolean somewhere** in that movement, if it is changed, the direction it moves in inverts. When your conditions are met again, the boolean flips back to it's initial state, turning the character back around to the original direction, etc.

**Then have checks to change that bool.** Certain amount of time: make a timer and when it elapses, change the bool. For hitting a wall: search for object collision with walls (maybe a trigger on the enemy and collider on the wall, so when the wall enters the trigger, the bool is flipped)?

These are just some pointers to go on, there are multiple ways to approach it, but this should get you something workable and steps to lookup / learn.
> 1 votes

# Answer
## Build a Finite State Machine

Finite State Machines (FSM) are a simple but effective programming pattern which is very useful for implementing the behavior of AI enemies.

FSM's in a nutshell:

* An enemy can be in different states
* Its current behavior depends on what state they are currently in
* Certain conditions might cause them to switch to a different state, thus changing their behavior

In this case, the state machine which describes the behavior of your enemy has only two states:

1. MOVE\_LEFT state:
    * Move to the left.
    * When a certain amount of time passed, reset that timer and change to the MOVE\_RIGHT state.
    * When there is a wall to the left, reset the timer and transit to the MOVE\_RIGHT state.
2. MOVE\_RIGHT state:
    * Move to the right
    * When a certain amount of time passed, reset that timer and change to the MOVE\_LEFT state
    * When there is a wall to the right, reset the timer and transit to the MOVE\_LEFT state.

## So how would a basic implementation of this pattern look in Unity?

First you need to define the states and a variable to store the current state. You only have two states right now, so a `bool currentState` variable could do the job. But you might want to add more than those two states later, so I would recommend to use an `enum` instead:

```
private enum States {
    MOVE_RIGHT,
    MOVE_LEFT
}
private State currentState;

```

Then your `Update()` method could use a `switch(currentState)` to execute different code depending on the current state: Moving left it's in the MOVE\_LEFT state and move right when it's in the MOVE\_RIGHT state. That code should also include the code to check if the condition for switching the state is met, and when that's the case change `currentState` to the respective other state.

## How would a more advanced implementation look?

When you have an enemy with a lot of states and when those states get pretty complex regarding their behavior and transition logic, then it can be useful to not just create an enumeration and a large `switch` statement, but to create a separate C# class for every possible state. All these classes which represent states for the same type of entity should implement the same interface (or alternatively: extend the same abstract base-class). When I implement the FSM state pattern this way, then my `IState` interface usually has these methods

* `Enter` which gets called when transitioning to this state.
* `Update` which gets called each frame while the FSM is in this state.
* `Leave` which gets called when transitioning out of this state.

The actual `MonoBehaviour` which implements the FSM itself then looks something like this:

```
public class GoombaAI : MonoBehaviour {

    public IState<GoombaAI> moveLeftState;
    public IState<GoombaAI> moveRightState;

    Start() {
        moveLeftState = new GoombaMoveLeftState(this);
        moveRightState = new GoombaMoveRightState(this);
        currentState = moveLeftState;
    }

    Update() {
        currentState.Update();
    }

    public void SwitchState(IState<GoombaAI> newState) {
        currentState.Leave();
        newState.Enter();
        currentState = newState;
    }
}

```
> 1 votes

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


# Question
Title: How to create a spiral brightness gradient
I am stuck on creating a brightness gradient that looks as below(the values are continuous from the inner circle). What formulae can create such brightness gradient? So that when \_Time is added to it, it will slowly brighten up from the inner circle in a spiral form?

Tried a long time to modify from codes below but fail.

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

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

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

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

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

        sampler2D _MainTex;
        float4 _MainTex_ST;

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

        fixed4 frag (v2f i) : SV_Target
        {
            //Define boundary value for radius
            float radius=length(i.uv);
           radius = radius - (radius % 0.5) + 0.5;

            //convert to polar coordinates
            float angle=atan2(i.uv.y,i.uv.x);
            float angle1=frac(angle/(2*3.142f));
            float result=-4*radius+angle1+13*frac(_Time.x);
            return result;

        }
        ENDCG
    }
}
}
```
</code></pre>

# Answer
It looks to me like you want something like this:

```
Shader "Unlit/BrightSpiral"
{
    Properties
    {
        _Turns ("Turns", float) = 3
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

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

            float _Turns;

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                // Place (0, 0) at the center of the coordinate space/quad
                // and scale the extremes to accommodate n turns of the spiral.
                o.uv = (v.uv - 0.5f) * 2.0f * _Turns;
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                // Convert to polar coordinates, with angle normalized to 1 per turn.
                float radius = length(i.uv);
                float angle = atan2(i.uv.y, i.uv.x) / (2.0 * 3.141592653589);

                // Add the number of full turns we need to reach this radius.
                angle += floor(radius - angle);

                // Shape a gradient from bright interior to dark outside,
                // that grows to fill the spiral over time.
                return 4.0f * (frac(3.0f * _Time.x) * (_Turns + 1.0f) - angle - 1.0f);
            }
            ENDCG
        }
    }
}

```

The version above is simple, but it has a little ugliness. The brightness ramps up linearly with angle, which means you get a harsh Mach band where it hits white - looking like a sharp corner, not a smooth blend. It also moves at a constant angular rate, meaning it moves faster in pixel distance as we go further out in radius, and the gradient ramp gets longer.

A few tweaks to the code can smooth that out, if you prefer:

```
fixed4 frag(v2f i) : SV_Target
{
    float radius = length(i.uv);
    float angle = atan2(i.uv.y, i.uv.x) / (2.0 * 3.141592653589);
    angle += floor(radius - angle) + 1.0f;
    angle = angle * angle;

    float t = frac(3.0f * _Time.x);

    float gradient = saturate(1.0f - (0.25f + 0.5f * t) * (t * (_Turns * _Turns + 1.0f) - angle - 1.0f) );
    gradient *= gradient;
    return 1.0f - gradient * gradient;
}

```

This version still has a sharp aliased edge between turns of the spiral, but that too can be smoothed if you need for your application.
> 17 votes

# Answer
You can analytically generate the same shader effect. This isn't unity or HLSL code, but you should be able to translate this easily to HLSL, plus it runs in shader toy and you can play around with it, here is the shader toy link:

https://www.shadertoy.com/view/tl3fRM

Here is a gif (left spiral length based time variation, right is theta based).

here is the code (produces above gif on shadertoy):

```
const float pi  = 3.1415926535897932384626433832795;
const float sqrt3 = 1.7320508075688772935274463415059;
const float sqrt2 = 1.4142135623730950488016887242096;
const float inf = uintBitsToFloat(0x7F800000u);

//takes uv in 0->1 coordinates and turns it into normalized cordinates centered at 0,0.
vec2 center_corrected_uv(vec2 uv, vec2 resolution){
    vec2 uvn = (uv - 0.5);
    //this accounts for aspect ratio, so the spiral is not skewed.
     if(iResolution.y > iResolution.x){
        uvn.y *= resolution.y/resolution.x;
    }else{
        uvn.x *= resolution.x/resolution.y;
    }
    return uvn;
}
//"atan + normalized" (0 -> 2*pi)
float atann(float y, float x){
    float theta = atan(y, x);
    //we add 2*pi because the result of atan in GLSL is pi -> -pi, and we want 0 -> 2*pi
    if(theta < 0.0){
        theta += 2.0*pi;
    }
    return theta;
}

bool approx_eq(float a, float b, float threshold){
    return abs(a - b) < threshold;
}

//this is the same thing as the spiral length function, mathematically, I just wasn't sure if this was more or less performant.
//these functions are basically the analytic integral of r = coef*theta, the equation of an archimedes spiral (a spiral with evenly spaced rings).
float spiral_length_sinh(float theta, float coef){
    //integral from https://math.stackexchange.com/a/424722/
    //and from wolfram alpha
    return coef*(1.0/2.0) * (sqrt(theta*theta + 1.0)*theta + asinh(theta));
}

float spiral_length(float theta, float coef){
    //integral from https://math.stackexchange.com/a/424722/
    //and from wolfram alpha
    float sqrt_theta_1 = sqrt(theta*theta + 1.0);
    return coef*(1.0/2.0) * (sqrt_theta_1*theta + log(sqrt_theta_1 + theta));
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{

    //increase this to "zoom out"
    const float image_scale = 100.0;
    //increase this to increase the speed of the spiral.
    const float speed = 100.0;
    //*decrease* this to INCREASE fade length
    const float left_fade = 0.3;
    //need a seperate additional fade modifier for the right side
    //otherwise will be transparent.
    const float right_fade = 4.0*left_fade;
    //decrease this to increase fade spacing.
    //pi gaurantees filled in distance, going smaller will make a "gapped" spiral.
    const float swirl_radius = pi;
    //this controls the swirl of the marker (the white line that shows up periodically)
    const float marker_swirl_radius = 0.05*pi;
    //time before whole animation restarts.
    const float restart_interval_s = 24.0;
    //time interval for blinking spiral line.
    const float blink_interval_s = 4.0;
    // Normalized pixel coordinates (from 0 to 1)
    vec2 uv = fragCoord/iResolution.xy;

    // Time varying pixel color (this is what will display as the background if we make swirl radius even smaller).
    vec3 col = 0.5 + 0.5*cos(iTime+uv.xyx+vec3(0,2,4));

    //I want to display two different types of swirls, one which increases with spiral length, and one that increases with theta.
    bool display_right = uv.x > 0.5;
    if(display_right){
        uv.x -= 0.5;
    }
    uv.x /= 0.5;
    //divide resolution by two to account for split screen.
    vec2 uvn = center_corrected_uv(uv, vec2(iResolution.x/2.0, iResolution.y)) * image_scale;
    float r = length(uvn)*1.0;
    float theta = 1.0*atann(uvn.y, uvn.x);

    //theta needs to be incresed to with r increasing value, ever 2pi r we need to add 2 pi to theta, since it will reset to zero.
    // we assume every 2*pi r we want to wrap around, our r = coef*theta is actually r = 1.0*theta.
    // This would need to change to account for a different coeff.
    float theta_fixed = theta + 2.0*pi*floor(r/(2.0*pi));

    float time = mod(iTime,restart_interval_s) * speed;
    //right side too fast if we don't do this
    if(display_right){
        time *= 0.1;
    }
    //if we only check for the distance from the adjusted theta we'll get this odd semi circular pattern,
    //because inner radii will not pass the threshold for the next theta, so we need to look at 2*pi back
    //and forward to actually get the proper distance to spiral line from current pixel
    bool theta_the_eq = approx_eq(r, theta_fixed, swirl_radius);
    bool theta_min_eq = approx_eq(r, theta_fixed - 2.0*pi,swirl_radius);
    bool theta_max_eq = approx_eq(r, theta_fixed + 2.0*pi,swirl_radius);
    bool within_swirl_radius = theta_the_eq || theta_min_eq || theta_max_eq;
    float relative_theta;
    if(theta_the_eq){
        relative_theta = theta_fixed;
    }else if(theta_min_eq){
        relative_theta = theta_fixed - 2.0*pi;
    }else if(theta_max_eq){
        relative_theta = theta_fixed + 2.0*pi;
     }

    if(within_swirl_radius){
        if(display_right){
        //on the right, we show theta used as the time/distance modifier.
        // Notice that it appears to get "faster" the further out it goes.
        // This is because it is covering larger amounts of spiral length in the same angle space (theta).
        // this may or may not be the effect you want.
        //Notice, we have to use the appropriate theta which passed the approximate equal threshold, for similar reasons to why
        //we needed to test three different distance metrics in the first place.

            //we use log in addition to the fade coefficient to create a more athsetically pleasing fade, but this isn't actually necessary.
            //using only fade will still work, just with a linear ramp up to color.
            col = vec3(right_fade*log(-(relative_theta - time)));
        }else{
        //on the LEFT, we show the actual spiral distance used as the time/distance modifier.
        // Notice that it appears to get "slower" the further out it goes.
        // This is because it is covering larger amounts of spiral length, and as it gets further out theres more spiral to cover per angle area.
        // this may or may not be the effect you want.
        //Notice, we have to use the appropriate theta which passed the approximate equal threshold, for similar reasons to why
        //we needed to test three different distance metrics in the first place.

            //we use log in addition to the fade coefficient to create a more athsetically pleasing fade, but this isn't actually necessary.
            //using only fade will still work, just with a linear ramp up to color.
            col = vec3(left_fade*log(-(spiral_length(relative_theta, 1.0) - time)));
        }
    }

    // this is used to display the white line, so you can be sure this is an archimedes spiral (again, an equally ringed distance spiral),
    //if you removed this code, it would not display the line.
    if(approx_eq(r, theta_fixed, marker_swirl_radius)
    || approx_eq(r, theta_fixed - 2.0*pi,marker_swirl_radius)
    || approx_eq(r, theta_fixed + 2.0*pi, marker_swirl_radius)){
    //we blink this to show this is only temporary.
        if(mod(mod(iTime,restart_interval_s), blink_interval_s) < 2.0){
            col = vec3(1.0);
        }
    }
    // Output to screen
    fragColor = vec4(col,1.0);
}

```

The code is well documented, but basically we can analytically represent the same thing using our knowledge of the function for an Archimedes spiral, `r = a + b*theta` though in this case I simplify it to `r = 0.0 + 1.0*theta`. We get the polar coordinate for each fragment (which can be based off of vertex attribute data instead of screen coordinates, ie like texture coordinates). This results in a r, and theta. We then figure out if our given theta is close enough to the associated radius r (remember, `r = theta`). We can then vary the width, speed, fade, and many other factors of the spiral arbitrarily. We fade based on the current time - the theta or the current spiral length.

On the left side, there is some additional math going on. To actually get the spiral length, you need an integral. Luckily the analytic integral is pretty simple, you can see more information about this integral here: https://math.stackexchange.com/a/424722/. My equation simplification makes this integral equivalent to https://www.wolframalpha.com/input/?i=integral+sqrt%28%28x%5E2%29+%2B+1%29, or

This indefinite integral is for the equation `sqrt(x^2 + 1)`, which doesn't match the integral used in the mathematics stack exchange post, because of our simplification, we remove the a term, and with our b term the equation was `integral sqrt((b*x)^2 + b^2)`. We can extract b from the inner term like so:

`sqrt(b^2*(x^2 + 1))`

and then extract it from the `sqrt` like so:

`sqrt(b^2)*sqrt(x^2 + 1)` `b*sqrt(x^2 + 1)`

then we can fully remove it from the integral and put it on the outside due to the constant multiple rule. so now we have

`b * integral sqrt(x^2 + 1)`

the indefinite analytical integral we generated earlier will need to be turned into a definite integral. But because the our integral(0) is 0, we only need to evaluate the integral with out subtracting to evaluate the total integral length from the start to the end.
> 4 votes

---
Tags: unity, mathematics, shaders, hlsl
---


# Question
Title: Button reacts to the screen event in Unity
I use Unity 2019.4. I made a script so that if a make a long press on the screen of my mobile phone, my Personnal Character stops. I created a button to shoot gun too. The problem is when I make long press on that button too (shoot button), my personal character also stops. How to avoid this and use "Shoot button" only for shooting.

```
        if (MobileInput.Instance.LongPress)
        {
            {
                speed = Mathf.Lerp(speed, 0, 1f);
                if (speed <= 0)
                {
                    speed = 0;
                    isIdle = true;
                    isRunning = false;
                }
            }
        }

```

# Answer
This is how I fixed it thanks to suggestions I received.
In my Input script(where Mobile and Keyboard Inputs are handled),I inserted "EventSystem.IsPointerOverGameObject()". I removed Image component in the UI Panel coz Image component can be transparent so invisible but it can block interaction with the screen (taps and swipes on the screen).

```
    if (Input.GetMouseButtonDown(0))
    {
        if (EventSystem.current.IsPointerOverGameObject())
            return;

        tap = true;
        startTouch = Input.mousePosition;
    }

```
> 1 votes

# Answer
As Zibelas said in the comments, you could use an `isShooting` bool to check whether or not you are firing, and thus prevent the player from stopping when the input happens to be a longpress. Here's the script:

```
public bool isShooting;

        if (MobileInput.Instance.LongPress && !isShooting)
        {
            {
                speed = Mathf.Lerp(speed, 0, 1f);
                if (speed <= 0)
                {
                    speed = 0;
                    isIdle = true;
                    isRunning = false;
                }
            }
        }

```
> 0 votes

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


# Question
Title: In unity how can I make a checkpoint system
I have a `2D platformer` and if my player dies, he goes back to the start, but I want there to be checkpoints.

My current Respawn script:

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

public class Respawn : MonoBehaviour
{
    public GameObject PlayerPrefab;
    public Transform SpawnPoint;

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Trap")
        {
            PlayerPrefab.transform.position = SpawnPoint.transform.position;
        }
    }

}

```

I don't know how to implement checkpoints into this.

# Answer
I would recommend you to structure your project a bit differently. Instead of having the `Respawn` script on the player (I assume it's on the player) detect and handle all the interactions with different objects in the world, you should make those objects themselves responsible for detecting the player and triggering a response from it.

So first of all, don't make the player a trigger. Give it a Rigidbody2D, so it can be detected by trigger areas (if you don't want to use the Unity physics and handle movement yourself, make it kinematic). Turn the `private void OnTriggerEnter2D` into a `public void DieAndRespawn()` method which can be called by other scripts if they want the player to die and respawn. Note that when this script is on the player, it doesn't need an explicit reference to the player because it can just access the properties of the gameObject it's on directly.

```
public class Respawn : MonoBehaviour
{
    public Transform spawnPoint;

    public void DieAndRespawn()
    {
         Debug.Log("Nooooooooo!");
         transform.position = spawnPoint.transform.position;
    }
}

```

Then create separate scripts for `Trap` and `Checkpoint`. Give the objects they are on Colliders with "Is Trigger?" enabled, so they can detect the player and cause something to happen to it. Their collision methods then would look like this for the Trap component:

```
void OnTriggerEnter2D(Collider2D other)
{
     Respawn respawn = other.GetComponent<Respawn>();
     if (respawn != null) {
          Debug.Log(other.name + " ran into " + name);
          respawn.DieAndRespawn();
     }
}

```

And like this for the Checkpoint component:

```
void OnTriggerEnter2D(Collider2D other)
{
     Respawn respawn = other.GetComponent<Respawn>();
     if (respawn != null) {
          Debug.Log("Setting spawn point of " + other.name + " to location of " + name);
          respawn.spawnPoint = gameObject.transform;
     }
}

```

Note that these traps and checkpoints don't recognize the player by a tag, but instead by having a specific component. That means that they can now not just interact with the player but also with anything else which has the `Respawn` component. Like for example a second player or an AI actor which you want to die and respawn just like a human player.
> 2 votes

# Answer
You clearly know how to move the player to a spawn point when hitting a trap.

You can use the same logic to move the spawn point to a checkpoint when hitting the checkpoint.
> 0 votes

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


# Question
Title: Is web browsers, how much latency is there with event listeners?
I have an event listener in JavaScript looking for keydown events.

```
document.addEventListener('keydown', e => {
    // Callback code
});

```

What is the latency between someone pressing a key and my function executing. Is the function immediately added to the event queue or does it wait until the next frame is ready to be drawn? Is the behavior consistent between web browsers?

Just to be extra clear, I'm only interested latency in the context of web browsers, not anything before it.

# Answer
The JS engine of the web browser operates in a single thread and has a task queue which operates on the first-come-first-served principle. That means anytime an event occurs, that event is pushed to the end of the task queue and gets acted upon as soon as everything that happened before was executed completely.

`requestAnimationFrame` tells the web browser to run a function on the next repaint-event. Repaint-events are generated constantly by the browsers rendering engine. Pressing a key also generates an event - a keydown-event. So whether the keydown-event gets processed before or after the next repaint-event depends on whether or not a repaint-event is already in the queue and waiting to be executed.

For more information on how events in JS are handled under the hood, I recommend this article: Understanding JavaScript Call Stack, Task Queue and Event Loop
> 1 votes

---
Tags: input, web, latency
---


# Question
Title: Non-invocable memeber 'Text.text' can not be used as a method
Trying to change text in a text box, and have multiple lines on it, i found something online talking about "\n" but this came up.

> Non-invocable memeber 'Text.text' can not be used as a method.

This is my code

```
private void Start()
{
    if (creditEnding)
    {
        startText.text("You, died? \n well you should get some sleep anyways");
    }
}

```

# Answer
> 0 votes
Since text is of type string and not a method, all you need to do is

```
startText.text = "You, died? \n well you should get some sleep anyways";

```

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


# Question
Title: SDL_SetColorKey in SDL c++ removes most of the white pixels but there is a border around my character
I have drawn all of the images of my sprite in paint. Is there a way to remove all white pixels?

```
bool Game::loadFromFile(std::string path)
{
    free();

    SDL_Texture* newTexture = NULL;
    SDL_Surface* loadedSurface = IMG_Load(path.c_str());

    if(loadedSurface == NULL)
    {
        printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
    }

    else
    {
        //Color key image
        Uint32 colorKey = SDL_MapRGB(loadedSurface->format, 255, 255, 255);
        SDL_SetColorKey(loadedSurface, SDL_TRUE, colorKey);

        //Create texture from surface pixels
        newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);

        if(newTexture == NULL)
        {
            printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
        }

        else
        {
            //Get image dimensions
            mWidth = loadedSurface->w;
            mHeight = loadedSurface->h;
        }

        //Get rid of old loaded surface
        SDL_FreeSurface(loadedSurface);
    }

    //Return success
    mTexture = newTexture;
    return mTexture != NULL;
}

void Game::free()
{
    //Free texture if it exists
    if(mTexture != NULL)
    {
        SDL_DestroyTexture(mTexture);
        mTexture = NULL;
        mWidth = 0;
        mHeight = 0;
    }
}

void Game::render(int x, int y, SDL_Rect* clip)
{
    //Set rendering space and render to screen
    SDL_Rect renderQuad = {x, y, mWidth, mHeight};

    //Set clip rendering dimensions
    if(clip != NULL)
    {
        renderQuad.w = clip->w;
        renderQuad.h = clip->h;
    }

    //Render to screen
    SDL_RenderCopy(gRenderer, mTexture, clip, &renderQuad);
}

int Game::getWidth()
{
    return mWidth;
}

int Game::getHeight()
{
    return mHeight;
}

bool Game::Initialize()
{
    bool success = true;

    if(SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
        success = false;
    }

    else
    {
        if(!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
        {
            printf("Warning: Linear texture filtering not enabled!");
        }

        gWindow = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

        if(gWindow == NULL)
        {
            printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
            success = false;
        }

        else
        {
            gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
            sBackground = SDL_LoadBMP("BackgroundLeft.bmp");
            tBackground = SDL_CreateTextureFromSurface(gRenderer, sBackground);

            if(gRenderer == NULL)
            {
                printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
                success = false;
            }

            else
            {
                SDL_SetRenderDrawColor(gRenderer, 255, 0, 255, 0xFF);

                int imgFlags = IMG_INIT_PNG;

                if(!(IMG_Init(imgFlags) & imgFlags))
                {
                    printf("SDL_image could not initialize! SDL_mage Error: %s\n", IMG_GetError());
                    success = false;
                }
            }
        }
    }

    return success;
}

```

# Answer
> 2 votes
The `SDL_SetColorKey()` function color keys a specific color in an image. In this case it's the color white `(255, 255, 255)`.

If you zoom in on the second image you've added to your post, where the color key has been applied, you'll see that the border around your character isn't actually completely white and those pixels hasn't been color keyed. Some of the pixels are *almost* white, some of them are light gray, some are dark gray etc.

To make the color keying to work properly, the pixels that you want to color key has to be **completely** white.

Your other choice is to use an image format that supports an alpha channel, like the png format for example. Instead of using a white background color around the character, you instead erase the background and let the `IMG_Load()`function (from the SDL\_Image library) handle the alpha/color keying for you.

# Answer
> 1 votes
Because the source image is monochrome, you can use use a different blend mode to get nicely blended edges. If you multiply the sprite colour by the thing it's drawn on top of, you will get the blended effect that you want.

That's because white is 1, and black is 0. Multiplying by 1 will do nothing, and multiplying by zero will give you black.

To get that effect you need to use `SDL_SetSurfaceBlendMode()` instead of `SDL_SetColorKey()`.

```
SDL_SetSurfaceBlendMode(loadedSurface, SDL_BLENDMODE_MOD);

```

If you want to use a more colourful sprite image, then you will need an alpha channel, along with `SDL_BLENDMODE_BLEND`.

---
Tags: c++, sdl
---


# Question
Title: What project template to use for an 8bit RPG?
Should I use a 2D or 3D dimension for an 8-bit RPG game in Unity? I have been searching and I haven't found anything on this yet. Can anyone please tell me the better option because sometimes people recommend to do 3D just in case, but I don't want to mess anything up later on.

# Answer
It doesn't really matter that much what project template you use, because it actually changes very little. Anything it changes can be changed back after you created the project.

And it does not lock you out of any features either. You will have both the 2d and the 3d features of the engine available, no matter if you choose 2d or 3d when you create your project. You can in fact mix and match sprites and meshes in the same scene without issues. The only part of the engine where 2d and 3d are separated are the physics engines. 2D colliders won't interact with regular (3D) colliders. But they can still coexist in the same scene.

For more information on this topic check out the article 2D or 3D projects from the Unity Manual.

That being said, for a game where environment and characters are represented by sprites and not by 3d models, you likely want to start with the **2d template**, because then any image files you import will by default be imported as sprites and not as textures. You can change the import type of an image asset very easily, but it's still more convenient to have the right preset.
> 1 votes

# Answer
If you want your game to be 2D, choose 2D, if you want it to be 3D, choose 3D.
> 0 votes

---
Tags: unity, rpg
---


# Question
Title: Vertex Snapping on a mesh with an armature
I've made a selection of modular walls for a game i'm working on and some of the pieces have moving parts, like doors and flaps, but the moving pieces with an armature attached don't use vertex snapping like all of the other pieces and it leaves ugly gaps in the walls.

I've tried everything I can think of to get them lined up, the closest I can get is lining them up by eye and this leaves small gaps when in game and isn't perfect.

Does anyone know of a way to get vertex snapping to work with meshes that have an armature attatched?

I've attached a picture to try and explain:

# Answer
Quickest solution I can think of is to disable the Skinned Mesh Renderer and add a Mesh Renderer and Mesh Filter to the wall. Add the mesh to the mesh filter. Now you can see the same mesh( in a static way) and vertex snap will work. After you have placed them you can delete the extra components.
> 1 votes

---
Tags: unity
---


# Question
Title: How do I fade between scenes when my player reaches a certain point
I have made a 2d Platformer but when my player reaches the end of a level I want it to fade to the next level.

How can I have multiple scenes that each have one level and that fade in and out?

Load Scene -

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

public class Loader : MonoBehaviour
{
    public Animator Switch;
    // Update is called once per frame
    void Update()
    {
        void OnTriggerEnter2D(Collider2D other)//I try to check for the checkpoint but failed
        {
            if (other.tag == "End")
            {
                LoadNextLevel();
            }

        }
    }

    public void LoadNextLevel()
    {
        StartCoroutine(LoadLevel(SceneManager.GetActiveScene().buildIndex + 1));

    }

    IEnumerator LoadLevel(int LevelIndex)
    {
        Switch.SetTrigger("Start");
        yield return new WaitForSeconds(1);
        SceneManager.LoadScene(LevelIndex);
    }
}

```

# Answer
Make a shader transition in any shader language (this website is a great one) and before loading the next scene, activate the transition.

If the player enters the level (scene) then forward and backward when he exit.

You can use a raycast with a collider at the end of the level to know if you are at the end of the level or not.
> 0 votes

# Answer
You've nested your `OnTriggerEnter2D` method *inside* your `Update` method:

```
void Update()
{
    void OnTriggerEnter2D(Collider2D other)//I try to check for the checkpoint but failed
    {
        if (other.tag == "End")
        {
            LoadNextLevel();
        }

    }
}

```

That means the method named `OnTriggerEnter2D` exists *only* when Unity is running your `Update`, and can only be called from *inside* the `Update` method. When Unity is doing the physics simulation step and handling trigger events (which happens *before* `Update` is called), if it checks this script for an `OnTriggerEnter2D` method, it won't find one.

**Lesson:** *never* nest Unity message events inside another method. 99.9% of the time, *all* your methods should be directly within the class, not wedged inside one another.

Secondly, you'll want to add a flag or something to prevent the loading coroutine from firing multiple times over the second that it's active, something like...

```
public class Loader : MonoBehaviour
{
    public Animator sceneChange;
    private Coroutine _loadInProgress;

    void OnTriggerEnter2D(Collider2D other)
    {
        // Don't need to check for "End" tag if this is on
        // your "End" object itself. You could however
        // check if the player is the one that hit
        // the endpoint, if other things can.
        // if (other.CompareTag("Player"))
        {
            LoadNextLevel();
        }
    }

    public void LoadNextLevel()
    {
        if (_loadInProgress == null) {
            int nextLevel = SceneManager.GetActiveScene().buildIndex + 1;
            _loadInProgress = StartCoroutine(LoadLevel(nextLevel));
        }
    }

    IEnumerator LoadLevel(int LevelIndex)
    {
        sceneChange.SetTrigger("Start");
        yield return new WaitForSeconds(1);
        SceneManager.LoadScene(LevelIndex);
        _loadInProgress = null;
    }
}

```

You might also want to use `LoadSceneAsync` to start the load while your animation is in progress, that way you can minimize any stutter or delay at the end of the animation.
> 0 votes

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