# Question
Title: Scene Tab doesn't show anything beside canvas while Game Tab shows everything
i've been building my script normally, but suddently after the last build, i don't see any GameObject Rendered in Scene Tab beside a canvas i have in another scene. I can see everything rendered in my Game Tab scene through camera.

If i move some object in Scene Tab, it moves in Game Tab too but no display of it at all. and i see the following warnings:

```
Internal: JobTempAlloc has allocations that are more than 4 frames old - this is not allowed and likely a leak

Internal: deleting an allocation that is older than its permitted lifetime of 4 frames (age = 6)

Internal: JobTempAlloc has allocations that are more than 4 frames old - this is not allowed and likely a leak

Internal: deleting an allocation that is older than its permitted lifetime of 4 frames (age = 12)

```
* I tried to reverse back the last build but no success
* I close and reopen the Scene Tab
* I Restarted my Computer too.
* I Observed that after the restart the project did load far slower ( like if it was the first time i open the project in the pc) Nothing of this did work

Edit: found out that the problem persists only within same project

Compiling Vertex program
Platform defines: UNITY_ENABLE_REFLECTION_BUFFERS UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BOX_PROJECTION UNITY_SPECCUBE_BLENDING UNITY_ENABLE_DETAIL_NORMALMAP SHADER_API_DESKTOP UNITY_COLORSPACE_GAMMA UNITY_LIGHT_PROBE_PROXY_VOLUME UNITY_LIGHTMAP_RGBM_ENCODING
Disabled keywords: UNITY_NO_DXT5nm UNITY_ENABLE_NATIVE_SHADOW_LOOKUPS UNITY_METAL_SHADOWS_USE_POINT_FILTERING UNITY_NO_SCREENSPACE_SHADOWS UNITY_PBS_USE_BRDF2 UNITY_PBS_USE_BRDF3 UNITY_NO_FULL_STANDARD_SHADER UNITY_HARDWARE_TIER1 UNITY_HARDWARE_TIER2 UNITY_HARDWARE_TIER3 UNITY_HALF_PRECISION_FRAGMENT_SHADER_REGISTERS UNITY_LIGHTMAP_DLDR_ENCODING UNITY_LIGHTMAP_FULL_HDR UNITY_VIRTUAL_TEXTURING UNITY_PRETRANSFORM_TO_DISPLAY_ORIENTATION UNITY_ASTC_NORMALMAP_ENCODING SHADER_API_GLES30

Shader warning in 'Hidden/CameraMotionBlurDX11': integer modulus may be much slower, try using uints if possible. at line 153 (on d3d11)

Compiling Fragment program
Platform defines: UNITY_ENABLE_REFLECTION_BUFFERS UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BOX_PROJECTION UNITY_SPECCUBE_BLENDING UNITY_ENABLE_DETAIL_NORMALMAP SHADER_API_DESKTOP UNITY_COLORSPACE_GAMMA UNITY_LIGHT_PROBE_PROXY_VOLUME UNITY_LIGHTMAP_RGBM_ENCODING
Disabled keywords: UNITY_NO_DXT5nm UNITY_ENABLE_NATIVE_SHADOW_LOOKUPS UNITY_METAL_SHADOWS_USE_POINT_FILTERING UNITY_NO_SCREENSPACE_SHADOWS UNITY_PBS_USE_BRDF2 UNITY_PBS_USE_BRDF3 UNITY_NO_FULL_STANDARD_SHADER UNITY_HARDWARE_TIER1 UNITY_HARDWARE_TIER2 UNITY_HARDWARE_TIER3 UNITY_HALF_PRECISION_FRAGMENT_SHADER_REGISTERS UNITY_LIGHTMAP_DLDR_ENCODING UNITY_LIGHTMAP_FULL_HDR UNITY_VIRTUAL_TEXTURING UNITY_PRETRANSFORM_TO_DISPLAY_ORIENTATION UNITY_ASTC_NORMALMAP_ENCODING SHADER_API_GLES30

Shader warning in 'Hidden/SSAO': 's': loop control variable conflicts with a previous declaration in the outer scope; most recent declaration will be used at line 228 (on d3d11)

Compiling Vertex program
Platform defines: UNITY_ENABLE_REFLECTION_BUFFERS UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BOX_PROJECTION UNITY_SPECCUBE_BLENDING UNITY_ENABLE_DETAIL_NORMALMAP SHADER_API_DESKTOP UNITY_COLORSPACE_GAMMA UNITY_LIGHT_PROBE_PROXY_VOLUME UNITY_LIGHTMAP_RGBM_ENCODING
Disabled keywords: UNITY_NO_DXT5nm UNITY_ENABLE_NATIVE_SHADOW_LOOKUPS UNITY_METAL_SHADOWS_USE_POINT_FILTERING UNITY_NO_SCREENSPACE_SHADOWS UNITY_PBS_USE_BRDF2 UNITY_PBS_USE_BRDF3 UNITY_NO_FULL_STANDARD_SHADER UNITY_HARDWARE_TIER1 UNITY_HARDWARE_TIER2 UNITY_HARDWARE_TIER3 UNITY_HALF_PRECISION_FRAGMENT_SHADER_REGISTERS UNITY_LIGHTMAP_DLDR_ENCODING UNITY_LIGHTMAP_FULL_HDR UNITY_VIRTUAL_TEXTURING UNITY_PRETRANSFORM_TO_DISPLAY_ORIENTATION UNITY_ASTC_NORMALMAP_ENCODING SHADER_API_GLES30

Menu Cinemachine/Storyboard Global Mute can't be checked because it doesn't exist
UnityEngine.StackTraceUtility:ExtractStackTrace ()
Cinemachine.Editor.CinemachineStoryboardMute/<>c:<.cctor>b__2_0 () (at Library/PackageCache/com.unity.cinemachine@2.6.4/Editor/Editors/CinemachineStoryboardEditor.cs:29)
UnityEditor.EditorApplication:Internal_CallDelayFunctions ()

 ```

# Answer
The solution to my problem was to click on Layers found on the top in Unity and hit that slashed eye to unhide Default layer. I don't know how did the hide came to be triggered.

For all the warnings, all of them came from me trying to solve the problem by deleting ProjectSettings and Packages files since problem was on this Project only. Except the job warning which came from nowhere. Anyway all the warnings where solved by closing/reopening the project.
> 1 votes

---
Tags: unity, editors, unity-job-system
---


# Question
Title: IDE cannot find CoreMinimal.h, Unreal Engine 4 course
I'm following this tutorial on Udemy about learning the basics of Unreal Engine as I start up my CS degree, and I've reached a problem where `CoreMinimal.h` cannot be found.

This solution was proposed in the Q&A community, however I still could not quite understand it! I'm still learning and would love some help ;)

Here is my code!

```
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "ShipController.generated.h"

UCLASS()
class SPACESHOOTER_API AShipController : public APawn
{
    GENERATED_BODY()

public:
    // Sets default values for this pawn's properties
    AShipController();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:
    // Called every frame
    virtual void Tick(float DeltaTime) override;

    // Called to bind functionality to input
    virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
};

```

# Answer
Add your engine's Public path to your compiler include path, so that the IDE knows where to find UE header files.

Where did you install the engine? Ex:

```
E:\Program Files\Epic Games\UE_4.26\

```

Then (assuming you're using Visual Studio Code, as recommended in the Udemy tutorial) go to: View / Command Palette / "C/C++: Edit Configurations(UI)"

Scroll down to "Include path" and, if missing, add your UE Public folder, ex: `E:\Program Files\Epic Games\UE_4.26\Engine\Source\Runtime\Core\Public`

Intellisense should now know where to find CoreMinimal.h

You may have to close and re-open your .cpp file to trigger the modified Intellisense path.

Also note that as of this posting 5/6/2021 Intellisense will continue to have difficulty loading CoreMinimal.h because of a separate and unrelated problem relating to macro expansion. You may see:

> cannot open source file "UBT\_COMPILED\_PLATFORM/UBT\_COMPILED\_PLATFORMPlatformCompilerPreSetup.h" (dependency of "CoreMinimal.h")

So while CoreMinimal.h will still appear red-underlined, the reason is different now. That's progress!
> 3 votes

# Answer
Got the same problem a few days back. This is most likely because of visual studio acting up. The normal solution is to replace `CoreMinimal.h` with `Engine.h` or `EngineMinimal.h` with severely increased compile time.

The given solution of the community is to ONLY INCLUDE WHAT YOU USE(IWYU). Meaning that you go to the unreal documentation, find your desired component and include ONLY that component as a header in your files.

What worked for me was going to project folder and search and delete the .suo files in that project(These files can be hidden, so you should check the show hidden files settings from the control panel). Open the project and you should most likely see it working.

If this doesn't work, you can probably ignore it. As long as you can compile and build your project, it doesn't matter whether or not you are getting autocomplete suggestions. Although it is annoying, the problem goes away after sometime, like mine did. Good Luck.
> 1 votes

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


# Question
Title: Unity ECS: How do I stop an entity from spawning twice?
I am implementing a flight dynamics model using Unity's built-in ECS package, Entities, and I keep running into one particular issue where the aircraft I'm trying to spawn gets converted into an entity twice.

Essentially, I have a singleton Monobehaviour that handles setting up the aircraft entity from a GameObject Prefab. Here's the script:

```
public class GameManager : MonoBehaviour
{

    private BlobAssetStore blobAssetStore;

    public static GameManager main;

    public GameObject planePrefab;

    public float zBound = 0.0f;
    public float throttleMaxBound = 1.0f;
    public float alphaMaxBound = 20.0f;
    public float bankMaxBound = 20.0f;
    public float flapMaxBound = 40.0f;
    public float throttleMinBound = 0.0f;
    public float alphaMinBound = 0.0f;
    public float bankMinBound = -20.0f;
    public float flapMinBound = 0.0f;

    public State state;
    public Properties prop;

    Entity planeEntityPrefab;
    EntityManager manager;

    private void Awake()
    {
        if (main != null && main != this)
        {
            Destroy(gameObject);
            return;
        }

        main = this;

        manager = World.DefaultGameObjectInjectionWorld.EntityManager;

        blobAssetStore = new BlobAssetStore();

        GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore);
        planeEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings);

        SpawnEntity();
    }

    private void OnDestroy()
    {
        blobAssetStore.Dispose();
    }

    void SpawnEntity()
    {
        Entity plane = manager.Instantiate(planeEntityPrefab);

        prop = new Properties(
            16.2f,
            10.9f,
            2.0f,
            0.0889f,        // slope of Cl-alpha curve
            0.178f,         // intercept of Cl-alpha curve
            -0.1f,          // post-stall slope of Cl-alpha curve
            3.2f,           // post-stall intercept of Cl-alpha curve
            16.0f,          // alpha when Cl=Clmax
            0.034f,         // parasite drag coefficient
            0.77f,          // induced drag efficiency coefficient
            1114.0f,
            119310.0f,
            40.0f,          // revolutions per second
            1.905f,
            1.83f,          //  propeller efficiency coefficient
            -1.32f          //  propeller efficiency coefficient
            );

        state = new State(
            0.0f,           // time
            0.0f,           // ODE results
            0.0f,
            0.0f,
            0.0f,
            0.0f,
            0.0f,
            0.0f,           // roll angle
            4.0f,           // pitch angle
            0.0f,           // throttle percentage
            0.0f            // flap deflection
            );

        float3 position = new float3(state.q1, state.q3, state.q5);

        manager.SetComponentData(plane, new Translation { Value = position });
    }

}

```

After a little bit of commenting here and there, I was able to determine that the following two lines are responsible for creating two separate entities, though the latter is the only one I'm capable of manipulating using the system. It's also worth mentioning that these two entities are virtually identical in the Entity Debugger, except for the fact that the first entity contains the "prefab" tag.

```
planeEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings);

```

and...

```
Entity plane = manager.Instantiate(planeEntityPrefab);

```

Is there a way to spawn this entity without both showing up in the debugger or is this unavoidable? If not, is there a way to remove the entity with the "prefab" tag from the world?

Thanks! :)

# Answer
> 0 votes
Turns out the solution was more simple than I expected it to be.

To remove the prefab, I simply included this line after instantiating the prefab in the SpawnEntity method:

```
manager.DestroyEntity(planeEntityPrefab);

```

I needed the planeEntityPrefab variable in order to instantiate the aircraft, but after the following line, it seemed safe for me to delete the prefab. The entire GameManager script now looks as follows:

```
public class GameManager : MonoBehaviour
{
    private BlobAssetStore blobAssetStore;

    public static GameManager main;

    public GameObject planePrefab;

    public float zBound = 0.0f;
    public float throttleMaxBound = 1.0f;
    public float alphaMaxBound = 20.0f;
    public float bankMaxBound = 20.0f;
    public float flapMaxBound = 40.0f;
    public float throttleMinBound = 0.0f;
    public float alphaMinBound = 0.0f;
    public float bankMinBound = -20.0f;
    public float flapMinBound = 0.0f;

    public State state;
    public Properties prop;

    Entity planeEntityPrefab;
    EntityManager manager;

    private void Awake()
    {
        if (main != null && main != this)
        {
            Destroy(gameObject);
            return;
        }

        main = this;

        manager = World.DefaultGameObjectInjectionWorld.EntityManager;

        blobAssetStore = new BlobAssetStore();

        GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore);
        planeEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings);

        SpawnEntity();
    }

    private void OnDestroy()
    {
        blobAssetStore.Dispose();
    }

    void SpawnEntity()
    {
        Entity plane = manager.Instantiate(planeEntityPrefab);

        manager.DestroyEntity(planeEntityPrefab);

        prop = new Properties(
            16.2f,
            10.9f,
            2.0f,
            0.0889f,        // slope of Cl-alpha curve
            0.178f,         // intercept of Cl-alpha curve
            -0.1f,          // post-stall slope of Cl-alpha curve
            3.2f,           // post-stall intercept of Cl-alpha curve
            16.0f,          // alpha when Cl=Clmax
            0.034f,         // parasite drag coefficient
            0.77f,          // induced drag efficiency coefficient
            1114.0f,
            119310.0f,
            40.0f,          // revolutions per second
            1.905f,
            1.83f,          //  propeller efficiency coefficient
            -1.32f          //  propeller efficiency coefficient
            );

        state = new State(
            0.0f,           // time
            0.0f,           // ODE results
            0.0f,
            0.0f,
            0.0f,
            0.0f,
            0.0f,
            0.0f,           // roll angle
            4.0f,           // pitch angle
            0.0f,           // throttle percentage
            0.0f            // flap deflection
            );

        float3 position = new float3(state.q1, state.q3, state.q5);

        manager.SetComponentData(plane, new Translation { Value = position });
    }

}

```

When I run the game, the entity debugger only shows the instantiated aircraft and world time entities. Problem solved!

---
Tags: unity, entity-component-system, unity-dots
---


title: Can't save Screenshot to Android

text:
# Question
Title: Can't save Screenshot to Android
so I have a method for taking a screenshot, it works just fine on PC, but I've tried everything and cannot get it to work on Android. I've tried creating custom folders, saving to persistentDataPath, saving to dataPath, and none of it works.

I had a way of testing it which said the name of the screenshot, logically it should keep the name as screenshot1 if it fails to take the screenshot, which it does on mobile, whereas the one on desktop increments properly.

Here's the method I most recently attempted...

```
    public void captureScreenshot(string name)
    {
        if (!countDown)
        {
            for (int i = 1; i < 500; i++)
            {

                if (!File.Exists(Application.dataPath + name + i + ".png"))
                {
                    if (!Directory.Exists(Application.dataPath + "/appScreenshots"))
                    {
                        Directory.CreateDirectory(Application.dataPath + "/appScreenshots");
                    }
                    ScreenCapture.CaptureScreenshot(Application.dataPath + name + i + ".png");
                    break;
                }
            }
        }
    }

    public void captureScreenshot(string name)
    {
        if (!countDown)
        {
            for (int i = 1; i < 500; i++)
            {

                if (!File.Exists(Application.dataPath + name + i + ".png"))
                {
                    if (!Directory.Exists(Application.dataPath + "/appScreenshots"))
                    {
                        Directory.CreateDirectory(Application.dataPath + "/appScreenshots");
                    }
                    ScreenCapture.CaptureScreenshot(Application.dataPath + name + i + ".png");
                    break;
                }
            }
        }
    }

```

So, it works just fine on PC, just not on mobile... Do I need to get special permissions or something?

Thanks

# Answer
> 0 votes
Well, I fixed it. I think the issue was that I had a / in the name, I tried test but nothing happened, so i tried just "Screenshot.png" and it worked, now it's taking screenshots. Here's the updated code,

```
        public void captureScreenshot(string name)
    {

            for (int i = 1; i < 500; i++)
            {

                if (!File.Exists(Application.persistentDataPath + "/Screenshot.png" + (i + 1)))
                {
                    ScreenCapture.CaptureScreenshot("Screenshot" + (i + 1)+".png");

                    text.GetComponent<TextMeshProUGUI>().text = name + i + ".png";
                    break;
                }

             }
    }

```

---
Tags: unity, android
---


# Question
Title: How can I draw a circle around a specific object, not necessarily the object the script is attached to?
I have this script that draws a circle around the object the script is attached to.

I would like also to use the `centerObject` variable as an option to draw another circle around the `centerObject`, or just only around the `centerObject` and not the transform the script is attached to. I'm not sure how to do it.

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

[ExecuteAlways]
[RequireComponent(typeof(UnityEngine.LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    public GameObject centerObject;
    [Range(1, 50)] public int segments = 50;
    [Range(1, 500)] public float xRadius = 5;
    [Range(1, 500)] public float yRadius = 5;
    [Range(0.1f, 5)] public float width = 0.1f;
    [Range(0, 100)] public float height = 0;
    public bool controlBothXradiusYradius = false;
    public bool draw = true;

    [SerializeField] private LayerMask targetLayers;
    [SerializeField] private LineRenderer line;

    private void Start()
    {
        if (!line) line = GetComponent<LineRenderer>();

        if (draw)
            CreatePoints();
    }

    private void Update()
    {
        if (Physics.CheckSphere(transform.position, xRadius, targetLayers))
        {
            Debug.Log("player detected");
        }
        else
        {
            Debug.Log("player NOT detected");
        }
    }

    public void CreatePoints()
    {
        line.enabled = true;
        line.widthMultiplier = width;
        line.useWorldSpace = false;
        line.widthMultiplier = width;
        line.positionCount = segments + 1;

        float x;
        float y;

        var angle = 20f;
        var points = new Vector3[segments + 1];
        for (int i = 0; i < segments + 1; i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xRadius;
            y = Mathf.Cos(Mathf.Deg2Rad * angle) * yRadius;

            points[i] = new Vector3(x, height, y);

            angle += (380f / segments);
        }

        // it's way more efficient to do this in one go!
        line.SetPositions(points);
    }

#if UNITY_EDITOR
    private float prevXRadius, prevYRadius;
    private int prevSegments;
    private float prevWidth;
    private float prevHeight;

    private void OnValidate()
    {
        // Can't set up our line if the user hasn't connected it yet.
        if (!line) line = GetComponent<LineRenderer>();
        if (!line) return;

        if (!draw)
        {
            // instead simply disable the component
            line.enabled = false;
        }
        else
        {
            // Otherwise re-enable the component
            // This will simply re-use the previously created points
            line.enabled = true;

            if (xRadius != prevXRadius || yRadius != prevYRadius || segments != prevSegments || width != prevWidth || height != prevHeight)
            {
                CreatePoints();

                // Cache our most recently used values.
                prevXRadius = xRadius;
                prevYRadius = yRadius;
                prevSegments = segments;
                prevWidth = width;
                prevHeight = height;
            }

            if (controlBothXradiusYradius)
            {
                yRadius = xRadius;
            }
        }
    }
#endif
}

```

# Answer
The LineRenderer component has two modes of interpreting its positions: local space and world space.

In local space mode (default), all the positions are relative to the gameObject the line renderer is on. This is useful if you want the line to move when the object moves.

But in a scenario like yours, where you want the line to be relative to something other than the parent, it makes sense to enable "Use World Space" in the inspector settings. Now any points you set via `LineRenderer.SetPositions` are relative to the world origin.

When you enable that setting without changing your code, then the line should appear as it does now, but around the world origin instead of the gameObject.

If you want it to appear around an arbitrary `Vector3 center` instead, you would just add that vector to all the positions you calculate.

Another way to do this which does not just apply the position but also the rotation and scale of another gameObject would be to use the `Transform.TransformPoint` method of that other transform. Whether that's desirable or not depends on your particular use-case.

Modified code for using only position:

```
    var centerPos = centerObject.transform.position;
    for (int i = 0; i < segments + 1; i++)
    {
        x = Mathf.Sin(Mathf.Deg2Rad * angle) * xRadius;
        y = Mathf.Cos(Mathf.Deg2Rad * angle) * yRadius;

        points[i] = new Vector3(x, height, y) + centerPos;

        angle += (380f / segments);
    }

```

Modified code using position, rotation and scale:

```
    var centerTransform = centerObject.transform;
    for (int i = 0; i < segments + 1; i++)
    {
        x = Mathf.Sin(Mathf.Deg2Rad * angle) * xRadius;
        y = Mathf.Cos(Mathf.Deg2Rad * angle) * yRadius;

        points[i] = centerTransform.TransformPoint(new Vector3(x, height, y));

        angle += (380f / segments);
    }

```
> 1 votes

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


# Question
Title: Specify the size of the points when building a mesh based on a point cloud
I create a mesh in Unity3D based on a point cloud in this way:

```
// The standard sequence for creating a mesh
Mesh mesh = new Mesh();
Vector3[] points = new Vector3[numPoints];
int[] indecies = new int[numPoints];
Color[] colors = new Color[numPoints];

// Fill in points, indecies, colors

mesh.vertices = points;
mesh.colors = colors;
mesh.SetIndices(indecies, MeshTopology.Points, 0);

```

I learned that it is possible to set the size of points in PSIZE through Vertex Shader. Applied such a Shader, but without result.

```
Shader "VertexColor"
{
    Properties
    {
        _PointSize("Point size", Float) = 5.0
    }
    SubShader
    {
        Pass
        {
            LOD 200

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            uniform float _PointSize;

            struct VertexInput
            {
                float4 vertex: POSITION;
                float4 color: COLOR;
             };

             struct VertexOutput
             {
                 float4 pos: SV_POSITION;
                 float4 col: COLOR;
                 float size: PSIZE;
              };

              VertexOutput vert(VertexInput v)
              {
                  VertexOutput o;
                  o.pos = UnityObjectToClipPos(v.vertex);
                  o.col = v.color;
                  o.size = _PointSize;

                  return o;
              }

              float4 frag(VertexOutput o) : COLOR
              {
                  return o.col;
              }
              ENDCG
          }
      }
}

```

Tell me, please, how to set the size of points correctly?

# Answer
I found that if the launch Unity with the flag `-force-opengl` the shader you have supplied will work.
> 1 votes

# Answer
`_PointSize` is defaulting to 0; use:

```
uniform float _PointSize = 2;

```

and expose it as a param at the top of the shader if you want to adjust it in the material

```
Properties
{
    _PointSize ("Point Size", Float) = 1
}

```
> 0 votes

---
Tags: unity, mesh, point-cloud
---


# Question
Title: How can I detect when the player or any object that is moving is touching or entered a drawn linerenderer circle radius area?
In the screenshot, the object that is in the center and the circle is drawn around is the small spaceship.

What I'm trying to do is when the player or any object that moves towards the circle if the object touch or better if the object enters the circle area then do something.

For example, the cube in the screenshot is inside the circle area then do something like ontriggerenter and if the object moves out do something like in ontriggerexit. The same idea.

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

[ExecuteAlways]
[RequireComponent(typeof(UnityEngine.LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(1, 50)] public int segments = 50;
    [Range(1, 500)] public float xRadius = 5;
    [Range(1, 500)] public float yRadius = 5;
    [Range(0.1f, 5)] public float width = 0.1f;
    [Range(0, 100)] public float height = 0;
    public bool controlBothXradiusYradius = false;
    public bool draw = true;

    [SerializeField] private LayerMask targetLayers;
    [SerializeField] private LineRenderer line;

    private void Start()
    {
        if (!line) line = GetComponent<LineRenderer>();

        if (draw)
            CreatePoints();
    }

    private void Update()
    {
        if (Physics.CheckSphere(transform.position, xRadius, targetLayers))
        {
            Debug.Log("player detected");
        }
        else
        {
            Debug.Log("player NOT detected");
        }
    }

    public void CreatePoints()
    {
        line.enabled = true;
        line.widthMultiplier = width;
        line.useWorldSpace = false;
        line.widthMultiplier = width;
        line.positionCount = segments + 1;

        float x;
        float y;

        var angle = 20f;
        var points = new Vector3[segments + 1];

        for (int i = 0; i < segments + 1; i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xRadius;
            y = Mathf.Cos(Mathf.Deg2Rad * angle) * yRadius;

            points[i] = new Vector3(x, height, y);

            angle += (380f / segments);
        }

        line.SetPositions(points);
    }

#if UNITY_EDITOR
    private float prevXRadius, prevYRadius;
    private int prevSegments;
    private float prevWidth;
    private float prevHeight;

    private void OnValidate()
    {
        if (!line) line = GetComponent<LineRenderer>();
        if (!line) return;

        if (!draw)
        {
            line.enabled = false;
        }
        else
        {
            line.enabled = true;

            if (xRadius != prevXRadius || yRadius != prevYRadius || segments != prevSegments || width != prevWidth || height != prevHeight)
            {
                CreatePoints();

                prevXRadius = xRadius;
                prevYRadius = yRadius;
                prevSegments = segments;
                prevWidth = width;
                prevHeight = height;
            }

            if (controlBothXradiusYradius)
            {
                yRadius = xRadius;

                CreatePoints();
            }
        }
    }
#endif
}

```

I tried inside the Update to do :

```
if (Physics.CheckSphere(transform.position, xRadius, targetLayers))
        {
            Debug.Log("player detected");
        }
        else
        {
            Debug.Log("player NOT detected");
        }

```

but it's not working even if I change in the Inspector the targetLayers to the player layer.

The player is not the cube in the screenshot and the player have a collider but the drawn circle don't have a collider. not sure how to do it with the Physics.CheckSphere or some other way but the idea is when the player or any other object enter the drawn circle area do something. maybe some how to calculate the distance from the circle ? not sure how to do it.

# Answer
> 1 votes
The LineRenderer is not a good candidate for defining an area, because it doesn't even know it's a circle or even a closed polygon.

What I would do is add a child-object to the object with a SphereCollider of appropriate size which has the "Is Trigger?" flag set. You can then implement OnTriggerEnter, OnTriggerStay and OnTriggerExit accordingly. Keep in mind that this requires a Rigidbody on any objects it is supposed to detect.

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


# Question
Title: LibGDX - Rendering problem when in a Timer.Task
I have a "console" window in-game where I log messages. When starting up, the game checks for updates by way of a `Timer.Task`. Any messages I try to log in the task are not displayed, but the file logs show that they were recorded at the proper time. I assume it's a rendering problem and the console's screen fails to render during the task execution.

I use Dagger2 for dependency-injection but the Screen is a `@Singleton`, plus there are logs in the constructor that are only written once, so I'm confident that the instance injected in `MyGame` and the one passed to `StartupTask` are the same.

**I would like the console to continue displaying messages "in real time" while the update task is running. What am I missing?**

**Game class:**

```
public class MyGame extends Game {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyGame.class);

    private final Lazy<ConsoleScreen> bootScreen;
    private final Lazy<StartupTaskProvider> startupTaskProvider;

    public MyGame(Lazy<ConsoleScreen> bootScreen, Lazy<StartupTaskProvider> startupTaskProvider) {
        super();
        this.bootScreen = bootScreen;
        this.startupTaskProvider = startupTaskProvider;
    }

    @Override
    public void create() {
        LOGGER.info("Startup phase.");
        final ConsoleScreen console = bootScreen.get();
        this.setScreen(console);
        console.addLog("Initialization"); // <--- Correctly displayed

        // Update when booting.
        Timer.schedule(startupTaskProvider.get().create(), 2);
    }

    @Override
    public void render() {
        super.render();
    }

    @Override
    public void dispose() {
    }

```

**Provider for MyGame:** (Used as a glue between Dagger2 and the call to new Lwjgl3Application)

```
@Module
public class GameModule {

    @Provides
    @Singleton
    static MyGame provideGame(Lazy<ConsoleScreen> bootScreen, Lazy<StartupTaskProvider> startupTaskProvider) {
        return new MyGame(bootScreen, startupTaskProvider);
    }

}

```

**Screen class:**

```
@Singleton
public class ConsoleScreen implements Screen {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleScreen.class);

    @Inject
    DebugUtils debugUtils;

    @Inject
    TextUtils textUtils;

    private final Stage stage;
    private final Table table;
    private final List<Label> logs;
    private final int maxSize;

    @Inject
    public ConsoleScreen(DebugUtils debugUtils, TextUtils textUtils) {
        // Creates the Stage and adds the Table to it, works fine.
    }

    public void addLog(String text) {
        // Adds the text to the Table, works fine.
    }

    @Override
    public void show() {
        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act();
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();
    }

```

**Startup task:**

```
public class StartupTask extends Timer.Task {

    private final MyGame game;
    private final ConsoleScreen consoleScreen;
    private final MainScreen mainScreen;
    private final UpdateService updateService;

    public StartupTask(ConsoleScreen consoleScreen, MyGame game, MainScreen mainScreen, UpdateService service) {
        this.game = game;
        this.consoleScreen = consoleScreen;
        this.mainScreen = mainScreen;
        this.updateService = service;
    }

    @Override
    public void run() {
        consoleScreen.addLog("Starting update"); // <-- Does not display, at least not before the screen is changed.
        updateService.start().get(); // <-- Executes correctly

        // The screen is then switched and rendered correctly.
        game.setScreen(mainScreen);
        mainScreen.fadeIn();
    }

}

```

**Provider for startup tasks:**

```
@Module
public class StartupTaskProvider {

    @Inject
    MyGame game;

    @Inject
    ConsoleScreen consoleScreen;

    @Inject
    MainScreen mainScreen;

    @Inject
    UpdateService service;

    @Inject
    public StartupTaskProvider() {}

    @Provides
    @Singleton
    public StartupTask create() {
        return new StartupTask(consoleScreen, game, mainScreen, service);
    }

}

```

# Answer
I found it, rookie mistake. `UpdateService.start()` call runs asynchroneously, but by waiting on it with `AsyncTask::get`, I effectively tie up the main thread, hence no rendering during the update.
> 0 votes

---
Tags: libgdx
---


# Question
Title: Using name and 3d models of real product
I'm making tycoon game where you manage your shop. I'm not 3d modeler and purchase most of assets. I managed to find all 3d assets required for making game. All are having license to allow use for commercial usage. My question is can I use those model who are clearly modeled after their real world product in my game? Even though license for each of them permits me. I know,I can't use their real name like for example I will change nintendo switch to ginmendo ditch or apple to mapple. I'm even planning to slightly modify each asset in 3d modeling software. will that work? Can I use them in my game ?

# Answer
> 0 votes
You can legally modify all of these assets to avoid copyright infringement. TV Shows have edited products like apple by turning them into pears or other fruits. Video games have changed other products around to look like something in the real world, but not *exactly* close enough to get sued. Make sure to change both the logo and the company name itself.

**Word of advice**: Check the licensing rights for modification. Unlicensed modification of assets can lead to C&D orders.

---
Tags: legal
---


# Question
Title: What is the legality regarding allowing players to mod a game with real-life players in a sports game?
Let's say I'm doing an Indie sports game, and ship it with fictional players, but make the game capable of reading a config file, so that players are able to edit in real names to suit themselves.

The game is a free multi-player, peer-to-peer (p2p) game, and so once the game is published, there is no central server authority which controls what the players are doing, thus allowing them to mod the game as they please.

What's the legal situation with something like that? The file is literally just a plain text file with some names in it. I would imagine that if I were to host that file, and have my game download and consume it on start up, that would be unacceptable, as it would be the same as shipping the game with real player names?

So that makes me wonder, would such a file be illegal for people to share? If I were to make such a file, and distribute it to the community via a forum, would that be illegal? What about if I didn't do that, but a customer did?

# Answer
They can mod any name into the game as they please. If the original product of the game uses fake names, and a user edits them to be real, that shouldn't effect you because it is a **modification of the original product, which had no copyrighted names within it.** If you distribute the game with the names in it, that's a different licensing area to explore with people like FIFA or the MLB.
> 1 votes

---
Tags: legal, modding, copyright, trademark
---


title: DeltaTime is smaller than it should be

text:
# Question
Title: DeltaTime is smaller than it should be
I have a gameloop for a simulation I'm making, I noticed that the simulation is going very slow, When i checked the DeltaTime it was very small, I set the target fps to be 1 (deltatime should be 1 in that case) and it was still very small (1.1920929E-07) which is making the simulation super slow even with huge numbers.

Here's the gameloop code

```
    public void Run()
    {
        Ticks = 0;
        _running = true;

        float totalTimeBeforeUpdate = 0;
        float previousTimeElapsed = 0;

        var clock = new Stopwatch();
        clock.Start();

        while (_running)
        {
            var totalTimeElapsed = (float) clock.Elapsed.TotalSeconds;
            var deltaTime = totalTimeElapsed - previousTimeElapsed;
            previousTimeElapsed = totalTimeElapsed;

            totalTimeBeforeUpdate += deltaTime;

            if (totalTimeBeforeUpdate >= TimeUntilUpdate)
            {
                GameTime.Update(deltaTime, (float) clock.Elapsed.TotalSeconds);
                totalTimeBeforeUpdate = 0;

                Update(GameTime);

                Draw(GameTime);

                Ticks++;
            }
        }
    }

```

Edit: Yes I'm getting the correct target fps

Edit: Here's the results I'm getting when debugging

```
Ticks: 0, Total Time Elapsed: 1.0002049, Delta Time: 1E-07, FPS: 10000000
Ticks: 1, Total Time Elapsed: 2.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 2, Total Time Elapsed: 3.0000003, Delta Time: 1E-07, FPS: 10000000
Ticks: 3, Total Time Elapsed: 4.0000004, Delta Time: 1E-07, FPS: 10000000
Ticks: 4, Total Time Elapsed: 5.0000004, Delta Time: 1E-07, FPS: 10000000
Ticks: 5, Total Time Elapsed: 6.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 6, Total Time Elapsed: 7.0000004, Delta Time: 1E-07, FPS: 10000000
Ticks: 7, Total Time Elapsed: 8.0000003, Delta Time: 1E-07, FPS: 10000000
Ticks: 8, Total Time Elapsed: 9.0000002, Delta Time: 1E-07, FPS: 10000000
Ticks: 9, Total Time Elapsed: 10.0000003, Delta Time: 1E-07, FPS: 10000000
Ticks: 10, Total Time Elapsed: 11.0000012, Delta Time: 1E-07, FPS: 10000000
Ticks: 11, Total Time Elapsed: 12.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 12, Total Time Elapsed: 13.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 13, Total Time Elapsed: 14.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 14, Total Time Elapsed: 15.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 15, Total Time Elapsed: 16.0000004, Delta Time: 1E-07, FPS: 10000000
Ticks: 16, Total Time Elapsed: 17.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 17, Total Time Elapsed: 18.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 18, Total Time Elapsed: 19.0000006, Delta Time: 1E-07, FPS: 10000000
Ticks: 19, Total Time Elapsed: 20.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 20, Total Time Elapsed: 21.0000006, Delta Time: 1E-07, FPS: 10000000
Ticks: 21, Total Time Elapsed: 22.0000006, Delta Time: 1E-07, FPS: 10000000
Ticks: 22, Total Time Elapsed: 23.0000002, Delta Time: 1E-07, FPS: 10000000

```

it says the FPS is really high, that's because I'm using the deltatime to calculate it, you can see its running at 1 FPS (which is what i set it to) from the Ticks and total time elapsed, Delta Time is really smalls (very close to 0) and it should be actually 1 since I'm running at 1 FPS

# Answer
You're using the wrong time delta to advance your simulation.

You want "the time since I performed the last simulation step", but what you're using is "the time since I last checked if it was time to perform another simulation step". Your code is written to do a very fast busy-loop while it waits for the next time to tick, so naturally that "time since I last checked" is very very short - only the few microseconds it takes the CPU to read a value from the stopwatch, add some floats, and skip a branch that reliably predicts to false.

Your inner `if` should be something more like...

```
if (totalTimeBeforeUpdate >= TimeUntilUpdate)
{
      totalTimeBeforeUpdate -= TimeUntilUpdate;

      Update(TimeUntilUpdate);
      Draw(TimeUntilUpdate);

      Ticks++;
}

```

ie. if you only do a simulation step once every `TimeUntilUpdate` seconds, then each simulation step is `TimeUntilUpdate` seconds long. Since `TimeUntilUpdate` is a constant that doesn't change from frame to frame, this makes it a fixed time step, which is good for consistency and fairness.

Subtract `TimeUntilSeconds` rather than zeroing `totalTimeBeforeUpdate` to ensure you're correctly managing any "loose change" time left-over past the end of the interval.

In some game loops, this will be a `while` loop instead of an `if`, so you can tick multiple times to catch up (say if you had a temporary slowdown or went out of focus). Though in those cases you'll usually also have a maximum ticks condition to ensure you don't get stuck in the `while` forever, and the `Draw` call will be moved outside the loop so it triggers only after the last simulation tick of the catch-up.
> 1 votes

---
Tags: c#, game-loop, deltatime
---


# Question
Title: How can I prevent a follower from participating in fights in RPG Maker?
I'm developing a game with RPG Maker VX Ace. In this game, one of your followers is ghost-like demon that observes the player. I was going to have him appear during dialogues, but all of the playtesters were getting confused as he looks like the character the player interacts with.

I decided to make him a follower so it gets less confusing, but I don't think it would be interesting for him to participate in fights, as he would be too overpowered. I was able to prevent him from attacking, but not able to prevent him from *being attacked*.

How can I make this follow not participate in fighting at all?

# Answer
Before every battle, have the game trigger a `Common Event` that removes him as a follower from the party. Using some more battle scripting within the `Database > Troops` menu can add him back as a follower when the battle is won.
You can also have him be a follower just as a basic event that travels along with you, and therefore, cannot enter into battle alongside the party.
> 0 votes

---
Tags: rpg-maker
---


# Question
Title: How to inherit of a scene tree structure in a way that a change in the ancestor is updated in the descendant?
Consider this structure:

```
* KinematicBody2D (Actor)
|_ AnimationPlayer (able to make a rotation of 360)

```

Now I want to make a Player and an Enemy that inherits of that structure in a way that when I change the animation on the Actor Scene, Enemy and Player are updated.

Is there a pattern that allows that?

# Answer
You can make an inherited scene. From the "Scene" menu, select "New Inherited Scene…" and pick the base scene. Then apply the modifications you need (e.g. change textures).

---

There is also a composition equivalent:

* Create a new scene.
* Add the "base" scene as a node.
* Make it editable ("Editable Children" on the context menu on the Scene panel).
* Then add the modifications you need (e.g. change textures).

---

Either way, you cannot remove from the original, only add or modify. And whatever you didn't change will be inherited from the base scene.
> 1 votes

---
Tags: godot, inheritance, gdscript
---


# Question
Title: how can I rotate a tetrahedron's vertices so that it's pointing straight up?
I am trying to render an Equilateral triangle in 3D, and I came across this answer: https://math.stackexchange.com/a/562895/15497

So based off of that, I made my vertex points:

```
(1, 1, 1),
(1, -1, -1),
(-1, -1, 1),
(-1, 1, -1),

```

This looks great when I draw lines across these points, however the triangle is not pointing straight up as I would like it to. I am trying to understand how to calculate the right amount to rotate the X, and Z axis so that it is pointing upwards?

I messed around with rotating the X by PI / 5 and Z by -PI / 5 and got something close:

But that is not right...

# Answer
> 1 votes
Let's designate the point \\$(1, 1, 1\\$) as the one you want to rotate to point straight up.

Normalized, that's \\$\frac 1 {\sqrt 3} (1, 1, 1)\\$. So its dot product with the unit vector pointing straight up is just \\$\frac 1 {\sqrt 3}\\$, meaning the angle between them is \\$\cos^{-1}( \frac 1 {\sqrt 3})\\$. Rotate by this angle along the axis \\$x = z\\$.

Or even better, we can just build the tetrahedron point up by construction. Let's say we want it to have an edge length of 1. Then we can draw the base of the tetrahedron in the \\$xz\\$ plane like so:

That gives us the x and z coordinates of the three base vertices, and we can place the apex vertex somewhere above the cross at the center \\$(x, z) = (0, 0)\\$. Now we just need to know what (positive) height \\$h\\$ will put it exactly 1 unit away from the others.

$$\begin{align} (h - 0)^2 + (0 - \frac {\sqrt 3} 3)^2 &= 1^2\\ h^2 + \frac 3 9 &= 1\\ h^2 &= 1 - \frac 1 3\\ h &= \sqrt \frac 2 3 \end{align}$$

So, you can place the other three vertices on the plane \\$y = 0\\$, and place the apex vertex at \\$y = \sqrt \frac 2 3\\$. Or, if you'd like the origin to sit at the centroid, you can subtract the centroid height \\$c\\$ from all those \\$y\\$ coordinates.

$$\begin{align} (c - 0)^2 + (0 - \frac {\sqrt 3} 3)^2 &= (h - c)^2\\ c^2 + \frac 3 9 &= h^2 - 2 hc + c^2\\ \frac 1 3 &= \frac 2 3 - 2\sqrt \frac 2 3 c\\ 2\sqrt \frac 2 3 c &= \frac 2 3 - \frac 1 3\\ c &= \frac 1 3 \cdot \frac 1 2 \sqrt \frac 3 2\\ c &= \frac {\sqrt 3} {6 \sqrt 2}\\ c &= \frac 3 {6 \sqrt 6}\\ c &= \frac 1 {2 \sqrt 6} \end{align}$$

# Answer
> 0 votes
You basically want the vector \<1, 1, 1\> to be rotated to point up \<0, 1, 0\> - or rather \<0, k, 0\> where k is some constant.

Copying the matrix I use in domain-rotating noise functions the opposite direction, and transposing to invert (works because rotation matrix \<=\> orthonormal matrix), you can use this to transform each vertex.

$$\begin{align} \begin{bmatrix} 0.788675134594813 & -0.577350269189626 & -0.211324865405187\\ 0.577350269189626 & 0.577350269189626 & 0.577350269189626\\ -0.211324865405187 & -0.577350269189626 & 0.788675134594813 \end{bmatrix} \end{align}$$

note that `-0.211... = G2 = (SQRT3-3)/6`, `0.788... = G2+1`, and `0.577... = SQRT3/3`

---
Tags: 3d, rotation, 3d-meshes
---


# Question
Title: How can I clear the screen on Corona SDK
I have objects on the screen that create the main menu, and I want the the screen to clear when I get press the play button. I did it the way the other question on this subject said, but when I simulate the code the screen doesn't clear when I press play. Can you explain why this is wrong and if it is what I should do instead.

This is the function I am using to clear the screen:

```
--Clear Screen of All Objects
function clearScreen(numOfObjectsOnScreen)
    for i=1, numOfObjectsOnScreen do
        objectsOnScreen[i]:removeSelf()
        objectsOnScreen[i] = nil
    end
end

```

I am incrementing the variable that contains the number of Objects on Screen every time I create an object in the main menu.

This is the code for my play button where the clearScreen function is excecuted

```
local playButton = display.newImage( "Assets\\Art\\GUI\\MainMenu\\PlayButton.png", display.contentCenterX, display.contentHeight * .75)
playButton:scale(2, 2)
insertObjectsOnScreen(playButton)
incrementVariable(mainMenuObjects)

--Play Button Event Handling
function playButton:touch( event )
    if ( event.phase == "began" ) then
        playButton:scale(.9, .9)
    elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
        playButton:scale(10 / 9, 10 / 9)
        clearScreen(mainMenuObjects)
        mainMenuObjects = 0
        gameStatus = "inGame"
        beginGame()
    end
end
playButton:addEventListener( "touch", playButton )

```

I am pretty sure this is enough for you to be able to answer this question, but if not here is a all the code I have done so far

```
--Main.Lua
-----------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------
---Variables
-----------------------------------------------------------------------------------------

--All things on screen at one given time
objectsOnScreen = {}

--Scene the Game is on
gameStatus = "mainMenu"

--Number of Objects in Each Scene
mainMenuObjects = 0
inGameObjects = 0
shopObjects = 0

-----------------------------------------------------------------------------------------
---Functions
-----------------------------------------------------------------------------------------

-- Setting up Image Sheet Options
function setImageSheet(w, h, numF)
    local sheetOptions =
    {
        width = w,
        height = h,
        numFrames = numF
    }

    return sheetOptions
end

--Resize Object to Whole Screen
function resizeToFullScren(object)
    local ow = object.contentWidth / display.contentWidth
    local oh = display.contentHeight / object.contentHeight
    object:scale(ow, oh)
end

--Insert Images / Sprites into Objects on Screen
function insertObjectsOnScreen(object)
    table.insert(objectsOnScreen, object)
end

--Clear Screen of All Objects
function clearScreen(numOfObjectsOnScreen)
    for i=1, numOfObjectsOnScreen do
        objectsOnScreen[i]:removeSelf()
        objectsOnScreen[i] = nil
    end
end

--Increment a Variable by 1
function incrementVariable(x)
    x = x + 1
end

----------------------------------------------------------------------------    ------------
---Main Menu Init
----------------------------------------------------------------------------    ------------

--Establishing Background
local background = display.newImage("Assets\\Art\\GUI\\MainMenu\\Background.png", display.contentCenterX, display.contentCenterY)
    resizeToFullScren(background)
    insertObjectsOnScreen(background)
    incrementVariable(mainMenuObjects)

--Establishing Button
local sheet_redButton = graphics.newImageSheet( "Assets\\Art\\Buttons\\redButton_PressedAnimation.png", setImageSheet(500.5, 404, 2))
local sequence_redButton = {
    {
        name = "pressButton",
        start = 1,
        count = 2,
        loopCount = 0,
        loopDirection = "forward"
    }
}
local redButton = display.newSprite( sheet_redButton, sequence_redButton)
redButton.x = display.contentCenterX
redButton.y = display.contentHeight / 5
redButton:scale(1.5, 1.5)
insertObjectsOnScreen(redButton)
incrementVariable(mainMenuObjects)

--Button Event Handling
function redButton:touch( event )
    if ( event.phase == "began" ) then
        redButton:setFrame(2)
    elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
        redButton:setFrame(1)
    end
end
redButton:addEventListener( "touch", redButton )

--Establishing Play Button
local playButton = display.newImage( "Assets\\Art\\GUI\\Main Menu\\PlayButton.png", display.contentCenterX, display.contentHeight * .75)
playButton:scale(2, 2)
insertObjectsOnScreen(playButton)
incrementVariable(mainMenuObjects)

--Play Button Event Handling
function playButton:touch( event )
    if ( event.phase == "began" ) then
        playButton:scale(.9, .9)
    elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
        playButton:scale(10 / 9, 10 / 9)
        clearScreen(mainMenuObjects)
        mainMenuObjects = 0
        gameStatus = "inGame"
        beginGame()
    end
end
playButton:addEventListener( "touch", playButton )

--Establishing Mute Button
mute = true
local sheet_muteButton = graphics.newImageSheet( "Assets\\Art\\GUI\\Main Menu\\MuteButton.png", setImageSheet(232.5, 228, 2))
local sequence_muteButton = {
    {
        name = "pressButton",
        start = 1,
        count = 2,
        loopCount = 0,
        loopDirection = "forward"
    }
}
local muteButton = display.newSprite( sheet_muteButton, sequence_muteButton)
muteButton.x = -display.contentWidth*.8
muteButton.y = display.contentHeight*.85
muteButton:scale(2, 2)
insertObjectsOnScreen(muteButton)
incrementVariable(mainMenuObjects)

--Mute Button Event Handling
function muteButton:touch( event )
    if ( event.phase == "ended" and muteButton.frame == 1) then
        muteButton:setFrame(2)
        mute = true
    elseif ( event.phase == "ended" and muteButton.frame == 2 ) then
        muteButton:setFrame(1)
        mute = false
    end
end
muteButton:addEventListener( "touch", muteButton )

---------------------------------------------------------------------------------------
--Start Game - init
---------------------------------------------------------------------------------------

function beginGame()

end

```

# Answer
> 0 votes
I'm not sure this is the actual right way to do it, but for very simple apps I do it like this:

```
local playButton = display.newImage()
-- all you code
local menuGroup = display.newGroup()
menuGroup:insert( playButton )

function playButton:touch( event )
    if ( event.phase == "began" ) then
        playButton:scale(.9, .9)
    elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
        menuGroup.isVisible = false
        beginGame()
    end
end

```

I'm pretty sure this would be bad for larger games, because the group is not deleted from memory, but it definitely works for smaller ones and I like it because I can also get back to the menu by just doing:

`menuGroup.isVisible = true`

---
Tags: lua, corona-sdk
---


# Question
Title: How can I move objects on to positions declared by their clicking order?
I'm trying to create a quiz game with clickable letters. How can I move them to another area based on their clicking order?

Though you probably already understand what I'm trying to ask, lets clarify: If I was to click the "H" letter first, it would move to the first white box, clicking "O" after that, would move it to the second white box etc.

# Answer
Like @zoran404 commented there are a lot of ways to implement it, but I would proceed with the counter as well, doing something like this:

```
-- you either have a function for each letter or have a class and turn this into a method
-- but the process is similar

-- create a table with all the free spaces' coordinates
-- and a counter to check the first free space
-- remember in lua arrays start at 1
local spaces = {}
local i = 1

local function increaseCounter()
    i = i + 1
end

local function letter:onClick( listener )
     transition.to( letter, { x = spaces[i].x, y = spaces[i].y } )
     -- check documentation for info (docs.coronalabs.com)
     increaseCounter()
end

```
> 0 votes

# Answer
I dont know which language u are using but in JS i would do something like:

```
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

$(".letter").on("click", function(){
  $(".box").each(function(){
    if(!$(this).attr("filled")){
      $(this).attr("filled",true);
      fillTheGap();
      break;
    }
  });
});

```
> -1 votes

---
Tags: corona-sdk
---


title: Unity - Understanding the SRP batcher

text:
# Question
Title: Unity - Understanding the SRP batcher
Im trying to understand the SRP batcher. I have a scene with 300 fairly low-poly models.

These are my rendering stats with SRP Batcher:

And this is without SRP Batcher:

Some observations (This is all with dynamic batching enabled, models share a GPU instanced material):

1. With SRP Batcher the Tris and Verts seem to lower almost impossibly low, sitting at the low thousands, while without the SRP Batcher they are almost 5 million.
2. With SRP Batcher the draw calls are at almost 3000, with none being batched. On the other hand, without SRP Batcher the draw calls are at 103, with almost 2500 being batched.

I cannot really make sense of this. I see no noticable effect on the FPS. I have no idea which is actually better for performance. The stats above make no real sense to me, seems strange that enabling SRP batcher removes all batched calls... Can someone help me understand which is better and when to use what?

Everything is tested on latest unity and URP versions.

# Answer
Maybe this link could help: https://catlikecoding.com/unity/tutorials/basics/measuring-performance/

The idea on Unity is to use SRP Batcher for URP instead of GPU Instancing. The idea is: if you use URP shader compatible, it will batch directly, you only need to share the shader. You can use different meshes, different materials, etc. But if they share the same shader and keywords, they will batch.
> 1 votes

# Answer
What you need to understand regarding the SRP Batcher is, that it is not batching your draw calls like the static or dynamic batching system. Instead, it reduces the overhead of each draw call by making part or all of the material data persistent in the GPU memory. That way, the CPU doesn't need to set up and upload the buffer to the GPU each time, effectively reducing bandwidth and time to render a drawcall.

This blogpost explains it in greater detail:

Don't forget, that GPU instancing won't work if the SRP Batcher is enabled.

And as explained in another answer here, it's more important that your meshed share the same shader rather than the same material. Traditional batching only works with the same material.
> 0 votes

---
Tags: unity
---


# Question
Title: Poly Count in Unity games. 3d Asset detail
I've begun making my own characters for my games. These are just tests that I copied from other references (ie. Cartoons TV etc). I used Maya with the 'Convert Smooth Preview To Polygons' to make the mesh nice and smooth.

However upon importing to Unity, perhaps I am wrong, but the number of polys looks way higher than models I just downloaded from Unity Store etc.

If I continue making ALL my assets in this detail, would the game run ok. (I'm targeting PC, not mobile phones. And I don't mind if low end pcs struggle but anything mid-range and up.)

Should this detail be ok and I can focus on my game dev? Or should I spend some more time trying to reduce the poly count on my models (without compromising too much detail)?

Thanks

# Answer
> 2 votes
The polygon count you can get away with depends on a ton of details:

* How many objects you have in the scene
* How many *different* objects you have in the scene
* How many non-baked light sources shine on them
* How computationally complex your shaders are
* What minimum hardware configuration you intend to target

The only way to find out how close you are to exceeding your polygon budget is to regularly test your game and check the framerate. When your game is not in a state of development where you have a scene which looks close to the final product, then it can make sense to set up a couple "stress test" scenes where you just throw in a ton of objects to see how much you can get away with before the FPS start to drop.

---
Tags: unity, 3d, maya
---


# Question
Title: What is GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS?
I am a beginner in OpenGL. I am learning about **textures** in OpenGL. What I don't understand is how to determine how many texture units are in the GPU. I heard someone said that you can see how many texture units by writing the following code.

```
int total_units;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &total_units);
std::cout << total_units << '\n';  // the result is 192

```

Is there 192 texture units in my GPU? In documentation, it says:

> GL\_MAX\_COMBINED\_TEXTURE\_IMAGE\_UNITS params returns one value, the maximum supported texture image units that can be used to access texture maps from the vertex shader and the fragment processor combined. If both the vertex shader and the fragment processing stage access the same texture image unit, then that counts as using two texture image units against this limit. The value must be at least 48. See glActiveTexture.

So I wanted to know how many texture units can be used to access texture maps from the vertex and fragment shaders. So I wrote and run the following code.

```
int vertex_units, fragment_units;
glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vertex_units);
std::cout << vertex_units << "\n";   // the result is 32
glGetInteferv(GL_MAX_TEXTURE_IMAGE_UNITS, &fragment_units);
std::cout << fragment_units << "\n"; // the result is also 32

```

So 32+32=64. But why does `GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS` shows me the result of 192? I think I am missing something. What do I need to calculate to get 192?

And also, in OpenGL, why are there only `GL_TEXTURE0` to `GL_TEXTURE31` macros? I think these macros are for each shaders. Am I right?

# Answer
> What do I need to calculate to get 192?

You need to recognize the fact that there are more than 2 shader stages. OpenGL 4.5 has *six* programmable stages: vertex, tessellation control, tessellation evaluation, geometry, fragment, and compute. Each of them can access some number of textures, and the "combined" value specifies how many can be accessed by all stages in total.

> why are there only GL\_TEXTURE0 to GL\_TEXTURE31 macros?

The proper way to set the active texture unit is with the value `GL_TEXTURE0 + i`, where `i` is the texture unit index. All of the macros 1 to 31 are monotonically increasing in value, so `GL_TEXTURE0 + 5` is the same value as `GL_TEXTURE5`.

So to set the active texture unit, use `glActiveTexture(GL_TEXTURE0 + i);`.

Basically, OpenGL only defines 32 macros because they never needed to define more than 1. The other 31 are just for the sake of convenience.
> 4 votes

---
Tags: opengl, c++, graphics-programming
---


# Question
Title: Now that Articles 17 & 11 have passed, what should indie developers do?
Since on the 26th of March 2019 the EU has voted in favor of Articles 17 (previously known as Article 13) and 11, what should an indie developer who is based in the EU do to setup a game and a website for the game s/he develops?

I'm taking into consideration the following:

* The developer has a website for the game he publishes.
* The developer also has an account system on the said website (required by the game for customizability and authentication).
* The developer sells the game on his/her own website (for 100% profit).
* The indie developer is funding the game entirely from his/her own money (no investors).
* The game is fully customizable, i.e. all text, textures, sounds and models can be changed.
* The marketing is handled only by the game developer. This also takes into consideration the platforms which are available in the EU when these Articles take effect.

I'm curious about this as I'm based in the EU and wish to create a game with a lot of user customizability (to the level that the game's assets are all replaced by custom ones), but I'm unsure of how Articles 17 (upload filter) and 11 (link tax) will affect me. I'm also concerned about how link tax will affect the website, and how marketing is supposed to be done on the EU internet.

# Answer
> 1 votes
Link Tax means something like this:
For a company to use your content on their website, you must license them, and they must pay an appropriate fee before they can publish some part of your content.
And Upload Filter means something like this:
The Upload Filters are algorithms to prevent copywritten content from being published without the necessary developer permission.
So long as you own everything in the game, you could definitely go through with it without worry. Upload Filter and Link Tax wouldn't affect you publishing your own content because **you own it.** If changing assets is done on the user-end, that's the user problem in terms of legality, not yours. This seems to comply with the EU laws.

---
Tags: legal, copyright
---


# Question
Title: If I use someone else's idea (not work, an *idea*), do I have to give them credit?
Ideas are everywhere for games, products, algorithms, etc. In hypothetical terms, let's say user number x posts on (insert social media site here) that they would like to see a game about (insert game topic here). Can I take their idea and formulate it into a game without giving them any credit?

# Answer
An idea isn't protected by United States copyright law, and ideas are stolen by entrepreneurs often. To quote 17 U.S. Code § 102:

> (b)In no case does copyright protection for an original work of authorship extend to any idea, procedure, process, system, method of operation, concept, principle, or discovery, regardless of the form in which it is described, explained, illustrated, or embodied in such work.

This means that an idea is not in a tangible form (or a copy), and is perfectly able to be taken by you without any *legal* repercussions. It explicitly states an idea cannot be copyright protected.
> 1 votes

---
Tags: legal, copyright
---


# Question
Title: Maya 3d Model. 2+ Materials on a face? Snooker Table felt with lines overlay
I've made a snooker table in Maya for use in a game in Unity. The felt texture on the table is a tiled texture, I used Blinn, and 'place2dTexture' node to do the tiling.

It all looked great. Except I had hoped to 'overlay' another texture on top of the felt which is the straight line and semi-circle drawn across the table.

I couldn't use the same texture with UV mapping because the felt texture is tiled, and of course the lines texture is not (ie. It is intended to fill the whole plane on 1 to 1).

Is there a solution to this? Basically I need to know a way to overlay a non-tiled, partly transparent texture, on top of a tiled one.

Thanks for any help.

# Answer
There are a few ways you could accomplish this effect, likely more ways than I can list here:

## 1. Manual Tiling

Open your tiled felt texture in an image editor like Photoshop, tile it manually to the size of the overlaid texture, producing a single texture, like so:

Then, simply apply this one texture to your model. This approach shouldn't be *too* expensive in the long run if your textures aren't insanely large, although it doesn't feel very elegant or flexible.

## 2. A Second Plane

This is a bit of a 'hack' solution: In your model, create a second plane *very* close to the first, and apply the translucent texture to *that* instead (make it much closer than in this screenshot, and allow the top texture to be transparent):

One possible downside of this solution is that, at further distances, your near-together planes may begin to z-fight.

## 3. A custom Unity shader

Unity has introduced a shader graph system that makes it easier to author shaders by connecting nodes together, similar to how you define materials in rendering software. You would likely simply need to source two textures, using two different sets of UVs on your model, and blend the two textures for your albedo output. You could also author Unity shaders manually to serve this purpose, if you prefer.

This may or may not be more expensive than the above two solutions, on either file size or performance - if you're concerned about that, you could simply test each solution to see what works best for your problem.

One thing to keep in mind when approaching problems like this is that materials authored in programs like Maya using their own material editors, intended for use with their own renderers (i.e. Arnold), can't necessarily map 1:1 to the behaviour of game engines like Unity when you actually go and import your asset - if you spend lots of time trying to get the perfect Hypershade material, chances are you'll have to do a lot of that work over again in your engine.
> 1 votes

---
Tags: 3d, materials, maya
---


# Question
Title: How does Unity know that you make more than one hundred thousand dollars on the Personal plan?
How do they check if you make more than 100k? That is really puzzling me.

# Answer
According to the ToS, they ask you for the appropriate documents and/or send someone at your office to check your data:

> 6. Compliance
>
> To ensure compliance with the Agreement, you agree that within ten (10) days from the date of Unity or its authorized representative’s request, you shall provide all pertinent records and information requested in order to verify that your installation and use of any and all Services is in compliance with the Agreement along with a signed verification that all such information is complete and correct. Furthermore, if you are a Legal Entity, Unity or its authorized representatives may upon reasonable prior notice access and inspect your facilities and computer systems to review and verify your compliance with the Agreement. Any such inspection shall be conducted during regular business hours at your facilities or electronically via remote access. In the event you have impermissibly used Unity Personal (or other products) or have not paid the applicable fees for all Services you have deployed or used, you agree to immediately pay for such Services, as well as the reasonable inspection costs, upon Unity’s demand.
> 1 votes

---
Tags: unity, licensing
---


title: Function destroying wrong object

text:
# Question
Title: Function destroying wrong object
I am using the `collision_line_list` function to detect all objects of a type.

In this case, the object is **obj\_CapMan**.

**Code:**

```
collision_line_list(obj_HatMan.x,obj_HatMan.y,mouse_x,mouse_y,obj_CapMan,false,true,listaCap,false);

```

This code is in an object that would be equivalent to the game administrator. What should not influence anything, but in any case, is the information.

**Full Code:**

```
listaCap=ds_list_create();
listaNum=collision_line_list(obj_HatMan.x,obj_HatMan.y,mouse_x,mouse_y,obj_CapMan,false,true,listaCap,false);

if(listaNum>0){
    instance_destroy(listaCap);
    ds_list_destroy(listaCap);
}

```

As a result, none of the objects on the list are being destroyed, but another one that is neither the manager nor the **obj\_CapMan**, is being destroyed.

**Documentation Link:**

https://manual-en.yoyogames.com/#t=GameMaker\_Language%2FGML\_Reference%2FMovement\_And\_Collisions%2FCollisions%2Fcollision\_line\_list.htm&rhsearch=collision\_line&rhhlterm=collision\_line\_list%20collision\_line

---

This red square is an object to detect a **headshot**.

**That same object that is being destroyed, even though it is not mentioned in that part of the code at any time:**

# Answer
> 0 votes
There's an error in your code:

> `instance_destroy(listaCap);`

You are destroying the instance referenced by `listaCap`, which is a data structure instead. GameMaker Studio doesn't have strong language types, and treats `listaCap` like a regular resource id; since you used it in the `instance_destroy()` function, GMS pretends it is an instance id and does its job. The result is, a random object is being destroyed.

You can fix your code by accessing the content of your `ds_list` and destroying the referenced instance:

```
if (listaNum > 0) {
    for (var i = 0; i < listaNum; ++i) {
        instance_destroy(listaCap[| i]);
    }
    ds_list_destroy(listaCap);
}

```

Additionally, you may want to check if there's one instance only in your `ds_list` before destroying it, just to make sure no more issues arise.

---
Tags: collision-detection, game-maker
---


# Question
Title: Need help getting an objects orientation / all my OpenGL rotations are reversed
I'm using OpenGL on Ubuntu Linux with the Eclipse IDE and the GCC compiler. I am bringing blender models into a homemade renderer/game engine. I parse a text file containing object descriptions to load models.

*Example object:*

```
begin_object generic_object
generic_object_name lampost
generic_object_parent_name world
generic_object_position -10.0000 -10.0000 2.000000
generic_object_rotation 90.000000 0.000000 0.000000
generic_object_scale 1.000000 1.000000 1.000000
end_object

begin_object ...

```

The `generic_object_rotation 90.000000 0.000000 0.000000` line describes 3 values:

* Rotation around Z (XY).
* Rotation around X (YZ).
* Rotation around Y (XZ).

After going through all the headaches of Euler angles and their gimbal lock and singularities, I switched all my code to quaternions (highly recommended).

I am told that a counter-clockwise rotation around the Z-axis, looking down the Z-axis toward the origin uses a rotation matrix like:

```
cos(theta)  -sin(theta)  0  0
sin(theta)  cos(theta)   0  0
0           0            1  0
0           0            0  1

```

I got this from a document (rotgen.pdf) off the Song-Ho website.

If I replace `theta` with `+90.0` (just like in my input file above), the result is:

```
  0.0 ,  -1.0 ,  0.0 ,  0.0
  1.0 ,   0.0 ,  0.0 ,  0.0
  0.0 ,   0.0 ,  1.0 ,  0.0
-10.0 , -10.0 ,  2.0 ,  1.0

```

So, I make a quaternion for +90.0 degrees, turn it into a matrix and then print out the matrix to see if it is the same, and I actually get the same matrix.

```
  0.0 ,  -1.0 ,  0.0 ,  0.0
  1.0 ,   0.0 ,  0.0 ,  0.0
  0.0 ,   0.0 ,  1.0 ,  0.0
-10.0 , -10.0 ,  2.0 ,  1.0

```

All is well... Then, I send this matrix to the shader to draw this object and it rotates my object CW instead.

In the shader there's:

```
gl_Position = projection_matrix * view_matrix * model_matrix * vec4( aPos , 1.0 );

```

which seems correct.

So, I made a cube in Blender, attached different colour textures to each side of the cube so I could verify that my input data was good and, as long as the `model_matrix` is the identity matrix, the object is oriented correctly in space. Any time I add rotations, the models rotate in the opposite direction. This happens on all 3 axes.

My current goal/project is the parenting system. I want to be able to extract orientation and position from the model matrix of any object (that data is stored with the object).

Specifically, right now, I want to extract the forward vector from the `model_matrix` so I can attach a light source to this rotating object. Set its light direction for the fragment shader. That is when I found this error.

**What I am seeing:**
The rotation of the object is opposite to what I command. When I rotate 0-360 over and over again, the forward vector I am reading from the objects `model_matrix` diverges from the direction of the object until it gets to 180 degrees, where the face of the object and the forward vector are coincident again; then they diverge again until we reach 360 and they are again coincident.

**What I expect (and this may be part of my issue):**
I want the rotation part of the `model_matrix` that rotates the object to *be* the current orientation of the object. And it *looks like* it is but the object does not render that way. The object rotates in the opposite direction (which is preventing me from getting the correct light direction vector, i.e. the forward vector).

Is this an OpenGL thing? Is the orientation of an object the transpose of the 3x3 rotation section of the `model_matrix`?

# Answer
> 0 votes
The solution was to transpose the rotation matrix.

The link TomTsagk provided lead me to the solution.

I was using:

\[0\]\[0\] , \[1\]\[0\] , \[2\]\[0\] as the side vector.
\[0\]\[1\] , \[1\]\[1\] , \[2\]\[1\] as the up vector.
\[0\]\[2\] , \[1\]\[2\] , \[2\]\[2\] as the forward vector.

The correct method was:
\[0\]\[0\] , \[0\]\[1\] , \[0\]\[2\] as the side vector.
\[1\]\[0\] , \[1\]\[1\] , \[1\]\[2\] as the up vector.
\[2\]\[0\] , \[2\]\[1\] , \[2\]\[2\] as the forward vector.

So , position was always correct but rotation was not.

Also , thanks to liggiorgio for editing the original post.

---
Tags: opengl, shaders, rotation, matrix, orientation
---


# Question
Title: The .apk file for my built game is much larger than expected
Assets of my game are 15 MB, Player Settings are default, but my `.apk` file is 45 MB. I tried to change Player Settings and convert PNG images to JPEG, but this didn't work.

# Answer
> 1 votes
-- question was changed after writing the original answer --

One thing you can do is unzip the APK (it is basically just a renamed zip file) and look inside.

Don't forget that your binary + any icons/logos/etc assets take up more space. It might also include debug symbols, 1x/2x/etc resized assets.

# Answer
> 0 votes
The `.apk` file is also be bundling itself with manifests and necessary data files that make an `.apk` work as an installer package (because that's what `.apk`'s are. They're an installer.)
I had the same problem with extracting my small amount of assets and getting a file way larger than I thought. You should be okay, as this is not a problem, just Unity doing its job right.

---
Tags: unity, android, build-process
---


# Question
Title: Difference between _process(delta) and _physics_process(delta)?
The documentation is pointing one main difference, this is the concept of being synced or not with the physics engine, so the `delta` parameter has more chance to be constant in `_physics_process(delta)` than in `_process(delta)`.

But I am pretty sure that no one counts on that. And that everybody checks the value of delta in `_physics_process(delta)`.

So what are the different use cases of those two functions?

# Answer
*I made an more in depth explanation on GitHub: link.*

---

## Graphics or Physics

One difference is that `_process` is tied to graphics (it runs once per frame), while `_physics_process` isn't. As such, VSync (which is on by default) will affect `_process`, depending on the monitor frame rate, of course. Use it for anything graphics related.

The other is that `_physics_process` is tied to the physics, while `_process` isn't. As such, Physics FPS (which is 60 by default) will be the target frame rate for `_physics_process`. Godot will call `_physics_process` before computing physics response, and thus to get that correct physics response, use `_physics_process` for anything physics related.

If your script need to read any properties that the physics server will update (e.g position, ray casts), then avoid reading them in `_process`. See Physics process callback.

Is moving a node graphics or physics? If it is a `PhysicsBody` or `PhysicsBody2D` consider it physics (corollary: use `_physics_process` to move `KinematicBody` and its 2D counterpart). Otherwise, it is graphics.

---

What if you need to compute something with a stable frequency, but it does not affect physics, nor graphics? Well, it is neither. While it is often harmless to hijack either `_process` or `_physics_process`, consider using a `Timer` (or a coroutine, or a `Thread` with a good old loop).

---

By the way, you can disable using `set_process` and `set_physics_process`.

---

## Input

For input, I would make the same distinction as for anything else. Should the input update graphics (e.g. it is a `Control`)? then either `_input` or `_process`. Should input update physics? then either `_input` or `_physics_process`.

I'd prefer using `Input` from `_process` or `_physics_process`, until you run into a situation where you need `_input`.

By the way, the `just_pressed` and `just_released` methods are intended to work on both `_process` and `_physics_process`, they check on which one you are calling them.

---

## On smooth motion

Either `_process` or `_physics_process` could be the faster one, depending on hardware and configuration. Any visual only change that happens faster than `_process` will not be seen. On the other hand, if it changes any slower, then it will not appear as smooth motion.

Since Godot will execute physics according to Physics FPS, if you configure a low Physics FPS, the physic bodies appear to teleport. Plus, tunneling will be more likely to happen. For which you want to configure your `RigidBody` to use continuous collision detection (set it to Cast Ray, because shape Cast Shape is not great on the current version - *note: I wrote this referring to Godot 3.x*).

It is possible to apply smooth motion to sprites and meshes (moving them in `_process`) to follow physic bodies (which move in `_physics_process`), see also smoothing-addon. You may see shapes intersect because it does not predict collisions. *But that might be the price for better performance.*

*You might also be interested in the proposal Fixing physics timestep vs refresh rate problems (jitter), and the proposal Add object position interpolation between physics frames*

---

## On delta

Godot will try to keep stable the frequency of both `_physics_process` and `_process` (when VSync is enabled). However, that is not certain. Not on a machine where there are other applications running, or where you can write a code that takes too much time to run for the time budget of a frame. And thus, both need and have `delta`.

There are some things that will not require you to use `delta`. For example, for graphics if you use an `AnimationPlayer` or `Tween`, it is handled for you. *Of course, `AnimationPlayer` or `Tween` are not only useful for graphics.*

Similarly, for physics if you use `force` and `torque` methods of `RigidBody` and its 2D counterparts, you don't have to worry about `delta`.

And then on `KinematicBody` and its 2D counterpart, `move_and_slide` automatically applies `delta`, but `move_and_collide` and `test_motion` doesn't. Notice that `move_and_collide` and `test_motion` take `rel_vec` not `linear_velocity`. Thus, you should multiply by `delta` from `_physics_process` for them to be frame independent. Which is another reason to use them in `_physics_process`.
> 11 votes

---
Tags: godot, physics-engine
---


# Question
Title: Help me Make Sense of Unity 2D Resolution Management
I am trying to set up an environment for a retro style pixel art game in Unity 2D. I aim for a vertical resolution of 240 pixels, and then, I would like the horizontal resolution to be dependent on the target screen's aspect ratio, so, on a 4:3 screen 320x240, on 16:9 around ˜432x240, and so on.

I have read a bunch of tutorials, added pixel perfect to my main camera, set up a target resolution in player preferences, set the pixel in a unit to 8 pixels everywhere, but still cannot make heads or tails of how it actually works.

Here is an image of my scene with my camera selected:

If I am correct, the dashed line of the camera is my target resolution, although it is weird as the green image I used as a background has a native resolution of 216 pixel vertical, yet it fills up the supposedly 240 pixel high camera. I have no idea what the solid green line is, and don't even get me started of the canvas, whose render target is set for camera yet it is obviously many times bigger than that.

Can someone please explain it to me how to properly set up a 2D environment described in my opening, point out my mistakes, point me to a good tutorial, or just give me advice on how to understand Unity's resolution management?

# Answer
The pixel-perfect camera component automatically scales your view so each texel in your sprites maps to an integer number of pixels on the screen. That means it's limited to scaling by whole-number ratios: 1x, 2x, 3x etc.

Within those constraints, it tries its best to fill the current size of the window/screen with the largest texels it can, while still showing everything inside the "reference resolution" box.

Above, I've pressed the "Run in Edit Mode" button so we can see what it's doing. In the background is an 8 PPU grid, where the large grey squares are 80 px.

You can see the dashed green outline exactly matches the 320 x 240 reference resolution I asked it for. (If you're not observing this, you might not have Run in Edit Mode ticked, or there may be a scale applied to another object in your scene that's throwing it off).

My current game window is larger than this though, so the current rendered bounds are shown by the solid green box outside that. Rendering these bounds lets us fit the current window with a 3x zoom (see the "Current Pixel Ratio 3:1" in the bottom-right).

Now we'll try making the game window narrower in width. We can get as tight as this while keeping our 3:1 zoom factor:

If I make the game window any narrower, it starts to creep into the space we reserved for the reference resolution. So the pixel-perfect camera component drops down a zoom level, from 3:1 to 2:1, so that it can still show the full width of the reference space. Zooming out like that means we can also see more above and below the reference range too.

If you want your vertical resolution to remain absolutely capped, you can tick the "Crop Frame Y" checkbox.

This snaps the height of the displayed area to exactly match the reference resolution, letterboxing the display so that pixels above and below aren't drawn, even if the current window size leaves a little extra space at the selected zoom factor. Instead you get black bars above and below.

If you want your 240 vertical texels of scene to exactly fill the height of the window, no matter how tall it is, then you'll have to sacrifice pixel perfection. Some possible screen/window sizes aren't multiples of 240, so the only way to stretch 240 source texels to cover it is to interpolate them, or repeat some texels more than others.

If that's the look you want, it's reasonably easy to set up:

1. Get rid of your pixel perfect camera component, since we've decided pixel perfection isn't the goal.
2. Create a new RenderTexture in your assets folder. We'll make it 1024x240 to have lots of room for wide screens. (You can also dynamically create this in script to match the width you actually need)
3. Set your camera's Target Texture to this texture. Now you'll render exactly 240 vertical texels of the screen into the 240 vertical texels in the texture.

You can use a script to adjust the Viewport Rect of the camera to match the current display aspect ratio so you're not rendering stuff that will be off-screen.
4. Place a quad in the scene on a new layer that's not seen by your main camera. We'll scale it so it measures 128 x 30 (1024 x 240 divided by 8 PPU).
5. Create an unlit material that display your Render Texture, and assign it to the quad.
6. Create a new orthographic camera that sees only the quad's layer, and give it a size of 15 (15 above + 15 below = 30 units x 8 PPU = 240 texels). Frame it so it looks at the center of the quad.

By outputting to the display, this camera handles upscaling your 240 texel high render texture to whatever vertical resolution the window/screen happens to be at this moment.

By default, the Render Texture will be set to use bilinear filtering, which will look smooth, but potentially blurry. You can change that to point filtering to keep the edges crisp, though at the cost that some lines might look wider than others because of the inconsistent zoom factor. You can even apply a custom shader to the quad material to implement your own upscaling algorithm, to get a different compromise between crispness and smoothness/consistency.
> 2 votes

---
Tags: 2d, html-canvas, resolution
---


# Question
Title: How does HPA*(Hierarchical Pathfinding A*) really work?
I'm currently researching for a summary paper on the different variants of A\* search algorithm and how they are used in games and I stumbled across the name HPA\*. I've heard that it's much more faster than traditional A\* but I don't understand it completely. There's hardly any videos or articles written about it so I tried reading a research paper on it and I'm having trouble grasping it. All I can understand is it divides the huge graph in many smaller segments(divide and rule), it creates clusters(subgrids) and precomputes optimal distance between clusters etc..

I would be grateful to any of you if you helped explain it! Thanks in advance.

# Answer
> 7 votes
One of the creators of HAA\* *(a generalization of HPA\*)* wrote a very accessible article explaining how it works on aigamedev.com. Unfortunately that site seems to be dead, but fortunately archive.org has the article archived.

I highly recommend reading it, but to summarize: HPA\* breaks the map into chunks. In each chunk, you identify the possible entrances/exits to the chunk, and cache the paths/distances between them. You can then use this to create a graph of the chunks which is much smaller and faster to path-find over than the original map.

The paths you find with this method are only *near* optimal, but *(after the initial setup cost)* the pathfinding runs much more quickly than plain A\*. You can even group the chunks into larger chunks recursively *(hence the "H" in "HPA", meaning "Hierarchical")* for greater speed benefits.

For more details, see the original paper.

---
Tags: algorithm, path-finding, grid, graph, dijkstra
---


# Question
Title: How to ensure new players aren't blocked from the leaderboards?
There is a simple word game, where players score points for each game they play. It creates a global chart, ranking players by their score.

The problem is that when a new player comes into the game, there are already old players occupying the chart top. Even if they are no longer active players.

To smooth this inequity, we introduced a super game that happens once a day and is stuffed with multiple bonuses like easier extra time, score x5 multiplication, and some others. It offers upward mobility, allowing players to get to the top if they play long enough.

Now I am thinking of another mechanism. What if all scores are subject to a little inflation, like 0.1% a day? It will affect the "poor" just a little bit and "score-fat cats" are going to be stripped of their score a bit harder. But not too much also.

I am trying to think forward on how such a mechanism could affect players' motivation, and if there some commonly used alternatives to fighting the issue?

**P.S.** Another idea is to reset the leaderboard at midnight on New Year's Eve, keeping a global all-time leaderboard available but just for historical purposes.

Deleting players after a certain long enough period of inactivity (like a year) is also a considered option. Another option is to reset a score if a player is inactive for a certain period of time (like half a year), but keep their profile. If the player decides to resume playing, all new games are bound to the same existing profile, but the score is counted only for games after a date when activity is restored.

# Answer
> 1 votes
A good way to do this would be having separate leaderboards that reset daily/weekly/monthly/yearly/all time. That way, regardless of when they started, they still have an equal chance of getting up each leaderboard when it resets. The all-time leaderboard can be used to keep track of everyone's score ever.
The system you mentioned for deleting player scores after x inactivity is a good option for keeping everything smooth and refreshed, even if they aren't ever coming back.

---
Tags: leaderboards, scoring, ranking
---


title: Why the object is not rotating slowly?

text:
# Question
Title: Why the object is not rotating slowly?
At the top

```
public float secondsToRotate;
private float secondsSoFar = 0.0f;

```

Then in the Update

```
private Update()
{
  secondsSoFar += Time.deltaTime;
  float t = secondsSoFar / secondsToRotate;
  Vector3 lerpPoint = Vector3.Lerp(transform.position, -transform.position, t);
  transform.rotation = Quaternion.LookRotation(lerpPoint);
}

```

but instead of slowly smooth rotating it's just waiting X seconds then rotate too fast like rotating at once. I wanted it to rotate slowly smooth. for example, if I set the secondsToRotate to 5 so the rotation will take 5 seconds.

The full script :

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

public class PlayerSpaceshipAreaColliding : MonoBehaviour
{
    public float rotationSpeed;
    public float movingSpeed;
    public float secondsToRotate;

    private float timeElapsed = 0;
    private float lerpDuration = 3;
    private float startValue = 1;
    private float endValue = 0;
    private float valueToLerp = 0;
    private Animator playerAnimator;
    private bool exitSpaceShipSurroundingArea = false;
    private bool slowd = true;
    private float secondsSoFar = 0.0f;

    // Start is called before the first frame update
    void Start()
    {
        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (exitSpaceShipSurroundingArea)
        {
            if (slowd)
                SlowDown();

            if (playerAnimator.GetFloat("Forward") == 0)
            {
                slowd = false;
            }

            if (slowd == false)
            {
                secondsSoFar += Time.deltaTime;
                float t = secondsSoFar / secondsToRotate;
                Vector3 lerpPoint = Vector3.Lerp(transform.position, -transform.position, t);
                transform.rotation = Quaternion.LookRotation(lerpPoint);
            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = false;
            Debug.Log("Entered Spaceship Area !");
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = true;
            Debug.Log("Exited Spaceship Area !");
        }
    }

    private void SlowDown()
    {
        if (timeElapsed < lerpDuration)
        {
            valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
            playerAnimator.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;
        }

        playerAnimator.SetFloat("Forward", valueToLerp);
        valueToLerp = 0;
    }
}

```

In that place in the script, I'm trying to rotate the player smooth slowly to the opposite direction. I want also to increase the "Forward" speed when it's rotating while it's rotating but for now the rotation itself is not working at all the player is not rotating.

```
if (slowd == false)
                {
                    secondsSoFar += Time.deltaTime;
                    float t = secondsSoFar / secondsToRotate;
                    Vector3 lerpPoint = Vector3.Lerp(transform.position, -transform.position, t);
                    transform.rotation = Quaternion.LookRotation(lerpPoint);
                }

```

The main goal is to create some realistic effect when the player is leaving the colliding area the player will slow down then when the player has stopped to start rotating slowly to the opposite direction and start moving by increasing the "Forward" value while rotating.

Some realistic preventing from the player to leave the colliding area. when he try to leave the area he should move back in the colliding area.

# Answer
> 1 votes
If your goal is to rotate to the opposite of the current facing direction, that would be `-transform.forward`, not `-transform.position` as you're currently using in your code. Positions and directions are different things.

It looks like you want something more like this:

```
Quaternion targetOrientation;

void Update()
{
    if (exitSpaceShipSurroundingArea)
    {
        if (slowd) {
            SlowDown();

            if (playerAnimator.GetFloat("Forward") == 0)
            {
                slowd = false;
                // Cache the 180 degree direction change once, when we start rotating.
                targetRotation = Quaternion.LookRotation(-transform.forward);
            }
        }
        else
        {
            // Rotate toward our cached orientation.
            transform.rotation = Quaternion.RotateTowards(
                  transform.rotation,
                  targetOrientation,
                  Time.deltaTime * 180f / secondsToRotate
            );
        }
    }
}

```

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