# Question
Title: Can i use a method to change a variable that is external to it?
I'm trying to change two booleans that exist outside my method. I read about passing by value and passing by reference and in this case i think the correct way is to use passing-by-reference.

However, it is not working. I call the method and my booleans still with the same value as before the calling.

Can someone help me? Thanks!

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

public class CheckingPosition : MonoBehaviour
{
    public bool isClose = false;
    public bool isFar = false;
    public float radius;
    public float distance;
    private Vector3 initPos;
    private Vector3 actualPos;

    // Start is called before the first frame update
    void Start()
    {
        initPos = this.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        actualPos = this.transform.position;
        Vector3 direction = actualPos - initPos;
        var distance = direction.magnitude;

        CheckPositionAndCount1(ref isClose, ref isFar);
    }

private void CheckPositionAndCount1(ref bool close, ref bool far)
    {
        if (close == false && far == false && distance > radius && distance != 0)
        {
            far = true;
            Debug.Log("Saiu pela primeira vez");
            return;
        }
        else if (isClose == false && isFar == true && distance <= radius)
        {
            far = false;
            close = true;
            Debug.Log("Está perto");
            return;
        }
        else if (isClose == true && isFar == false && distance > radius)
        {
            close = false;
            far = true;
            Debug.Log("Está longe");
            return;
        }
        return;
    }
````
</code></pre>

# Answer
> 1 votes
Expanding on @Vaillancourt's comment,

If you take a closer look at your `CheckPositionAndCount1` method, you'll notice that you have somewhere used `close` and `far` and somewhere `isClosed` and `isFar`. If you want to solve this problem using pass by reference then replace all the `isClose` and `isFar` with `close` and `far` respectively inside the `CheckPositionAndCount1` method. Like this,

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

public class CheckingPosition : MonoBehaviour
{
    public bool isClose = false;
    public bool isFar = false;
    public float radius;
    public float distance;
    private Vector3 initPos;
    private Vector3 actualPos;

    // Start is called before the first frame update
    void Start()
    {
        initPos = this.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        actualPos = this.transform.position;
        Vector3 direction = actualPos - initPos;
        var distance = direction.magnitude;

        CheckPositionAndCount1(ref isClose, ref isFar);
    }

private void CheckPositionAndCount1(ref bool close, ref bool far)
    {
        if (close == false && far == false && distance > radius && distance != 0)
        {
            far = true;
            Debug.Log("Saiu pela primeira vez");
            return;
        }
        else if (close == false && far == true && distance <= radius)
        {
            far = false;
            close = true;
            Debug.Log("Está perto");
            return;
        }
        else if (close == true && far == false && distance > radius)
        {
            close = false;
            far = true;
            Debug.Log("Está longe");
            return;
        }
        return;
    }

```

Another thing to note is that, class variables are available inside all the methods of the same class. So you can directly use `isClose` and `isFar` inside `CheckPositionAndCount1` without the need to pass them as arguments. Like this

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

public class CheckingPosition : MonoBehaviour
{
    public bool isClose = false;
    public bool isFar = false;
    public float radius;
    public float distance;
    private Vector3 initPos;
    private Vector3 actualPos;

    // Start is called before the first frame update
    void Start()
    {
        initPos = this.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        actualPos = this.transform.position;
        Vector3 direction = actualPos - initPos;
        var distance = direction.magnitude;

        CheckPositionAndCount1();
    }

private void CheckPositionAndCount1()
    {
        if (isClose == false && isFar == false && distance > radius && distance != 0)
        {
            isFar = true;
            Debug.Log("Saiu pela primeira vez");
            return;
        }
        else if (isClose == false && isFar == true && distance <= radius)
        {
            isFar = false;
            isClose = true;
            Debug.Log("Está perto");
            return;
        }
        else if (isClose == true && isFar == false && distance > radius)
        {
            isClose = false;
            isFar = true;
            Debug.Log("Está longe");
            return;
        }
        return;
    }

```

@WeckarE. correctly points out that using both `isClose` and `isFar` is redundant as `isClose = !isFar`. So you can essentially remove `isFar`, like this,

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

public class CheckingPosition : MonoBehaviour
{
    public bool isClose = false;
    public float radius;
    public float distance;
    private Vector3 initPos;
    private Vector3 actualPos;

    // Start is called before the first frame update
    void Start()
    {
        initPos = this.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        actualPos = this.transform.position;
        Vector3 direction = actualPos - initPos;
        var distance = direction.magnitude;

        CheckPositionAndCount1();
    }

private void CheckPositionAndCount1()
    {
        if (isClose == false && distance > radius && distance != 0)
        {
            Debug.Log("Saiu pela primeira vez");
            return;
        }
        else if (isClose == false && distance <= radius)
        {
            isClose = true;
            Debug.Log("Está perto");
            return;
        }
        else if (isClose == true && distance > radius)
        {
            isClose = false;
            Debug.Log("Está longe");
            return;
        }
        return;
    }

```

# Answer
> 0 votes
The problem has something to do with the distance != 0 in the first if of the method. When i removed that it worked just fine.

Thanks for everyone that contributed.

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


# Question
Title: Why the loop is never working in the Waypoints?
```
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.AI;

public class Waypoints : UnityEngine.MonoBehaviour
{
    public List<GameObject> waypoints = new List<GameObject>();
    public Animator _animator;
    public int waitTimeBeforeGo;
    public int num = 0;
    public float minDist;
    public float speed;
    public bool rand = false;
    public bool go = true;
    public bool loop = false;
    public bool waitTime = false;
    public float smoothRotation;

    private bool lastPoint = false;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float dist = Vector3.Distance(gameObject.transform.position, waypoints[num].transform.position);

        if (waitTime == true)
        {
            StartCoroutine(WaitBeforeGo());
        }
        else
        {
            if (go)
            {
                //_animator.SetBool("Walk", true);

                if (dist > minDist && lastPoint == false)
                {
                    Move();
                }
                else
                {
                    if (!rand)
                    {
                        if (num + 1 == waypoints.Count)
                        {
                            if (loop == true)
                            {
                                num = 0;
                            }

                            lastPoint = true;
                            //_animator.SetBool("Idle", true);
                        }
                        else
                        {
                            num++;
                        }
                    }
                    else
                    {
                        num = Random.Range(0, waypoints.Count);
                    }
                }
            }
        }
    }

    public void Move()
    {
        Quaternion lookOnLook =
 Quaternion.LookRotation(waypoints[num].transform.position - transform.position);

        transform.rotation =
        Quaternion.Slerp(transform.rotation, lookOnLook, Time.deltaTime * smoothRotation);

        gameObject.transform.position += gameObject.transform.forward * speed * Time.deltaTime;
    }

    IEnumerator WaitBeforeGo()
    {
        yield return new WaitForSeconds(waitTimeBeforeGo);

        waitTime = false;
    }
}

```

For some reason when it's getting to this part it keep doing this part over and over again like in a endless loop and never continue :

```
if (num + 1 == waypoints.Count)
                            {
                                if (loop == true)
                                {
                                    num = 0;
                                }

                                lastPoint = true;

```

It keep doing the lines num = 0 and lastPoint = true all the time in a loop and never continue to the rest of the code.

For example there is only 1 waypoint it's moving to the waypoint but never get back it's staying at the waypoint. The loop(ping pong) is never working.

# Answer
> For example there is only 1 waypoint it's moving to the waypoint but never get back it's staying at the waypoint. The loop(ping pong) is never working.

How can it loop if there's only one waypoint? Where else would it go?

When you can't figure out why your code doesn't work the way you want, usually one of the first things you should do is add some logging code that will help you understand what's going on. For example:

```
if (num + 1 == waypoints.Count) {
    Debug.Log("Reached final waypoint at index " + num + ", looping back to index 0");

```

Then if your output looks like this

> Reached final waypoint at index 0, looping back to index 0

you know the problem is that there aren't any other waypoints to travel to.
> 1 votes

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


# Question
Title: VSCode OmniSharp crashing on startup from UnityEngine.TestRunner.dll
I'm running Unity 2020.1 on Ubuntu 20.04.

My OmniSharp extension for VSCode is crashing on startup. I had everything working properly with intellisense and all but then I rebooted. Now when I open the unity C# solution file in VSCode I get the following output from OmniSharp.

```
Starting OmniSharp server at 2020-11-28, 4:00:21 p.m.
    Target: /home/timmeh/work/unity/3_Project_Boost/3_Project_Boost.sln

OmniSharp server started.
    Path: /home/timmeh/.vscode/extensions/ms-dotnettools.csharp-1.23.6/.omnisharp/1.37.3/run
    PID: 3596

[info]: OmniSharp.Stdio.Host
        Starting OmniSharp on ubuntu 20.4 (x64)
[info]: OmniSharp.Services.DotNetCliService
        DotNetPath set to dotnet
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Located 1 MSBuild instance(s)
            1: StandAlone 16.8.0 - "/home/timmeh/.vscode/extensions/ms-dotnettools.csharp-1.23.6/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin"
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        MSBUILD_EXE_PATH environment variable set to '/home/timmeh/.vscode/extensions/ms-dotnettools.csharp-1.23.6/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin/MSBuild.exe'
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Registered MSBuild instance: StandAlone 16.8.0 - "/home/timmeh/.vscode/extensions/ms-dotnettools.csharp-1.23.6/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin"
            CscToolExe = csc.exe
            MSBuildToolsPath = /home/timmeh/.vscode/extensions/ms-dotnettools.csharp-1.23.6/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin
            CscToolPath = /home/timmeh/.vscode/extensions/ms-dotnettools.csharp-1.23.6/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin/Roslyn
            BypassFrameworkInstallChecks = true
            MSBuildExtensionsPath = /home/timmeh/.vscode/extensions/ms-dotnettools.csharp-1.23.6/.omnisharp/1.37.3/omnisharp/.msbuild
[info]: OmniSharp.Cake.CakeProjectSystem
        Detecting Cake files in '/home/timmeh/work/unity/3_Project_Boost'.
[info]: OmniSharp.Cake.CakeProjectSystem
        Could not find any Cake files
[info]: OmniSharp.MSBuild.ProjectSystem
        Detecting projects in '/home/timmeh/work/unity/3_Project_Boost/3_Project_Boost.sln'.
[info]: OmniSharp.MSBuild.ProjectManager
        Queue project update for '/home/timmeh/work/unity/3_Project_Boost/Assembly-CSharp.csproj'
[info]: OmniSharp.Script.ScriptProjectSystem
        Detecting CSX files in '/home/timmeh/work/unity/3_Project_Boost'.
[info]: OmniSharp.Script.ScriptProjectSystem
        Could not find any CSX files
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider, Order: 0
[info]: OmniSharp.MSBuild.ProjectManager
        Loading project: /home/timmeh/work/unity/3_Project_Boost/Assembly-CSharp.csproj
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.Completion.CompletionOptionsProvider, Order: 0
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.RenameWorkspaceOptionsProvider, Order: 100
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.ImplementTypeWorkspaceOptionsProvider, Order: 110
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.BlockStructureWorkspaceOptionsProvider, Order: 140
[info]: OmniSharp.WorkspaceInitializer
        Configuration finished.
[info]: OmniSharp.Stdio.Host
        Omnisharp server running using Stdio at location '/home/timmeh/work/unity/3_Project_Boost' on host 3477.
Can't find custom attr constructor image: /home/timmeh/work/unity/3_Project_Boost/Library/ScriptAssemblies/Unity.Rider.Editor.dll mtoken: 0x0a000004 due to: Could not find method '.ctor' due to a type load error: Could not set up parent class, due to: Could not set up parent class, due to:  assembly:/home/timmeh/work/unity/installs/2020.1.10f1/Editor/Data/NetStandard/ref/2.0.0/netstandard.dll type:Object member:(null) assembly:/home/timmeh/work/unity/installs/2020.1.10f1/Editor/Data/NetStandard/ref/2.0.0/netstandard.dll type:Attribute member:(null) assembly:/home/timmeh/work/unity/3_Project_Boost/Library/ScriptAssemblies/UnityEngine.TestRunner.dll type:TestRunCallbackAttribute member:(null) assembly:/home/timmeh/work/unity/3_Project_Boost/Library/ScriptAssemblies/UnityEngine.TestRunner.dll type:TestRunCallbackAttribute member:(null)
[fail]: OmniSharp.MSBuild.ProjectLoader
        The "ResolveAssemblyReference" task failed unexpectedly.
System.TypeLoadException: Could not find method '.ctor' due to a type load error: Could not set up parent class, due to: Could not set up parent class, due to:  assembly:/home/timmeh/work/unity/installs/2020.1.10f1/Editor/Data/NetStandard/ref/2.0.0/netstandard.dll type:Object member:(null) assembly:/home/timmeh/work/unity/installs/2020.1.10f1/Editor/Data/NetStandard/ref/2.0.0/netstandard.dll type:Attribute member:(null) assembly:/home/timmeh/work/unity/3_Project_Boost/Library/ScriptAssemblies/UnityEngine.TestRunner.dll type:TestRunCallbackAttribute member:(null)
  at (wrapper managed-to-native) System.MonoCustomAttrs.GetCustomAttributesDataInternal(System.Reflection.ICustomAttributeProvider)
  at System.MonoCustomAttrs.GetCustomAttributesDataBase (System.Reflection.ICustomAttributeProvider obj, System.Type attributeType, System.Boolean inheritedOnly) [0x00010] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at System.MonoCustomAttrs.GetCustomAttributesData (System.Reflection.ICustomAttributeProvider obj, System.Boolean inherit) [0x00011] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at System.Reflection.CustomAttributeData.GetCustomAttributes (System.Reflection.Assembly target) [0x00000] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at System.Reflection.RuntimeAssembly.GetCustomAttributesData () [0x00000] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at Microsoft.Build.Tasks.AssemblyInformation.GetFrameworkName () [0x00025] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.AssemblyInformation.get_FrameworkNameAttribute () [0x00028] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.AssemblyDependency.AssemblyMetadata..ctor (System.String path) [0x00019] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.AssemblyInformation+<>c.<GetAssemblyMetadata>b__21_0 (System.String p) [0x00000] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) [0x00034] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at Microsoft.Build.Tasks.AssemblyInformation.GetAssemblyMetadata (System.String path, System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue] assemblyMetadataCache, Microsoft.Build.Shared.AssemblyNameExtension[]& dependencies, System.String[]& scatterFiles, System.Runtime.Versioning.FrameworkName& frameworkName) [0x00006] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at (wrapper delegate-invoke) <Module>.invoke_void_string_ConcurrentDictionary`2<string, AssemblyMetadata>_AssemblyNameExtension[]&_string[]&_FrameworkName&(string,System.Collections.Concurrent.ConcurrentDictionary`2<string, Microsoft.Build.Tasks.AssemblyDependency.AssemblyMetadata>,Microsoft.Build.Shared.AssemblyNameExtension[]&,string[]&,System.Runtime.Versioning.FrameworkName&)
  at Microsoft.Build.Tasks.SystemState.GetAssemblyMetadata (System.String path, System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue] assemblyMetadataCache, Microsoft.Build.Shared.AssemblyNameExtension[]& dependencies, System.String[]& scatterFiles, System.Runtime.Versioning.FrameworkName& frameworkName) [0x00010] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.GetUnifiedAssemblyMetadata (Microsoft.Build.Tasks.Reference reference, System.Collections.Generic.IEnumerable`1[Microsoft.Build.Tasks.UnifiedAssemblyName]& unifiedDependencies, System.String[]& scatterFiles) [0x00023] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.FindDependenciesAndScatterFiles (Microsoft.Build.Tasks.Reference reference, System.Collections.Generic.List`1[T] newEntries) [0x0003a] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.FindAssociatedFiles () [0x000ea] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.ComputeClosure () [0x0000a] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.ComputeClosure (System.Collections.Generic.IEnumerable`1[T] remappedAssembliesValue, Microsoft.Build.Framework.ITaskItem[] referenceAssemblyFiles, Microsoft.Build.Framework.ITaskItem[] referenceAssemblyNames, System.Collections.Generic.List`1[T] exceptions) [0x00038] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ResolveAssemblyReference.Execute (Microsoft.Build.Shared.FileExists fileExists, Microsoft.Build.Shared.DirectoryExists directoryExists, Microsoft.Build.Tasks.GetDirectories getDirectories, Microsoft.Build.Tasks.GetAssemblyName getAssemblyName, Microsoft.Build.Tasks.GetAssemblyMetadata getAssemblyMetadata, Microsoft.Build.Shared.GetRegistrySubKeyNames getRegistrySubKeyNames, Microsoft.Build.Shared.GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, Microsoft.Build.Tasks.GetLastWriteTime getLastWriteTime, Microsoft.Build.Tasks.GetAssemblyRuntimeVersion getRuntimeVersion, Microsoft.Build.Shared.OpenBaseKey openBaseKey, Microsoft.Build.Tasks.GetAssemblyPathInGac getAssemblyPathInGac, Microsoft.Build.Tasks.IsWinMDFile isWinMDFile, Microsoft.Build.Tasks.ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader) [0x00515] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ResolveAssemblyReference.Execute () [0x00077] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute () [0x00029] in <25851c819cf84f6c96378e77482fea8f>:0
  at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask (Microsoft.Build.BackEnd.ITaskExecutionHost taskExecutionHost, Microsoft.Build.BackEnd.Logging.TaskLoggingContext taskLoggingContext, Microsoft.Build.BackEnd.TaskHost taskHost, Microsoft.Build.BackEnd.ItemBucket bucket, Microsoft.Build.BackEnd.TaskExecutionMode howToExecuteTask) [0x002fc] in <25851c819cf84f6c96378e77482fea8f>:0
[warn]: OmniSharp.MSBuild.ProjectManager
        Failed to load project file '/home/timmeh/work/unity/3_Project_Boost/Assembly-CSharp.csproj'.
/home/timmeh/work/unity/3_Project_Boost/Assembly-CSharp.csproj
/home/timmeh/.vscode/extensions/ms-dotnettools.csharp-1.23.6/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin/Microsoft.Common.CurrentVersion.targets(2123,5): Error: The "ResolveAssemblyReference" task failed unexpectedly.
System.TypeLoadException: Could not find method '.ctor' due to a type load error: Could not set up parent class, due to: Could not set up parent class, due to:  assembly:/home/timmeh/work/unity/installs/2020.1.10f1/Editor/Data/NetStandard/ref/2.0.0/netstandard.dll type:Object member:(null) assembly:/home/timmeh/work/unity/installs/2020.1.10f1/Editor/Data/NetStandard/ref/2.0.0/netstandard.dll type:Attribute member:(null) assembly:/home/timmeh/work/unity/3_Project_Boost/Library/ScriptAssemblies/UnityEngine.TestRunner.dll type:TestRunCallbackAttribute member:(null)
  at (wrapper managed-to-native) System.MonoCustomAttrs.GetCustomAttributesDataInternal(System.Reflection.ICustomAttributeProvider)
  at System.MonoCustomAttrs.GetCustomAttributesDataBase (System.Reflection.ICustomAttributeProvider obj, System.Type attributeType, System.Boolean inheritedOnly) [0x00010] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at System.MonoCustomAttrs.GetCustomAttributesData (System.Reflection.ICustomAttributeProvider obj, System.Boolean inherit) [0x00011] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at System.Reflection.CustomAttributeData.GetCustomAttributes (System.Reflection.Assembly target) [0x00000] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at System.Reflection.RuntimeAssembly.GetCustomAttributesData () [0x00000] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at Microsoft.Build.Tasks.AssemblyInformation.GetFrameworkName () [0x00025] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.AssemblyInformation.get_FrameworkNameAttribute () [0x00028] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.AssemblyDependency.AssemblyMetadata..ctor (System.String path) [0x00019] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.AssemblyInformation+<>c.<GetAssemblyMetadata>b__21_0 (System.String p) [0x00000] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) [0x00034] in <9f0df102fe6e4cfea29d2e46f585d8a5>:0
  at Microsoft.Build.Tasks.AssemblyInformation.GetAssemblyMetadata (System.String path, System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue] assemblyMetadataCache, Microsoft.Build.Shared.AssemblyNameExtension[]& dependencies, System.String[]& scatterFiles, System.Runtime.Versioning.FrameworkName& frameworkName) [0x00006] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at (wrapper delegate-invoke) <Module>.invoke_void_string_ConcurrentDictionary`2<string, AssemblyMetadata>_AssemblyNameExtension[]&_string[]&_FrameworkName&(string,System.Collections.Concurrent.ConcurrentDictionary`2<string, Microsoft.Build.Tasks.AssemblyDependency.AssemblyMetadata>,Microsoft.Build.Shared.AssemblyNameExtension[]&,string[]&,System.Runtime.Versioning.FrameworkName&)
  at Microsoft.Build.Tasks.SystemState.GetAssemblyMetadata (System.String path, System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue] assemblyMetadataCache, Microsoft.Build.Shared.AssemblyNameExtension[]& dependencies, System.String[]& scatterFiles, System.Runtime.Versioning.FrameworkName& frameworkName) [0x00010] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.GetUnifiedAssemblyMetadata (Microsoft.Build.Tasks.Reference reference, System.Collections.Generic.IEnumerable`1[Microsoft.Build.Tasks.UnifiedAssemblyName]& unifiedDependencies, System.String[]& scatterFiles) [0x00023] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.FindDependenciesAndScatterFiles (Microsoft.Build.Tasks.Reference reference, System.Collections.Generic.List`1[T] newEntries) [0x0003a] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.FindAssociatedFiles () [0x000ea] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.ComputeClosure () [0x0000a] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ReferenceTable.ComputeClosure (System.Collections.Generic.IEnumerable`1[T] remappedAssembliesValue, Microsoft.Build.Framework.ITaskItem[] referenceAssemblyFiles, Microsoft.Build.Framework.ITaskItem[] referenceAssemblyNames, System.Collections.Generic.List`1[T] exceptions) [0x00038] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ResolveAssemblyReference.Execute (Microsoft.Build.Shared.FileExists fileExists, Microsoft.Build.Shared.DirectoryExists directoryExists, Microsoft.Build.Tasks.GetDirectories getDirectories, Microsoft.Build.Tasks.GetAssemblyName getAssemblyName, Microsoft.Build.Tasks.GetAssemblyMetadata getAssemblyMetadata, Microsoft.Build.Shared.GetRegistrySubKeyNames getRegistrySubKeyNames, Microsoft.Build.Shared.GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, Microsoft.Build.Tasks.GetLastWriteTime getLastWriteTime, Microsoft.Build.Tasks.GetAssemblyRuntimeVersion getRuntimeVersion, Microsoft.Build.Shared.OpenBaseKey openBaseKey, Microsoft.Build.Tasks.GetAssemblyPathInGac getAssemblyPathInGac, Microsoft.Build.Tasks.IsWinMDFile isWinMDFile, Microsoft.Build.Tasks.ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader) [0x00515] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.Tasks.ResolveAssemblyReference.Execute () [0x00077] in <de5a1b3cad9b40f1b4a72c6fbcf8f237>:0
  at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute () [0x00029] in <25851c819cf84f6c96378e77482fea8f>:0
  at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask (Microsoft.Build.BackEnd.ITaskExecutionHost taskExecutionHost, Microsoft.Build.BackEnd.Logging.TaskLoggingContext taskLoggingContext, Microsoft.Build.BackEnd.TaskHost taskHost, Microsoft.Build.BackEnd.ItemBucket bucket, Microsoft.Build.BackEnd.TaskExecutionMode howToExecuteTask) [0x002fc] in <25851c819cf84f6c96378e77482fea8f>:0

[fail]: OmniSharp.MSBuild.ProjectManager
        Attempted to update project that is not loaded: /home/timmeh/work/unity/3_Project_Boost/Assembly-CSharp.csproj

```

I've tried changing the useGlobalMono to each possible choice, but none of those help. I have another project using the exact same version of Unity, VSCode, etc. that does not exhibit the same problems. I'm not sure where to begin troubleshooting this.

# Answer
> 5 votes
In Unity Preferences, External Tools section, I turned on the options to generate .csproj files for

* Registry Packages
* Built-in Packages

Now OmniSharp starts without any errors and intellisense appears to be working correctly.

---
Tags: unity
---


# Question
Title: How can I represent location in a massive world?
I've been thinking about No Man's Sky a lot recently and all the technical challenges they must face. For example, how on earth do you store a players location in a world that is so enormous?

I assume x,y,z isn't feasible. I notice the advertised number of planets (18 quintillion) is exactly double the maximum integer you can store on 64-bits, if that is relevant.

From watching tech videos of him (Sean Murray) describing the architecture, he seems to say everything is generated by formula where the inputs are x and y. Obviously he's simplifying, but how might one accomplish this?

# Answer
> 9 votes
Two possible options might be:

* "big number" classes, such as this one, which represent arbitrarily large numbers through mathematics on arrays of integers used to simulate an appropriate storage space.
* hierarchy; that is, using a tiered coordinate system possibly represented by two integers per component; the first integer represents the position of (say) a planetary system within a galaxy, and the second represents position within that system (et cetera)

Fundamentally these are very similar approaches, differing mainly in the interface they present over the multiple-integer abstraction.

A given game may choose one over the other depending on it's needs. For example, in a space game like No Man's Sky, you might only be able to "warp" between star systems. In this case there is a distinct transition phase that the game can use to smoothly transition from one coordinate space to another.

However, you might be able to smoothly and arbitrarily fly from space on to a planet surface, in which case you might have a harder time masking the coordinate system transition (it's doable but might be annoying depending on the rest of your game's implementation and how you deal with straddling cells or something). In that case you might prefer to represent coordinates using a "big number" class that simply let's you pretend you have a larger coordinate space to work in, at the minor cost of some performance now and then.

# Answer
> 2 votes
An int64 is pretty huge (really!), but one way to deal with this sort of a problem is to have one coordinate set define what grid cell you are in (gridx, gridy) then another coordinate set to define the offset within that cell (offsetx, offsety).

Note though that if you used 32 bit ints for the grid cell x and y, and 32 bit ints for the offset x and y, you could combine them into one 64 bit number for each full coordinate component.

In this way, a 64 bit int for positions can be thought of as being equivalent to a 32 bit grid cell with a 32 bit offset within that cell :p

# Answer
> 0 votes
The simplest solution to storing any position is to use floating point numbers (specifically, 3 of them can store a 3D position in a `Vector3`).

Floating point numbers have different levels of precision. Most programs and games use 32-bit single-precision floats, which are not super accurate, they work well for for most games but not ones that take place on huge scales. Single-precision floats have a limited amount of precision, which is unsuitable for games that use large scales. Single-precision floats have 23 significant binary digits (they are 32-bit, 8 of the bits are used for the exponent and 1 bit is used for positive/negative). First-person games depend on the world having better than about half a millimeter of precision. The formula `0.0005 * (2^23)` shows us that errors big enough to notice appear approximately a few kilometers away from the world origin. This is fine for most games, as most games take place on scales smaller than a few kilometers.

The solution, simply put, requires us to add more significant digits. Double-precision floats are 64-bit, with 52 of those bits being significant binary digits. This is 29 more significant binary digits than single-precision floats, which increases the maximum usable area by a factor of about half a billion, to about 2 Tm (2 billion km). We go from a fifth the length of Manhattan to an area greater than the orbital radius of Saturn.

A fair question to ask is how other games handle large scales. Some games that use 64-bit doubles for large scales include Star Citizen, Arma 3, Space Engineers, and Minecraft. There's also Unigine, which is focused on being an engine for simulations, and Unigine can use doubles. For games that need somewhat large scales, sometimes maps are designed around the constraint of 32-bit floats, to be square and approximately 4 kilometers in radius, such as PlanetSide 2's Indar map. Kerbal Space Program had to implement their own 64-bit math types, doing a huge amount of calculations in user code. Even with all their effort, KSP struggled with floating-point issues for many years since the engine they are using (Unity) uses 32-bit single-precision floats, and these issues came to be known as The Kraken.

A commonly cited technique is origin shifting. This involves moving the world around the player such that the player is always near the world origin. This technique can work, but it comes with many of its own limitations. For example, it doesn't always work for multiplayer, where the server needs to have precision for *all* players at once. There are many tricks to make this work better, but this heavily complicates things to the point that it's both easier and more efficient to use doubles.

When this question was asked in 2015, hardware supported acceleration for 64-bit doubles was not as good as it is now, so other techniques such as origin shifting and manually calculating positions with grids and offsets (like Alan Wolfe said) were considered a better idea for AAA games that need as much performance as possible. The modern solution is to simply use doubles, since they are more precise numbers, and they are well supported on modern hardware with things like AVX2 on Intel CPUs from 2013 or newer and AMD CPUs from 2015 or newer (this is especially true if you want to make a AAA game like No Man's Sky where you want to target high-end hardware new enough to have these features).

We don't know what No Man's Sky uses, but I'm going to guess that it uses 64-bit doubles somewhere in its code, and it probably uses shifting and/or grids since it's an older game made when relying on doubles wasn't as efficient of an option.

TL;DR: If you have the choice, use doubles. They are the easiest and most reliable solution, and on modern hardware they are still a performant and efficient solution. Read more here.

---
Tags: mmo, coordinates
---


# Question
Title: How can one achieve the mechanic of hitting cars or bumping into them like in Burnout games' takedown modes?
In Burnout games there's this game mode where the player can trash other cars by bumping into them or bumping them into walls. As you can see in this video link This is known as a takedown.

I'm working on a racing game and I would like to work on a similar feature. I added a bouncy material to my cars collider in hopes that this effect would be replicated to some degree but all it did was to slightly push the cars away from the player.

I don't have that much experience in making games so I'd appreciate any help I could get about the subject.

# Answer
The Unity physics system aims to be realistic. Whether or not it achieves that is a different question, but that's what it tries to do. Unfortunately, realism can be pretty boring. When you want to create a game with spectacular stunts and chaotic crashes, then it can be useful to cheat a little and add forces which technically shouldn't be there but make the game more exciting.

So you might want to add a script to the player which implements `OnCollisionEnter(Collison collision)`. This method gets called when one rigidbody touches another. Use it to check if the object the player's car collided with is an AI car, and if so add a lot more additional force to that car.

How much force exactly and in what direction is a matter of personal taste. But some information which could be helpful to decide that can be found in the Collision object passed to the method:

* gameObject: The thing you actually collided with. Make sure you always verify if this is actually the object you want to influence. Collisions can happen for a lot of reasons with a lot of things you didn't think about. You might not want to push the road around, for example.
* relativeVelocity: The speed and direction with which the two objects collided
* impulse: How powerful the collision was (this is based on the relativeVelocity, but takes masses into account).
* GetContacts(): The point(s) where the two objects collided. This might be interesting if you want different things to happen depending on how the player rammed into the other car.

You can then obtain the rigidbody of the other car with `collision.rigidbody`. Useful methods to make that car fly and spin are:

* AddForce: Adds a force to the car exactly through its center of mass (so it should not directly cause rotation)
* AddTorque: Adds a rotational force (which should not directly affect movement)
* AddForceAtPosition: Adds a force at a certain point, which causes both force and torque depending on where that point is and in what direction you push it.

All these methods should use ForceMode.Impulse, because you are dealing with a one-time event causing a sudden acceleration and not a force acting over time.

I am looking forward to making some cars fly in your game.
> 2 votes

---
Tags: unity, car, racing
---


# Question
Title: Why does ForceMode.VelocityChange work but not Rigidbody.velocity = ... in script?
I have a FPS movement script that I created that has a jump function that looks like this

```
public void Jump()
{
    if (jumpAble && grounded)
    {
        jumpAble = false;
        gameObject.GetComponent<Rigidbody>().velocity = (Vector3.up * jumpForce * Time.deltaTime);
    }
}

```

For some reason, this does not make the player jump. However, replacing the .velocity =... to

```
gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce * Time.deltaTime, ForceMode.VelocityChange);

```

makes the player jump. Why is this? I'm under the impression that the two are essentially the same thing, but is there a slight difference?

Also, not sure if it affects the function, but this is the whole script

```
public class Player_Movement : MonoBehaviour

```

{ public Transform camera;

```
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public bool grounded;

public GameObject joystick;
public bool isWalking = false;
public bool isRunning = false;
public float walkForce = 12f;
public float runForce = 30f;

public float jumpForce;
public bool jumpAble = true;

public GameObject playerRotationHandler;
public float cameraTouchSensitivity;

public Animator animator;

// Update is called once per frame
void Update()
{
    grounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

    if (grounded)
    {
        jumpAble = true;
    }

    Vector3 direction = joystick.GetComponent<Joystick>().inputDirection.x * transform.right + joystick.GetComponent<Joystick>().inputDirection.y * transform.forward;

    if (isRunning)
    {
        gameObject.GetComponent<Rigidbody>().velocity = (direction * runForce * Time.deltaTime);
    }

    else if (isWalking)
    {
        gameObject.GetComponent<Rigidbody>().velocity = (direction * walkForce * Time.deltaTime);
    }

    else
    {
        gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
    }
}

public void Jump()
{
    if (jumpAble && grounded)
    {
        jumpAble = false;
        gameObject.GetComponent<Rigidbody>().velocity = (Vector3.up * jumpForce * Time.deltaTime);
        gameObject.GetComponent<Rigidbody>().AddForce (Vector3.up * jumpForce * Time.deltaTime, ForceMode.VelocityChange);
    }
}

public void Rotate(float xMoveValue, float yMoveValue)
{
    float xRotation = Mathf.Atan2(yMoveValue, cameraTouchSensitivity) * Mathf.Rad2Deg;
    float yRotation = Mathf.Atan2(xMoveValue, cameraTouchSensitivity) * Mathf.Rad2Deg;

    playerRotationHandler.transform.Rotate(xRotation, 0, 0);
    transform.Rotate(0, yRotation, 0, Space.World);

    if (playerRotationHandler.transform.localEulerAngles.x < 300 && playerRotationHandler.transform.localEulerAngles.x > 60)
    {
        if (xRotation < 0)
        {
            playerRotationHandler.transform.localEulerAngles = new Vector3(300, playerRotationHandler.transform.localEulerAngles.y, 0);
        }

        if (xRotation > 0)
        {
            playerRotationHandler.transform.localEulerAngles = new Vector3(60, playerRotationHandler.transform.localEulerAngles.y, 0);
        }
    }
}

```

}

# Answer
> 1 votes
The difference is that while `velocity = value` *sets* the velocity to a new value, `AddForce(value)` *adds to* the existing velocity. The rigidbody will retain any existing momentum it received from velocity changes and forces it received previously. However, in your case it does not, because you overwrite the velocity in every update, causing the rigidbody to "forget" any previous forces and velocity changes.

However, I am a bit confused how your code allows your player to jump at all. Because your Update function will in every situation replace the velocity with a new value, canceling any velocity the rigidbody might have received from the `Jump()` method. Not sure where that method gets called from, though, because there is no reference to it in the code you posted. Perhaps the method gets called from a different script on every single frame while the player holds the jump button? In that case what happens is that the script which called `Jump` and the `Update` method of the script here will compete about who can set the velocity to its preferred value. Whatever script gets executed last wins. Apparently this is the script which does the updating when you use `.velocity =` and the script which does the jumping when you use `.AddForce`.

But how could that be? The script execution order shouldn't be affected by that. Would it?

The answer is that `AddForce` does not actually change the velocity *immediately*. What it actually does is order the physics engine to change the velocity during the next physics update but before applying the velocity to the position. This would happen after all your `Update`s were processed. So the physics engine will add that force on top of the velocity you set in `Update`.

So what can we learn from that?

* Avoid replacing the velocity with `velocity =`. Only add to the velocity directly (`velocity += value`) or indirectly through forces.
* If you *really really want to* set the velocity, then the velocity of each rigidbody should be controlled by one method only, so different methods don't compete with who can set the velocity to its preferred value.

---
Tags: unity, c#, movement, jumping
---


# Question
Title: Why does reading my depth texture in GLSL return less than one?
I've created a depth texture in OpenGL (using C#) as follows:

```
// Create the framebuffer.
var framebuffer = 0u;

glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);

// Create the depth texture.
var depthTexture = 0u;

glGenTextures(1, &depthTexture);
glBindTexture(GL_TEXTURE_2D, depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, 800, 600, 0, GL_DEPTH_COMPONENT, GL_FLOAT, null);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);

```

Later, I sample from the depth texture as follows:

```
float depth = texture(depthTexture, texCoords).r;

```

But even when no geometry has been rendered to that pixel, the depth value coming back is less than 1 (seems to be very slightly above 0.5). This is confusing to me since, per the documentation on `glClearDepth`, the default value is 1. Note that this is *not* a problem of linearizing depth since I'm attemping to compare depth directly (using the same near and far planes), not convert that depth back to world space.

**Why is my depth texture sample returning \<1 when no geometry has been rendered?**

# Answer
I solved it! The problem resulted from sharing a depth texture between two framebuffers. The reason for sharing the texture is that my question was actually simplified compared to reality: it's actually a depth-*stencil* buffer, since I need to share the stencil buffer between two framebuffers while the second reads depth values from the first.

The first framebuffer is generated as shown in my question (except that I used `GL_DEPTH_STENCIL_ATTACHMENT` rather than just `GL_DEPTH_ATTACHMENT`). The second looks like this:

```
var secondBuffer = 0u;

glGenFramebuffers(1, &secondBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, secondBuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthStencilTexture, 0);

```

Later (after rendering the first framebuffer), I render to the second as follows:

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, depthStencilTexture);

quad.Draw();

```

The fix was to **toggle depth testing before and after the draw call**:

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, depthStencilTexture);
glDisable(GL_DEPTH_TEST);

quad.Draw();

glEnable(GL_DEPTH_TEST);

```

As for *why* toggling depth testing fixes the problem (or conversely, why *not* toggling caused the depth value in GLSL to be slightly \> 0.5), I'm not sure. Hoping this answer helps someone else in the future!
> 0 votes

---
Tags: opengl, glsl, depth-buffer, frame-buffer, depth
---


# Question
Title: What's causing this stutter when framerate fluctuates?
I'm working on a class responsible for arm sway in an fps engine, and am having an issue with a stutter that appears to be related to fluctuating framerate. However I have also noticed it when locking the framerate, but to a much lesser almost unnoticeable degree (so maybe NOT related to framerate variance). As far as I can tell I have everything setup the way it should be to account for framerate fluctuations, but apparently I've missed something?? Curious if I've made a glaring oversight that might jump out at someone. I have uploaded a video where you can see exactly what it is I'm talking about.

Any ideas? `update()` is where the magic happens.

```
#include "glm/gtx/string_cast.hpp"
#include "vel/App.h"
#include "vel/helpers/functions.h"

#include "ArmSwayController.h"

ArmSwayController::ArmSwayController() :
    input(vel::App::get().getInputState()),
    swayXYPos(glm::vec2(0.0f, 0.0f)),
    maxSwayDistance(0.1f),
    swaySpeed(0.0f),
    mouseBufferSize(44),
    firstMouseInput(true),
    currentMousePosition(glm::vec2(0.0f, 0.0f)),
    lastMousePosition(glm::vec2(0.0f, 0.0f)),
    mouseDelta(glm::vec2(0.0f, 0.0f)),
{};

glm::vec2 ArmSwayController::getAverageMouse()
{
    glm::vec2 out;

    for (auto& x : this->mouseXBuffer)
    {
        out.x += x;
    }
    out.x = out.x / this->mouseXBuffer.size();

    for (auto& y : this->mouseYBuffer)
    {
        out.y += y;
    }
    out.y = out.y / this->mouseYBuffer.size();

    return out;
}

void ArmSwayController::bufferMouse(glm::vec2 in)
{
    if (this->mouseXBuffer.size() == this->mouseBufferSize)
        this->mouseXBuffer.pop_front();
    if (this->mouseYBuffer.size() == this->mouseBufferSize)
        this->mouseYBuffer.pop_front();

    this->mouseXBuffer.push_back(in.x);
    this->mouseYBuffer.push_back(in.y);
}

void ArmSwayController::bufferMouseXSpeed(float in)
{
    if (this->mouseXSpeedBuffer.size() == this->mouseBufferSize)
        this->mouseXSpeedBuffer.pop_front();

    this->mouseXSpeedBuffer.push_back(in);
}

void ArmSwayController::bufferMouseYSpeed(float in)
{
    if (this->mouseYSpeedBuffer.size() == this->mouseBufferSize)
        this->mouseYSpeedBuffer.pop_front();

    this->mouseYSpeedBuffer.push_back(in);
}

void ArmSwayController::updateMouseDelta()
{
    this->currentMousePosition.x = this->input.mouseXPos;
    this->currentMousePosition.y = this->input.mouseYPos;

    if (this->firstMouseInput)
    {
        this->lastMousePosition = this->currentMousePosition;
        this->firstMouseInput = false;
    }

    this->mouseDelta.x = this->currentMousePosition.x - this->lastMousePosition.x;
    this->mouseDelta.y = this->lastMousePosition.y - this->currentMousePosition.y;

    this->lastMousePosition = this->currentMousePosition;
}

glm::vec2 ArmSwayController::update(float dt) // called once per tick
{
    this->updateMouseDelta();

    this->bufferMouse(this->mouseDelta);
    this->swaySpeed = 0.00000625f / dt;

    glm::vec2 vecToAdd = vel::helpers::functions::invertVec2(this->getAverageMouse());

    // X
    this->bufferMouseXSpeed(vecToAdd.x);

    float pullBackAmountX = this->mouseXSpeedBuffer.size() > 1 ? this->mouseXSpeedBuffer[this->mouseXSpeedBuffer.size() - 2] : this->mouseXSpeedBuffer[0];
    pullBackAmountX = pullBackAmountX < 0 ? fabs(pullBackAmountX) : (-1.0f * pullBackAmountX);

    this->swayXYPos.x += ((vecToAdd.x + pullBackAmountX) * this->swaySpeed);

    // Y
    this->bufferMouseYSpeed(vecToAdd.y);

    float pullBackAmountY = this->mouseYSpeedBuffer.size() > 1 ? this->mouseYSpeedBuffer[this->mouseYSpeedBuffer.size() - 2] : this->mouseYSpeedBuffer[0];
    pullBackAmountY = pullBackAmountY < 0 ? fabs(pullBackAmountY) : (-1.0f * pullBackAmountY);

    this->swayXYPos.y += ((vecToAdd.y + pullBackAmountY) * this->swaySpeed);

    return this->swayXYPos;
}

```

# Answer
> 4 votes
You're averaging the total travel of the mouse on a frame.

The travel of the mouse is proportional to the speed the player is moving the mouse *and the duration over which you measure the movement*.

Assuming the player has been moving the mouse at approximately the same speed for several frames in a row, if some of those frames were shorter (less time between calls to `updateMouseDelta`), then you'll store a smaller number in your buffer for those frames. If some of those frames were longer, you'll store a larger number.

So these are not exactly comparable measurements. Let's say the player moves the mouse right at 1000 screen pixels per second. Then at a given moment, your buffer might contain records of...

```
Mouse delta +16 in 16 ms
Mouse delta +17 in 17 ms
Mouse delta +15 in 15 ms
Mouse delta +20 in 20 ms

```

(Average delta +17)

If that +20 in 20 ms gets evicted for a new sample of +15 in 15 ms, that will substantially shift the average of the buffer (to 15.75). But it shouldn't, because the player's movement didn't actually change.

By weighing all these values equally in your average, you're claiming they all measure the same thing, but they don't, they represent observations over different durations.

So this is why you get a slight vibration here, from the happenstance of a stray short or long frame (or a random run of a few) dropping into your buffer and biasing the results one way or another.

To correct for this, you should divide your mouse delta by the time elapsed since you last set `lastMousePosition`. This will give you an estimate for how *fast* the mouse is moving, and that's something you can directly compare between frames. In that case our buffer might look more like...

```
Mouse delta +16 in 16 ms => speed +1 px/ms
Mouse delta +17 in 17 ms => speed +1 px/ms
Mouse delta +15 in 15 ms => speed +1 px/ms
Mouse delta +20 in 20 ms => speed +1 px/ms

```

Now our average speed stays stable.

---
Tags: c++, movement, mouse, frame-rate
---


# Question
Title: UE4 - Event Tick and getting Forward Vector
I'm trying to make a game where my character rotates towards cursor (that works). He can choose between a few weapons (also works). One of the weapons works like a machine gun. My idea was to make a simple solution with:

Event tick -\> gate (opened by pulling LBM and closed by releasing it) -\> gate (closed after firing and opened after some delay) -\> spawning projectile which leads to a sequence that closes / opens the second gate.

It doesn't work perfectly. The projectile spawns with the right scale and location, but the rotation is always pointing straight forward.

If the exactly same blueprint is attached to anything else (straight up to the LMB pull or a timer), it works perfectly. However, doing the LMB pull defeats the whole purpose, as it's not a machine gun any more, and timer... is less then perfect I believe. I liked my solution using gates but it just doesn't want to work.

For example, this bit works with no problem (even though the spawning and rotation code is literally copy pasted):

Does anyone have an idea on how to fix this?

# Answer
I found out what is wrong.

Apparently, the rotation of the gun finished only after the projectile was spawned. (It's weird because it doesn't happen usually).

This fixed it:

The setting in red is the default one. Any of the green settings are good enough for this solution to work.

I hope that someone with similar issue finds this one day and saves some time :)
> 2 votes

---
Tags: rotation, unreal-4
---


# Question
Title: How to resolve "Accessed None trying to read property" error?
**Whenever I finish running the project, this error message appears:**

> Blueprint Runtime Error: "Accessed None trying to read property jogador". Blueprint: Jogador\_BP\_Anim Function: Execute Ubergraph Jogador BP Anim Graph: Transition Node: Result

**By clicking to know where the error is coming from, the program tells me this code:**

**This is the code I made to get the player reference (jogador/player Animation Blueprint):**

**This is basically for the transition code between animations, to receive information whether or not the player is jumping (jogador/player Blueprint):**

Animations perform normally, so the error doesn't seem to compromise project execution, but why does it occur?

I looked at some links, but I don't know how to remove it.

https://forums.unrealengine.com/development-discussion/blueprint-visual-scripting/86607-accessed-none-trying-to-read-property

# Answer
> 2 votes
Do not ever dereference anything from any other classes In animation’s state machine. (You can dereference only in the EventGraph).

First the reference may not be there yet, when the AnimBP is running. Second, AnimBP state machine is designed to be multithreaded, but dereferencing any other class in BP is not thread safe.

TL DR: Do not use any bool variables from any other classes, all the state changing booleans should be within the animation blueprint itself.

Then set the booleans in anim’s BP EventGraph from any other class.

# Answer
> 2 votes
Easy fix, in the `animBP Update Animation` sequence, instead of checking `pawn owner`, check the `player` variable that is created by `begin play`. In this case labelled "Jogador".

The pawn will be available before the animation begin play can officially execute, so there will be a singular execution of the update before the required player reference is actually set. Checking the variable validity instead of the player pawn will ensure everything is set before updating.

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


# Question
Title: Draw LineRenderer gradually, rather than all at once
I'm drawing a line with a `LineRenderer`. It works, but now I would like it the line to be drawn gradually, instead of appearing all at once.

How can I modify my code to achieve this?

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

public class LineController : MonoBehaviour
{

    private LineRenderer Ir;
    private Transform [] points;

    private void Awake(){

        Ir = GetComponent <LineRenderer>();
    }

    public void SetUpLine (Transform[] points){
        Ir.positionCount = points.Length;
        this.points = points;
    }

    private void Update (){
        for (int i = 0; i < points.Length; i++) {
            Ir.SetPosition(i, points[i].position);
            Debug.Log (points[i].position);
        }

    }
}

```

# Answer
You can use MathF.lerp. You would draw it from the start position to finish position by lerping it between them based on the elapsed time.
> 0 votes

---
Tags: unity, c#, line-renderer
---


# Question
Title: Unity - 2D Platformer Controller responsiveness issue
I've been designing some basic controls for a 2D platformer and managed to get the feeling that I've been looking for when moving and jumping, but something is not quite right, it's not very responsive.
Most of the inputs are detected, but a lot of times, for example, the simple action of pressing some key to jump is completely ignored and the player ends up falling when the key was pressed at the right time. I don't consider that I'm developing on a laptop with low specs at all if that matters.
Looking at some other questions it has always been said that input detection should be inside the Update function and that physics related stuff should be on FixedUpdate, however, it has not always been very clear what exactly should be on which function, as far as I understand it should go something like this...right?

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

public class PlayerController : MonoBehaviour {
    public float speed;
    public float jumpForce;
    public float groundCheckRadius;

    public Transform groundCheck;
    public LayerMask groundMask;

    private float direction;

    private bool facingRight;
    private bool shouldJump;
    private bool isGrounded;
    private bool shouldFall;

    private SpriteRenderer renderer;
    private Rigidbody2D rigidbody;

    void Awake() {
        this.renderer = GetComponent<SpriteRenderer>();
        this.rigidbody = GetComponent<Rigidbody2D>();
    }

    void Start () {
        this.facingRight = true;
        this.shouldJump = false;
        this.isGrounded = false;
        this.shouldFall = false;
    }

    void Update () {
        this.direction = Input.GetAxisRaw("Horizontal");
        this.isGrounded = Physics2D.OverlapCircle(this.groundCheck.position, this.groundCheckRadius, this.groundMask);
        this.shouldJump = Input.GetKeyDown(KeyCode.S) && this.isGrounded;

        if (this.facingRight && this.direction < 0 || !this.facingRight && this.direction > 0)
            this.Flip();

        if (Input.GetKeyUp(KeyCode.S) && this.rigidbody.velocity.y > 0)
            this.shouldFall = true;
    }

    void FixedUpdate() {
        Vector2 velocity = this.rigidbody.velocity;

        if (this.shouldFall) {
            velocity.y = 0f;
            this.shouldFall = false;
        }

        if (this.shouldJump)
            velocity.y = this.jumpForce;

        velocity.x = this.speed * this.direction;

        this.rigidbody.velocity = velocity;
    }

    private void Flip() {
        this.renderer.flipX = this.facingRight;
        this.facingRight = !this.facingRight;
    }
}

```

I'm not sure if I got the idea of Update vs FixedUpdate correctly because of this lack of responsive jumps, and I'm guessing that if I add some more mechanics, later on, those will react the same or worse.

Something that I noted is that if I move everything to update it now feels right every time I press the jump button, but I'm still not sure if that should be the right approach when building tight controls.

And I still feel lost about what everyone means by "You should manage physics in FixedUpdate", what do you mean by physics here?

# Answer
> 0 votes
There’s no explicit guarantee about how many times `FixedUpdate` gets called between calls to `Update`, so it can get called any number of times, including zero. Your problem may be that `shouldJump` is getting set to true and then to false again before it gets a chance to be applied. Try instead only setting it to true in `Update`, and setting it to false in `FixedUpdate`. You should also check `isGrounded` in `FixedUpdate`.

```
    void Update () {
        if (Input.GetKeyDown(KeyCode.S))
            this.shouldJump = true;
    }

    void FixedUpdate() {
       if (this.shouldJump) {
            if (Physics2D.OverlapCircle(this.groundCheck.position, this.groundCheckRadius, this.groundMask))
                velocity.y = this.jumpForce;
            this.shouldJump = false;
       }
    }

```

# Answer
> 0 votes
Unfortunately a little input lag is likely to happen when using the Unity Physics engine. This is because physics updates happen after the FixedUpdate functions are called and input updates are processed just before the Update functions. Typically FixedUpdate *tries* to run 50 times per second while Update *tries* to run 30 times per second, 60 times per second, or more. As a result you can't expect your FixedUpdate function to always run immediately before or after your Update function. I would suggest you ready this page of documentation for more information on how Unity decides the execution order of functions.

Although I haven't tested it, I think these changes should prevent commands from getting lost during execution, however you will still experience about 0.02 seconds of input lag while you wait for the physics engine. This should behave the same if you were to run everything inside the Update function since **Physics updates do not get processed until after FixedUpdate**.

```
// Read input updates and process non-physics updates.
private void Update()
{
    direction = Input.GetAxisRaw("Horizontal");

    shouldJump = shouldJump || (Input.GetKeyDown(KeyCode.S) && isGrounded); // jump may not be processed immediately so remember old jump requests

    if ((facingRight && direction < 0) || (!facingRight && direction > 0)) // There was a parenthesis bug here
        Flip();

    if (Input.GetKeyUp(KeyCode.S))
        shouldFall = true;
}

private void FixedUpdate()
{
    isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundMask);

    Vector2 velocity = rigidbody.velocity;

    // be careful with this check if you need to move your character up in the Y for any non-jump related reasons.
    if (shouldFall && rigidbody.velocity.y > 0)
    {
        velocity.y = 0f;
        shouldFall = false;
    }

    if (shouldJump) // always put { } even on a one line if to save yourself future bugs
    {
        velocity.y = jumpForce;
        shouldJump = false;
    }

    velocity.x = speed * direction;

    rigidbody.velocity = velocity; // if you call rigidbody chances are this is a physics update.
}

```

I believe (can't test to be sure) the main reason you are occasionally losing jump commands is because your old logic over wrote the shouldjump variable every update frame. In the case you have high fps you could expect unity to execute your update logic like this: Update(), Update(), Update(), FixedUpdate(), Update(), Update(), FixedUpdate(), Update(), Update(), Update(), FixedUpdate(), etc.. As a result some of your jumps never had a chance to update the characters velocity. That being said, I am personally a hypocrite and often run physics in the Update function, for simple toy games and experiments it doesn't hurt to do stuff the wrong way once in a while so don't stress best practices like only running physics updates in the FixedUpdate function too much.

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


# Question
Title: Finding the position of a point inside a triangle, based on the position of a point in another triangle (barycentric coordinates in Godot)
I'm trying to translate a UV coordinate into a world coordinate. (this is not in a shader, it's in GDScript in Godot, to bake out a texture based on some raycasts).

So I find out which triangle in the UV map the coordinate is in and then I find the corresponding triangle in the mesh and get it's world position, that's all good.

But then I can't figure out how to translate the points relative position inside the UV triangle to the mesh triangle.

I've been trying to use the distance from the point to each of the triangle points as weights to how much of each of the mesh points I should use to find the point I'm looking for, but having no luck.

Any help would be much appreciated.

Not sure how best to illustrate this. But imagine you had a triangle where you knew the corner points a, b, and c, and a position inside it p. And you had another triangle where you knew the corner points A, B and C, how would you find a point that was relative in the same as p is to abc in triangle ABC.

***EDIT: I added an answer based on the comments from DMGregory***

# Answer
As DMGregory suggested, Barycentric Coordinates were indeed the solution. Since there are no built-in functions for converting Cartesian to Barycentric in Godot, I converted the c++ answer here What's the most efficient way to find barycentric coordinates? to GDScript:

```
func cart2bary(p : Vector3, a : Vector3, b : Vector3, c: Vector3) -> Vector3:
    var v0 := b - a
    var v1 := c - a
    var v2 := p - a
    var d00 := v0.dot(v0)
    var d01 := v0.dot(v1)
    var d11 := v1.dot(v1)
    var d20 := v2.dot(v0)
    var d21 := v2.dot(v1)
    var denom := d00 * d11 - d01 * d01
    var v = (d11 * d20 - d01 * d21) / denom
    var w = (d00 * d21 - d01 * d20) / denom
    var u = 1.0 - v - w
    return Vector3(u, v, w)

func bary2cart(a : Vector3, b : Vector3, c: Vector3, barycentric: Vector3) -> Vector3:
    return barycentric.x * a + barycentric.y * b + barycentric.z * c

```
> 3 votes

# Answer
I just stumbled across this question and wanted to post my solution, which is a lot smaller and more efficient than Kaspers answer:

```
static func transfer_point(from : Basis, to : Basis, point : Vector3) -> Vector3:
    return (to * from.inverse()).xform(point)

```

`from` and `to` are the triangles represented as a Basis like this: `Basis(x, y z)`. A basis is a 3x3 matrix.
> 0 votes

---
Tags: geometry, godot, uv-mapping, barycentric-coordinates
---


# Question
Title: reading input from multiple mice in QB64 in Windows 10?
I am looking to write a non-network multiplayer game for Windows 10 with QB64 that accepts input from 2 or more USB mice plugged into the system. Like a simple Pong game where additional players plug mice into a USB hub to use as game controllers.

I have been googling this and found some older threads

however these are pretty old threads from before Windows 10, also they seem to be more oriented towards C++ or .NET.

Can anyone provide some example how it might be done with QB64 under Windows 10?

Thanks

# Answer
From the docs on Controller\_Devices:

> * In order to read the device controls, the number of input devices MUST first be found using `_DEVICES`.
> * After the device count is determined we can find out the type of device, the device name and the type of controls available using the `_DEVICE$(device_number)` function. The function returns a `STRING` containing information about each numbered device.

When I tried the example code for displaying attached devices, on my system it failed to report the presence of an additional mouse.

The project maintainer suggested using `MOUSEPIPEOPEN`, but I was not able to separate clicks from two mice on the same PC.
> 0 votes

---
Tags: multiplayer, mouse, multitouch
---


# Question
Title: OpenGL: What to do after running glBufferData?
I am interested in understanding a bit more behind how OpenGL does its memory management and what are some good practices before I start heavily coding and back myself into a corner.

The real question I have is regarding memory. I have a class called `Mesh` that consists of a pointer to some vertex data, a pointer to the face data, as well as the number of vertices and faces. I am familiar with one possible process that OpenGL uses to get these drawn on the screen: generate a buffer for vertices and a buffer for faces, bind them as `GL_ARRAY_BUFFER` and `GL_ELEMENT_ARRAY_BUFFER`, call `glBufferData` to move the data to the buffers, and lastly call `glDrawElements` to draw them. From here I can understand how I can load several `Mesh` objects and draw them on screen, and I have no issue there.

My question then lies in where the memory is stored and what I should be doing in order to conserve memory. My assumption is that after the call to `glBufferData`, the data is copied to the GPU (or to some other register to later be copied to the GPU). Is it safe for me to delete the original `Mesh` object that was used with the buffer calls? In my head, the mesh data is retained inside the GPU so the data is not lost, and so long as I do not need to reload this data using OpenGL later then I won't miss this data at any point. Also in my head, this frees up RAM space for other uses, so my `Mesh`, in some sense, now totally lives in GPU memory and nowhere else, and I can do my drawing solely by making OpenGL calls to the correct buffers (so I obviously need to save the generated buffer IDs, but that part goes without saying).

If someone could tell me if this is correct/incorrect logic, as well as good/bad game dev practice?

# Answer
We all started once. Let me suggest to get the OpenGL Pogramming Guide 9th Edition, aka the "Red Book". It's worth so much more than any internet tutorial, especially in the beginning.

Yes, after calling glBufferData() the data has been passed to the video driver and been copied to VRAM (to be exact, where exactly it resides depends on a few settings) and can be deleted from your application's memory if it is not needed elsewhere.

And yes you must store the buffer names ("ids"). They are the handles to the OpenGL objects and you need them everywhere, including deletion when they are no longer needed.
> 2 votes

---
Tags: opengl, graphics-programming, memory-efficiency
---


# Question
Title: C++ SDL2: How to join two windows in one: top_Window + bottom_Window?
I have a code where the camera scroll left, right, up, down, and I would like to add a progress bar similar to the one below at the bottom of my window

Is it possible to create the progress bar in a different window and then join my top game window with this new window, so they can render at different times? If not (by using only one window) when scrolling up and down I would have that progress bar in the way, indeed my camera is set to the exact dimension of window height and window width and currently works flawlessly without that bar because the bar is not part of my current texture.

Any suggestion how to join two windows in one? I have created the bottom\_Window so far (so I can try to develop the progress bar) but I want it to be fully merged with the top one (the actual game) so they can be moved at the same time)

Many thanks!

# Answer
> 0 votes
The X, Y positions of Player and Backgrounds were rendered relative to the camera:

Example:

const SDL\_Rect PlayerQuad = {(int)(Player.XPosition - Camera.XPosition), (int)(Player.YPosition - Camera.YPosition), (int)Player.Width, (int)Player.Height};

SDL\_RenderCopy(pRenderer, Player.playerTexturewr, nullptr, &PlayerQuad);

The X, Y positions of the progressing bar had to be rendered NON RELATIVE TO THE CAMERA):

const SDL\_Rect BarQuad = {(int)Bar.XPosition, (int)Bar.YPosition, (int)Bar.Width, (int)Bar.Height}; SDL\_RenderFillRect(pRenderer, &BarQuad);

---
Tags: c++, sdl2
---


# Question
Title: How to disable present function when window is invisible to user. Win32 & DXGI
When my game window is hidden say by minimising it or hitting Ctrl, Alt, Del. I get the DXGI error:

*0x087A0001 : The Present operation was invisible to the user.*

I've tried wrapping the present function inside an if statement to check whether the window is visible, this comes from: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-iswindowvisible

And looks like this in my code:

```
bool Graphics::WindowVisible() const
{
    if (IsWindowVisible(hWnd) == TRUE)
    {
        return true;
    }
    return false;
}

```

I've created the function in my window object too, and applied it to my EndFrame() call but this doesn't work either.

The function never seems to return false. Any ideas on the best way forward would be gratefully received. If using a check for visibility isn't on the cards, Is there a way to simply disregard the DXGI error and simply throw the frame away and would that be a good idea.

# Answer
> 1 votes
Well, after some checking and some help from some more tenured practitioners, I have learned that this 'error' is actually a status.

I was doing some pretty wrong (so wrong) hresult checking which was throwing this result as an error. However the recommended error check for present:

```
if (FAILED(hr = pSwapChain->Present(1u, 0)))

```

just passes this by and doesn't throw a hissy fit which is what we probably all want.

Thanks to those who commented!

---
Tags: c++, directx11, win32, dxgi
---


# Question
Title: How do I delete all saved preferences in my libgdx project?
I want to delete the preferences that saved my last highscore. How can I do this?

Here's how I am saving preferences at the moment:

```
prefs = Gdx.app.getPreferences("ZombieBird");
if (!prefs.contains("highScore")){
    prefs.putInteger("highScore", 0);
}

public static void setHighScore(int val) {
   prefs.putInteger("highScore", val);
   prefs.flush();
}

```

# Answer
To delete preferences data—

## Manually

On **desktop**, shared preferences data is in `User/.prefs`. Simply delete the files in it.

On **Android**, do *App Info**Clear data*.

## Programmatically (Android and Desktop)

If you change the Key (string) of your sharedpreferece you will lose your data. To do this, use

```
prefs.putInteger("keyString", newValue)

```
> 8 votes

# Answer
To do it programmatically without having to keep track of all the keys:

```
Preferences prefs = Gdx.app.getPreferences( "your_preferences_name_here" );

// Clears the values
prefs.clear();

// Saves the change
prefs.flush();

```
> 4 votes

# Answer
Just for the Mac to delete preferences/data you need to go to:

```
~/.prefs

```

and delete you game file.

https://github.com/libgdx/libgdx/wiki/Preferences#storage
> 1 votes

---
Tags: libgdx
---


# Question
Title: How do I determine the player's grid position?
My original method for doing this involved taking the player's position, dividing it by the grid cell size, and rounding the result. This works for most cases except when I move my player up above y-axis zero or to the left of x-axis 0. I use the grids to load chunks of procedurally generated tiles into my scene.

it keeps resulting in -0 being a component of the position vectors, which throws my system off. I fixed that by converting each component to integers, but that doesn't solve the greater problem.

There must be a more effective method for this available.

EDIT:

I am using Godot Engine and GDscript for the game I am creating.

This is my code:

```
    func calculate_grid_position():
    var grid_position = Vector2(int(round(position.x/ 1600)),
                                int(round(position.y/ 1600)))
    return grid_position

```

# Answer
It's common for negative zero to behave in unintuitive ways. Complicating things, I wasn't able to find an official doc detailing what sort of behavior a programmer should expect from Godot regarding negative zero.

So the best suggestion I can offer is to special case `-0` to behave as needed:

```
func calculate_grid_position():
    var tempX = int(round(position.x/ 1600)
    if tempX == -0:
        tempX = -1
    var tempY = int(round(position.y/ 1600)
    if tempY == -0:
        tempY = -1
    var grid_position = Vector2(tempX, tempY)
    return grid_position

```

It would be a good idea not to hard coded the cell size (int this case `1600`), but without more knowledge about your code, I can't specifically tell you how to fix that other than suggesting you to move those values into a variable or a constant.

As an end note, the desired mapping as described in the question & comments seems a bit unusual. I generally wouldn't expect `-0` to arise under most situations. When I have needed to handle it as a special case, I've either converted it to `0` or treat it as an error / exception.
> 1 votes

---
Tags: mathematics, procedural-generation, tilemap, grid, godot
---


# Question
Title: How do I add materials to a glTF model in Godot Engine?
I'm using **glTF Embedded files** because I was told they are the best files to use with Godot, so I got a pack of a bunch of really lovely trees and other things to use in my game. But when I import it, it has all the materials on the side with the base being completely white. I know how to add textures onto things but it seems there is no way to add anything to the model? How would I use these materials then? Is this my fault or the model creator's fault?

# Answer
> 0 votes
*This answer applies for the Godot 3 branch.*

Open the model scene. Godot will ask if you want to open an inherited scene, or open anyway. Either works※.

Once you have it open, find the MeshIntance nodes in the scene tree. They have a material attribute where you can load or modify your materials.

Once you have it set up. Use **Save as** to save a copy of the scene as a new one. It is the new scene the one you will use.

※: What is the difference? The inherited scene will reference the original, and keep track of the modifications. Which is good if you are also doing 3D design and you want to work on it after it was imported in Godot, and have Godot re-import it automatically. The inherited scene also has the limitation that it will not let you remove anything. If you are not doing 3D design, I suggest to avoid that option. *There have been discussion on changing this, since the way models are imported causes confusion to many users, which is why I specify this answer is for Godot 3.*

---

*If you are using Godot 3.2.4, you have the new fbx importer. It solves a lot of problems that Godot had with fbx in the past. I would still suggest gltf or glb because they are an open specification (fbx is a provative format), yet you won't have go out of your way if you want to import fbx into Godot, most of the time (some material attributes are not supported at the time of writing).*

---
Tags: models, godot, materials
---


# Question
Title: How can I fix “Cannot read value of type Vector2 from composite” error in Unity?
I'm making a 2D game with Unity using the new Input System. I used `spriteRenderer.flipX` to flip the player but since it is made of three parts (body and two eyes), the `spriteRenderer` didn't work. Also, I couldn't convert them to a single sprite because I need the eyes in order to animate them. So, I decided to use `transform.localscale` for flipping and change `movementInput` value from a float to a Vector2. The problem is that when I press the arrow or AD keys to move the character, an error pops up saying "Cannot read value of type Vector2 from composite". This error is from `InputActionState` which is a long and complicated code related to the new Input System. Also, getting input from gamepad causes the same error. I don't know what does this error mean and how can I fix it. Now, the player can jump but it can't move or flip. You can see the code, the error and my action map down below.

This is my Player Controller:

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

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float speed, jumpSpeed;
    [SerializeField] private LayerMask ground;
    private PlayerActionControls playerActionControls;
    private Rigidbody2D rb;
    private PolygonCollider2D pol;
    private Animator animator;
    private bool facingRight = true;
    private Vector2 movementInput;

private void Awake() {

    playerActionControls = new PlayerActionControls();
    rb = GetComponent<Rigidbody2D>();
    pol = GetComponent<PolygonCollider2D>();
    animator = GetComponent<Animator>();

   }

private void OnEnable() {

    playerActionControls.Enable();

   }

 private void OnDisable() {

    playerActionControls.Disable();
   }

 void Start()
   {
     playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue<float>());

    }

private void Jump(float val) {
       if (val == 1 && IsGrounded()) {
           rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);
       }
   }

private bool IsGrounded() {

       Vector2 topLeftPoint = transform.position;
       topLeftPoint.x -= pol.bounds.extents.x;
       topLeftPoint.y += pol.bounds.extents.y;

       Vector2 bottomRightPoint = transform.position;
       bottomRightPoint.x += pol.bounds.extents.x;
       bottomRightPoint.y -= pol.bounds.extents.y;

       return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground);
   }
     void FixedUpdate()
   {
       if(facingRight == false && movementInput.x > 0){
           Flip();
       } else if (facingRight == true && movementInput.x < 0){
           Flip();
       }
   }
   void Flip(){
        facingRight = !facingRight;
        Vector3 Scaler = transform.localScale;
        Scaler.x *= -1;
        transform.localScale = Scaler;
   }

   void Update()
   {
      movementInput = playerActionControls.Land.Move.ReadValue<Vector2>();

       Vector2 currentPosition = transform.position;  // This was a Vector3 but since I got the error  "Operator '+=' is ambiguous on operands of type 'Vector3' and 'Vector2", I changed it to a Vector2.
       currentPosition += movementInput * speed * Time.deltaTime;
       transform.position = currentPosition;

   }
}

```

This is the error I get when I want to move the player.

This is my action map.

# Answer
There are a few errors in your code.

1. In your Update you declare a second local movementInput Vector2. This one hides your movementInput in your class and while no errors are produced, your Flip() won't work. Delete the Vector2 in front of movementInput.
2. Your actionMap looks wrong. Your action needs to be of the type Value with ControlType Vector2. Next you are missing the Composite 2D Vector for your input. It should look like this
> 1 votes

# Answer
> The only reason why I want to change the value from float to Vector2 is for `movementInput.x`. If I keep movementInput as a float, then I get an error because the float doesn't contain a definition for x

Yes, a float doesn't have an `x` property because it's a single numeric value. The `x` property of Vector2 *is* a float. It sounds like you need to brush up on your basic data structures like floats and Vectors.

What you need is this:

```
private float movementInput;

void FixedUpdate() {
    if(facingRight == false && movementInput > 0){
        Flip();
    } else if (facingRight == true && movementInput < 0){
        Flip();
    }
}

void Update() {
    movementInput = playerActionControls.Land.Move.ReadValue<float>();

    transform.Translate(movementInput * speed * Time.deltaTime, 0);
}

```
> 0 votes

---
Tags: unity, c#, movement, input, jumping
---


# Question
Title: UNITY : how to pause baking and quit project?
How to pause the lighting bake and quit the project ? so when i re-open the scene it will continue baking without have to start the bake from beginning ?

I need to take a break to do other job on my computer, because after i turn on 'auto generate' , the baking takes very very long. I want to quit unity and continue later.

Right now if i reopen the project , it will bake from start again.

Thanks

# Answer
> 1 votes
Since your hardware should be up to the task of baking, it's time to troubleshoot other possible issues. I can't comment on whether there's an issue with baking in Mac versions of Unity.

Some simple things to try:

1. Upgrade to the latest version of Unity if you haven't already, in case this is a bug they've already fixed.
2. Try creating a new scene in a new project, add a couple of cubes, and bake. If it goes fast, this suggests there's something wrong with the settings or assets in the scene you're trying to bake in your main project.
3. Try switching the lightmapper between "Progressive CPU" and "Progressive GPU" to see if that resolves the issue

---
Tags: unity, lighting
---


# Question
Title: In Unity, how do I set constant player numbers such that all network clients agree on them?
We are currently writing an online game in Unity. The essential idea is that it is structured like a split-screen, couch co-op game, with the online being offered as an extension to allow multiple players (up to 4) to play remotely or using their own screens. In a network game, players can devote the screen to their own view, but can also see exactly what each other player sees either using screen switching or split screen. As such, it is important for each player to synchronize their own camera, and for each player to have a constant player index number so that other players can easily call up their camera (i.e. from a `SyncList` or similar).

However, I cannot figure out how to implement this. I am attempting to use the UNet RPC interface to have the client call into the server, assign a player number, then report that value back to the client. However, not only do RPCs not return values, they also appear to have a very limited style that only allows them to be called on objects owned by a particular player - `ClientRpc` and `TargetRpc` can only be called by clients, and `Command` does not give a reliable way to tell which client called it. I did manage to get around the first problem with a library that lets async calls return values using what are essentially JavaScript Promises, but when I try to make directed Rpc calls, the Unity runtime rejects the call from the client.

Simply put, I want a single client to ask the server a question, and get a response back from it. This seems like a fundamental thing to have in a network architecture, and is the basis of many RPC systems such as HTTP REST calls. Is UNet simply not designed for this kind of interaction whatsoever?

My code is below - this is a NetworkBehaviour script attached to a root object that is visible to all clients, but has no other duties. The design is that the client would call `AssignPlayerNumber` to get a Promise yielding their canonical player index, and the server would maintain the actual list of player numbers so that numbers don't get mixed up.

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

public class PlayerNumberBroker : NetworkBehaviour {

    // NOTE: Right now, this uses the player GameObjects as the universal key,
    // which might not work if player objects are despawned

    public struct PlayerUniversalKey
    {
        public bool present;
        public GameObject playerObject;
    }

    public class SyncListPlayers : SyncListStruct<PlayerUniversalKey>
    {

    }

    private SyncListPlayers players;

    private void Start()
    {
        players = new SyncListPlayers();
    }

    private int assignPlayerNumberRequestSequenceNum = 0;
    private Dictionary<int, IPendingPromise<int>> assignPlayerNumberRequests = new Dictionary<int, IPendingPromise<int>>();

    public IPromise<int> AssignPlayerNumber(GameObject player)
    {
        if (isServer)
        {
            return Promise<int>.Resolved(AssignPlayerNumber_Inner(player));
        }
        else if (isClient)
        {
            Promise<int> promise = new Promise<int>();
            int requestNum = assignPlayerNumberRequestSequenceNum++;
            assignPlayerNumberRequests.Add(requestNum, promise);
            TargetAssignPlayerNumberRequest(this.connectionToServer, player, requestNum);
            return promise;
        }
        else
            throw new System.Exception("Caller to AssignPlayerNumber is neither client nor server");
    }

    private int AssignPlayerNumber_Inner(GameObject player)
    {
        PlayerUniversalKey keyToUse = new PlayerUniversalKey()
        {
            present = true,
            playerObject = player
        };
        int indexToUse;
        for (int i = 0; i < players.Count; i++)
        {
            if (!players[i].present)
            {
                indexToUse = i;
                goto indexFound;
            }
            else if (players[i].playerObject.Equals(player))
            {
                // Simply return the already assigned player number
                return i;
            }
        }
        indexToUse = players.Count;
        players.Add(keyToUse);

        indexFound:
        players[indexToUse] = keyToUse;
        players.Dirty(indexToUse);
        Debug.Log(player.ToString() + ":" + indexToUse.ToString());

        return indexToUse;
    }

    [TargetRpc]
    private void TargetAssignPlayerNumberResponse(NetworkConnection target, int playerNumber, int requestNumber)
    {
        IPendingPromise<int> promise = assignPlayerNumberRequests[requestNumber];
        assignPlayerNumberRequests.Remove(requestNumber);
        promise.Resolve(playerNumber);
    }

    // run on server only
    // TODO: Apparently this STILL doesn't work, because a TargetRpc can only be called by a server.
    // We will have to figure out a way to pass a message more directly (though, as can be seen here,
    // we don't have to do much to make that happen).
    [TargetRpc]
    private void TargetAssignPlayerNumberRequest(NetworkConnection caller, GameObject player, int requestNumber)
    {
        int indexToUse = AssignPlayerNumber_Inner(player);

        TargetAssignPlayerNumberResponse(caller, indexToUse, requestNumber);
    }

    // run on server only
    [TargetRpc]
    public void TargetFreeAssignmentRequest(NetworkConnection caller, GameObject player)
    {
        for (int i = 0; i < players.Count; i++)
        {
            if (players[i].playerObject.Equals(player))
            {
                players[i] = new PlayerUniversalKey()
                {
                    present = false,
                    playerObject = null
                };
            }
        }
    }

    public int GetPlayerNumber(GameObject player)
    {
        for (int i = 0; i < players.Count; i++)
        {
            if (players[i].present && players[i].playerObject.Equals(player))
            {
                return i;
            }
        }
        return -1;
    }
}

```

# Answer
> 1 votes
Forgive me if this answer is a little rough, I am copying it from a similar project I have where users need to know their own IDs so some of this may be a mix of real code and untested pseudo code. What I do is similar to your promise system, I have the server/host create players and assign their IDs and then have the networked clients query the server/host for their ID and the other players IDs. This is usually the only script I attach to the player prefab in the network settings. Let me know if anything is broken, I cleaned it up on the spot and removed all references to local players (my game allowed a mix of local players on gamepads and networked players).

```
public class ClientHandle : NetworkBehaviour
{
    public GameObject playerPrefab;
    public PlayerController localPlayer;
    private static int nextAvailablePlayerId = 0;

    private void Start()
    {
        if (isLocalPlayer)
        {
            CmdSpawnPlayerPrefab(); // I am a new player
        }

        if (!isServer && hasAuthority)
        {
            CmdReloadPlayersOnNewClient(); // This guy was here before it was cool
        }
    }

    #region Initialize New Players

    [Command]
    private void CmdSpawnPlayerPrefab()
    {
        GameObject spawnedPlayer = Instantiate(playerPrefab);
        NetworkServer.SpawnWithClientAuthority(spawnedPlayer, connectionToClient);

        RpcInitializePlayer(spawnedPlayer, nextAvailablePlayerId);

        if (!isClient)
        {
            PlayerInitialize(spawnedPlayer, nextAvailablePlayerId);
        }

        nextAvailablePlayerId++;
    }

    [ClientRpc]
    private void RpcPlayerInitialize(GameObject playerObject, int playerId)
    {
        PlayerInitialize(playerObject, playerId);
    }

    #endregion

    #region Initialize Older Players

    [Command]
    private void CmdReloadPlayersOnNewClient()
    {
        foreach (ClientHandle otherClientHandles in FindObjectsOfType<ClientHandle>())
        {
            if (otherClientHandle != this) // Ignore new players handle
            {
                PlayerController player = otherClientHandle.localPlayer;
                TargetPlayerInitialize(connectionToClient, player.gameObject, player.PlayerId);
            }
        }
    }

    [TargetRpc]
    private void TargetPlayerInitialize(NetworkConnection targetConnection, GameObject playerObject, int playerId)
    {
        PlayerInitialize(playerObject, playerId);
    }

    #endregion

    private void PlayerInitialize(GameObject playerObject, int playerId)
    {
        localPlayer = playerObject.GetComponent<PlayerController>();
        localPlayer.PlayerId = playerId;
    }

```

# Answer
> 0 votes
If you want to stick with your current request/response paradigm, you can try a pair of NetworkMessages. One type gets sent from the client, and the server responds with the other.

However, the method I'm using is this: add an integer property, annotated with SyncVar, on a `MonoBehavior` attached to the player object. Then, have the server assign that attribute before spawning the player object (in your `NetworkManager`). This way you don't need the Client to request it at all.

---
Tags: unity, client-server, unet
---


# Question
Title: Textures not working on glTF Embedded Models. Picture Explains The Issue. (GODOT ENGINE)
I wanted the tree to look a bit more stylized, or have a bit more to it than just flat planes. Yet when I tried to put this texture on it, it just looks completely wrong. Is this a model issue or a mapping issue?

# Answer
> -1 votes
Mapping issue, will fix in the future

---
Tags: 3d, textures, models, godot, uv-mapping
---


title: Rendevouz Calculations

text:
# Question
Title: Rendevouz Calculations
Say you have two objects in a vacuum with no forces acting on them.

The objects may or may not be moving.

Object A's acceleration is not equal in all directions, and object B may change its acceleration over time.

```
Knowns:
A position
A velocity
A acceleration
A max acceleration for a given vector
B position
B velocity
B acceleration

```

So for object A, how can I iteratively calculate the the direction of thrust needed to go to B's position and match B's velocity in the smallest amount of time?

# Answer
> 0 votes
**An easy to implement solution (naive algorithm)**

The idea is to first get A to match B's velocity. Once it's done, both objects will be stationary with respect to the other or, if you take A as the origin of your frame, B will be stationary in your frame and it becomes a problem of perform a rendez-vous with a stationary target (accelerate towards it, then decelerate before meeting it).

**An more optimized solution**

You'll need to use a state-space representation.
Write your system into equations using Newton's second law for both objects, then write using state-space representation and plug a suitable controller onto it.

First, let's model the system.
Variables with A (resp. B) subscript are relative to object A (resp. B). For state-space representation, I'm using the same notation as in the Wikipedia linked page.

Our goal is a rendez-vous, which means bringing A at B's position and with zero relative velocity. Using \\$X = x\_B - x\_A\\$, our target is \\$X = 0\\$ and \\$\dot{X} = 0\\$.
Using Newton's second law, we can write

* \\$T\_A = m\_A.\ddot{x}\_A\\$
* \\$\ddot{X} = \ddot{x}\_B - 1/m\_A.T\_A\\$

The state vector is equal to the output vector \\$y = x = \begin{pmatrix} X \\ \dot{X} \end{pmatrix} \\$
Then the system equation is \\$\dot{x} = \begin{pmatrix} \dot{X} \\ \ddot{X} \end{pmatrix} = \begin{bmatrix} 0 & 0 \\ 1 & 0 \end{bmatrix} x + \begin{pmatrix} 0 \\ -1/m\_A \end{pmatrix} T\_A + \begin{pmatrix} 0 \\ 1 \end{pmatrix} \ddot{x}\_B \\$

Oops, it's not linear, it's affine because of object B's acceleration. Depending on what is expected for \\$\ddot{x}\_B\\$ you have several options:

* Mainly zero, B will only use its thrusters sporadically: you can ignore \\$\ddot{x}\_B\\$ in the system equation.
* Its value is low compared to the other terms in the equation: you can also ignore it, but it might cause a steady-state error with a linear controller.
* Its value is not negligeable but can be considered constant with respect to time: you can add a 'virtual' constant input to make it look like it's linear. The system equation becomes: \\$\dot{x} = \begin{pmatrix} \dot{X} \\ \ddot{X} \end{pmatrix} = \begin{bmatrix} 0 & 0 \\ 1 & 0 \end{bmatrix} x + \begin{pmatrix} 0 & 0 \\ -1/m\_A & \ddot{x}\_B \end{pmatrix} \begin{pmatrix} T\_A \\ 1 \end{pmatrix}\\$
* Its value is not negligeable and time-dependant: expect a steady-state error, or a divergence.

In the first 3 cases, a linear controller such as a PID could do the trick. In the last case, you either have to use a higher-order controller, or use a modified PID to account for the non-linearity (in that case, the controller will not be linear).

---
Tags: physics, motion, kinematic
---