title: Mark positions of spawnpoint in editor

text:
# Question
Title: Mark positions of spawnpoint in editor
I am creating a digital boardgame, which consits of muliple boards, between which the gamepieces are moved by the players.

The script of the game board needs a 2D array of positions to know where to move a gamepiece when it recives one. Currently to mark the positions on the game boards, I added placeholder gameobjects to the prefab and named them "spawnpoint\d".In the `Awake()` method I use `Transform.Find()` to search for those gameobjects. Then, after I save their positions I call `Destroy()` on them, so they do not show up in the game.

I see two problems:

1. This is done for all Instantiated game board, altough the positions are the same on all of them.
2. I read that using `Transform.Find()` is heavily discourged by the experts in the community.

I wish to store the spawnpoint positions in a static array, so all instances refer to the same data. Furthermore I wish to easily modify these positions in the editor with visual help.

I tried serializing static members, but those do not show up in the editor to be able to modify.

```
    [SerializeField]
    public static int TestNumber;

```

TLDR: **How to make static members visually changeable from the Unity editor?**

# Answer
> TLDR: How to make static members visually changeable from the Unity editor?

First of all, there is **no way** to expose static variable to inspector. Although there is similar way to achieve this result via ScriptableObject. (Centralize data to one ScriptableObject) But it is not quite the same and do have some restriction to reference scene stuffs.

If I understand correctly, you want to share "2D array of positions" (List of Vector2?) for all boards. So that all boards does not have to repeat the same process of finding placeholder/record position/then destroy them.

### To visualize your place holder while able to adjust them

* I don't know how you visualize your place holder nodes initially, but you could use icon styling. (drop down menu near game object name) This enable you to see them and select them easily in Scene window. There are 2 styles to choose from, with and w/o name. The node content will be empty; not contain any rendering element that will appear in the game.
* You may use your same method of hardcoding the spawnpoint by name and `Transform.Find()` to reach them. But you should contain them to some root node, instead of scene-wide. This is not too bad since `Transform.Find()` find only 1 level of child node not entire scene.
* Instead of getting their Vector3 position then destroy them. You keep them around (since they have no render part to interfere with game view), save their 'Transform' reference to use as a mean to get position.
* Since you said you want to share them to future board object, you could pass them via static again, as you suggested.
* There is no more need to display them in inspector, since they are already visualized in scene view. And also editable/movable. (also remember that you lose changes while editing in play mode, find some way/plugin to save your work)

sample script for this idea could be like:

```
class Board : MonoBehaviour
{
    [Tooltip("Specify a scene object that contain all placeholders")]
    [SerializeField] Transform m_Root;

    static Transform[] s_AllPositions; // Shared between all Board instances. Could change to 2D array of your choice of implementation

    void Awake( )
    {
        // first board component that started will initialize this array,
        // second board onward will not repeat this work
        if( s_AllPositions == null )
        {
            s_AllPositions = new Transform[10];
            for( int i=0 ; i<10 ; i++ )
                s_AllPositions[i] = m_Root.Find( $"spawnpoint{i}" );
        }
    }
    void Update( )
    {
        s_AllPositions[i].position // Could use them like this
    }

```

### Post script

> Transform.Find() is heavily discourged by the experts in the community.

**IMO\>** It is very fine to use in one setup frame. Not called repeatedly in Update-manner since it can struggle the FPS.
> 1 votes

---
Tags: unity
---


# Question
Title: Momentum-wise accurate player controls in Unity regarding collisions
First post here. So I am a newbie to Unity and am willing to create a general character controller script to base my future characters. I understand a character's mechanics are pretty design (UX) dependent and I will need a few varients.

---

## What I want

Momentum-wise accurate physical simulation (as much as game performance allows). Some examples:

* If a flying canon-ball hits the player, it shall be crashed or flown away (some parameters would let us kill him in code hopefully) in accord with ball's momentum and player's mass.
* If the player hits a stationary canon-ball the ball most-probably wouldn't move (due to friction), yet if they push enough it gains some torque and rolls-over. Rotational and kinetic energy would need equal energy provided.
* Multiple player's could act upon a bunch of pieces just for fun.
* Regular character capabilities such as stair/ladder climbing, walking, etc.

## What I have read so far:

* CharacterController needs to write code for desired physics, and apt when not so interactive characters (e.g. first person shooter) are at hand.
* Rigidbody is good for non-agent dynamic items (e.g. falling boxes), and is hard to implement for agents (muscle powered humanoids, etc.), though possible.

## What I ask

How can I implement such momentum-wise accurate physics (regarding collisions) in Unity engine?

# Answer
The way I like to solve this is to use a dynamic `Rigidbody`, and give my character control script a notion of "traction" - the maximum force they can exert against the ground to alter their movement.

When traction is high, we can control the movement very precisely, like using a `CharacterContoller`. Imagine the character is wearing sturdy cleats with a planted stance so they can resist attempts to push them around.

External influences can still be used to modify this traction where we want to: for instance, we can check the material of the collider under the controller and use it to lower the current traction if, say, we're standing on slippery ice.

Or if the character is hit, we can put them into a stumbling state where they have reduced traction for a period of time, or until they drop below a certain speed, allowing strong hits to send them sliding/flying like a regular dynamic object.

The heart of this is a helper method something like this:

```
void PushToward(Vector3 targetVelocity, float maxStartingForce, float maxStoppingForce) {

    Vector3 deltaV = targetVelocity - rigidbody.velocity;

    Vector3 force = rigidbody.mass * deltaV / Time.deltaTime;

    // TODO: You may want to remove the component of force perpendicular to the
    // terrain, so that we can only push ourselves parallel to the ground.

    float forceLimit = Vector3.Dot(deltaV, rigidbody.velocity) < 0f ?
                    maxStoppingForce : maxStartingForce;

    force = Vector3.ClampMagnitude(force, forceLimit);

    rigidbody.AddForce(force);
}

```

Here we pass the velocity our character "wants" to have based on the player's input, but modulate that want according to a limiting force value (you could also parametrize these as accelerations instead of forces, to take the mass out of the equation). That way our control script respects some physical limits of how much "torque" our character's engine has, how much grip they have on the ground, how hard they can push against obstacles/etc. In contrast to a `CharacterContoller` that will always go exactly to the destination position, stopping only for collisions.

Character control generally feels best if you have a small window of acceleration when starting to move, but a very hard brake when releasing the controls or changing direction. That's why I like to use separate limits for "starting" and "stopping" forces - the latter can be much higher to keep the controls feeling tight and responsive, without making the character look too jerky.

These two force parameters become our avenue for managing our character's traction. When standing on ice, or when the character is in a stumbling/ragdoll state, (which we can trigger based on relative velocity/impulse of a collision inside `OnCollisionEnter`), we can scale both these force limits down to a small multiple, so the character exerts less and less control over their movement. Maybe even 0 to send them skating like a hockey puck. Then we can bring that multiplier back up to 1 when they're on solid ground or when they regain their footing after a knock back.

This gives us a controllable blend between pure rigid body dynamics-driven behaviour, and the tight control of a character controller, and we can dial the behaviour anywhere along that spectrum as the situation demands.
> 1 votes

---
Tags: unity, rigidbody, character-controller
---


# Question
Title: Problem importing Blender materials into Unity via FBX
I've created a simply low poly house in Blender (2.92) that I have imported into Unity as an FBX. Materials (simple colours) are all set up in Blender.

Initially this was all working fine. Colours all came across correctly (bit dark, but they always seem to do that), but now all of a sudden I am finding that in some cases the material for object A is applied to object B and the material for B applied to A, and so on. Most are fine, but not all (eg the window frames - meant to be white, are coming out dark wood, and the sills - meant to be dark wood, are coming out white.

The only thing that appears to have changed between working OK, and not working, is that I started to apply different colours to different faces of the walls for different rooms. However, the walls themselves are fine, all the right colours in the right places, it is just some other bits as above - and those bits were previously OK.

I've read there are issues in importing complex textures from Blender, but these are nothing complicated, just plain colours. Everything looks fine in Blender. What I do before creating the FBX is join most of the objects together in Blender with CTRL-J to minimise the number of objects going across, but again, this was all fine up to now.

I'd be grateful for any suggestions. I don't really want to have to reapply all material in Unity if I can avoid it.

UPDATE:

Having exported all the objects separately, the wrong ones actually have the wrong material assigned. For instance a window frame has material WindowSill assigned. It is the right colour for WindowSill - it just isn't meant to be that material at all, it is meant to be WindowFrame, and in Blender, that is what shows up as assigned.

# Answer
> 0 votes
**Might** have an answer to this.

One of the objects had an empty material slot - no material assigned. I added a material to this, and everything else came out right.

The empty slot must have caused Blender export to mis-index a material?

---
Tags: unity, blender, materials, fbx
---


title: Make part of albedo transparent

text:
# Question
Title: Make part of albedo transparent
I have a shader which creates a circle inside of a plane mesh. I would like to get get rid of the parts around the circle, which are the `r` and `b` parts of the `ALBEDO` but I can't seem to figure out how to do it.

The only thing I've managed to find is `ALPHA` but that changes the transparency of the entire shader and not just parts of it.

```
shader_type spatial;

float circle(vec2 position, float radius, float feather)
{
    return smoothstep(radius, radius + feather, length(position - vec2(0.5)));
}

void fragment() {
    ALBEDO = vec3(0, circle(UV - vec2(0), 0.5, 0.005), 0);
}

```

Which currently looks like:

# Answer
> 1 votes
`ALPHA` is what you want, except you want to set it to `1` anywhere you want it be transparent. So, we can reuse your `circle` function and do this:

```
shader_type spatial;

float circle(vec2 position, float radius, float feather)
{
    return smoothstep(radius, radius + feather, length(position - vec2(0.5)));
}

void fragment() {
    ALBEDO = vec3(0, circle(UV - vec2(0), 0.5, 0.005), 0);
    ALPHA = 1.0 - circle(UV - vec2(0), 0.5, 0.005);
}

```

*Yes, you could put `circle(UV - vec2(0), 0.5, 0.005)` in a variable and use that instead of calling `circle` twice, I didn't bother.*

Note that if I didn't put `1.0 - /*...*/` I would have the circle transparent, but we want the parts around the circle transparent instead.

This is how it looks like:

---
Tags: shaders, godot
---


title: Are there functions in GML?

text:
# Question
Title: Are there functions in GML?
I am trying to learn how to use GML to solve one of my previous prolems, as well as everything I have heard has said it is better to just learn it over DnD. As I have only ever programmed in python I am really fond of my functions, and it is at this point just how I think of code.

Is there any kind of functions similar to pythons in GameMaker?

# Answer
> 2 votes
**Yes.**

Open your favourite search engine and type in "GameMaker function" or "GML function" - your very first result will be this page from the official documentation:

> The general definition of a function is something like this: A function has an input and an output, and the output is related somehow to the input. In GameMaker: Studio you use functions as part of the program to make things happen in your game and there are a great number of GML (GameMaker Language) functions available to you, all of which are explained in the Reference section of the manual.
>
> **In GML a function has the form of a function name, followed by the input arguments between brackets and separated by commas** (if the function has no input arguments then just brackets are used). Here is an outline of the structure of a function:
>
> `<function>(<arg0>, <arg1> ,... <arg15>);`
>
> Generally there are two types of functions - First of all, there is the huge collection of built-in functions which are used to control all aspects of your game, and, secondly, any scripts you define in your game can also be used as a function (but not always).

You'll also find this other page from the documentation:

> **Scripts**
>
> Scripts are the way in which GameMaker: Studio permits you to **design your own functions**.
>
> ...
>
> **The Script Editor**
>
> When you open the script editor, you should first give your new script a name. This should be something sensible and easy to remember and recognise, and must not start with a number or have any symbols (except the under-bar "\_" symbol). **The name you give the script is the one you will use later as a function in code.** It is also a good idea to write some comments at the start of the script (see the above image) to outline the script arguments and how it should be used, especially if you are going to work as part of a team, or plan on using many scripts in your game.

Please remember to put in your best research effort before posting on this site. This is a question that's answerable in five seconds with a search engine or a quick look at the documentation for the tool you're using.

# Answer
> 0 votes
If you are looking for something similar to `def myFunction ():` in Python, you can use scripts.

In game maker studio, there are many built in functions you can use to design your games. If you want to create your own custom functions, you can use the a script tool in game maker studio. Once written, script can be called as a function in any game object of your game project.

---
Tags: game-maker
---


# Question
Title: Unity ScriptableObject Conversation Dialogue and Reading
I'm unsure as to how I would reference a scriptable object's variables within a struct from another class. I know I'd have to make a public `Conversation`, but I'm stuck understanding how I could access it's struct, and how I could access individual variables such as the `Position`, or `line` string array.

Is this method even viable or should I look at creating a different way of accomplishing a dialogue conversation scriptable object?

Thanks for any insights and help~

**My current code:**

<pre><code>[System.Serializable]
[CreateAssetMenu(fileName = "New Conversation", menuName = "Create/Conversation", order = 1)]

public class Conversation : ScriptableObject
{
    [System.Serializable]
    public struct LineData
    {
        public string[] line;
        public string[] option;

        public enum Position
        {
            BottomLeft,
            BottomCentre,
            BottomRight,
            MiddleLeft,
            MiddleCentre,
            MiddleRight,
            TopLeft,
            TopCentre,
            TopRight
        }

        public Position position;

        public enum TextSpeed
        {
            Normal,
            Slow,
            Fast,
            UltraFast
        }

        public TextSpeed textSpeed;

    }
    public LineData[] Line;

}

```
</code></pre>

# Answer
to be honest I didn't understand much about your codes but this is a right approach in many possible approaches:

any dialogue by a character can cause one or more dialogues from the same or other characters. so every dialogue can contain this model:

```
    class Dialogue
    {
public bool IsRoot;
public string Guid;// or any unique text
public string CharacterName;
public string DialogueText;
public List<string> ResultingDialoguesIds;
    }

```

you can make a ScriptableObject class that holds a list of this class(and also you can make a graph editor in unity to let designers make dialogues for you):

```
class LevelDialogues : ScriptableObject
{
public List<Dialogues> Dialogues;
}

```

when you want to start the dialogue in your game just query for dialogue that is signed as `IsRoot` and step by step generate Upcoming Dialogues. that is a simple way. maybe you can include some of your text formatting variable in Dialogue class.
> 0 votes

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


# Question
Title: Specifying a root signature in the HLSL code of a DXR shader
I've noticed that I cannot specify a root signature in the HLSL code of a DXR shader. For example, if I got a ray generation shader with the following declaration

```
[rootsignature(
    "RootFlags(LOCAL_ROOT_SIGNATURE),"  \
    "DescriptorTable("                  \
    "UAV(u0, numDescriptors = 1),"  \
    "SRV(t0, numDescriptors = 1))")]
[shader("raygeneration")]
void RayGen()
{}

```

`CreateRootSignature` yields the error message

> No root signature was found in the dxil library provided to CreateRootSignature. \[ STATE\_CREATION ERROR #696: CREATE\_ROOT\_SIGNATURE\_BLOB\_NOT\_FOUND\].

I've noticed that even when I add a typo (for example, write `roosignature` instead of `rootsignature`), the compiler doesn't complain about this typo. So, it seems like the whole attribute declaration is simply ignored.

If I change the code to a simple rasterization shader, everything works as expected.

So, is the specification of a root signature in the HLSL code of a DXR shader not supported?

# Answer
> 2 votes
The solution here is to build an explicit root signature binary and then use that one. The DXIL Library itself doesn't contain the signature, only references to it.

The actual command-line is a bit tricky and unintuitive, but it's much easier if you define your signature as a `#define`:

```
#define LocalRootSignature "RootFlags(LOCAL_ROOT_SIGNATURE),"  \
    "DescriptorTable("                  \
    "UAV(u0, numDescriptors = 1),"  \
    "SRV(t0, numDescriptors = 1))"

[rootsignature(LocalRootSignature)]
[shader("raygeneration")]
void RayGen()
{}

```

So you end up with a command-line like:

```
dxc /T rootsig_1_1 /E LocalRootSignature LocalRootSignature.hlsl -rootsig-define LocalRootSignature -Fo test.cso

```

The other problem is that the VS HLSL Properties dialog doesn't support this setup, so you have to use a CustomBuild command. Something like:

```
Command>dxc.exe /T rootsig_1_1 /E LocalRootSignature -rootsig-define LocalRootSignature /Fo"$(IntDir)\%(Filename).cso" "%(Fullpath)"</Command>
<Outputs>$(IntDir)%(Filename).cso</Outputs>

```

You can then load the `LocalRootSignature.cso` as a binary blob at runtime (using something like ReadData), and create the rootsig object from it :

#include "ReadData.h"

Microsoft::WRL::ComPtr<ID3D12RootSignature> m_rootSignature;

auto lrootsig = DX::ReadData(L"LocalRootSignature.cso");

DX::ThrowIfFailed(
    device->CreateRootSignature(0, lrootsig.data(), lrootsig.size(),
    IID_PPV_ARGS(&m_rootSignature)));
```

---
Tags: shaders, directx, raytracing, directx12
---


# Question
Title: Mcreator (Minecraft Mod-making) Compile Error
I'm trying to make a tool pack but every time I get the message:

```
New Dep: net.minecraftforge:forge:1.15.2-31.2.0_mapped_snapshot_20200514-1.15.1
> Task :compileJava FAILED
C:\Users\MCreatorWorkspaces\tree\src\main\java\net\mcreator\tree\item\ObsidianAxeItem.java:43: error: illegal start of expression
                     new ItemStack(, (int)(1))
                                   ^
C:\Users\MCreatorWorkspaces\tree\src\main\java\net\mcreator\tree\item\ObsidianHoeItem.java:43: error: illegal start of expression
                     new ItemStack(, (int)(1))
                                   ^
C:\Users\\MCreatorWorkspaces\tree\src\main\java\net\mcreator\tree\item\ObsidianPickaxeItem.java:43: error: illegal start of expression
                     new ItemStack(, (int)(1))
                                   ^
C:\User\MCreatorWorkspaces\tree\src\main\java\net\mcreator\tree\item\ObsidianShovelItem.java:43: error: illegal start of expression
                     new ItemStack(, (int)(1))
                                   ^
C:\User\MCreatorWorkspaces\tree\src\main\java\net\mcreator\tree\item\ObsidianSwordItem.java:43: error: illegal start of expression
                     new ItemStack(, (int)(1))
                                   ^
5 errors
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/4.10.3/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 7s
1 actionable task: 1 executed
BUILD FAILED

```

# Answer
> 1 votes
The first five lines are indicating where you have errors. Looking at the first one:

```
C:\Users\MCreatorWorkspaces\tree\src\main\java\net\mcreator\tree\item\ObsidianAxeItem.java:43: error: illegal start of expression
                     new ItemStack(, (int)(1))
                                   ^

```

This tell us that the code file `ObsidianAxeItem.java` has an error on line 43. The specific problem is the expression `new ItemStack(, (int)(1))`.

The `^` symbol underneath indicates where the problem is. In this case, your leading off with a `,` symbol in the parameter list for the `ItemStack` constructor.

The other four errors are similar, but in different code files. In terms of fixing the problem, you either need to remove the offending comma or possibly add one or more parameters in front of it. According to the `ItemStack` documentation I found, here are the valid ways to make a new `ItemStack`

> ```
> ItemStack(Block blockIn)
> ItemStack(Block blockIn, int amount)
> ItemStack(Block blockIn, int amount, int meta)
> ItemStack(Item itemIn)
> ItemStack(Item itemIn, int amount)
> ItemStack(Item itemIn, int amount, int meta)
> ItemStack(Item itemIn, int amount, int meta, NBTTagCompound capNBT)
>
> ```

I can't definitively say how to correct this because I don't know what the code originally looked like or what changes you were trying to make, but this should give you a start on fixing the errors.

---
Tags: java, minecraft-modding, modding
---


# Question
Title: convert world to screen coordinates with camera position and camera angle
Heyho :)

I'm trying to convert world coordinates to screen coordinates. I have available: fov, screen width, screen height, camera position, camera angle and obviously the position of the object in world space.

This is what I tried:

```
glm::vec3 world_to_screen(glm::vec3 pos,
                          glm::vec3 cam_angle,
                          glm::vec3 cam_pos) {
    glm::mat4 projection = glm::perspective(
        glm::radians(FOV), (float)SCREEN_W / (float)SCREEN_H, NEAR, FAR);

    glm::mat4 model(1.0);

    model = glm::translate(model, cam_pos);

    model = glm::rotate(model, cam_angle.x, glm::vec3(1.0f, 0.0f, 0.0f));
    model = glm::rotate(model, cam_angle.y, glm::vec3(0.0f, 1.0f, 0.0f));
    model = glm::rotate(model, cam_angle.z, glm::vec3(0.0f, 0.0f, 1.0f));

    glm::mat4 view = glm::inverse(model);

    glm::mat4 modelview = view * model;

    return glm::project(pos, modelview, projection,
                        glm::vec4(0, 0, SCREEN_W, SCREEN_H));
}

```

However it is not working, the output screen coords are over 30000 (I don't have a 30k monitor...) and I'm not sure what I did wrong. There is a correlation though, sometimes the screen coords happen to be in my screen (I draw an indicator at the position to see if I did it right) and if the object moves the indicator also moves with (kinda) the same speed etc.

Help is very much appreciated :) Thanks a lot in advance!

# Answer
> 1 votes
Here is a working code, for your reference -- I got it at https://www.gamedev.net/forums/topic/708406-opengl-screen-to-world-coordinates-varying-eye-position-and-look\_at-position/5432692/

```
void WorldToScreen (float screen[3], float world[3])
    {
        float s[4];
        s[0] = ( world[0] * MVP[0][0] ) + ( world[1] * MVP[1][0] ) + ( world[2] * MVP[2][0]) + MVP[3][0];
        s[1] = ( world[0] * MVP[0][1] ) + ( world[1] * MVP[1][1] ) + ( world[2] * MVP[2][1]) + MVP[3][1];
        s[2] = ( world[0] * MVP[0][2] ) + ( world[1] * MVP[1][2] ) + ( world[2] * MVP[2][2]) + MVP[3][2];
        s[3] = ( world[0] * MVP[0][3] ) + ( world[1] * MVP[1][3] ) + ( world[2] * MVP[2][3]) + MVP[3][3];

        screen[0] = s[0] / s[3] * viewportWidth/2 + viewportWidth/2;
        screen[1] = s[1] / s[3] * viewportHeight/2 + viewportHeight/2;
        screen[2] = s[2] / s[3];
    }

    void ScreenToWorld (float world[3], float screen[3])
    {
        float s[3];
        s[0] = 2 * screen[0] / viewportWidth - 1;
        s[1] = 2 * screen[1] / viewportHeight - 1;
        s[2] = screen[2];

        float p[4];
        p[0] = ( s[0] * MVPinv[0][0] ) + ( s[1] * MVPinv[1][0] ) + ( s[2] * MVPinv[2][0]) + MVPinv[3][0];
        p[1] = ( s[0] * MVPinv[0][1] ) + ( s[1] * MVPinv[1][1] ) + ( s[2] * MVPinv[2][1]) + MVPinv[3][1];
        p[2] = ( s[0] * MVPinv[0][2] ) + ( s[1] * MVPinv[1][2] ) + ( s[2] * MVPinv[2][2]) + MVPinv[3][2];
        p[3] = ( s[0] * MVPinv[0][3] ) + ( s[1] * MVPinv[1][3] ) + ( s[2] * MVPinv[2][3]) + MVPinv[3][3];

        float w = 1 / p[3];
        world[0] = p[0] * w;
        world[1] = p[1] * w;
        world[2] = p[2] * w;
    }

```

---
Tags: opengl, mathematics, matrix, coordinates, glm
---


# Question
Title: Distance between moving, rotated rectangles in snake game
I am trying to implement basic Snake game with movement based on timestep. For now I've got something along those lines:

Update function:

```
glm::vec2 headPosition = glm::vec2(m_segments.begin()->m_sprite.get_position());
float angle = m_segments.begin()->m_sprite.get_angle();

m_segments.begin()->move();

for (auto it = m_segments.begin() + 1; it != m_segments.end(); it++)
{
    glm::vec2 oldPosition = it->m_sprite.get_position();
    float oldAngle = it->m_sprite.get_angle();

    it->m_sprite.set_position(headPosition);
    it->m_sprite.set_angle(angle);

    headPosition = oldPosition;
    angle = oldAngle;
}

```

Move function:

```
glm::vec2 position(m_sprite.get_position());
position.x +=  cosf(glm::radians(90.0f - m_sprite.get_angle())) * VELOCITY_SCALAR;
position.y += -sinf(glm::radians(90.0f - m_sprite.get_angle())) * VELOCITY_SCALAR;

m_sprite.set_position(position);

```

Basically I set next segment position to the old position of previous segment. As expected spacing between those segments is equal to timestep value. How can I calculate position so I can manipulate spacing between those segments?

**EDIT**

I've found following implementation of snake segments following each other:

```
float distance = sqrt( pow( ( snakeParts[i-1].x - snakeParts[i].x ), 2) + pow( ( snakeParts[i-1].y - snakeParts[i].y ), 2 ) );

        // Rotate to look at previous part
        snakeParts[i].r = atan2( snakeParts[i-1].y - snakeParts[i].y, snakeParts[i-1].x - snakeParts[i].x ) + ( M_PI / 2 );

        // If the distance is too far, move to the correct distance
        if( distance > FOLLOW_DISTANCE )
        {
            snakeParts[i].x += sin( snakeParts[i].r ) * ( distance - FOLLOW_DISTANCE );
            snakeParts[i].y -= cos( snakeParts[i].r ) * ( distance - FOLLOW_DISTANCE );
        }

```

Source (follow function): https://github.com/Grzybojad/vitaSnake/blob/master/src/player.cpp

Could somebody help me to understand what's happening here so I can apply it to my implementation?

# Answer
The answer to my question is as follows:

```
auto currentPosition = it->m_sprite.get_position();
auto previousPosition = (it - 1)->m_sprite.get_position();

float distance =
sqrtf
(
    powf(abs(currentPosition.x - previousPosition.x), 2.0f) +
    powf(abs(currentPosition.y - previousPosition.y), 2.0f)
);

float a = currentPosition.x - previousPosition.x;
float b = currentPosition.y - previousPosition.y;
float angle = glm::degrees(atan2(b, a)) - 90.0f;
it->m_sprite.set_angle(angle);

if (distance > SPACING)
    it->move({ sinf(glm::radians(angle)) * (distance - SPACING), -cosf(glm::radians(angle)) * (distance - SPACING) });

```

Basic idea is that segments excluding snake's head are following each other with spacing between them applied.
> 0 votes

---
Tags: opengl, c++, timestep, snake
---


# Question
Title: How do I activate a game action when a UI button is held?
I want to make my button do stuff when the player holds it. In this case, I want to make a grab function: when the button is down the character can grab objects, but if the button is up they do not grab it.

I already have the function using the Standard Assets `CrossPlatformInput`.

Here is how I have configured my button so far:

Here is my script:

```
void Update()
{

    Physics2D.queriesStartInColliders = false;
    RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right * transform.localScale.x, distance, boxMask);

    if (PushKey())
    {
        isGrab = !isGrab;

        if (hit.collider != null && hit.collider.gameObject.tag == "Box" && isGrab)
        {
            box = hit.collider.gameObject;
            box.GetComponent<FixedJoint2D>().connectedBody = this.GetComponent<Rigidbody2D>();
            box.GetComponent<FixedJoint2D>().enabled = true;
            box.GetComponent<Rigidbody2D>().gravityScale = 1;
            box.GetComponent<Rigidbody2D>().mass = 1;

        }
        else if (!isGrab)
        {
            box.GetComponent<FixedJoint2D>().enabled = false;
            box.GetComponent<Rigidbody2D>().gravityScale = 6;
            box.GetComponent<Rigidbody2D>().mass = 6;
        }
    }
}

public bool PushKey()
{
    return CrossPlatformInputManager.GetButtonDown("E");
}

```

With this function, the first tap on the button means "grab activated" and the second tap means "grab deactivated", like a toggle. Instead, I want the grab to be active as long as the button is held.

# Answer
> 1 votes
First, change your event trigger. Right now you have both "Set Down State" and "Set Up State" called from the "Pointer Down" event.

You want to remove "Set Up State" from this event. Add a second event that listens for "Pointer Up" and attach your "Set Up State" to that one instead.

Then you want to change your code to check `GetButton()` (which returns true if the button is currently held), not `GetButtonDown()` (which returns true only the first frame that a button is pressed, and false for subsequent hold frames)

Something like this:

```
void Update()
{
    if (CrossPlatformInputManager.GetButton("E"))
    {
        if (box == null) {
            TryGrab();
        }
    }
    else if (box != null) {
        Drop();
    }
}

void TryGrab() {
    Physics2D.queriesStartInColliders = false;
    RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right * transform.localScale.x, distance, boxMask);

    // Use CompareTag, not .tag ==
    if (hit.collider != null && hit.collider.gameObject.CompareTag("Box"))
    {
        box = hit.collider.gameObject;
        var body = hit.rigidbody;
        var joint = box.GetComponent<FixedJoint2D>();

        joint.connectedBody = GetComponent<Rigidbody2D>();
        joint.enabled = true;
        body.gravityScale = 1;
        body.mass = 1;
    }
}

void Drop() {
    box.GetComponent<FixedJoint2D>().enabled = false;

    var body = box.GetComponent<Rigidbody2D>();
    body.gravityScale = 6;
    body.mass = 6;

    box = null;
}

```

As an aside, I'd also recommend naming your virtual button "Grab" not "E" - you might one day want to map it to a different control than "E", or give the player options to remap the control, so hard-coding a specific letter can cause trouble in the future.

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


# Question
Title: What is the proper way to create a camera matrix?
I am having issues when trying to create a camera transform. It seems to have odd distortions and it does not seem to rotate properly, though it will translate alright. While I have seen issues like this where the rotation does not work, I have not found any like my issue.

This is what I currently do to create the matrix:

```
Mat4 TransformLookAt(Vec3 from, Vec3 to, Vec3 world_up) {
    Mat4 view_matrix = Mat4New(1.0f);
    Mat4 rot_matrix = Mat4New(1.0f);

    Vec3 axis_n = Vec3Normalise(Vec3Subtract(to, from));
    Vec3 axis_v = Vec3Normalise(Vec3Cross(from, Vec3Cross(world_up, from)));
    Vec3 axis_u = Vec3Normalise(Vec3Cross(axis_n, axis_v));

    // Rotate on the X-axis
    rot_matrix.ax = axis_u.x;
    rot_matrix.ay = axis_u.y;
    rot_matrix.az = axis_u.z;

    // Rotate on the Y-axis
    rot_matrix.bx = axis_v.x;
    rot_matrix.by = axis_v.y;
    rot_matrix.bz = axis_v.z;

    // Rotate on the Z-axis
    rot_matrix.cx = axis_n.x;
    rot_matrix.cy = axis_n.y;
    rot_matrix.cz = axis_n.z;

    // Translate the camera
    view_matrix.aw = -from.x;
    view_matrix.bw = -from.y;
    view_matrix.cw = -from.z;

    view_matrix = Mat4ByMat4Multiply(view_matrix, rot_matrix);

    return view_matrix;
}

```

The camera is at (1.0, 0.0, 3.0) at is set to look at (0.0, 0.0, 0.0), which is where the centre of the cube is located. Here is what it looks like:

I would expect to see the left side and possibly top of the cube (since that is what this is supposed to do), but instead the cube has been distorted so that its left side cannot be seen.

That leads me to this question: If none of the methods like the one I've tried to implement works, then what is the *proper* way to create a camera matrix? What am I missing so that this does not work?

I understand how it should work, but I just can't get it to work. I feel like it might be something obvious, but I can't seem to figure it out.

# Answer
> 0 votes
I recommend that you try GLM for your math library. Here is some sample code from my camera class -- https://github.com/sjhalayka/opengl4\_stlview/blob/6ea4b942a8a5b40f923f5cd99da0cdec5e06e0e4/uv\_camera.cpp#L48

Until you switch to GLM, here is another code for your reference:

```
// https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml
// https://www.opengl.org/sdk/docs/man2/xhtml/gluLookAt.xml

void multiply_4x4_matrices(float (&in_a)[16], float (&in_b)[16], float (&out)[16])
{
    //   matrix layout:
    //
    //   [0 4  8 12]
    //   [1 5  9 13]
    //   [2 6 10 14]
    //   [3 7 11 15]

    out[0] = in_a[0] * in_b[0] + in_a[4] * in_b[1] + in_a[8] * in_b[2] + in_a[12] * in_b[3];
    out[1] = in_a[1] * in_b[0] + in_a[5] * in_b[1] + in_a[9] * in_b[2] + in_a[13] * in_b[3];
    out[2] = in_a[2] * in_b[0] + in_a[6] * in_b[1] + in_a[10] * in_b[2] + in_a[14] * in_b[3];
    out[3] = in_a[3] * in_b[0] + in_a[7] * in_b[1] + in_a[11] * in_b[2] + in_a[15] * in_b[3];
    out[4] = in_a[0] * in_b[4] + in_a[4] * in_b[5] + in_a[8] * in_b[6] + in_a[12] * in_b[7];
    out[5] = in_a[1] * in_b[4] + in_a[5] * in_b[5] + in_a[9] * in_b[6] + in_a[13] * in_b[7];
    out[6] = in_a[2] * in_b[4] + in_a[6] * in_b[5] + in_a[10] * in_b[6] + in_a[14] * in_b[7];
    out[7] = in_a[3] * in_b[4] + in_a[7] * in_b[5] + in_a[11] * in_b[6] + in_a[15] * in_b[7];
    out[8] = in_a[0] * in_b[8] + in_a[4] * in_b[9] + in_a[8] * in_b[10] + in_a[12] * in_b[11];
    out[9] = in_a[1] * in_b[8] + in_a[5] * in_b[9] + in_a[9] * in_b[10] + in_a[13] * in_b[11];
    out[10] = in_a[2] * in_b[8] + in_a[6] * in_b[9] + in_a[10] * in_b[10] + in_a[14] * in_b[11];
    out[11] = in_a[3] * in_b[8] + in_a[7] * in_b[9] + in_a[11] * in_b[10] + in_a[15] * in_b[11];
    out[12] = in_a[0] * in_b[12] + in_a[4] * in_b[13] + in_a[8] * in_b[14] + in_a[12] * in_b[15];
    out[13] = in_a[1] * in_b[12] + in_a[5] * in_b[13] + in_a[9] * in_b[14] + in_a[13] * in_b[15];
    out[14] = in_a[2] * in_b[12] + in_a[6] * in_b[13] + in_a[10] * in_b[14] + in_a[14] * in_b[15];
    out[15] = in_a[3] * in_b[12] + in_a[7] * in_b[13] + in_a[11] * in_b[14] + in_a[15] * in_b[15];
}

// centre is the look at position
void init_perspective_camera(float fovy, float aspect, float znear, float zfar,
                             float eyex, float eyey, float eyez, float centrex, float centrey,
                             float centrez, float upx, float upy, float upz,
                             float (&model_matrix)[16],
                             float (&view_matrix)[16],
                             float (&projection_matrix)[16])
{
    get_model_matrix(model_matrix);
    get_view_matrix(eyex, eyey, eyez, centrex, centrey, centrez, upx, upy, upz, view_matrix);
    get_projection_matrix(fovy, aspect, znear, zfar, projection_matrix);
}

void get_model_matrix(float (&in_a)[16])
{
    // Identity matrix
    in_a[0] = 1; in_a[4] = 0; in_a[8] =  0; in_a[12] = 0;
    in_a[1] = 0; in_a[5] = 1; in_a[9] =  0; in_a[13] = 0;
    in_a[2] = 0; in_a[6] = 0; in_a[10] = 1; in_a[14] = 0;
    in_a[3] = 0; in_a[7] = 0; in_a[11] = 0; in_a[15] = 1;
}

void get_view_matrix(float eyex, float eyey, float eyez, float centrex, float centrey, float centrez, float upx, float upy, float upz, float (&in_a)[16])
{
    vertex_3 f, up, s, u;

    f.x = centrex - eyex;
    f.y = centrey - eyey;
    f.z = centrez - eyez;
    f.normalize();

    up.x = upx;
    up.y = upy;
    up.z = upz;
    up.normalize();

    s = f.cross(up);
    s.normalize();

    u = s.cross(f);
    u.normalize();

    in_a[0] = s.x;  in_a[4] = s.y;  in_a[8] = s.z;   in_a[12] = 0;
    in_a[1] = u.x;  in_a[5] = u.y;  in_a[9] = u.z;   in_a[13] = 0;
    in_a[2] = -f.x; in_a[6] = -f.y; in_a[10] = -f.z; in_a[14] = 0;
    in_a[3] = 0;    in_a[7] = 0;    in_a[11] = 0;    in_a[15] = 1;

    float translate[16];
    translate[0] = 1; translate[4] = 0; translate[8] = 0;  translate[12] = -eyex;
    translate[1] = 0; translate[5] = 1; translate[9] = 0;  translate[13] = -eyey;
    translate[2] = 0; translate[6] = 0; translate[10] = 1; translate[14] = -eyez;
    translate[3] = 0; translate[7] = 0; translate[11] = 0; translate[15] = 1;

    float temp[16];
    multiply_4x4_matrices(in_a, translate, temp);

    for(size_t i = 0; i < 16; i++)
        in_a[i] = temp[i];
}

void get_projection_matrix(float fovy_degrees, float aspect, float znear, float zfar, float (&in_a)[16])
{
    const static float pi = 4.0f*atanf(1.0);

    // Convert fovy to radians, then divide by 2
    float f = 1.0f / tan(fovy_degrees/360.0f*pi);

    in_a[0] = f/aspect; in_a[4] = 0; in_a[8] = 0;                              in_a[12] = 0;
    in_a[1] = 0;        in_a[5] = f; in_a[9] = 0;                              in_a[13] = 0;
    in_a[2] = 0;        in_a[6] = 0; in_a[10] = (zfar + znear)/(znear - zfar); in_a[14] = (2.0f*zfar*znear)/(znear - zfar);
    in_a[3] = 0;        in_a[7] = 0; in_a[11] = -1;                            in_a[15] = 0;
}

```

---
Tags: opengl, camera, graphics
---


# Question
Title: Unity 2019 Error : com.unity.xr.arsubsystems@2.2.0-preview.3/Runtime/ImageTrackingSubsystem/XRImageTrackingSubsystem.cs57,30): error CS0506:
I am opening an old project created in 2019.3 inside my new Unity 2019.4. I got this error message in Unity Console:

```
Library/PackageCache/com.unity.xr.arsubsystems@2.2.0-preview.3/Runtime/ImageTrackingSubsystem/XRImageTrackingSubsystem.cs(57,30): error CS0506: 'XRImageTrackingSubsystem.Destroy()': cannot override inherited member 'Subsystem.Destroy()' because it is not marked virtual, abstract, or override

```

---

Please note that this current project does not use anything related to AR "Augmented Reality" or XR package.

I have already Googled this error message, but have not seen a solution yet.

However, I guess that this error likely comes from some conflicts in the AR or XR versions.

To fix this error, should I install or update the basic Unity XR or AR package ?

Thank you very much.

# Answer
I've figured out the answer to my own question. Here are the steps that help me to solve the issue:

1. Open Package Manager (From "Window" -\> "Package Manager")
2. Upgrade or install the latest version of the following packages:

AR Foundation

AR Subsystems

ARKit Face Tracking

ARKit XRPlugin

XR Plugin Managerment

XR Legacy Input helpers

XR Interaction Subsystems

**Note:**

1. You may not need to install/upgrade all of those packages unless the errors do not go away. Sometimes, you just need to upgrade/install 1 or 2 packages to solve the issues.
2. Usually, you have to upgrade to the latest versions of the packages to fix the issue. But, some times, you need to go back to the previous or older versions of the packages because the latest versions may have a bug.
3. There may be more AR or XR packages you need to install/upgrade as the list may grow when Unity adds more features in the future.
> 1 votes

---
Tags: unity, augmented-reality
---


# Question
Title: Mission system for a FPS game to force the player into following the storyline
Lately I've been working on a FPS game with a storyline in unity and I've encountered something that has been making my head explode for days. My objective is to be able to force the player to do a certain objective before being able to continue the game and to also give the new missions straight after the player has completed the past ones.

To help the player out I've created a panel with the description of the mission so that the player can check it out whenever he wants to. I've already created some code of my own for one mission but it seems to be a mess, I'm sure I should have different scripts for different things so that I didn't need to repeat code so much when I'm about to create a new mission script.

My problem is that I don't have the skills yet to do and I would like some suggestions: how could reduce my code and how I could create a universal script that would be able to recognize which missions are done and which are not, instead of doing it over and over again in every single mission script?

I'm kinda of new to unity and I've never posted to stack overflow so if I made any mistakes I'm sorry.

Extra information: the storyline is a linear, what I mean by that is that it doesn't give the player a choice to change it, it will always be the same and the quests/missions are here to force the player into following it. For example, the first mission is for the player to go down stairs and turn on two batteries. The second mission is for the player to kill a certain amount of enemies that appear right after.

# Answer
There is never just one solution for a problem. And this is one of those problems where you can ask 10 different programmers and will get 20 different answers.

First of all, what are our requirements? The requirements I would want for such a system are:

* Each mission should be a separate asset. No one humongous script including the whole story of the game.
* Each mission should be separately testable. I want to be able to place the player character in a room and then test a specific mission as quickly as possible.
* I would like to script each mission in C# (or perhaps in Bolt), because I won't yet know all the things I want missions to be able to do.
* Follow the KISS principle. Avoid building complex systems on top of Unity. Work with the engine instead of against it.

One solution I would try for this problem is this:

1. Create a folder "Missions" in your assets.
2. For each mission, create an empty prefab and a script with the same name. When the game is linear, I would consistently name them `Mission_01` to `Mission_99`. You might want to follow these names with a short description of the mission so you have an easier time navigating them (e.g. `Mission_17_TalkToBob`). Attach each of those scripts to the corresponding prefab.
3. Implement each of those scripts as follows:

* An inspector-accessible variable for the prefab for the next mission
* The Start-method sets up anything which needs to happen at the beginning of the mission. Update the UI to show the next objective, spawn things which are specific to the mission, and so on. (Although mission-specific game objects could also be implemented as children of the mission prefab)
* The Update-method checks if the fulfillment conditions of this particular mission are met. Both batteries are in the on-state, all enemies are destroyed, etc. When that's the case, the mission script destroys its own game object and instantiates the prefab for the next mission.

4. Add the prefab for the first mission (or the one you want to test) to the scene
> 1 votes

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


title: Unity - One time grab token in scene

text:
# Question
Title: Unity - One time grab token in scene
So let's say I have a project that contains 100 scenes or levels. Each scene contains a token (some coin or diamond) that can only be grabbed once. If the player takes the token in level N and replays level N the token should no longer be there but saved in some sort of wallet when he first grabbed it.

What would be the correct way to implement such a system? I'm looking just for a general idea of how this is implemented in most games.

# Answer
I recommend to serialize your token position and count in JSON format and deserialize it in each scene each time the scene is loaded.
> 0 votes

---
Tags: unity
---


# Question
Title: How to instantiate cubes at every given positions
I have a list of coordinates in 3D (XYZ)

> list = {{226.29, 485.28, 345.396}, {298.292, 108.226, 551.422}, {452.987, 164.874, 416.242}, {562.8, 29.4951, 297.651},{-610.087, -99.9056, -156.377}, {470.804, 12.3284, 428.671}, {590.609, 197.615, -137.146}}

I want to instantiate cubes at every given positions, how to define given list correctly in C# and use it as a vector3 ?

I tried something like that..

```
    for (int i = 0; i < 7; i++)
    {
        Instantiate(prefab, new Vector3(list[i]), Quaternion.identity);
    }

```

# Answer
I think should be ok to have a better list structure using List.

If your input is JSON Object, you can use SimpleJson.cs (search on google) to parse the data into a list.

And your coordinates would be:

```
List<Vector3> coordinates = new List<Vector3>() {
    new Vector3(  226.29f,   485.28f,  345.396f),
    new Vector3( 298.292f,  108.226f,  551.422f),
    new Vector3( 452.987f,  164.874f,  416.242f),
    new Vector3(   562.8f,  29.4951f,  297.651f),
    new Vector3(-610.087f, -99.9056f, -156.377f),
    new Vector3( 470.804f,  12.3284f,  428.671f),
    new Vector3( 590.609f,  197.615f, -137.146f)
}

```

Then you can instantiate your prefab in this way:

```
for (int i = 0; i < coordinates.Count; i++)
{
    GameObject go = Instantiate(prefab, coordinates[i], Quaternion.identity);
}

```
> 2 votes

---
Tags: unity
---


# Question
Title: What is the best rate at which to send updates to clients for a first person shooter NodeJS WebSocket server?
I developed a multiplayer FPS using WebGL, Nodejs and WebSockets. So far it is running great.

I am currently using setInterval(sendPlayerPositions, 16); to send updates to WebGL clients. Ideally I would use 16.66667 but this is not possible to my understanding.

So I wonder if I should change to setInterval(sendPlayerPositions, 10); to make up for the drift. And in general it might be a good idea to send stuff faster than the client frame rate (60 in most cases).

I also recently learned about process.nextTick and setImmediate and I wonder if I should use those instead...

Any advice ?

PS: I am currently using Nodejs 10 on my Linux server and Nodejs 14 on my dev machine.

# Answer
Sending updates constantly with each server frame limits the amount of data you can send and might cause unnecessary work on both - server and the client.

A good idea is to send only changes in the world and implement physics/behaviour for both - server and client.

> using setInterval(sendPlayerPositions, 16);

`setInterval()` is not a good idea for FPS networking. On a slow internet connection or any tiny networking issue or lag, you might get into problems.

The most efficient approach is to send data only when objects change:

* Object Created - where and what.
* Object Removed - where (and how - if you need explosion for example).
* Object starts to move - send direction and speed.
* Object speed changes - send speed change.
* Object stops - where it stops.
* Object changes direction while moving - send a new direction
* Object turns in place - where it looks.

Sure, you need to mirror units behaviour on the client and the server.

This way when the unit is not moving - you basically not sending any information. Of if many units on the screen moving simultaneously - you only send one message for it.

Also, as you expect the same behaviour on the client and on the server - you can start moving on the client instantly if the player moves or jump - and send a message at the same time w/o waiting for an update from the server. It will improve the user experience a lot.

Bulk messages also a good optimization - especially for RTS-like control. When you can select multiple units and make them move simultaneously - combining multiple messages into one will increase networking performance a lot for WS.

> process.nextTick and setImmediate

It will confuse your backend login a lot.

`setInterval` is still can be used as the main game loop, as you still might need NPC to walk w/o player interactions, or so some other updates. As long as it's not polluting networking.
> 0 votes

---
Tags: webgl, three.js, websocket
---


# Question
Title: DOTween: How to make a spring bounce effect?
I am looking how to make a bouncing effect with DOTween, like when the object is attached to a spring. How can I make an effect like this?

# Answer
> 4 votes
As it was not clear to me in the documentation I am exposing the answer here:

You can use

```
DOShakePosition(float duration, float/Vector3 strength, int vibrato, float randomness, bool snapping, bool fadeOut)

```

> Shakes a Transform's localPosition with the given values.

This configuration worked for me:

```
transform.DOShakePosition(2.0f, strength: new Vector3(0, 2, 0), vibrato: 5, randomness: 1, snapping: false, fadeOut: true);

```

Result:

---
Tags: unity, animation, tweening, dotween
---


# Question
Title: How does time-dependent camera rotation with a mouse work?
The commonly used equation for camera rotation with a mouse does not involve time. This make sense since higher frame rates have smaller changes in mouse position and vise-versa so it all evens out. If time slows down or speeds up, however, camera rotation from the mouse does not adjust accordingly. Just as you move slower when time is slowed, logically I also want rotating to be slower.

One option is to multiply the change-in-position of the mouse with the same multiplier I'm using on time, but shouldn't it be possible to have change-in-rotation and change-in-time in the same equation, independent from framerate?

# Answer
> 0 votes
I'm not quite sure what you mean in the last sentence, but usually the equation used for change-in-rotation multiplied by the time scale is actually framerate independent.
As you said, the mouse position change is framerate independent. And to get the rotation change according to time scale you multiply the mouse position change vector by time scale. The time scale is just from 0 to whatever where 0 is 'time has stopped', 1 is normal time, 2 is double time speed, etc, and it doesn't depend on framerate delta time.

---
Tags: camera, mouse, frame-rate, time
---


# Question
Title: How to teleport a game object to an empty game object?
I am trying to make a respawn system where if the player touches a plane, (the name of the object is tutlvl1\_flrdead) they get teleported to an empty object at player spawn named "RESPAWN". But, several tutorials and unity answers threads lead me to nowhere since they were written from back in 2013 or somewhere around there.

Code:

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

public class deathfloor : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        public gameObject myObject; //You can name it whatever you want.
        myObject.transform.position = new Vector3(3.076, 1.74, -3.651);
    }
}

```

How can I fix this to do what I need for my game?

# Answer
You've added only two lines that are not in the default script template, and neither of them are correct. One of them is illegal and will not compile, the other is simply useless and does nothing related to what you're aiming to achieve.

If you've really studied multiple tutorials and past Q&A threads and worked at this for *days*, I have to say that research and effort is not in evidence here, and you should very seriously consider putting this project on pause. Go pick up a beginner's tutorial - even if it's for a different kind of game than you want to make, and follow all the steps from beginning to end. Then do it again with a different tutorial. Then again with another.

Once you've gotten this amount of practice, you'll be able to write at least two lines of original code that actually compile, and you can consider resuming your current project with your better-developed understanding of how the language and engine work.

A script that does what you describe might look something like this:

```
// Class names use PascalCase, with an initial capital letter.
public class DeathFloor : MonoBehaviour {

    // Call this method when something enters the death floor's trigger volume.
    // Add a "2D" to the method name and Collider type if your game is 2D.
    // Be sure your player has a collider and dynamic rigidbody of character
    // controller component attached, and your floor's collider has its
    // "Is Trigger" box ticked.
    void OnTriggerEnter(Collider collider) {

        // Better yet, make this a member variable assigned in the inspector,
        // so you don't need to search for it at runtime.
        var spawnPoint = GameObject.Find("RESPAWN");

        if (spawnPoint == null) {
            Debug.LogError("Could not find a spawn point object named 'RESPAWN'");
            return;
        }

        // You might want to check whether collider is the player,
        // or some other object to ignore. Here I'll assume only the player
        // can fall into and activate this particular trigger.
        collider.gameObject.transform.position = spawnPoint.transform.position;
    }
}

```
> 3 votes

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


# Question
Title: How to vertically flip a DDS texture on import?
I have a program capable of rendering 3D graphics using Direct3D11 and it is currently compatible with two different texture formats, TGA and DDS. The code to read and load a TGA texture in memory I'm using was from Rastertek tutorials here and it handle TGA textures which are upside down by reading their bytes backwards, but the code to read and load a DDS texture I'm using is just `D3DX11CreateShaderResourcesViewFromFile` function from `D3DX11tex.h`, and it was good enough for me until a while ago.

Now I'm facing a problem as some of DDS textures I want to use are upside down in a similar way to the TGA textures, so I need somehow a code where I can control how it reads the texture so I can modify it to read the DDS texture upside-down.

I've read this article from Microsoft, but even their simplest code is far more complex than the code from Rastertek to TGA file. It's not clear to me how I can implement a method to read a DDS upside-down.

What I 'think' I understand about TGA's data it that its first 18 bytes are their header and the rest is 4 bytes for each pixel(in a RGBA style), but I really don't understand how DDS works.

# Answer
The simplest option for loading DDS files is probably to use the open source library that Microsoft provide - https://github.com/Microsoft/DirectXTK. That doesn't include functionality to turn them upside down when loading them though.

If you really want to do it manually, then take a look at https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide which documents the file format. It's not a simple file format though.

For example, the pixel data for the texture can be in a wide variety of formats, including things like BC7 compressed data (which is intended to be stored compressed in GPU memory, and get decompressed on the fly when read by the GPU). There's often data for more than one mipmap in the file too.

For compressed pixel formats like BC7, turning the texture upside down at load time isn't really practical. In addition, the compression is lossy, which makes it a bad choice for storing editable content anyway. Ideally you'd author content for the game in a losslessly compressed editable file format (e.g. .PNG or .PSD). You can then convert those source images into compressed DDS files with mipmaps for use in the game as part of the build process.

Microsoft also provide an open source library for creating DDS textures - https://github.com/microsoft/DirectXTex. That can be used to do things like loading a DDS file, turning it upside down, and saving it again, as well as the more sensible case of loading a PNG and converting it to a DDS.

As a side note, you can also easily flip a texture upside down when rendering with it, by adjusting the UV coordinates you use.
> 1 votes

# Answer
I'm a newbie too. In the answer above, it talks about decoding the DDS into a bitmap, and the re-encoding it once the rows have been reversed.

For your reference, here is a code to reverse the row order of a bitmap. Note that the image has 4 channels, hence the magic number 4. Where `Pixels` is a vector of unsigned char, of size `width*height*4`:

```
// Reverse row order
short unsigned int num_rows_to_swap = height;
vector<unsigned char> buffer(static_cast<size_t>(width) * 4);

if (0 != height % 2)
    num_rows_to_swap--;

num_rows_to_swap /= 2;

for (size_t i = 0; i < num_rows_to_swap; i++)
{
    size_t y_first = i * static_cast<size_t>(width) * 4;
    size_t y_last = (static_cast<size_t>(height) - 1 - i) * static_cast<size_t>(width) * 4;

    // Probably should have used std::copy here...
    memcpy(&buffer[0], &Pixels[y_first], static_cast<size_t>(width) * 4);
    memcpy(&Pixels[y_first], &Pixels[y_last], static_cast<size_t>(width) * 4);
    memcpy(&Pixels[y_last], &buffer[0], static_cast<size_t>(width) * 4);
}

```
> 0 votes

---
Tags: c++, textures, directx11, dds
---


# Question
Title: unsmooth blending with deferred shading and light volumes
So I implemented deferred Shading with a single full screen light pass (picture 2) (by passing the light-data as an array to the shader) and deferred shading with point light volumes (picture 1) (by rendering the back faces of spheres with the radius of the light). To "add" the color of two separate lights i used blending

```
glCullFace(GL_FRONT);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);

```

(while in the single light pass i just added the light values to the rgb color)   Else both light calculations are the same. Yet i get those weird "lines" where one pixel is being lit by more than one light source, whereas the single pass results in a smooth transition. I guess the problem is the blending equation, but i can't find a solution. The resulting color of the light volume shader looks like this

```
//d is the normal/light direction equation
//sp is the specular value
//att is the attenuation
//diff is the material color
color = vec4(diff * light_color * (d + sp) * att, 0.0);

```

The described values should be right.

# Answer
> 1 votes
You actually have noticeable banding in both images.

This can occur due to **quantization**.

Inside your shader, your local variables can be stored at floating point precision, able to represent differences in light intensity to a precision of \\$\pm 2^{-24}\\$ or better. But when you blend that result into a low dynamic range buffer that's storing just 8 bits per channel, you're limited to a precision of \\$\pm 2^{-9}\\$ \- that's a lot more coarse, so some rounding has to happen.

Worse, when you render your next pass and try to blend the result, you need to read the previously rounded value, modify it, then round it *again* \- so the rounding errors can stack up and get worse. (And sRGB vs linear conversions complicate this further)

Where a pixel that was just a little too dark to round up buts up against a pixel that was just a little too light to round down, you get a line - a visible step up in colour or intensity.

One robust fix is to use an HDR render target in a floating point format, so you can maintain your precision through multiple rounds of blending, and then resolve to a low dynamic range in a single pass at the end when presenting the finished frame.

This also costs a substantial amount of bandwidth, but it comes with other benefits, like being able to render high-contrast scenes with realistically bright hot spots on lights - something we usually have to compromise on to fit within the LDR limits. Optical effects like exposure adaptation, bloom/glow, lens flares, after images, and motion blur are all a little easier to implement correctly in HDR, whereas we sometimes have to cheat them to compensate for the clamped intensity range in LDR.

If you can't afford HDR rendering in your case, then another common way to battle banding is to add dithering. This diffuses out the quantization errors so they don't all align in obvious bands and lines. And if you're using a temporal anti-aliasing pass, it can smooth out the resulting noise to give you the smooth blend you wanted. This is how Inside achieves its low-contrast gradients, and the developers have shared some details about their specific dithering techniques.

# Answer
> 1 votes
I solved the problem by using an extra fbo for the point lights which's color texture then is passed to the deferred shader and added to the directional lights shading. This actually solved the banding, but is there a smarter way? FBOs cost a lot of bandwidth...

---
Tags: opengl, shaders, glsl, blending, deferred-shading
---


# Question
Title: How do I contiguously store and iterate over ECS components in C++?
I'm writing an entity component system and want to store each type of component separately and contiguously in memory in a way that's easy to iterate over.

`Component` is a simple base class from which like classes like `MoveComponent` derive.

I store components inside the `World` class:

```
struct World {
    ...
    std::vector<Component> components;
};

```

This would work fine if there was only one type of component, just a `Component` class. The problem is I don't know how to handle component subclasses. For example every `MoveComponent` should be stored contiguously in memory in a way that I can easily iterate over and process them.

I want to avoid this kind of copy-paste junk code for hopefully obvious reasons:

```
struct World {
    ...
    std::vector<MoveComponent> move_components;
    std::vector<PhysicsComponent> physics_components;
    etc.
};

```

I'd like to instead structure it in a way that permits iterating over each component of a certain type in a `World` like, for example, this (inspired by Overwatch's entity component system video, see here):

```
for (MoveComponent *mc : ComponentIterator<MoveComponent>(world)) { ... }

```

I'm at a loss as to how to implement this.

# Answer
> 1 votes
Entity component systems store data in one of three ways:

1. Centrally allocated arrays, accessable by all systems.
2. Contigious arrays of subsets of components that each system is interested in.
3. Contigious array of "entities" allocated in a centrally located memory buffer.

Naughty Dog uses scenario 1. An entity in this context is just a collection of numbers:

```
struct Entity
{
    static const int FOO = 0;
    static const int BAR = 1;
    int components[MAX_COMPONENTS];
    uint32_t id;
};

```

The "components" in the above code are either "-1" meaning "no component of this type, or a positive number, zero inclusive. This is an index to a centrally stored array of each set of components:

```
class ComponentAllocator
{
public:
    FooComponent foo_components[MAX_FOO_COUNT];
    BarComponent bar_components[MAX_BAR_COUNT];
};

```

Then any system can use some singleton/service locator pattern to get access to it, and iterate over it:

```
void FooBarSystem::update()
{
    for (auto& entity: entities) //entities is just a collection of type Entity
    {
        Foo& foo = getComponentAllocator().foo_components[entity.components[FOO]];
        Bar& bar = getComponentAllocator().bar_components[entity.components[BAR]];
        // Do something that requires interaction between foo and bar.
        // ...
    }
}

```

In scenario 2, your entity is the storage for each set of components, and each system stores a collection of proxies to that entity.

```
class Entity
{
public:
    std::map<std::type_index, std::shared_ptr<IComponent>> m_Components;
    uint32_t id;
    // some helpful functions for adding and removing via templates.
}

```

Each system stores a "proxy" to the entity, but only has access to a subset of the components. The component is also a "subject", from the subject/observer pattern, which allows any change in the component to propogate to any interested proxy. Whilst this is a good way to do things, it carries a lot of boiler plate, and isn't good for the novice to learn.

Scenario 3 just allocates a byte array, which gets set with as many components as you need. This is also complex, but very good for embedded systems, such as mobile devices and consoles.

I have purposely left out in depth explanations on most of this stuff, as it would take too long to explain all three, so I recommend you look them up and figure out which is best for you.

---
Tags: c++, architecture, entity-system, entity-component, entity-component-system
---


# Question
Title: How do I detect if my object is grounded?
I am trying to detect when an object is grounded.

My script right now is:

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

public class playermovement : MonoBehaviour
{
    public CharacterController2D controller;
    public Rigidbody2D rb;
    float horizontalMove = 0f;
    public float runSpeed = 40f;
    Vector2 forceapplied;
    public bool isGrounded;
    public float NumberJumps = 0f;
    public float MaxJumps = 2;
    public float jumpHeight = 7f;
    public CircleCollider2D bc;

    void Start()
    {
        forceapplied = new Vector2(0.0f, 30f);
    }

    void Update()
    {
        if(bc.gameObject.name == "Grid") {
            isGrounded = true;
            NumberJumps = 0;
        }
        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

        if (NumberJumps > MaxJumps - 1)
        {
            isGrounded = false;
        }
    }

    private void FixedUpdate()
    {
        if (isGrounded)
        {
            if (Input.GetButtonDown("Jump"))
            {
                rb.AddForce(Vector2.up * jumpHeight);
                NumberJumps += 1;
            }
        }
        controller.Move(horizontalMove * Time.fixedDeltaTime, false, false);
    }
}

```

In the inspector it always says that Isgrounded is false.

Can someone please help?

# Answer
> 0 votes
As @DMGregory pointed out, there are soo many tutorials on this subject, but since I have just answered a similar question (https://stackoverflow.com/a/66938817/1405906) I will try to address some parts of your code:

I assume that the collider (bc) is connected to your player. If so, bc.gameObject.name, will always be the name of your player object. That is why isGrounded never is set to true.

```
if(bc.gameObject.name == "Grid") {
        isGrounded = true;
        NumberJumps = 0;
    }

```

Physics should be done in FixedUpdate(), so that is good, but you should not try to get the input there. You might miss "one-time" events like a jump since it is not guaranteed that FixedUpdate() will be called in every frame. Move the check to Update() and store the jump flag in a boolean.

```
bool jump = false;
Update()
{
    if( Input.GetButtonDown("Jump") )
        jump = true;
    ...
}

```

Since you want to support a double jump (or more), the ground check should only be done before the first jump is launched. Once jumping, the player is in the air and there is no ground - but you still want to be able to do the second jump.

```
FixedUpdate()
{
    if(jump)
    {
        if( isGrounded || (NumberJumps>0 && NumberJumps<MaxJumps)
        {
            rb.AddForce(Vector2.up * jumpHeight);
            NumberJumps += 1;
        }
        jump = false; // Remember to reset the jump flag.
    }
    controller.Move(horizontalMove * Time.fixedDeltaTime, false, false);
}

```

Now it should work. For more information on how to do the ground-check, see my answer above, or google. Remember to reset the NumberJumps to 0 as soon as you are grounded. Good luck!

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


# Question
Title: How can I implement an aiming system like the Tank Stars mobile game?
I have been trying to implement the same aiming system as in Tank Stars, but I got a little stuck. I implemented simple stick aiming, which basically aims towards the stick movement.

In Tank Stars, it is much different compared to the simple aim stick. It remembers the last position and uses it as something like a pivot point.

I tried to implement a virtual pivot point as in the image given. The red circle is a virtual pivot. The green circle is the stick center point, and the green arrow is the supposed stick movement. This implementation kind of works, but I don't understand how I should update that pivot point.

Is my approach correct? What is the name of this aiming system? I need a bit of help with the math behind it.

# Answer
> 2 votes
To me it looks like the joystick is simply controlling two deltas; the `Y`-axis controls the pitch of the cannon and the `X`-axis controls the force or power of the cannon. I don't think you need to consider any pivot point for this.

Taking the pitch only as an example, you can implement it by keeping track of a `baseAngle` and a `deltaAngle` of the cannon. The current angle of the cannon is `baseAngle + deltaAngle`, and when the joystick is moved the `deltaAngle` is set to `distanceMovedVertically * some_constant`, where `distanceMovedVertically` is normalized to range `[-1, 1]`. `some_constant` is just scaling how much moving the joystick impacts the angle of the barrel.

When the joystick is released, the `baseAngle` is set; `baseAngle = baseAngle + deltaAngle` and `deltaAngle` is reset to zero.

Applying the same logic but using `distanceMovedHorizontally` allows for tuning the power or force of the cannon.

This approach yields a result that lets you control the cannon in this manner:

---
Tags: geometry, mobile, control, aiming
---


# Question
Title: Tower Defense: Sorting Algorithm with multiple weights (enemy AI)
I'm writing a sorting algorithm for a tower defense mobile game. As a quick synopsis, I have a "tower" that can shoot at incoming threats that are within X distance from the base of the tower.

Each incoming enemy, will have an associated {distance\_from\_tower} and {enemy\_weight}. The {distance\_from\_tower} will be a value between 0 and X (X being the max range of the tower). The {enemy\_weight} is a valued weight of "how important" it is to target that enemy mob. For example:

Three enemies:

Archer: {distance\_from\_tower} = 3 , {enemy\_weight} = 1

Knight: {distance\_from\_tower} = 7 , {enemy\_weight} = 5

Zombie: {distance\_from\_tower} = 10 , {enemy\_weight} = 3

Currently, I have a simple sorting algorithm that only sorts enemies by their distance from the tower. (So, in the above example, the tower would target: Archer --\> Knight --\> Zombie)

Which is a "fine" first logical step, but I want my towers targeting to be more robust. I want the sorting to take into account both the {distance\_from\_tower} AND the {enemy\_weight}. (For reference as well, these two values are updated at every Z seconds during the game, so they are constantly being recalculated).

I would like for the tower to be "smarter" and have a more robust sorting mechanism, that takes into account both weights, as said above. That could potentially lead to the tower targeting an enemy mob that is further away because the {enemy\_weight} value of that respective enemy mob is of "high priority". (So, in the above example, the inclusion of using both weights could lead to the tower targeting in this order: Knight --\> Archer --\> Zombie).

I've been digging around for a few possible solutions, such as using a Travelling Salesman approach, Dijkstra's algorithm, or Floyd's algorithm, and I can't figure out the best way to go about sorting using both weights in a manner that makes sense to me. Any intuition or help is greatly appreciated! Thanks!

# Answer
I'd argue that allowing the towers to disperse the firepower over multiple priorities is the opposite of "robust", because the towers would tend to **avoid finishing the targets**. To get a better mental model of priority, think about the cost of missed opportunity: how much damage would the player take, if given enemy would be allowed to pass.

For that calculation, the distance to the tower will be completely useless, unless there is the damage fall-off over the distance. The distance metric could actually make things much worse: imagine an almost killed enemy getting out of the range because the tower got distracted by someone closer.

Much more interesting metrics would be the distance, that the enemy has to travel — that's what the pathfinding algorithms would be needed for. Use remaining travel distance together with the tower's fire rate and the enemy's traveling speed to calculate the fraction of enemy's health that could be removed. Multiply that by the penalty to get the final missed opportunity cost.

Most TDs I've played so far are using much simpler heuristics, such as:

* choose one enemy and stick to it
* the enemy closest to the finish
* the enemy with least health

And yet these rules would work much smarter that just biting a chunk out of everyone while not actually trying to kill anyone.

---

If you *absolutely* want to stick to these 2 metrics, I advise to introduce some form of configurable target priority: either via the tower variety, or as an per-tower setting.

* The "killer mode" should prioritize most dangerous enemies, to minimize the risk in the long term.
* The "finisher mode" is for a single tower closer to the finish, to finish low-health enemies that slipped by. It should prioritize by distance. Although I want to repeat that distance metric is virtually useless.
> 2 votes

# Answer
There are two common approaches to the problem of prioritizing or sorting with multiple values of interest. I'm going to use your example of sorting based on distance & weight, but the idea holds true for multidimensional data in general & can be applied to a variety of algorithms.

### Ranked Data Comparison

This approach gives precedence (ranks) the various criteria and then applies them in some order. For instance, first you compare items based on weight. In the event that their weight are identical, you then compare them by distance.

In some respects this is similar to some of the ways we sorting names: comparing last name and in the event of a tie, comparing first name. While simple, this approach will only give good results if there is a meaningful precedence between your categories of data.

### Aggregated Data Comparison

**Math Version**
This approach combines the different criteria mathematically. For instance, we might use the formula `dist * weight` to combine the criteria into a single value. These values could then be used to sort the list.

This reveals a new problem: in your original problem statement small distances have priority over large ones whereas heavy weights have priority over low ones. Let's reverse the weights such that we have the following:

```
 Knight.weight = 1;
 Zombie.weight = 3;
 Archer.weight = 1;

```

Now when we apply the `dist * weight` formula, we get:

* the closest & most important enemies will get the lowest values
* the furthest & least important enemies will get the highest values
* enemies of equal distance will be prioritized by weight

And when sorted from least to greatest, your highest priorities will be at the front of your list. This makes more sense, though you will likely need to tune the weights to get good results with mixed situations.

**Math + Logic Version**
In some cases you'll want something more sophisticated to account for other aspects of your base problem. For example, let's say it takes two hits to neutralize an incoming enemy. If an enemy is so close that it can reach the tower before two shots can be fired at it, there might be no value in attacking it even though it is closest! By assigning it a special category that get sorted separately and appended after 'normal' enemies you can prevent your tower from wasting shots on it unless nothing else is present.

We could also have handled the last situation by assigning a very large penalty weight. But it's easy to turn the math into a mess with too many special penalties &/or bonuses. Sometimes it's simpler to add clean layer of game logic instead of hunting for a universal algebraic formula. This approach of using math and logic is what I have used the most often with problems of this sort.

### Bonus

By using different weight presets &/or formulas, you can also support different behaviors. For example, instead of assigning the weights directly to the enemies, we can give each enemy an index and give each tower type a table of enemy weights. Thus you could make a special tower that prioritized zombies simply by giving them a higher weight in that tower's lookup table.

### Conclusion

Ultimately, sorting/prioritizing a list means that for any two items we can definitively determine which one comes first. Even if there are multiple values of interest for each item, it comes down to using some means to say "this comes before that". Working through small example by hand and saying that out loud can help get the process started.
> 0 votes

---
Tags: c++, algorithm, sorting
---


title: 8-way aiming in run 'n' gun

text:
# Question
Title: 8-way aiming in run 'n' gun
I am developing a 2D run 'n' gun game in Unity and am having an issue getting the aiming to "feel right".

Some background:

* The player can aim in 6 directions when running (left, right, and the four diagonals)
* The player can aim in 8 directions when standing still and holding a lock button (left, right, up, down, and the four diagonals)

For digital input like a keyboard or D-pad, aiming is pretty easy. I do it with conditionals like

```
if (left_key.pressed && up_key.pressed) { aim_diagonal_up();}

```

But I have yet to find a satisfying way to deal w/ analog input from the thumbstick, should the player be using that instead of the D-pad.

**The first thing I tried** was a naïve implementation where I treated crossing various deadzone thresholds as, essentially, digital button presses, and then used conditionals like the above to set the aim (I'm using the popular Rewired extension to handle input in Unity, which makes this a breeze).

But even permuting all the different parameters in Rewired (for example, deadzone threshold, radial deadzone versus axial deadzone, sensitivity, and so on), I couldn't find a configuration that "felt good".

Either aiming w/ the joystick felt sluggish and unresponsive, or was too sensitive so that it was easy to accidentally shoot diagonally when you wanted to shoot forward. Some permutations felt better than others for aiming, but resulted in character movement itself feeling slugging (since any deadzones set on the thumbstick for aiming are also used for movement of the character left and right).

**The second thing I tried** was polling the thumbstick in my code to get its current position. If the length of the vector is above some custom deadzone I specify (say, 0.3), I aim according to the angle that vector makes with `Vector2.right`, looking at which sector of the unit circle the angle falls in (where there are 8 sectors, each spanning 45 degrees)

Here's a snippet:

```
    // aim
    Vector2 input_vector = Vector2.zero;
    input_vector.x = player.GetAxis("HorizontalAxis");
    input_vector.y = player.GetAxis("VerticalAxis");
    float length = input_vector.magnitude;
    input_vector = input_vector.normalized;
    float angle;
    angle = Utility.GetAngle(input_vector, Vector2.right);

    if (CustomInputManager.instance.IsJoystickConnected())
    {
        if (length > 0.3f)
        {
            // right forward
            if (-22.5f < angle && angle <= 22.5f)
            {
                upper_animator.Play("upper_shoot_forward");
                firing_point = forward_point.position;
            }

            // right forward up
            else if (-67.5f < angle && angle <= -22.5f)
            {
                upper_animator.Play("upper_shoot_diagonal_up");
                firing_point = diagonal_up_point.position;
            }

            // up
            else if (-112.5f < angle && angle <= -67.5f)
            {
                upper_animator.Play("upper_shoot_up");
                firing_point = up_point.position;
            }

```

You get the idea.

But even this felt off. I was still running into the problem of accidentally aiming diagonal when trying to aim forward (especially in frenetic situations), or accidentally aiming upwards or downwards when I was trying to aim diagonal.

**So the next think I did** was started studying run 'n' guns like Mummy Demastered, Blazing Chrome, and Valfaris (all games whose game feel I am trying to emulate). Then I noticed that it seems like they are doing something a bit more nuanced than just mapping thumbstick angle to equivalently-sized sectors of the unit circle.

For example, in Mummy Demastered, if you push the thumbstick directly up, once you pass the deadzone, the player will first aim diagonal up, then straight up, suggesting aiming in these directions is entirely based on the vertical component of the axis, rather than both vertical and horizontal. Aiming down, however, does not work like this in the game.

As another example, in Blazing Chrome & Valfaris, it seems like the sector for aiming diagonal up is not simply -22.5 to -67.5. It seems to start later than you'd expect, closer to -45, and extends closed to -90. The sector for aiming directly up actually feels quite small. And this feels good in game.

Similarly, the sector for aiming diagonal down starts earlier than you might expect, and this also feels good.

My question is not whether these games are actually using these techniques (I know that's off topic), but rather, **What are the different techniques you can use for implementing 8-way aiming in a 2D sidescrolling run 'n' gun (are there other nuanced techniques like those I think I've identified above)?**

**And what are efficient ways of actually implementing those techniques? (For example, I am currently using inequalities to capture the notion of sectors of a unit circle, when I'd like a more flexible representation that would allow me to easily tweak sector sizes as I balance the game feel)**

Some references

1. Mark Venturelli's Everything I Learned About Dual-Stick Shooter Controls
2. Josh Sutphon's Doing Thumbstick Deadzones Right

# Answer
I would suggest making a visual representation of what your joystick or D-pad is doing, so you can "see" your different input strategies. You could make a plane that lights up in segments in front, to the side, to the rear, when you use the joystick (or D-pad).

I made an illustration with colored squares, you could light them up based on input. In the code, when you detect joystick movement you can change the colors by calling the object's material renderer.  If you move the joystick "Up", and the value crosses your threshold, light up the square in front. Or move "Left", and see how far left you have to get to light up the left square.

My thinking is that when you see the sections light up as you move the stick, you can see the results of your calculations.

Also, if you take your threshold values and make them public, they will show up as sliders in the editor, and you can tweak them easily as you run tests.
> 1 votes

---
Tags: unity, c#, 2d, input, side-scroller
---


# Question
Title: Full-screen window hangs when debug break or crash (Windows/GLFW/Cocos2D)
I run into an issue if my game application becomes unresponsive when running in fullscreen on Windows. This mostly applies when I want to use breakpoints in Visual Studio, however if the application crashes, such as from a memory error, the window doesn't close.

I don't think this is strictly a WGL/GLFW/Cocos2D problem, since I have seen this problem in other Windows games, including ones that use Direct3D.

I searched around, but I can't find a definitive answer as to what causes this problem or how to fix it. From what I have read, this issue is only supposed to be caused by using HWND\_TOPMOST (or maybe HWND\_TOP); however, even changing all uses of that in GLFW to HWND\_NOTOPMOST doesn't seem to fix the problem.

I imagine that registering a custom signal handler using std::signal might work, but I am not sure which parts of the Windows API, if any, I should call in an exit handler, that would solve this problem.

# Answer
> 0 votes
The "problem" is that when running the application within Visual Studio, even in Release mode, it automatically attaches its debugger. This appears to be strictly related to Visual Studio trying unsuccessfully to become the active window underneath another unresponsive window. And of course the "deadlock" occurs because it is the MSVC debugger itself keeping the process open/suspended, and preventing the window from closing.

# Answer
> 1 votes
You did not mention if you are running Visual Studio and your game application on the same computer or not. If you have not already done so you should utilize the remote debugger functionality of Visual Studio when developing an application that changes the screen resolution.

It allows you to run Visual Studio on a development computer and then deploy and run your game executable on a remote computer. In Visual Studio 2019 (current for 2021), the Visual Studio remote debugging components are available for download on Microsoft.com: download link

This will save you a lot of head aches and allow you to debug more effectively.

---
Tags: windows, cocos2d-x, visual-studio, glfw, fullscreen
---


# Question
Title: Method subscribed to an event is called twice for every time the event is raised
I am trying to make an inventory system in Unity with ScriptableObjects and a text driver that displays the contents of an inventory. So far the code looks like this:

-An InventoryObject is defined as having a "Container" List of ItemObjects (simple scriptable objects, they just have a little information on the object as its sprite, its name, and whether or not it is stackable) and some methods to properly add or remove items (taking item stacking into account) from that list. https://pastebin.com/t4P3aGmi

-A PlayerInventory is a script that will be carried by the player's character. It contains a method for adding items collided with to its assigned InventoryObject instance. It also contains an OnItemPickedUp event that takes its InventoryObject instance as a parameter and passes it to listeners like UpdateDisplay. OnItemPickedUp is raised whenever a collision with a compatible item happens. https://pastebin.com/RsV7XYPp

-An UpdateDisplay script that listens to the OnItemPickedUp event and subscribes the ProcessInventoryToSingleString(InventoryObject \_inventory) method, that subsequently calls several methods to transform the contents of the InventoryObject's Container list into a single, formatted string. https://pastebin.com/N0nsvcWH

-The items are represented by giving a GameObject with a collider2D, aSpriteRenderer and script that contains the particular ItemObject's data and sets its SpriteRenderer's sprite to the ItemObject's.

The problem I'm having is that the method subscribed to the event is being called more than once for each time the event is raised. as shown by the debug logs. Sometimes it's called twice, sometimes even four. This results in my UI display showing more items than there are. https://files.catbox.moe/afa467.mp4

https://files.catbox.moe/6oxh9b.mp4

Here are pictures of the console debug logs:

I appreciate any help.

EDIT: These errors also appear. I'd like to believe that they're unrelated.

# Answer
I fixed it. There was a duplicate script subscribing twice to the events, but deleting it didn't fix the problem. The problem was in InventoryObject's AddItem() function. I forgot to add a Break; statement to the first Else, and that screwed everything up. Here's what it should look like.
> 0 votes

---
Tags: unity, events, inventory
---


# Question
Title: Refactoring fighting game Movement class responsibilities
I'm a web developer, new to C# and trying to learn Unity. I've learned the C# syntax, I understand how to write working code, although I'm having a hard time understanding when and to what classes should I split my code.

At the moment I'm doing a simple 2D fighting game, similar to Mortal Kombat, I've started out with creating some basic sprites and basic scripts for the environment, like clouds spawning and moving (the action takes places on a rooftop), created a fighter character with animations and started with writing the movement script.

At this point, the Movement script deals with moving, jumping, animations (also triggers for punches and kicks) and player input (I'm using the new Input System), also I want to make the game a two player game, so the Movement script also checks if the the fighter is controlled by player 1 or player 2 and everything is crammed in this little Movement script, not that it's too large, it's just funny that a Movement script is doing so much and furthermore I'll need to add health and attacks (not just animations).

I think it's about time I refactor, my questions are:

1. Should I create a Character, CharacterController, CharacterManager or whatever script that inherits from MonoBehaviour and other scripts as simple C# scripts, or should all of my scripts inherit from MonoBehaviour and be attached as components to my GameObject with references to each other?
2. Should I have a separate script for my animations or should they be at their respective scripts as in Attack, Movement, maybe Jumping or Death, whatsoever?
3. What would be the best way or what would be the ways of managing my Fighter GameObject to determine if it is controlled by player 1 or player 2 and if I'll plan to add an AI for example? Should I have a PlayerController/AIController inherit from Character script, or have a separate AI class, or just have some variable to check against?

My problem with various tutorials is that most of them don't give a larger overview of the whole picture, most of them just focus on a single subject: movement, animations, spawning, pathfinding or some other concrete thing or term, etc. and don't show how they are intertwined together.

# Answer
> 0 votes
There are lots of ways to structure an Unity project. There are no right or wrong ways, just ways which work or don't work for you.

But personally I am a fan of the single responsibility principle. This principle interpreted in the context of Unity scripting would mean that each MonoBehaviour should be responsible for one thing the object it's on does. Unity supports this pattern very well by its philosophy of composition over inheritance: A game object does not have a specific class. The properties and behaviors of each game object are the sum of its components.

A "Character" in a usual game does quite a lot of things. Attacking, walking, jumping, animating, taking damage and more. So each of these functionalities should be represented by a separate script. You often need to communicate between scripts (like temporarily disable movement while attacking or cancel an attack when taking damage). Such script-script communication can be realized with `GetComponent<OtherClass>()`, Messages or Unity Events.

`Controllers` (which I would call scripts which control a different game object than the one they are attached to) or `Managers` (which I would call scripts which orchestrates multiple game objects at once) do have their purposes. But in my opinion they should generally be avoided if the same feature can be feasibly implemented by a Component which acts on the object it's attached to.

Applying this philosophy to the topic of player input vs. ai input would be to create two different components `AIInput` and `PlayerInput` (when you are using the new input system, you might be able to use the PlayerInput component already provided). Those scripts should communicate with other classes in exactly the same way. This ensures that the AI can not accidentally cheat by doing things the player can not do. The difference is that one relays decisions made by the player through input, while the other relays decision made by code. And if you later want to add multiplayer, you can even create a 3rd component `NetworkInput` which relays decisions communicated through network messages. Only one of these components would be attached to each character.

---
Tags: unity, c#, software-engineering, refactoring, fighting-game
---


# Question
Title: Why is the Set new visibility doesn't resets the hair's skeletal mesh visibility to be visible?
The helmet is loaded when pressed a defined key and helmet is removed automatically by setting the remove on 2s delay. The Problem when the helmet is removed, the hairs visibility doesn't sets to be visible while blueprint is set to restore the visibility. `setvisibility` and `sethiddeningame` both are tested, none of them works. How to fix it? any help appreciated.

# Answer
The Problem is solved, actually the node was not connected to the remove function.
> 0 votes

---
Tags: unreal-4, blueprints
---


# Question
Title: ECS multiple materials per mesh (sub-mesh)
In my toy engine I currently have a `MeshComponent` and a `MaterialComponent`.

psuedo:

```
struct MeshComponent
{
    Ptr<Mesh> Mesh;
};

struct MaterialComponent
{
    Ptr<Texture> DiffuseTexture;
    Ptr<Texture> NormalsTexture;
};

```

This is fine, for when a single mesh uses a single material.

pseudo:

```
Entity entity = CreateEntity();
AddComponentToEntity(entity, meshComponent);
AddComponentToEntity(entity, materialComponent);

```

But now I want to consider the concept of "sub-meshes" (regions of a mesh that are rendered with a different material, but each sub-mesh shares the parent vertex list). I don't want my `Mesh` class to know anything about materials, and vice-versa.

What good approaches are there for "joining" multiple `MaterialComponent` to a single `MeshComponent`?

I've considered having an entity for each sub-mesh, but that seems brittle (not to mention overkill, as I'm only interested in `MaterialComponent`s).

pseudo:

```
struct MeshComponent
{
    Ptr<Mesh> Mesh;
    std::vector<Entity> SubMeshEntities; // Would need to ensure the indices match those of the sub-meshes
};

```

What other approaches are there?

# Answer
There is no point putting GFX assets into dedicated components:

* Assets are allocated outside of a component, no cache locality boost.
* Most assets are not involved in the ECS update graph anyways.

Components are better reserved for things that have a state that will be processed by the systems running on the CPU (e.g. skeletal and other animations) or must be exposed to those systems (e.g. current physical transforms).

But the compositional part of the GFX department (that consists mostly of the references to the assets and their combinations) would not benefit from the ECS designs, so there is no point shoehorning it into the ECS framework.

Just as with many (mainstream and not) engines, it makes sense to build a single ECS component for housing entire **scene graph** of an entity. It's a good fit for composing graphics, physics and other spatial components (such as cameras and triggers) together in a single tree.

Because a scene graph has no limits of ECS, you can do the composition the way that seems most natural to you. Do a single renderable that can combine multiple assets, or go for a full blown tree.
> 1 votes

# Answer
You think wrong that you need to put everything in a component in the **ECS**. Material can be part of a mesh but nothing else really and you don't have to keep multiple copies of entities in your mesh component. Think of your entity as a model, then:

```
struct MeshComponent
{
    std::vector<Mesh> meshes;
    std::vector<Material*> materials; // you want to keep the addresses/ids of the materials
                                      // and not to do copies
}

```

Where each index **i** in meshes, corresponds to the material at index **i**. Then your drawing method would look like:

```
for(int i = 0; meshes.size(); i++){
    // bind material to shader
    // bind vertexBuffer
    // draw with indices or vertices
}

```

**EDIT:** its important to do it in a single draw call
> 0 votes

---
Tags: entity-component-system
---