title: Screen position in Deferred Shading

text:
# Question
Title: Screen position in Deferred Shading
I am trying to implement a program in Direct3D 11 which uses techniques like deferred shading and shadowmapping, but when I create my gBuffers, the position looks strange. After researching a bit I think my problem is that my positions are in screen space.

Position, Normals, Diffuse and final picture

My problem is that I don't understand what translations I am supposed to make with what matrix, and where?

my pipeline currently looks like this

Geometry stage: Vertexshader -\> Hullshader (tessellation) -\> Domainshader (currently where I multiply my positions with the world, view and projection matrices) -\> Lightshader (put position, normals and diffusion into the gbuffers)

Shading stage: Computeshader (use all the gbuffers together with light information and shadowmaps to create final image)

I've seen people talking about reconstructing word position from the depth buffer, but how would I achieve this? Would that be done in the Computeshader?

Thank you in advance!

Edit: Heres the Domain and Pixelshader as requested, keep in mind that most of the domainshader is tessellation stuff.

Domainshader:

```
cbuffer MatrixBuffer
{
    matrix world;
    matrix view;
    matrix proj;

};

struct ConstantOutput
{
    float edges[3] : SV_TessFactor;
    float inside : SV_InsideTessFactor;
};

struct DomainShaderInput
{
    float4 position : POSITION;
    float2 texcoord : TEXCOORD0;
    float3 normal : NORMAL;
};

struct DomainShaderOutput
{
    float4 position : SV_POSITION;
    float2 texcoord : TEXCOORD0;
    float3 normal : NORMAL;
};

// DOMAIN SHADER

[domain("tri")]

DomainShaderOutput DeferredDomainShader(ConstantOutput input, const OutputPatch<DomainShaderInput, 3> patch, float3 barycentric : SV_DomainLocation)
{

    float4 worldPos;
    float3 vertexPosition, flatPosition;
    DomainShaderOutput output;

    output.texcoord = barycentric.x * patch[0].texcoord + barycentric.y * patch[1].texcoord + barycentric.z * patch[2].texcoord;
    output.normal = barycentric.x * patch[0].normal + barycentric.y * patch[1].normal + barycentric.z * patch[2].normal;

    vertexPosition = barycentric.x * patch[0].position + barycentric.y * patch[1].position + barycentric.z * patch[2].position;

    float3 vecProj0 = dot(patch[0].position - vertexPosition, patch[0].normal) * patch[0].normal;
    float3 vecProj1 = dot(patch[1].position - vertexPosition, patch[1].normal) * patch[1].normal;
    float3 vecProj2 = dot(patch[2].position - vertexPosition, patch[2].normal) * patch[2].normal;

    float3 vecOffset = barycentric.x * vecProj0 + barycentric.y * vecProj1 + barycentric.z * vecProj2;

    vertexPosition += 0.5f * vecOffset;

    output.position = mul(float4(vertexPosition, 1.0f), world);
    output.position = mul(output.position, view);
    output.position = mul(output.position, proj);

    output.normal = mul(output.normal, (float3x3)world);
    output.normal = normalize(output.normal);

    return output;
}

```

Pixelshader:

```
Texture2D diffuseTexture : register(t0);
Texture2D specularTexture : register(t1);
Texture2D ambientTexture : register(t2);

SamplerState sampleTypeWrap : register(s0);

cbuffer MaterialBuffer
{
    float specularPower;
    float3 pad3;
};

struct PixelShaderInput
{
    float4 position : SV_POSITION;
    float2 texcoord : TEXCOORD0;
    float3 normal : NORMAL;
};

struct PixelShaderOutput
{
    float4 position : SV_Target0;
    float4 normal   : SV_Target1;
    float4 diffuse  : SV_Target2;
    float4 specular : SV_Target3;
    float4 ambient  : SV_Target4;
};

PixelShaderOutput DeferredPixelShader(PixelShaderInput input) : SV_TARGET
{
    PixelShaderOutput output;

    output.position = float4(input.position.xyz, 1.0f);

    input.normal = normalize(input.normal);
    output.normal = float4(input.normal, 1.0f);

    output.diffuse = diffuseTexture.Sample(sampleTypeWrap, input.texcoord);

    output.specular = specularTexture.Sample(sampleTypeWrap, input.texcoord);

    output.ambient = ambientTexture.Sample(sampleTypeWrap, input.texcoord);

    output.specular.w = specularPower;

    return output;
}

```

# Answer
> 0 votes
Since you're using D3D11, the deferred rendering algorithm that includes reconstructing position from the depth buffer, is explained thoroughly with code in *Practical Rendering & Computation with Direct3D 11* by Zink *et al*.

---
Tags: directx, directx11, hlsl, matrix, deferred-rendering
---


# Question
Title: How to structure a dynamic turn based system?
I'm attempting to create a turn based battle system in Unity that is made up of dynamic events. Attacks may involve a lot of movement, animation, and often player input during the attack. The current idea is to have these "events" encompass the player's decision phase, actual attacks, in-battle cutscenes, and so on. I would like the order of these to be completely flexible as well to allow for modifying turn orders if needed and inserting cutscenes into the flow of the battle.

My current solution is made up of instantiated BattleEvent classes, with the current active BattleEvent being updated every frame in the battle manager. The battle manger can also change to a new event as needed.

Here's the bare bones of the event class:

```
public abstract class BattleEvent
{
    protected BattleManager _battle;

    public bool isCompleted = false;

    public BattleEvent(BattleManager battleManager)
    {
        _battle = battleManager;
    }

    public abstract void UpdateEvent();

    public abstract void StartEvent();

    public abstract void EndEvent();
}

```

However, I'm still unsure of the best way to manage queuing up events, ordering them, and maybe splitting up events into smaller parts, such as if an attack has the player move to a position first, it would be nice to have a reusable "sub" event that can handle that part.

Currently I am considering just adding a queue to the battle manager that allows me to order up events and insert them where they might be needed. Events themselves would handle queuing up the next event. I could also add a queue of sub events to the events themselves, but I am unsure if this is a bad idea for reasons I might not be aware of. I guess my question is, what is the most logical way to be structuring this for scalability, or am I headed in the wrong direction entirely?

# Answer
> 0 votes
One architectural pattern that is very useful for turn-based combat systems is the "stack machine".

This is a pattern that is similar to a state machine, in that you have states with enter, update and leave logic. But the difference is that you don't just have one active state. You have a list of states (the "stack") with the upmost state in the list being the active one. State transitions are done by pushing a new state on top of the list, or popping the current top state off, so the previous state becomes active again.

Let's take combat, for example. The base state of combat is when the player chooses an attack. The state stack has just one entry:

```
pick_attack

```

When the Update() event occurs, you execute the logic of the `pick_attack` state, which probably means to show a menu and listen to player input.

Now when the player picked an attack, you first want to play the attack animation and then resolve the attack damage by applying damage to the enemies. So you push those two states onto the stack in reverse order. The stack looks like this:

```
play_attack_animation
resolve_damage
pick_attack

```

The active state is now the `play_attack_animation` state. Which means the Update() method does no longer execute the logic for listening to player input. It executes the logic that manages the animation.

But now while the state is being updated, there is an event in the attack animation. The player is supposed to do a quick-time event that affects how much damage their attack does. So we push another state:

```
quick_time_event
play_attack_animation
resolve_damage
pick_attack

```

The play attack animation state is no longer active. Which means it no longer updates the animation. It's basically frozen while the QTE event is active.

When the QTE state is finished, it pops itself from the stack, so the play\_attack\_animation state continues where it left off:

```
play_attack_animation
resolve_damage
pick_attack

```

When the attack animation is over, it also pops itself from the stack:

```
resolve_damage
pick_attack

```

The resolve damage event subtracts the HP from the enemies and when it's over it notices that two of them died. Which means that their death animations need to be played before we can go back to the pick\_attack state. So as it removes itself, it pushes those states onto the stack:

```
play_death_animation
play_death_animation
pick_attack

```

So these two death animations take over. When the second death animation finished playing, it removes itself making room for the first:

```
play_death_animation
pick_attack

```

And then the first one removes itself so we are back to where we started with the player picking another attack:

```
pick_attack

```

---
Tags: unity, architecture, turn-based
---


title: Ue5 AI MoveTo does not work

text:
# Question
Title: Ue5 AI MoveTo does not work
I have been having problems working with AI MoveTo and created a very basic version in the hopes of finding the problem:

As you may see, I have one single character with the default skeletal mesh and one call to AI MoveTo at the beginning of the game to move to a hardcoded location. This call resolves with on fail callback.

I have versions with navmeshbounds volume & random navigatiable points & different characters etc.. but they also fail and figured this simplified version better underlines what the problem may be.

This aside, is there a way to look at details on why on fail is triggered ?

Cheers!

# Answer
> 0 votes
I did not change anything in particular, after a full restart next day, all the AIMove To blueprints started working as expected.

# Answer
> 1 votes
I see you were using a custom scene (Not the template ones). Keep in mind that when using AI navigation functions, you **must** have a *navMeshBoundaryVolume* in your scene where your desired AI Actor/Pawn would be contained inside that volume.

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


# Question
Title: playerOne.Score += 1; isnt working when my player picks up a item?
so currerntly i am working on a game just uses visual studio using C# but i have a issue where the player picks up a coin but it is not added to the score any reason why this would be.

```
void CheckPlayerOnPickup()
    {
        foreach (Pickups pickup in pickups)
        {
            Console.SetCursorPosition(1, 30);
            Console.Write(pickup.x + " " + pickup.y + " " + playerOne.X + " " + playerOne.Y);
            if (playerOne.X == pickup.x && playerOne.Y == pickup.y)
            {
                if (pickup.mychar == 'O')
                {
                    playerOne.Score += 1;

                }
            }
        }
    }

```

happy to supply more code if needed

# Answer
> 0 votes
A simple way to compare position with the Pythagorean theorem:

```
void CheckPlayerOnPickup() {
    float pickupDistance = 1.0f;
    foreach (Pickups pickup in pickups) {
        if (DistanceFrom(playerOne.X, playerOne.Y, pickup.x, pickup.y)  < pickupDistance) {
            if (pickup.mychar == 'O') {
                playerOne.Score += 1;
            }
        }
    }
}

float DistanceFrom(float x1, float y1, float x2, float y2) {
    float a = x2 - x1;
    float b = y2 - y1;
    float distance = (float)Math.Sqrt(a * a + b * b);
    return distance;
}

```

Here, we calculate the distance from the player to the pickup using the Pythagorean theorem; if it is less than the `pickupDistance` threshold, the player can earn a point. Game engines will come with lots of functions for common operations like measuring distance, but if you aren't using a game engine, you either need to write these helper functions yourself, or find a library that includes them.

Note that this approach of comparing position using distance is usually necessary when you have a continuous coordinate system (e.g. coordinates are `float`s or `double`s). If you have a discrete coordinate system (such as on a chessboard) where positions are represented with integers or other discrete values, you should be able to simply perform an equality check.

Put more simply:

```
int a = 3;
int b = 3;
Debug.WriteLine(a == b); //outputs "True"

float x = 3.0f;
float y = 3.00001f;
Debug.WriteLine(x == y); //outputs "False"

```

---
Tags: c#, visual-studio
---


title: How to break out of nested loops?

text:
# Question
Title: How to break out of nested loops?
Is there a way in Godot's GDScript to quickly/easily break out of nested loops?

For example:

```
# Check if the entire grid is filled.
filled = true
for x in grid:
    for y in grid[x]:
        if grid[x][y] == null:
            filled = false
            break # Break out of both loops?

```

PHP's `break` has an optional numeric argument that allows breaking out of nested loops: https://www.php.net/manual/en/control-structures.break.php
And Python has a `for...else` construct that can be used for this purpose: https://stackoverflow.com/a/3150107/4168619

Is there anything similar in GDScript?

# Answer
### Option1 Use an extra bool flag to break

```
extends Node2D

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = true
    for row in grid:
        var isBreak = false
        for data in row:
            if data == null:
                filled = false
                isBreak = true
                break
        if isBreak:
            break
    print(filled)

```

### Option2 Use return

```
extends Node2D

func isFilled(array):
    for row in array:
        for data in row:
            if data == null:
                return false
    return true

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = isFilled(grid)
    print(filled)

```

### Option3 flatten the array and use a single loop

(use `append` or `append_array` or `+`):

```
extends Node2D

func flatten1(array):
    var result =[]
    for row in array:
        for data in row:
            result.append(data)
    return result

func flatten2(array):
    var result =[]
    for row in array:
        result.append_array(row)
    return result

func flatten3(array):
    var result =[]
    for row in array:
        result+=row
    return result

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = true
    for element in flatten1(grid):
        if element==null:
            filled = false
            break
    print(filled)

```

(use `reduce`):

```
extends Node2D

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = true
    for element in grid.reduce(func(acc, x): return x+acc):
        if element==null:
            filled = false
            break
    print(filled)

```

### Option4 Just check if the entire grid is filled

(use `reduce` and `has`)

```
extends Node2D

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = !grid.reduce(func(acc, x): return x+acc).has(null)
    print(filled)

```

Related link: Godot Engine 4.0 documentation:Array
> 6 votes

# Answer
Some languages, such as `C#`, doesn't have such feature, but there are workarounds.

I'd prefer to put the code in a seperate function, and then use `return;` or `return [value];` the moment you got the value you wanted.

Going through each loop with a boolean check (like `if (filled == false) break;`) is also possible in larger nested loops.
> 2 votes

---
Tags: godot, gdscript
---


# Question
Title: "ModelImporterClipAnimation" Settings don't get applied to FBX
I am trying to edit animation file settings in the FBX file. I managed to load the file and extract animation clip names using the code below, however, I am unable to actually edit any of the settings of the FBX via script.

I am not able to pin point any specific issues with my code as it's not throwing any null errors and properly returning debug information.

Any help is appreciated!

```
    public void SetupAnimations(string path)
    {
        ModelImporter modelImporter = (ModelImporter)AssetImporter.GetAtPath(path);
        modelImporter.importAnimation = true;
        ModelImporterClipAnimation clip = GetModelImporterClip(modelImporter);

        Debug.Log(clip.takeName);
        clip.loopTime = true;
        clip.mirror = true;
        clip.ConfigureClipFromMask(bothHandsAvatarMask);
    }

    static ModelImporterClipAnimation GetModelImporterClip(ModelImporter mi)
    {
        ModelImporterClipAnimation clip = null;
        if( mi.clipAnimations.Length == 0 )
        {
            //if the animation was never manually changed and saved, we get here. Check defaultClipAnimations
            if( mi.defaultClipAnimations.Length > 0 )
            {
                clip = mi.defaultClipAnimations[0];
                Debug.Log("Getting Default Animations");
            }
            else
            {
                Debug.LogError("GetModelImporterClip can't find clip information");
            }
        }
        else
        {
            clip = mi.clipAnimations[0];
            Debug.Log("Getting Changed Animations");

        }
        return clip;
    }
```

# Answer
1. Select all animation fbx, go to Animation Tab and enable Custom Properties, Hit Apply,
2. This step will create the clipAnimations: meta file in .meta files.
3. Use the following code to do the changes, here I am using the changes needed by me but you can use the changes you need. \`using System.IO; using UnityEditor; using UnityEngine;

public class AnimationModifier : MonoBehaviour { public string rootFolderPath = "Assets/Models"; // Specify the root path where to start looking for model files. public ModelImporterAnimationCompression animationCompression = ModelImporterAnimationCompression.Off;

```
public bool importAnimation = true;

[ContextMenu("Modify Animations")]
public void ModifyAnimations()
{
    string[] filePaths = Directory.GetFiles(rootFolderPath, "*.fbx", SearchOption.AllDirectories);
    foreach (string filePath in filePaths)
    {
        string assetPath = filePath.Replace("\\", "/");  // Convert Windows-style paths to Unity-style paths
        ModelImporter modelImporter = AssetImporter.GetAtPath(assetPath) as ModelImporter;
        modelImporter.importAnimatedCustomProperties = true;
        modelImporter.SaveAndReimport();
        modelImporter.importAnimatedCustomProperties = false;
        if (modelImporter != null)
        {
            if (modelImporter.clipAnimations != null && modelImporter.clipAnimations.Length > 0)
            {
                var name = Path.GetFileNameWithoutExtension(assetPath);
                var clip = modelImporter.clipAnimations[0];
                clip.firstFrame = 0;
                clip.name = name;
                clip.takeName = name;
                clip.loopTime = true;
                clip.keepOriginalPositionXZ = true;
                clip.keepOriginalPositionY = true;
                clip.keepOriginalOrientation = true;
                clip.lockRootRotation = true;
                clip.lockRootHeightY = true;
                clip.lockRootPositionXZ = true;
                modelImporter.clipAnimations = new []{clip};
            }

            modelImporter.animationCompression = animationCompression;
            modelImporter.importAnimation = importAnimation;
            modelImporter.SaveAndReimport();
        }
        else
        {
            Debug.LogWarning("No model found at " + assetPath);
        }
    }
}

```

} \`
> 0 votes

---
Tags: unity, animation, import
---


# Question
Title: Why is this Update function never Called?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Mos_Giant : Enemy
{
    public override void update()
    {
        Debug.Log("AAA");
    }

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

}

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

}
}

```

# Answer
> 5 votes
C# is case sensitive. Case sensitivity defines whether uppercase and lowercase letters are treated as distinct (case-sensitive) or equivalent (case-insensitive).

That means `update()` is not the same as `Update()`.

Change it to uppercase and it should now be called.

---
Tags: unity
---


# Question
Title: Physics.CheckSphere not accounting for changes to object transform
My current project is a turn-based board game in Unity. Here is what I am trying to accomplish and the issue I am having: In Start, I generate the board, then populate the surrounding area with decorations (trees, rocks, etc...), without overlapping with the board itself. To accomplish this, I essentially sample lots of points and use Physics.CheckSphere for overlap with the board, and only add an object if there is no overlap.

It all works perfectly well - except if before populating the area with decorations I translate or rotate the board. The Physics.CheckSphere calls treats it is as if the translation / rotations have not been made. What's strange is that a Debug call shows that the Physics.CheckSphere is indeed happening AFTER the board is translated / rotated. My guess is that since I am translating / rotating things in Start, the Physics system has not processed that the colliders have moved, and thus is still detecting them in their original positions. Is that correct, and is there any fix / alternative?

GameStateManager:

```
    void Start()
    {
        BoardManager.GenerateBoard(raceSettings.Stage);
        environmentManager.Generate(raceSettings.Stage.Environment, cameraController.Bounds);
    }

```

BoardManager:

```
        public void GenerateBoard(Stage stage)
{
    _board = new();
    Transform end = this.transform;
    foreach(TrackSetting trackSetting in stage.Tracks)
    {
        GameObject newTrack = Instantiate(trackSetting.track, end.position, end.rotation);
        newTrack.transform.parent = this.transform;
        TrackTile track = newTrack.GetComponentInChildren<TrackTile>();
        end = track.End;
    }
    CalculateBounds();
}
void CalculateBounds()
{
    _bounds = new();
    foreach(Transform square in this.transform)
    {
        foreach (Transform t in square.transform)
        {
            _bounds.Encapsulate(t.position);
        }
    }
    if (_bounds.size.z > _bounds.size.x)
    {
        //transform.rotation = Quaternion.Euler(90f * Vector3.up);
        //transform.SetPositionAndRotation(transform.position, Quaternion.Euler(90f * Vector3.up));
        transform.Rotate(Vector3.up, 90f);
        Debug.Log("ROTATE");
        CalculateBounds();
    }
}

```

EnvironmentManager:

```
        void SpawnEnvironment(EnvironmentSettings es, Bounds bounds)
{
    Debug.Log("BUILD WORLD");
    worldBounds = bounds;
    worldBounds.Expand(boundPadding);

    List<Vector2> points = PoissonDiscSampling.GeneratePoints(es.Range, worldBounds, rejectionSamples);
    foreach (Vector2 point in points)
    {
        Vector3 newPosition = new Vector3(point.x, 0f, point.y);
        if (Physics.CheckSphere(newPosition, es.Clearance)) continue;

        GameObject environmentalObject = GameObject.Instantiate(defaultTreePrefab);
        environmentalObject.transform.position = newPosition;
        environmentalObject.transform.parent = this.transform;
    }
}

```

# Answer
> 0 votes
You can use `Physics.SyncTransforms()` to synchronize transform changes to the physics engine.

---
Tags: unity, c#, collision-detection, physics, collider
---


# Question
Title: Cannot access pawn from attached actor component
I have a pawn blueprint that contains some AI movement code, and looks like this:

Now I'm attempting to move that functionality into an actor component so it's easily transferrable to other enemy types.

However, I'm having trouble grabbing the pawn itself for the AI Move To. Get Owner isn't compatible since it specifically wants an Actor Reference and not a Pawn Reference. Get Pawn Owner doesn't like that 'self' is an Actor Component and not a Pawn Movement Component.

Is there some other, magic function I should be using? Do I need to rewrite my entire entity as an actor instead of a pawn?

# Answer
I found out it's possible to cast from an actor to a pawn inside a blueprint.

That is so useful and I'm sure will solve a lot of problems going forward.
> 0 votes

---
Tags: ai, blueprints, unreal-5
---


# Question
Title: Make a script move a game object's transform when it has an animation
I am working on a melee game project, and i have a gameobject which holds the weapon, and it is what moves when i swing the weapon. It has an idle 'animation' (its just one keyframe of the idle position of the weapon), and then the 4 swing directions.

I do not use the animator to handle the transitions between idle and swinging, i want to use a script for that so i can control the windup speed easier, and also incase i decide to add feints and stuff that would interrupt the windup process, but i do use animations for the swing directions. What i want to happen is the script controls moving from the idle position to the very start of the swing position, and then the swing animation plays.

However, as long as the animator is active, any attempt to move the weapon with code does not work, it follows the animator instead. I tried removing the animation from the idle state, so theoretically there would be no animation playing when the idle state is active, and i also tried removing the keyframe from the idle animation, thinking that would work, but it didnt work either.

So, how can i still move the weapon to its swing starting point using code, even if there is an animation playing? Or just override what the animation is telling it to do. I could just script the swing animations but i would rather not.

# Answer
I found a solution. What i did was make an animation that has one keyframe on the start of the weapons attack position, or the end of the windup. Then what i did was make a blend tree, with the idle position in the middle of the tree, and then the new animation on the side the windup begins on.

Make a float parameter. The idle animation plays when the parameter is 0, the new animation plays when the parameter is 1. Then in the script you can use

```
windupLerp = Mathf.Clamp(windupLerp+Time.deltaTime,0,1);

Animator.SetFloat("parameterName", windupLerp);

```

Then when the windup lerp is 1, you play the swing animation. So i suppose to answer the original question, there probably isnt a way, but this is a solution to my specific problem.

Also, this solution worked really well for me because there are multiple attack directions. I can have a 2d blend tree and have windups to each direction, just by making more animations with the one keyframe at the end of the windup.
> 1 votes

# Answer
> However, as long as the animator is active, any attempt to move the weapon with code does not work, it follows the animator instead.

As you've noticed, any properties that are animated by the Animator will have their values set by the Animator every frame, overriding any changes to those properties that you make in code.

> i also tried removing the keyframe from the idle animation, thinking that would work, but it didnt work either.

My experience has been that this aspect of the animator is very buggy. Sometimes, when you remove a property from all animations, the animator still overrides that property every frame. I'm not sure exactly what the cause is, but it's very difficult to fix. IIRC one fix is to recreate the animations and Animator, but this can be very tedious.

A common solution to the general problem (changes to position are overridden by the Animator) is to utilize the transform hierarchy. For example, you might make a "SwordContainer" GameObject and make the sword a child of the "SwordContainer". Then, the Animator would move the sword, while your script would move the "SwordContainer".

Another solution is to temporarily disable the Animator while you are manually moving things around with code, though it can be a headache to ensure that nothing suddenly jumps to a new position when you next turn the Animator on.

---

However, before you spend lots of time and effort reinventing the wheel, perhaps you should reconsider. The things that you want to do should be possible with the Animator:

> i want to use a script for that so i can control the windup speed easier

You can do this with an Animator by adjusting the `Speed` property of the Animator

> also incase i decide to add feints and stuff that would interrupt the windup process

The Animator already supports transitioning from one state to a different state before the animation finishes, and even supports interrupting a transition between states.
> 3 votes

---
Tags: unity, animator
---


title: Display image by using tooltip

text:
# Question
Title: Display image by using tooltip
I want to display the image using a tooltip. So when I point to the 3dobject, it will display the image that I already created. Right now I already set the sprite in the tooltip but I have an error in the function **HideToolTip**. In this function, I want to hide the image when the arrow/cursor is away from the object.

**------TooltipManager Script-----**

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

public class TooltipManager : MonoBehaviour
{
    public static TooltipManager _instance;

    public Image imageComponent;

    //public SpriteRenderer imageComponent;
    // SpriteRenderer spriteRenderer = gameObject.GetComponent<SpriteRenderer>();

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            _instance = this;
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        Cursor.visible = true;
        gameObject.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Input.mousePosition;
    }

    public void SetAndShowToolTip(Sprite Image)
    {
        gameObject.SetActive(true);
        imageComponent.sprite = Image;
    }

    public void HideToolTip()
    {
        gameObject.SetActive(false);
        imageComponent.sprite = Sprite.Destroy();
    }

}

```

Right now, I have an error in **HideToolTip** function.

**------Tooltip Script-----**

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

public class Tooltip : MonoBehaviour
{
    public Sprite Image;

    private void OnMouseEnter()
    {
        TooltipManager._instance.SetAndShowToolTip(Image);
    }

    private void OnMouseExit()
    {
        TooltipManager._instance.HideToolTip();
    }
}

```

# Answer
> 1 votes
If you look up the documentation of the method Destroy, you will see that it requires the thing you want to destroy as an argument.

So instead of `imageComponent.sprite = Sprite.Destroy();`, you would write:

```
Destroy(imageComponent.sprite)

```

However, destroying the whole sprite asset just to hide the tooltip might be a bit radical. It would be better to use the `Image.visible` property:

```
imageComponent.visible = false;

```

Note how reading the documentation can literally save you days of waiting for people to answer your questions on the Internet. Being able to find and read documentation is one of the most important skills for a software developer.

# Answer
> 0 votes
You can use Unity event system and **IPointerEnterHandler**, **IPointerExitHandler** interfaces so something like this:

```
using UnityEngine;
using UnityEngine.EventSystems;

public class Tooltip : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    [SerializeField] private GameObject tooltipPanel;
    public void OnPointerEnter(PointerEventData eventData)
    {
        tooltipPanel.SetActive(true);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        tooltipPanel.SetActive(false);
    }
}

```

Just make sure you have a physic raycaster on your camera and collider on objects. If you use it on UI make sure the UI objects has raycast target enable.

---
Tags: unity, c#, collision-detection, raycasting, image
---


# Question
Title: Best way to store player data like scores, rewards, login info, checkpoints etc for offline PC games?
I am creating a VR game in Unity, it will be an offline PC game. I want to store user login info, score, checkpoints, learning points, rewards etc in the database. I checked out firebase but it doesnt work for pc games apparently. I only have Oculus Rift to test my game else I wouldve switched to android as which platform the end game is for doesn't really matter. What are some other good alternatives? What should I use for my pc game?

I will later use the score and rewards to create learning points which will then be processed in an ML model to perform categorization.

Moreover, it is possible that I integrate firebase with unity while keeping my game in Windows platform while I test it on Rift and in the end I build it for android so it works fine with firebase?

# Answer
> 1 votes
There's no single "best way" to store data. Which approach works best will depend on the complexity and volume of your data, and the way you interact with it.

With video game save data that just needs to be *loaded* rather than *queried*, a common solution is to serialize the data into a text (e.g. JSON) or binary format, and save that in one or more files.

If you're storing a very large amount of data, or data that's fairly complex or frequently queried, you can use a database. The easiest way to integrate a database is to find an existing C# library or Unity plugin for local database support; a common choice is SQLite, but you'll have to determine whether SQLite is appropriate for your use case.

If you determine that a database is the best solution for your needs, you should try to avoid anything that requires the player to install or run a database server.

---
Tags: unity, databases
---


title: Can I upgrade Unreal 4.27 to 5?

text:
# Question
Title: Can I upgrade Unreal 4.27 to 5?
I tried to get Unreal 5 directly but I couldn't, the only option on the table was unreal 4.27, can I upgrade to 5 after 4.27 or do I need to consume another 20 gigs for 5?

# Answer
> 2 votes
You cannot upgrade your installation to 5.X, as major unreal engine versions are separate installations (i.e. 4.26, 4.27, 5.0, 5.1, and 5.2 are all their own installation). You would have to download your desired 5.X version separately.

However, if you download 4.27.2, for example, if there ever is a 4.27.3 it will download the new files to the 4.27.2 installation, changing it to 4.27.3.

If you're asking if you can change your project's unreal engine version, then yes, you can freely change what engine version your project uses (if installed of course). For example, you can change your project from using 4.27 to using 5.2, but keep in mind that there are many deprecated features in newer versions from older versions.

Changing the project version is as easy as right-clicking on the project file -\> switch unreal engine version context option.

---
Tags: unreal-4, unreal, unreal-5
---


# Question
Title: Consistent cross platform procedural generation
What techniques have people successfully used or can suggest to deal with a consistent cross platform math for procedural world generation? Also, if you have done this, what were the pros and cons of your approach? In particular, I'm trying to decide whether to go with a lightweight fixed point approach, or a use a heavyweight multi-precision library \[I went with the lightweight approach\].

Context: I'm building a game (in C++) that involves generating a 400 billion star galaxy, for which I'm using procedural generation. The target platforms are Android (Arm-v8a), Linux (x86-64), and probably Windows (x86-64). The issue is that this generation involves quite a bit of math, including exp, pow, sqrt, sin, cos, tan and atan2, and the system is ill-conditioned (tiny differences in the calculations could propagate to large differences in the output, like a star turning up or not, or even a whole region of stars changing). I want the same seed to generate exactly the same galaxy on all platforms in case I ever want a multi-player version of this.

My reading so far is that different processors, compilers or libraries cannot be guaranteed to return the same results for transcendental functions, and even simple floating point math might be a problem (such as Arm using a multiply-add instruction having better intermediate precision than the x86-64 using two instructions).

Things I have considered:

* Using double precision floating point, including the same transcendental function code to generate the same results (which I've had to do anyway so that I can vectorize them), and tweaking the compiler flags so that everything compiles exactly the same way on both processors, and rely on IEE-754 conformance to take care of the rest. \[this part answered. It's nearly impossible to get right\]
* Using a lightweight fixed point framework such as fixedptc.h so I'm only doing integer math. Pros: will definitely be consistent. Cons: lots of effort to scale everything correctly, particularly as generating a galaxy requires numbers with a large dynamic range that is not normally suitable for fixed point.
* Using a heavyweight multi-precision framework such as GNU MPFR or Boost (which I think is built on something like MPFR. Pros: this is easier to use than a lightweight library. Cons: This is a lot of machinery to pull in to solve this, and I haven't found any guarantee that it is completely consistent cross platform.

Example of the sort of places where dynamic range can be a problem (although it turns out that in this case much of it can be precomputed and doesn't need to be in procedural generation):

* absolute star luminosities can range from about 430,000 times the mass of the sun to 1/10,000 the mass of the sun (that's not including planets and moons, they will have to have their own scale), that's a factor of 4,300,000,000, which can be represented in a 32.32 fixed number, but calculations before or after risk overflowing or underflowing.
* positions and distances store fine in a 64 bit integer, but when for instance working out how far from a spiral arm a point is (which affects the star density), it would be helpful to work with distance^2 to avoid expensive square roots, and squaring a number doubles the amount of dynamic range required - this may require a different scale factor for the generating a large elliptical galaxy like IC 1101 than it would to generate something like the Pleiades.

None of this is insurmountable, but it certainly requires a lot more than blindly replacing doubles by m.n fixed integers.

Notes:

* I'm not particularly concerned about performance, or even high accuracy. Most of the heavy math code is not called very often, and I can use a lightweight approach for the critical stuff.
* I'm not trying to get the rendering the same, as that appears to be a fools errand with all the different graphics cards out there, different screen resolutions, etc. I do want the underlying structure to be the same though.
* Generating it on one platform and storing it is not a solution - the galaxy is too big for that.
* This question is *not* asking about general cross-platform development and frameworks, about which I know there are many opinions (I've already made the major decisions for my case), just about getting consistent math for procedural generation.
* I'm not trying to solve the space scaling issues - I've already solved this (with for instance 64 bit integers for the star positions). I'm dealing with star distributions and properties which involve a bit of math.

RESULT: There is no one true answer, even in a single project. There seem to be four properties to think about when determining how to perform calculations on continuous quantities (things that would be represented mathematically with real numbers): accuracy, (cross platform) safety, speed and dynamic range.

* double has great accuracy, speed and dynamic range, but is not safe.
* float has great speed and dynamic range, but is not accurate or safe.
* fixed point has great speed and is safe, but not so good accuracy or dynamic range. More bits extends the dynamic range but slows things down. Either hand roll or use a lightweight library for this.
* multi-precision libraries like MPFR or crlibm have high accuracy and dynamic range, but are not fast, and I haven't found anything definitive on safety. (crlibm provides correctly rounded results, so it should be safe).

Looking at my project as an example:

* There are a lot of constants that can be pre-generated even without the seed, and the dynamic ranges get truly ugly here (I really don't want to do fixed math on calculations involving the speed of light squared and plank's constant). This needs accuracy and safety. For this I'm going to use doubles, but have a checksum or generate it statically on a known platform for safety.
* For the shape of the galaxy (spiral arms, sub-clusters etc.), all we need is safety and moderate dynamic range. Fixed point here (although multi-precision libraries might be ok), with a lightweight library for transcendental stuff.
* For star placement, we need safety, speed and some dynamic range (the dynamic range of luminosity can be factored out of this step). 64 bit fixed with occasional forays to 128 bits seems to be good here, although care needs to be taken with overflows and underflows. I'm using fixedptc.h for the sqrt stuff and rolling the rest myself.
* For star rendering, we need speed and dynamic range. floats are the way to go here, it's what low end graphics cards work with anyway.
* (later) for planet placement, we need safety and probably dynamic range. This will probably be the time to break out one of the multi-precision libraries.

This problem is now solved as far as I'm concerned (thanks for some really useful suggestions!), and I've done the bulk of the transition to fixed. Any further edits/comments are to leave ideas for anyone coming later who is trying to deal with the same issues.

Postscript: I found there were some places where fixed point had insufficient range (mostly in the setting up phase), so I ended up writing a small library to provide the floating point functionality I needed using integer instructions. See my answer below for details.

# Answer
The best resource I've found on this topic is Bruce Dawson's blog article "Floating-Point Determinism"

It establishes that yes, in theory, you could get cross-platform determinism out of floating point math, but **in practice you won't** if your use case is sufficiently general. Some of the thornier problems he points out include:

* If you need to support 32-bit x86 platforms, and you use any library code, that library could change the per-thread rounding, precision, or denormal settings, invisible to you. The only defense is to never call library code on your generator thread (unreasonably onerous), or force the setting to what you expect between every library call (both wasteful and error prone).

And just hope there's no gremlins showing up like misbehaving printer drivers!
* different compilers on different platforms can make different decisions about the order in which to evaluate expressions, or which sub-expressions to cache and re-use. While with infinite precision real numbers these should all give identical results, with floats they might not be bit identical. As you mention, you'd often have to disable optimization to prevent this, costing performance.
* C++ and IEEE-754 standards both leave it undefined what precision to use for intermediate calculations, so you can get different behaviour depending on the platform/compiler unless you explicitly capture every intermediate to a variable (and on x87, *store it to memory* ) and forbid the compiler from applying optimizations (onerous, error prone, and bad for performance, and costs you precision you might otherwise have had available to you).
* If you target any platforms that lack a fused multiply-add, you have to forgo it on all platforms, again costing performance and precision.

So my takeaway from that article is if I need bit-for-bit exact matches on a wide range of platforms, fixed point and integer math is still the way to go.
> 26 votes

# Answer
What I would be trying to do is to generate on multiple levels, where things at one level could be calculated from the level above with integer math.

For example, at the top level I might draw a bunch of spiral arms on a 256x256 map, where each point would store things like density, age etc. For each point on the top level map, I would make another 256x256 map, using information from the top level and adding detail, maybe using something like a plasma fractal. Then for each point on that map, generate anywhere from zero to a few thousand stars.
> 7 votes

# Answer
As others pointed out, if you want true determinism, then avoid floating point variables and use integer math instead. If you need a large universe, use 64bit integers. Their resolution is good enough to address points in our real-world galaxy with a precision of about 50m.

Also keep in mind that if you want to auto-generate a whole galaxy, then it usually makes little sense to handle the position of every single object relative to the origin of the galaxy. A galaxy with realistic proportions has huge distances of empty space between star systems, which means there won't be interactions between two objects in different star systems. So there is no point in simulating more than one star system within the same 3d space. That means can use a two-tiered hierarchy for your game universe. With the first tier being the stars and the second tiers being the contents of each star system. That means you first generate the position of every star relative to the center of the galaxy (where a couple light-minutes of inaccuracy are no big deal). Then you can generate the positions of everything within each star system relative to the main star.

For deterministic sine and cosine calculation from integer angles, you can use the good old technique of a precomputed sine table. A sine table is an array with the hard-coded sines of the angles from 0° to 360°. If you need the sine or cosine of a value, you just need to look it up. If you need to calculate the angle from a sine or cosine, you can perform a binary search on that table.

Sine tables were popular in the days of old where CPUs didn't have dedicated circuits for calculating sine and cosine. Lookup tables resulted in a considerable performance improvement back then. On modern CPUs they hurt performance more than they help while sacrificing accuracy. But in your particular use-case they could be useful again because they are deterministic.
> 2 votes

# Answer
Rather than designing your PCG around real number arithmetic and then trying to make it deterministic, it may be easier to start from this constraint and design around it. There are a wide variety of different PCG algorithms, many of which don't require calculations involving real numbers (whether represented by floats or fixed-point ints) at all.

One particularly nice example is Wave Function Collapse; if you don't use the Shannon entropy variant of the algorithm, then only integer arithmetic is used. The same author, Maxim Gumin, also has created a programming language called MarkovJunior specifically designed for PCG, which appears to be very powerful and flexible; likewise, it has a few features which use floating point arithmetic, but if you don't use those features then it's integers all the way down.

Many integer-based PCG algorithms use discrete grids, but even if your game doesn't have a fixed grid, you can either make the grid scale small enough that things don't appear to be on a grid, or you can apply a separate post-processing stage to shift things away from their grid cells by small pseudorandom amounts.

I understand that it may not be feasible to start again from scratch if you have already designed your game's PCG system to use floats and transcendental functions, but for others finding this Q&A while still in their planning stage, I think it's worth taking the determinism constraint into account from the very beginning.
> 2 votes

# Answer
Partly an answer, partly a followup:

I found that while I can mostly just use fixed point, there were some circumstances where fixed just did not have the dynamic range, which left me looking for some sort of soft floating point library. For this problem the requirements were:

* at least doubles (in some places floats had insufficient range/precision)
* at least somewhat performant and not too heavyweight
* a guarantee that floating point wasn't used somewhere internally
* a permissive license

I couldn't find anything that met those criteria to my satisfaction, so I ended up creating a bare-bones library myself, which I have been using successfully. It can be found at https://github.com/royward/pseudo-double and it includes basic operators, comparison, conversion, exp, log, pow, sqrt and some trig, and some other functions. There is a C and C++ binding.

To give an idea of how it works, rather than try and follow IEEE 754 which is used by nearly all hardware, I went with another format that simplifies things a bit for software:

bits 0..15: exponent
bits 16..63: signed mantissa

Here is a sample of the add, multiply and convert to and from fixed point using this idea, other functions are similar (some error checking has been stripped out here for simplicity):

```
#include <stdint.h>

#define PSEUDO_DOUBLE_TOTAL_BITS 64
#define PSEUDO_DOUBLE_EXP_BITS 16
#define EXP_MASK ((1LL<<PSEUDO_DOUBLE_EXP_BITS)-1)
#define EXP_MASK_INV (~((1ULL<<PSEUDO_DOUBLE_EXP_BITS)-1))
#define PSEUDO_DOUBLE_EXP_BIAS (1U<<(PSEUDO_DOUBLE_EXP_BITS-1))
#define PSEUDO_DOUBLE_HALF_ULP ((1ULL<<(PSEUDO_DOUBLE_EXP_BITS-1))-1)
#define clz __builtin_clzll

typedef uint64_t pseudo_double_i;
typedef int64_t signed_pd_internal;
typedef __int128 signed_large_pd_internal;

inline signed_pd_internal shift_left_signed(signed_pd_internal x, int shift) {
    if(shift>=0) {
        return x<<shift;
    }
    return x>>-shift;
}

pseudo_double_i int64fixed2_to_pdi(int64_t d, int32_t e) {
    if(d==0) {
        return 0;
    }
    int negative=(d<0);
    int lead_bits=clz(negative?~d:d);
    return ((shift_left_signed(d,PSEUDO_DOUBLE_TOTAL_BITS+lead_bits-65))&EXP_MASK_INV)
        +PSEUDO_DOUBLE_EXP_BIAS+65-lead_bits+e;
}

int64_t pdi_to_int64fixed2(pseudo_double_i x, int32_t e) {
    if(x==0) {
        return 0;
    }
    signed_pd_internal vx=((signed_pd_internal)x)&EXP_MASK_INV;
    int32_t exponent=(x&EXP_MASK)-PSEUDO_DOUBLE_EXP_BIAS-e;
    int64_t ret=vx>>(PSEUDO_DOUBLE_TOTAL_BITS-exponent);
    return ret;
}

inline pseudo_double_i pdi_add(pseudo_double_i x, pseudo_double_i y) {
    int32_t expx=x&EXP_MASK;
    int32_t expy=y&EXP_MASK;
    int32_t ydiffx=expy-expx;
    if(ydiffx>=(PSEUDO_DOUBLE_TOTAL_BITS-1)) {
        return y;
    }
    if(ydiffx<=-(PSEUDO_DOUBLE_TOTAL_BITS-1)) {
        return x;
    }
    int32_t exp_max;
    signed_pd_internal vx=((signed_pd_internal)(x&EXP_MASK_INV))>>1;
    signed_pd_internal vy=((signed_pd_internal)(y&EXP_MASK_INV))>>1;
    if(ydiffx>=0) {
        exp_max=expy;
        vx>>=ydiffx;
    } else {
        exp_max=expx;
        vy>>=-ydiffx;
    }
    exp_max+=1;
    signed_pd_internal vr=(vx+vy+PSEUDO_DOUBLE_HALF_ULP)&~PSEUDO_DOUBLE_HALF_ULP;
    if(vr==0) {
        // special case - a mantissa of zero will always make the whole word zero.
        // Makes comparisons much easier
        return (pseudo_double_i)0;
    }
    int32_t leading_bits=clz(vr>0?vr:~vr)-1;
    if(leading_bits>exp_max) {
        leading_bits=exp_max;
    }
    vr<<=leading_bits;
    int32_t new_exponent=exp_max-leading_bits;
    return (pseudo_double_i)((vr&EXP_MASK_INV)+new_exponent);
}

inline pseudo_double_i pdi_mult(pseudo_double_i x, pseudo_double_i y) {
    int32_t expx=x&EXP_MASK;
    int32_t expy=y&EXP_MASK;
    signed_pd_internal vx=(signed_pd_internal)(x&EXP_MASK_INV);
    signed_pd_internal vy=(signed_pd_internal)(y&EXP_MASK_INV);
    signed_pd_internal vr=(((signed_large_pd_internal)vx)*vy)>>64;
    if(vr==0) {
        // special case - a mantissa of zero will always make the whole word zero.
        // Makes comparisons much easier
        return (pseudo_double_i)0;
    }
    int32_t leading_bits=clz(vr>0?vr:~vr)-1;
    vr<<=leading_bits;
    int32_t new_exponent=expx+expy-PSEUDO_DOUBLE_EXP_BIAS-leading_bits;
    return (pseudo_double_i)((vr&EXP_MASK_INV)+new_exponent);
}

```

To add some type safety (preventing accidentally using integer operations on pseudo-doubles which will return garbage), there is a wrapper:

```
typedef struct {
    pseudo_double_i val;
} pseudo_double;

inline pseudo_double create_pseudo_double_from_internal(pseudo_double_i x) {
    pseudo_double ret;
    ret.val=x;
    return ret;
}

inline pseudo_double int64fixed2_to_pd(int64_t d, int32_t e) {
    return create_pseudo_double_from_internal(int64fixed2_to_pdi(d,e));
}
inline int64_t pd_to_int64fixed2(pseudo_double d, int32_t e) {
    return pdi_to_int64fixed2(d.val,e);
}
inline pseudo_double pd_add(pseudo_double x, pseudo_double y) {
    return create_pseudo_double_from_internal(pdi_add(x.val,y.val));
}
inline pseudo_double pd_mult(pseudo_double x, pseudo_double y) {
    return create_pseudo_double_from_internal(pdi_mult(x.val,y.val));
}

```
> 2 votes

# Answer
Using a noise-based RNG might be an option? It seems to work well, and generates its numbers via bit shifting, so there's no precision issues to get in the way.

Not sure where the slides are, but the video description lists some benefits:

> (unordered access, better reseeding, record/playback, network loss tolerance, lock-free parallelization, etc.) while being smaller, faster, and easier to use.
> 1 votes

# Answer
You can just use regular floating point math (single precision or double precision). It's a myth (that maybe once upon a time had some truth to it) that floating point math gives different results on different platforms or that it is difficult to get consistent results.

Regarding intermediate precision: on all modern 64-bit platforms the intermediate precision is the same (always 64 bits). If you are also targeting 32-bit platforms (i386 or arm) you can use `_FPU_SETCW` with the value `_FPU_DOUBLE` to also get identical results here. See here for more info: http://christian-seiler.de/projekte/fpmath/

SIMD/SSE should be fine as well. Also, web assembly is considered a 32-bit platform, but it uses 64 bit intermediate precision you are covered here as well with no effort.

This covers all PCs (windows/mac/linux), all mobile devices, and all modern game consoles.

Regarding compiler optimizations: A long time ago compilers were indeed buggy and you could get inconsistent results. But now this is not a problem. Just don't use `--ffast-math` and you will get consistent results on all compilers and all optimization levels.

Regarding sqrt: From my experience, the standard `sqrt` and `sqrtf` functions from \<math.h\> will give identical results on all modern platforms. I would test this on your target platforms just to be sure, but I would be very surprised if you find a platform that is different.

Regarding trigonometric functions: This is the one case where I have found differences between platforms/compilers. So you should use your own (fast) sin/cos implementation. Here is a good one: https://stackoverflow.com/a/28050328

In summary, don't just believe something you read on the internet from 15 years ago, try for yourself! floating point inconsistenty is a persistent myth that should perish.
> 0 votes

---
Tags: c++, mathematics, procedural-generation, c, cross-platform
---


# Question
Title: Considerations when applying C++ Core Guidelines in game development
I'm curious about the impacts of applying the C++ Core Guidelines to game development.

When I try to discuss about this, and point out that we should check return values, or validate user data, or just have good naming, I get objections like 'once shipped, no one will have to deal with this code', so why not just make it work, without wasting time with all this care about raw pointers, and raw loops etc. I believe it's mental laziness, but I'm not sure if there's really a major downside to following these guidelines.

What are the pros and cons of applying these guidelines in the context of game development?

# Answer
> 2 votes
Not a professional game developer, but do write high performance C++ code for a living.

In any non-tiny project, following some good guidelines (like the ones posted) will:

* result in faster development (debugging is a significant part of development time),
* result in a more robust product for a better user experience.

For example, not checking return values can result in either a miserable debugging session if it causes a problem that cascades to somewhere else (learned that the hard way), or a silent crash when the user runs your game in a way that causes some failure that didn't occur in testing.

A difference between game code and other code is that game code has a shorter expected lifetime, but I seriously doubt that is enough of a difference to make those guidelines any more or less useful.

For code that only I see that I plan to throw away after a week or so (say a one-off conversion), sure I'll not worry so much about guidelines.

Having said that, guidelines are a useful set of handrails, not a straightjacket, and you are sometimes doing yourself a disservice by following them slavishly - I routinely break many of them, and which ones are important will depend on your project.

For instance (as @DMGregory points out) in hot loops with a tight time budget (this happens in non-games too!), you don't want to follow guidelines at the expense of performance - for a hot enough loop you do whatever (safely) needs to be done to meet your time requirements. Even in those cases it is sometimes better to start with a guideline conforming version as a base, and an optimized loop should be very well commented so you can see what you did (and why) when you come back to it.

I have been involved in projects in which every guideline must be followed without fail, and projects where guidelines are ignored, and they are both awful.

Having spent more time in those guidelines, they seem pretty good and not over-prescriptive (but looks like they haven't been finished yet), and they give reasons. For instance, rather than the common "thou shalt never use goto" I've seen so often, in "ES.76: Avoid goto" they say why to avoid goto, and when goto is ok. Some of it is stylistic: "Enum.5: Don’t use ALL\_CAPS for enumerator". Overall, they are good enough that I'd want to be able to give a good reason for any part of them that I'm not following.

# Answer
> -3 votes
Short version:
There are no pros and only one con. Modern C++ is inefficient for game development.

Long version:
C++ is **by no means** inefficient, however real time application require **maximum** efficiency. Therefore using modern C++ is guaranteed to be at least in one place more slow than using simple C++98 or C-style. So there is the con in following this.
Guidelines like the one you linked are usually created after years of failure and development decisions that have set the project back a considerable amount of time.

I have to mention that a game is **not** a program on which the linked guideline is based upon. Commercial products like Excel, Blender3D, Unity, generate data, while games generate entertainment. This implies that the development process of games is unique from game to game. Therefore code guidelines in general provide **absolutely nothing beneficial** to the development of a game. This is also the reason people have said that as long as you ship it, it's OK to do whatever, because it's true.
There is however a youtube series that shows how a game is made step by step, from scratch, made by a professional programmer with 20+ years of experience in **game development**, if you're interested.

I also have to mention that Bjarne Stroustrup has, from my knowledge, NEVER shipped a commercial program OF ANY KIND and neither did Herb Sutter (but I could be very wrong about him), so you should definitely take that into consideration.

---
Tags: c++, software-engineering
---


# Question
Title: Orient a player mid-air to their predicted landing orientation in Unity?
Ever played Skate 3? When dropping into a ramp, or if you're midair, your player's up direction aligns to the normal of the surface you're about to land on, while respecting the player's forward direction as much as possible, while still allowing them to perform in-air 360 spins etc. How can I do this?

I've got the code for landing point prediction complete, that's not a issue. Just figuring out the rotation and actually rotating to it is proving difficult.

# Answer
If you know the normal of the landing point, you can get the after-landing forward direction by projecting the current forward onto the plane defined by the normal.

From there, it should be possible to build a quaternion to represent the final rotation using the forward and up vectors. For example, unity has a Quaternion.LookRotation function that does this. If you have to implement this yourself, there are several examples you can find with a quick google search of how to build the quaternion from the up and forward vectors.

As for actually rotating, the easiest way is probably to interpolate over time between the current rotation and the desired after-landing rotation with a Slerp. Since you already have a prediction for the landing, you could use a fixed duration for this interpolation (say, 0.5s), and when you are 0.5s away from touching the ground, record the current rotation and start interpolating between that value and the desired rotation.
> 0 votes

---
Tags: rotation, movement, transformation, quaternion, collision-prediction
---


title: Can I insert sound in the tooltip?

text:
# Question
Title: Can I insert sound in the tooltip?
Before this, I try to insert an image in a tooltip and it was already done. But right now, I want to try to insert a sound in the tooltip. What I want to do is when I point my cursor to the object it will display the image and also the sound at the same time.

**My question:**

1. Can sound insert in the tooltip?
2. Can I insert the code of sound in the same place as the image function?

**-----TooltipManager Script--------**

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

public class TooltipManager: MonoBehaviour
{
    public static TooltipManager _instance;

    public Image imageComponent;

    // public Sound soundComponent;

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            _instance = this;
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        Cursor.visible = true;
        gameObject.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Input.mousePosition;
    }

    public void SetAndShowToolTip(Sprite image)
    {
        gameObject.SetActive(true);
        imageComponent.sprite = image;
    }

    public void HideToolTip()
    {
         gameObject.SetActive(false);
    }

}

```

So can I insert the sound code inside the **SetAndShowToolTip**? or do I need to create a new function?

# Answer
The short answer is yes to both 1) and 2).

But if you should do it that simple is another matter for a different reason. It is a matter and ease of control of your sound. Unlike a tooltip that is requested by the user by clicking/ pointing on it, sound might not be. The usual way is to have an option somewhere to turn of sound effects somewhere in your settings. Now if all your toolmanager is doing is soundeffect.play() you will have a harder time to integrate the control over the sound itself like if it should play or how loud it should be.
> 0 votes

---
Tags: c#, raycasting, image, sound, sound-effects
---


# Question
Title: How do I make my player rotate in the current direction of my camera in Unity using C#?
I have a player with third and first person camera, I want to make my player move in the direction that my camera is looking at when I hold the right mouse in third person and move(Like my player is always looking forward based on where my camera is). But my player does not rotate, and I wish to implement it, I want help so that my player rotate In the current direction my camera is looking at. code:

code:

```
    using UnityEngine;
    using UnityEngine.InputSystem;
    public class PlayerCamera : MonoBehaviour
    {
        public GameObject[] cameras;
        public bool PlayerShouldRotateByCameraAngle = false;
        [Tooltip("As It's the main camera that rotates (cinemachinebrain), it should be the main camera")]
        public Transform cameraTransform;
        private int currentIndex;

        public float lookSpeed = 2f;
        public float lookXLimit = 90;
        private float rotationX = 0;

        private void Awake() {
            CursorLocker(true);
        }

        private void Start() {
            currentIndex = 1;
        }
        public void OnChangeCamera(InputAction.CallbackContext value) {
            if (value.started) {
               cameras[currentIndex].SetActive(false);
               currentIndex = (currentIndex + 1) % cameras.Length;
               cameras[currentIndex].SetActive(true);
            }
        }
        private void CursorLocker(bool shouldLock) {
            Cursor.lockState = shouldLock ? CursorLockMode.Locked : CursorLockMode.None;
        }

        public Vector3 CameraRotation(Vector3 direction) {
            if (PlayerShouldRotateByCameraAngle) {
                rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
                rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
                cameras[currentIndex].transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
                return Quaternion.AngleAxis(cameras[currentIndex].transform.rotation.eulerAngles.y, Vector3.up) * direction;
            }

            return direction;
        }
    }

public class PlayerMovement : MonoBehaviour
{
    [Header("Config Player")]

    [SerializeField] private float speed = 3f;
    [Tooltip("This is the Time for the player rotation - it makes smooth")][SerializeField] private float smoothTime = 0.05f;
    [SerializeField] private GameObject playerCameraObject;

    private PlayerCamera playerCamera;
    private CharacterController controller;
    private float currentSpeedRotationing;
    private float verticalVelocity = 0f;
    private Vector2 movement2D;
    private Vector3 direction;

    private bool IsGrounded() => controller.isGrounded;
    private void Awake() {
        controller = GetComponent<CharacterController>();
    }

    private void Start() {
        playerCamera = playerCameraObject.GetComponent<PlayerCamera>();
    }

    void FixedUpdate() {
        ApplyMovement();
        ApplyRotation();
    }

    public void OnMovement(InputAction.CallbackContext value)
    {
        movement2D = value.ReadValue<Vector2>();
        movement2D.Normalize();
        direction = new Vector3(movement2D.x, 0, movement2D.y);
        direction.Normalize();
    }

    public void OnShouldWalkBasedOnCamera(InputAction.CallbackContext value) {
        if (value.performed)
        {
            playerCamera.PlayerShouldRotateByCameraAngle = true;
        }
        if (value.canceled)
        {
            playerCamera.PlayerShouldRotateByCameraAngle = false;
        }
    }

    void ApplyMovement() {
        Vector3 currentDirection = playerCamera.CameraRotation(direction);
    }

    void ApplyRotation() {
        if (movement2D.sqrMagnitude == 0) return;

        float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
        float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref currentSpeedRotationing, smoothTime);
        transform.rotation = Quaternion.Euler(0.0f, angle, 0.0f);
    }

```

# Answer
> 0 votes
```
private Vector3 getDirection(Transform t, bool keepYhorizontal = false)
{

    Vector3 direction = t.rotation * t.forward;

    if(keepYhorizontal )
        direction.y = 0;

    return direction;

}

```

Multiple the quaternion my a directional vector. This multiplycation isn't actually multiplying. The order is important, otherwise the compiler will give an error.

Made the function so it can be used for any transform and so also for a camera.

---
Tags: unity, c#, camera, rotation, movement
---


title: How can I secure my data in Unity?

text:
# Question
Title: How can I secure my data in Unity?
I have a tenant ID and client secret that I use to access my server and return an API key for users. I put it in start()

However, hackers can decompile my game and access the server data. Is there any way to secure my tenant ID and client secret in my client code?

# Answer
> 4 votes
What is in clients hand is by definition not secret anymore. Regardless what you do, if they are dedicated enough they can get the information that is located inside the client.

Instead why not let the client authenticate itself against the server and let the client just ask for the data? The server would not hand out the api key to the user but the result of the request that the client would make. This has some further benefits:

* You can cache the results in case multiple clients make often the same requests
* You know and can control which client is calling how often the endpoint
* If data manipulation is needed (the return data from the endpoint), you can do this on the backend out of clients sight. In case of huge data this can save the client computation power. It could be a legal requirement. Or you can enrich the data. Or restructure to fit better your client.
* People just can't take apart your client to recreate your app since the business logic (handling of endpoints, secrets) is not located in the client.

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


title: 3D First person Rotate Character Unity

text:
# Question
Title: 3D First person Rotate Character Unity
I'm facing the problem that my chacter is spinning around itself when I try to move, that's because Im trying to make my player move in the direction of the camera, but when I move it keeps rotating around itself infinetly

Resuming my code:

```
public class PlayerMovement : MonoBehaviour
{
    [Tooltip("This is the Time for the player rotation - it makes smooth")]
    [SerializeField] private float smoothTime = 0.05f;

    [SerializeField] private GameObject playerCameraObject;
    private PlayerCamera playerCamera;

    private CharacterController controller;
    private float currentSpeedRotationing;

    private Vector2 movement2D;
    private Vector3 direction;

    private bool IsGrounded() => controller.isGrounded;
    private void Awake()
    {
        controller = GetComponent<CharacterController>();
    }

    private void Start()
    {
        playerCamera = playerCameraObject.GetComponent<PlayerCamera>();
    }

    void ApplyMovement()
    {
        Vector3 currentDirection = playerCamera.DirectionToMoveByCamera(direction);
        controller.Move(currentDirection * currentSpeed * Time.deltaTime);
    }

    void ApplyRotation()
    {

        if (movement2D.sqrMagnitude == 0) return;

        if (playerCamera.PlayerShouldRotateByCameraAngle && !playerCamera.isFirstPerson)
        {
            Debug.Log("sssssss");
            transform.rotation = Quaternion.Euler(0.0f, playerCamera.cameraTransform.transform.eulerAngles.y, 0.0f);
        }
        else if (playerCamera.isFirstPerson)
        {
            Debug.Log("should rotate");
        }
        else
        {
            float targetAngle = Mathf.Atan2(directiion.x, direction.z) * Mathf.Rad2Deg;
            float angle = Mathf.LerpAngle(transform.eulerAngles.y, targetAngle, smoothTime * Time.deltaTime);
            transform.rotation = Quaternion.Euler(0.0f, angle, 0.0f);
        }
    }

    void FixedUpdate()
    {
        ApplyMovement();
        ApplyRotation();
    }
}

```

```
    public class PlayerCamera : MonoBehaviour
    {
        public GameObject[] cameras;
        public bool PlayerShouldRotateByCameraAngle = false;
        [Tooltip("As It's the main camera that rotates (cinemachinebrain), it should be the main camera")]
        public Transform cameraTransform;
        private int currentIndex;

        public float lookSpeed = 2f;
        public float lookXLimit = 90;
        private float rotationX = 0;
        public bool isFirstPerson = false;

        private void Awake()
        {
            CursorLocker(true);
        }
    public Vector3 DirectionToMoveByCamera(Vector3 direction)
    {
        if (PlayerShouldRotateByCameraAngle || isFirstPerson)
        {
            return Quaternion.AngleAxis(cameraTransform.transform.rotation.eulerAngles.y, Vector3.up) * direction;
        }

        return direction;
    }

```

# Answer
By any chance, did you parent the `Camera` to the `PlayerMovement.gameObject.transform`?

Also the problem won't be in the `if`-statement, as you are overriding it here:

```
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
float angle = Mathf.LerpAngle(transform.eulerAngles.y, targetAngle, smoothTime * Time.deltaTime);
transform.rotation = Quaternion.Euler(0.0f, angle, 0.0f);

```

Unless you have `playerCamera.PlayerShouldRotateByCameraAngle` set to true.

Your scripts looks overly complicated. Try to reduce them. See no reason why this is in two scripts either.

When `public Transform cameraTransform;` should always be the main camera, consider:

```
public void Awake()
{
     cameraTransform = Camera.main.transform;
}

```

Also, always keep your indentations right, including the brackets, it will help you so much in keeping overview of your code.
> 1 votes

# Answer
Since my camera was inside my player it was also rotating itself when I was rotating my player.
> 0 votes

---
Tags: unity, c#, camera, rotation, quaternion
---


# Question
Title: Convert terrain vertex position to global position
I am trying to set the terrain's heights data at runtime with a simplex noise function, while stumbling with converting the local position of the vertices to global position to use as input to keep the simplex noise continuous.

At this time I am setting up multiple terrains tiles, which I added in the editor.

The `UnityEngine.Terrain` has a size of 1000 units on x and z and a (default) heightmap resolution of 513.

My actual question is; *What am I missing?*

I have the impression that next I should convert the vertex position of one terrain to a world position, so the tiles would be seamless, but the result shows a difference at the borders. The simplex noise function has been tested and is correct.

```
private Vector3 toGlobal(Vector3 position, UnityEngine.Terrain terrain)
{

    int     res     = terrain.terrainData.heightmapResolution;
    Vector3 size    = terrain.terrainData.size;

    Vector3 global = new Vector3( position.x / res * size.x, 0, position.z / res * size.z);

    global += terrain.transform.position;

    return global;

}

```

And less interesting, how I use it:

```
// Get all terrain tiles and cycle through them
UnityEngine.Terrain[] terrains = Resources.FindObjectsOfTypeAll(typeof(UnityEngine.Terrain)) as UnityEngine.Terrain[];
foreach(UnityEngine.Terrain terrain in terrains)
{

    int         res     = terrain.terrainData.heightmapResolution;
    float[,]    heights = new float[res, res];
    float       height  = 0;

    for (int z = 0; z < res; ++z)
    {

        for (int x = 0; x < res; ++x)
        {

            Vector3 v = toGlobal(new Vector3(x, 0, z), terrain);
            height  = (float)(simplex.Noise(v.x * 0.0001, v.z * 0.0001, 0) + 1) * 0.5);
            heights[x, z] = height;

        }

    }

    terrain.terrainData.SetHeights(0, 0, heights);

}

```

# Answer
> 1 votes
It happend to be the way I used the heights array. After my fight with how the `Terrain.terrainData` stores its data, I neglected this aspect.

Within the `foreach`-loop I've assigned the heights to the bidimensional array \`float\[,\] heights' like this:

```
heights[x, z] = height;

```

The `Terrain` uses the rows as first parameter and so it should be:

```
heights[z, x] = height;

```

This solved the main problem. @DMGregory was one step ahead, and solved the next issue already which saved me some time.

# Answer
> 0 votes
This looks like a fencepost error.

A terrain with a resolution of 513 has 513 rows, numbered 0 to 512. When you divide by 513 you get a number between 0 and 0.998, instead of reaching all the way to 1. That means your last vertex gets placed slightly less than a full `size` away from the start of the terrain, leaving a narrow gap between this terrain and the next one that's been shifted over by one full `size`.

You need to divide by the number of beams in the fence, not the number of posts:

```
position.x / (res - 1) * size

```

and similarly for z.

---
Tags: unity, terrain, coordinates, linear-algebra
---


# Question
Title: How to prevent colliders from knocking each other back before being destroyed?
For context, I have a player that can use a bow or a spear to shoot enemies in a 2D side scroller game. The bow shoots arrows and the spear shoots itself, and they both have rigidbody2Ds attached.

When the spear or arrow hits an enemy that also has a rigidbody2D, it gets destroyed as intended, however this also causes the projectile to knock back the enemy. I'm assuming this happens because the colliders hit each other right before being destroyed since the projectile moves at a semi-high speed.

Is there any way to work around this?

# Answer
The simplest way to fix this is to make the arrow or spear's collider have `isTrigger = true` during flight.

A trigger collider *detects* collisions, but does not *resolve* collisions by applying impulses to shift the objects apart. You'd handle the collision event in `OnTriggerEnter2D(Collider2D other)` instead of `OnCollisionEnter2D(Collision2D collision)`.

If you need spears and arrows to have collision resolution at other times, you can set `isTrigger` back to false during those times.

Or if you need both behaviours simultaneously, you can do this with two colliders on separate layers, and layer masks filter which collisions get processed. Something like this:

* Each character has:

+ trigger collider on "hurtbox" layer
    + non-trigger collider on "character" layer (interacts with "terrain" layer but not "projectile" layer)
* Each projectile has:

+ non-trigger collider on "projectile" layer (which interacts with "terrain" and "hurtbox" layers but not "character" layer)

I put the extra collider on the character on the assumption that you're likely to be spawning many projectiles and fewer characters, so this minimizes the expense of the extra collider. It also gives you flexibility to tune the physics of the character for terrain interactions separately from their combat physics - using a more permissive hurtbox for example, or a rounder navigation footprint to avoid snagging on small obstacles.
> 1 votes

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


title: How do game devs tie physics to fps?

text:
# Question
Title: How do game devs tie physics to fps?
If a GPU is rendering 3D graphics, doesn't it have to wait for the CPU to finish computing all the physics calculations before returning a frame? And if it does have to do that, then how does game development tie physics to fps?

# Answer
> 2 votes
It's true that there's a sequential dependency between physics/gameplay updates and rendering.

The usual structure here is a Game Loop, where we run through a sequence of steps like...

1. Read input
2. Tick gameplay sim forward one time step (or more, if the sim is currently behind)
3. Prepare draw commands to visualize the latest game state
4. Send those draw commands to the GPU
5. (Optional: wait for the time to start working on the next frame)
6. Return to 1

However, this does not necessarily mean we keep the GPU waiting in steps 1-3. We can pipeline our frames, so as soon as we issue the draw commands for one frame, we're already working on computing the gameplay state for the next frame while the GPU is busy rendering, and we can have fresh draw commands ready for it to pick up as soon as it's done. So both CPU and GPU can often be working in parallel, despite the sequential dependency.

When we tick the game simulation, we're typically calling a function like "Update" and passing it a delta time variable, representing the (fractional) amount of in-game seconds to advance the state by. Given the previous state and the delta time, we can compute the next state something like:

```
newPosition = oldPosition + velocity * deltaTime

```

(Of course this gets more complicated for more complex mechanics like collision resolution, but the basic idea is the same)

The delta time variable can be measured based on the time the last frame took to fully process, so we know how much time we have to account for in the next pass. But having a time delta that changes from tick to tick can make some calculations less deterministic and reliable, so for consistency many games prefer to use a fixed time step. They choose in advance some constant simulation step size, and then run multiple steps back-to-back when they need to catch up to a measured time delta longer than a single step. We have lots of Q&A getting into the nitty gritty of this, if you'd like to learn more.

---
Tags: physics, graphics, performance
---


# Question
Title: NullReferenceException whilst trying to set a Sprite on an Image component programmaticaly
I'm trying to create a prefab to instantiate things in a research tree, but when I try to set the text for the TextMeshPro text and the sprite for the Image, I get the following exception:

```
ResetScriptObjects: failed to reset objectNullReferenceException: Object reference not set to an instance of an object
Research..ctor () (at Assets/Scripts/Research.cs:27)

```

Here is the relevent code:

```
[SerializeField] private string DisplayName = "";
[SerializeField] private Sprite image;

[SerializeField] private TextMeshProUGUI m_displayText;
[SerializeField] private Image m_image;

public Research()
{
    Debug.Log("Set stuff");
    m_displayText.text = DisplayName;
    m_image.sprite = image;
}

```

`Research()` is a constructor for `public class Research : MonoBehaviour`and is attached to a prefab. This prefab has two child components: One with an `Image`, and one with a `TextMeshPro Text`. I've attached those two to the `m_displayText` and `m_image`, but when I try typing something in the `DisplayName`, or assigning a sprite to `image`, I get the error.

EDIT: I've tried replacing the constructor with Awake() OnEnable() and Start(), to no avail. I'm using linux ubuntu if it helps.

# Answer
> 1 votes
Do not use constructor functions to initialize `MonoBehaviour` classes.

At the time the object is constructed, there has not yet been a moment for the deserializer to populate its member variables with their proper values. Construction can also happen on the loading thread rather than the main thread, which can cause errors if you try to use any methods that are main thread exclusive.

Do your initialization in one of the following methods instead:

* `Awake()`: called just once after deserialization is finished, so you know all serialized member variables have been properly set up (and this is true recursively: if your member variables themselves have serialized members, they're also finished deserializing by now).

This runs immediately after deserialization, before `Instantiate()` or `AddComponent()` returns, and before any other member methods are called (other than `OnAfterDeserialize()`, if applicable), so it's effectively "construction time".
* `OnEnable()`: called immediately after `Awake()` and before `Instantiate()`/`AddComponent()` returns if the object is spawned in an enabled state, and called each time the script transitions from a disabled to enabled state.
* `Start()`: called just once, before the first call to `FixedUpdate()`/`Update()`/`LateUpdate()` on an enabled script. See here for nitty gritty details of how this works for objects spawned in the middle of an update pass. It's guaranteed to run after all other referenced objects' `Awake()` methods have been called, so it's a good choice for late initialization that depends on something else having already run an earlier initialization method.

# Answer
> 0 votes
In addition to DMGregory, as that goes first:

I'm guessing this line is line 27.

`m_image.sprite = Image;`

`m_image` is initialised as null and so there is no memory reserved yet for its member `sprite`. But as said by DMGregory, don't use constructors in unity. That's a really no go, and goes for any other reasoning.

If you really want a 'constructor' you can fake one. Mind you can access private member functions in the static function too.

```
public class Research : MonoBehaviour
{

    public static Research Instantiate(string displayName, Sprite image)
    {

        // Create a gameObject
        GameObject go               = new GameObject();

        // Add the component
        Research research           = go.AddComponent<Research>();

        // Add the two other components
        research.m_displayText      = go.AddComponent<TextMeshProUGUI>();
        research.m_image            = go.AddComponent<Image>();

        // Set it's members
        research.m_displayText.text = displayName;
        research.m_image.sprite     = image;

        // Return the instantiated research
        return research;

    }

    [SerializeField] private string DisplayName = "";
    [SerializeField] private Sprite image;

    [SerializeField] private TextMeshProUGUI m_displayText;
    [SerializeField] private Image m_image;

}

```

And you can use it like this:

```
Research research = Research.Instantiate("name", image);

```

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


title: Secure Login on Steam

text:
# Question
Title: Secure Login on Steam
Is there any API a steam game can use to check if a user bought the game (instead of having it pirated)?

What I want to do is just the following:

* **Call Steam API from Game** to get some kind of token.
* Then pass that unique token to my server.
* My server do a request to Steam API to check if user has bought with real money the game: if the user bought the game, then I'll allow him to access my game server (which enable multiplayer etc.)

In Addition, Is there anyway to force the Steam Token to change everytime I request it? (In that way, if someone steal the token once it would not be able to use it forever, or maybe steam offers already something more secure than that?).

# Answer
If you trust Steam to be secure enough that users can't add games to their account without actually purchasing them (which, let's be honest, if they could, Steam probably has waaay bigger problems than just that), then you could just query their Steam account.

### Method 1: OpenID

**Upsides:** No Steam binaries to bundle. Potentially no need to take the users password yourself (unless they can't be sent to Steams website through a web browser and you need to collect it yourself).

**Downsides:** Doesn't work for private profiles. Requires a web browser.

For just OpenID logins you can have the user do their login (either on Steams website or through your code) to assert their identity and then run queries to the Steam Web API based on that identity.

According to steamcommunity.com/dev,

> Steam can act as an OpenID provider. This allows your application to authenticate a user's SteamID without requiring them to enter their Steam username or password on your site (which would be a violation of the API Terms of Use.) Just download an OpenID library for your language and platform of choice and use http://steamcommunity.com/openid as the provider. The returned Claimed ID will contain the user's 64-bit SteamID. ...

Using that SteamID you can query Steam with any of the API endpoints but you'd specifically want to call GetOwnedGames and then make sure that it includes your game (note that this wouldn't work for private profiles though). It seems like there's already a bunch of implementations in various languages to query their API though.

### Method 2: Steamworks API

**Upsides:** Seamless integration

**Downsides:** Requires bundling with another library

If you bundle your game with the Steamworks API then you can use that API to do the calls mentioned in Method 1. They specifically say,

> Steamworks provides a variety of methods for authenticating a Steam user between game clients, game servers, and websites.

...and provide a documentation link (but it appears to be broken.

It seems like there's quite a few libraries that wrap the Steamworks API available on GitHub and are probably more.
> 1 votes

# Answer
You can use the methods outlined on Steamworks User Authentication and Ownership:

> Between a game client and other clients (P2P) or game servers using Session Tickets

Those pages should have all the information you need, but I'll summarize a bit.

# webapi

I think the most generic method is to use the Steamworks Web API: In the game you call ISteamUser.GetAuthTicketForWebApi and send that ticket to the server and on the server you use the ISteamUserAuth/AuthenticateUserTicket webapi endpoint. No steam-specific libraries required.

As the docs note mentions, the webapi call requires a publisher API key, which you create with your admin Steamworks account. Never include your API key with an executable downloaded by users or they can wreak havoc!

Now you know the user is who they say they are and can use ISteamUser/CheckAppOwnership to verify they own the game.

# ISteamGameServer

However, for a multiplayer game server, you may be better served by the ISteamGameServer API where you can begin and end an auth session and also have access to other game server features.
> 0 votes

---
Tags: steam, authentication
---


# Question
Title: How to implement rogue-lite skill system
I am creating a roguelike/lite game where in a player has a freedom to learn a number of skills.

For example, I have a projectile skills and I can learn three different behaviours.

* Behavior 1: shoot multiple projectiles in a straight line.
* Behavior 2: shoot multiple projectiles outwards in a circle.
* Behavior 3: shoot projectiles in a cone in front of you.

Structure wise I have thought of using:

* skills = scriptable objects
* skill manager = handles execution, skill tree and more.

My question is: what is the best way to approach programming each of the skills?

* Would it be best for example to create multiple separate classes that handle each of the behaviors individually?
* Or would it be better just to use "skill" class to include these behaviors/methods?
* Or is there any better way to approach this?

# Answer
> 2 votes
I would approach a flexible game element system with a mix of game managers, gameobjects and events. These are basic types of upgrades usually found in most games:

* Changes in numeric values
* Changes in functionality
* Added functionality that is independent from existing behaviour
* Replaced functionality of a basic skill
* any combination of the three above in a single upgrade

The first upgrade is the easiest to handle. One game manager that has all numeric values that are changeable. Our upgrade itself knows which value gets changes and by how much. It grabs the value from the game manager and adds it change on top. If the upgrade is temporary, on deactivation you remove the added value again. Typical upgrades under this category are max health, movementspeed, crit chance and dmg.

Example code for max health (the code is just written down, the Managers are basic static ones and need more code itself, code is untested)

```
public class HealthBonus: MonoBehaviour {

    [SerializeField]
    private float bonusAmount;

    void Start() {
        StatsManager.instance.maxHealth += bonusAmount;
        PlayerManager.instance.currentHealth += bonusAmount;
    }

    private void OnDestroy() {
        StatsManager.instance.maxHealth -= bonusAmount;
    }
}

```

The second upgrade is taking an existing behaviour and adds something on top of it. I'm going to use life steal as an example. The code that handles the collision between enemy and bullets is just calling an event like OnEnemyHit.invoke(dmgAmount). Your life steal gameobject adds a listener to the current OnEnemyHit event and can have all the logic inside itself where to add that life and how much. Other examples would be like want to add bullets shooting side ways? Add listener to the OnShoot. Want to add an explosion when dmg taken? Add listener to OnDmgTaken. While this is going to add one more call of the default behaviour (you are not calling a Shoot() directly but you have a shoot event and your shoot logic it listening to the shoot event), this gives you a lot of flexibility. If the upgrade is just temporary, when the time is up just remove again the listener.

A basic enemy would look usually something along the lines of this

```
public class Enemy: MonoBehaviour {

    private void OnCollisionEnter2D(Collision2D other) {
        if(other.gameObject.CompareTag("PlayerProjectile"))
            GetComponent<EnemyLife>().dealDmg(StatsManager.instance.currentDmg);
    }
}

```

The inbetween over the event system could look something like this

```
//Change of handling the hit in dmg, we pass it to the CombatManager
public class Enemy: MonoBehaviour {

    private void OnCollisionEnter2D(Collision2D other) {
        if(other.gameObject.CompareTag("PlayerProjectile"))
            CombatManager.instance.OnEnemyHit.Invoke(gameObject, StatsManager.instance.currentDmg);
    }
}

//Same behaviour as before
public class CombatManager: MonoBehaviour {

    public static CombatManager instance;
    public UnityEvent<GameObject, float> OnEnemyHit;

    void Start() {
        instance.OnEnemyHit.AddListener(HandleEnemyHit);
    }

    private void HandleEnemyHit(GameObject enemy, float dmgValue) {
        enemy.GetComponent<EnemyLife>().dealDmg(dmgValue);
    }
}

//But now we can put in extra code without changing the original
public class LifeSteal: MonoBehaviour {

    private float lifeStealValue = 0.1f;

    void Start() {
        CombatManager.instance.OnEnemyHit.AddListener(StealLife);
    }

    private void OnDestroy() {
        CombatManager.instance.OnEnemyHit.RemoveListener(StealLife);
    }

    private void StealLife(GameObject enemy, float hitDmg) {
        PlayerManager.instance.currentHealth += hitDmg * lifeStealValue;
    }
}

```

The added functionality that is independent upgrade is a self containing game object that has all the logic it needs but is not a current modification. For example one upgrade adds a spinning circle around the player. Or a small drone that starts shooting at enemies and follows the player. If this is temporary again, it just delete the gameobject after the time is up.

If you want to replace a basic functionality (say instead of shooting straight they curve now or your shots are homing), this is really similar to the life steal code. The only difference is that you first remove the listener of the basic function of shooting straight and plug in your replacement effect.

Of course it is possible to mix the upgrades as well.

---
Tags: unity, c#, software-engineering
---


# Question
Title: How to play only the active scene when entering Play Mode?
Complete Unity novice here. First project ever, trying to get familiar and understand the basic aspects of game development with Unity. Trying to work with scenes now.

I have two scenes in my **Hierarchy** view. I added both to the Build Settings.

The `MainScene` contains the player sprite and the main game elements, while the `TitleScene` contains the game name text and a progress bar.

I set `TitleScene` as the active scene using the option **Set Active Scene** in the ellipsis context menu of the scene element in the **Hierarchy** view.

I want to show only one scene on game start, the `TitleScene`.

The **TitleSceneLogic.cs** script is attached to a game object in the `TitleScene`

```
public class TitleSceneLogic : MonoBehaviour
{
    void Start()
    {
        print("Title Scene started");
    }
}

```

The **MainSceneLogic.cs** script is attached to a game object in the `MainScene`

```
public class MainSceneLogic : MonoBehaviour
{
    void Start()
    {
        print("Main Scene started");
    }
}

```

Every time I hit **Play** to see the game running:

* Both scenes are being shown (overlapping)
* **Console** panel shows both *Main Scene started* and *Title Scene started*.

**Is this really the default behavior in Unity, to load all scenes when the game starts?**

I need to show one scene only on game start, the `TitleScene`.

I gave it a shot by adding this to the **MainSceneLogic.cs**'s `Start` function

`SceneManager.LoadScene("TitleScene");`

and indeed only the title scene is shown now, but:

* I have the feeling this is not the right way, do I really have to manually load a specific scene in the code when the game starts?
* The logs:
    + Title Scene started
    + Main Scene Started
    + Title Scene started

What is the right way to load only one scene on game start?

# Answer
> I have two scenes in my Hierarchy view. I added both to the Build Settings.

The easier way is to have only one scene in the hierarchy.

From the documentation:

> If you need to create large streaming worlds or want to effectively manage multiple scenes at runtime, you can open and edit multiple scenes in the Unity Editor simultaneously. Having multiple scenes open at once also lets you improve the workflow, especially if you often have to edit scenes collaboratively.

But for a normal small start game, one scene at a time is the default work flow.

As you found out, you can switch scenes with `SceneManager.LoadScene("Your scene name");`. In the build settings you set which scene should load first.
> 1 votes

---
Tags: unity, scene
---