# Question
Title: Confused, maybe the mistake ik is the foreach loop
I dont know why but my jump method does not work. My character can only jump on one single object. The other obstacle haven't any influence on the player. I really don't see my mistake

```
     foreach (RectangleShape obstacles in MoveAtObjectList)
               {
                   MainPlayer.Move(deltaTime, obstacles);
               }

               foreach (RectangleShape obstacles in JumpAtObjectList)
               {
                   MainPlayer.Jump(deltaTime, obstacles);
                   break;
               }

               Draw();

               Window.Display();
           }
       }
   }
}

```

This was part of my main Class, where i call the jump method within a foreach loop. Here in my Payer class I tried to write the jump function.

```
using SFML.Graphics;
using SFML.System;
using SFML.Window;

namespace Pong3final
{
    class Player : RectangleShape
    {

        float CollisionDistance = 0.5f;

        float PlayerSpeed = 50;
        float JumpSpeed = 100;
        float FallSpeed = 100;
        float JumpTimer;

        bool JumpBool = false;
        bool Fall = true;

public  void Jump(float deltaTime, RectangleShape collisionObject)
        {

            if (Keyboard.IsKeyPressed(Keyboard.Key.Space) && !Fall && CheckCollision(this, collisionObject))
            {
                JumpBool = true;
            }

            //Player is jumping
            if (JumpBool)
            {
                JumpTimer += deltaTime;

                this.Position -= new Vector2f(0, JumpSpeed) * deltaTime;

                if (JumpTimer > 0.5f)
                {
                    JumpBool = false;
                    Fall = true;
                    JumpTimer = 0;
                }
            }

            //Player is falling when he doesnt touch anything and he isnt jumping
            else if (!CheckCollision(this, collisionObject))
            {
                Fall = true;
            }

            //Player is falling
            if (!JumpBool && !CheckCollision(this, collisionObject) && Fall)
            {
                this.Position += new Vector2f(0, FallSpeed) * deltaTime;

                if (CheckCollision(this, collisionObject)) //Player stops falling because of a collision with an object
                {
                    Fall = false;
                }
            }
        }

        public void Move(float deltaTime, RectangleShape collisionObject)
        {
            {
                Vector2f MovePlayerPosition = Position;

                if ((Keyboard.IsKeyPressed(Keyboard.Key.Left) || Keyboard.IsKeyPressed(Keyboard.Key.A)))
                {

                    MovePlayerPosition -= new Vector2f(PlayerSpeed, 0) * deltaTime;

                    FloatRect collisionOverlap;

                    if (CheckCollision(this, collisionObject, out collisionOverlap))
                    {
                       MovePlayerPosition = MovePlayerPosition + new Vector2f(collisionOverlap.Width + CollisionDistance, 0);
                    }
                }

                if (Keyboard.IsKeyPressed(Keyboard.Key.Right) || Keyboard.IsKeyPressed(Keyboard.Key.D))
                {

                    MovePlayerPosition += new Vector2f(PlayerSpeed, 0) * deltaTime;

                    FloatRect collisionOverlap;

                    if (CheckCollision(this, collisionObject, out collisionOverlap))
                    {
                       MovePlayerPosition = MovePlayerPosition - new Vector2f(collisionOverlap.Width + CollisionDistance, 0);
                    }
                }

                Position = MovePlayerPosition;
            }
        }

        public static bool CheckCollision(RectangleShape obj1, RectangleShape obj2, out FloatRect overlap)
        {
            FloatRect obj1Collider = obj1.GetGlobalBounds();
            FloatRect obj2Collider = obj2.GetGlobalBounds();

            //Nur die rechte, linke und obere Seite kollidiert
            if (obj1Collider.Intersects(obj2Collider, out overlap))
            {
                return true;
            }
            overlap = new FloatRect();
            return false;
        }

        public static bool CheckCollision(RectangleShape obj1, RectangleShape obj2)
        {
            FloatRect obj1Collider = obj1.GetGlobalBounds();
            FloatRect obj2Collider = obj2.GetGlobalBounds();

            return obj1Collider.Intersects(obj2Collider);
        }
    }
}

```

# Answer
> 3 votes
You have at least one obvious error at hand.

```
foreach (RectangleShape obstacles in JumpAtObjectList)
{
      MainPlayer.Jump(deltaTime, obstacles);
      break;
}

```

*break* tells the foreach loop to exit and since there is no condition, it will always exactly run one time for the first obstacles in JumpAtObjectList. What you probably wanted is to check if the obstacles (better naming would be obstacle since it is only one at a time) is the correct one, execute your MainPlayer.jump and break afterwards.

Next I'm almost sure that your move method is wrong as well. You are calling it once for each object and each time you move your player, but what you want is to only move him once.

I refactored it a bit for easier reading and probably this should fix as well your jumping issue. Since you are not moving if you don't press the key (no auto move), you only need to call it when you press the key compared to your jump method (where you can fall as well). Better naming would be handleVerticalMovement. I kept your code as close as you wrote it with just placing the loops where they should belong.

Main loop

```
if ((Keyboard.IsKeyPressed(Keyboard.Key.Left) || Keyboard.IsKeyPressed(Keyboard.Key.A))) {
       MainPlayer.Move(deltaTime, MoveAtObjectList, -1);
}
if (Keyboard.IsKeyPressed(Keyboard.Key.Right) || Keyboard.IsKeyPressed(Keyboard.Key.D)) {
       MainPlayer.Move(deltaTime, MoveAtObjectList, 1);
}
MainPlayer.Jump(deltaTime, JumpAtObjectList);
Draw();
Window.Display();

```

New move

```
public void Move(float deltaTime, List MoveAtObjectList, int direction){
    bool hitSomething = false;
    foreach (RectangleShape obstacles in MoveAtObjectList) {
        if (CheckCollision(this, collisionObject, out collisionOverlap)) {
            hitSomething = true;
            this.Position += new Vector2f(collisionOverlap.Width + CollisionDistance, 0) * direction;
            break; //hitting one thing is enough
        }
    }
    if (!hitSomething) {
        this.Position -= new Vector2f(PlayerSpeed, 0) * deltaTime * direction;
    }
}

```

Adjusted jump

```
public  void Jump(float deltaTime, List JumpAtObjectList) {
    bool hitSomething = false;
    foreach (RectangleShape collisionObject in JumpAtObjectList) {
        if (CheckCollision(this, collisionObject)) {
            hitSomething = true;
            Fall = false; //you can't if you hit something
            break;
        }
    }
    if (Keyboard.IsKeyPressed(Keyboard.Key.Space) && !Fall && hitSomething) {
        JumpBool = true;
    }
    if (JumpBool) {
        JumpTimer += deltaTime;
        this.Position -= new Vector2f(0, JumpSpeed) * deltaTime;
        if (JumpTimer > 0.5f) {
            JumpBool = false;
            Fall = true;
            JumpTimer = 0;
        }
    } else if (!hitSomething) {
        Fall = true;
    }
    if (!JumpBool && !hitSomething && Fall) {
        this.Position += new Vector2f(0, FallSpeed) * deltaTime;
    }
}

```

---
Tags: c#, 2d, platformer, sfml, oop
---


# Question
Title: What do language do I need to learn for Unity
Hi what language do I need to learn to start programming in unity? Can I learn it on code academy?

# Answer
> 1 votes
Unity scripts use C#.

There are courses available to learn C# on nearly every major code learning platform, including code academy.

---
Tags: unity
---


# Question
Title: Which programming languages can I use with Unity?
I'm familiar with Unity and most of its features, but I don't know which programming languages are supported. I think it uses C#, which I'm unfamiliar with, so I was wondering if Unity supports any other languages.

# Answer
In the time since this question was first asked, the **UnityScript** and **Boo** options in Unity have been deprecated, and are no longer available in current Unity versions.

(This is one reason why questions about the supported features of a particular software package aren't a great fit for the Q&A format we use here - old information can fossilize. Your first port of call should always be the documentation for that software itself, which will generally have the most up-to-date information about what it does and does not support)

The Unity documentation now reads:

> Unity supports the **C#** programming language natively. C# (pronounced C-sharp) is an industry-standard language similar to Java or C++.
>
> In addition to this, many other .NET languages can be used with Unity if they can compile a compatible DLL - see here for further details.
> 6 votes

# Answer
As found in the documentation, there is one "native" choice:

> * **C#** (pronounced C-sharp), an industry-standard language similar to Java

Additionally, many other .NET compatible languages (like C++) can be used, if they are first compiled into a DLL (then you'd have to write wrapper code in C#).
> 3 votes

---
Tags: unity
---


# Question
Title: Unity mesh shader for outlining colour changes
I've written a shader to change colour on a deformable mesh's Z position. This is to create the effect of topographic/contour maps where the colour changes based on the height of terrain of the mesh.

This is it viewed from the side

And viewed head-on (as it's meant to be)

What I need is for a black outline between two colour levels. I have done this, but the problem is that the black outline is not pixel perfect (look at the black grouping near the bottom left of the image).

My current shader simply uses if statements to determine which colour level each part should be in, and if it's within a certain threshold BETWEEN two colour layers, make it black. Obviously this is wrong.

Here's my shader code:

```
Shader "Unlit/MapEditorShader"
{
    Properties {

    _Level8Color ("Level8Color", Color) = (0.8,0.9,0.9,1)
    _Level8 ("Level8", Float) = 30
    _Level7Color ("Level7Color", Color) = (0.8,0.9,0.9,1)
    _Level7 ("Level7", Float) = 30
    _Level6Color ("Level6Color", Color) = (0.8,0.9,0.9,1)
    _Level6 ("Level6", Float) = 30
    _Level5Color ("Level5Color", Color) = (0.8,0.9,0.9,1)
    _Level5 ("Level5", Float) = 30
    _Level4Color ("Level4Color", Color) = (0.8,0.9,0.9,1)
    _Level4 ("Level4", Float) = 30
    _Level3Color ("Level3Color", Color) = (0.75,0.53,0,1)
    _Level3 ("Level3", Float) = 20
    _Level2Color ("Level2Color", Color) = (0.69,0.63,0.31,1)
    _Level2 ("Level2", Float) = 10
    _Level1Color ("Level1Color", Color) = (0.65,0.86,0.63,1)
    _Level1 ("Level1", Float) = 0
    _Level0Color ("Level0Color", Color) = (0.37,0.78,0.92,1)
    _OutlineColor ("OutlineColor", Color) = (0,0,0,1)
    _Slope ("Slope Fader", Range (0,1)) = 0

}
SubShader {
    Tags { "RenderType" = "Diffuse" }
    CGPROGRAM
    #pragma surface surf SimpleLight
    struct Input {
        float3 customColor;
        float3 worldPos;
    };

    half4 LightingSimpleLight (SurfaceOutput s, half3 lightDir, half atten) {
              half4 c;
              c.rgb = s.Albedo * 0.8;
              c.a = s.Alpha;
              return c;
          }

    float _Level8;
    float4 _Level8Color;
    float _Level7;
    float4 _Level7Color;
    float _Level6;
    float4 _Level6Color;
    float _Level5;
    float4 _Level5Color;
    float _Level4;
    float4 _Level4Color;
    float _Level3;
    float4 _Level3Color;
    float _Level2;
    float4 _Level2Color;
    float _Level1;
    float4 _Level1Color;
    float _Slope;
    float4 _Level0Color;
    float4 _OutlineColor;

    void surf (Input IN, inout SurfaceOutput o) {
    //at breakpoints we want a black line
        if((IN.worldPos.z > _Level8 - _Slope && IN.worldPos.z < _Level8 + _Slope)||
        (IN.worldPos.z > _Level7 - _Slope && IN.worldPos.z < _Level7 + _Slope)||
        (IN.worldPos.z > _Level6 - _Slope && IN.worldPos.z < _Level6 + _Slope)||
        (IN.worldPos.z > _Level5 - _Slope && IN.worldPos.z < _Level5 + _Slope)||
        (IN.worldPos.z > _Level4 - _Slope && IN.worldPos.z < _Level4 + _Slope)||
        (IN.worldPos.z > _Level3 - _Slope && IN.worldPos.z < _Level3 + _Slope)||
        (IN.worldPos.z > _Level2 - _Slope && IN.worldPos.z < _Level2 + _Slope)||
        (IN.worldPos.z > _Level1 - _Slope && IN.worldPos.z < _Level1 + _Slope))
            o.Albedo = _OutlineColor;
        else if (IN.worldPos.z > _Level8)
            o.Albedo = _Level8Color;
        else if (IN.worldPos.z > _Level7)
            o.Albedo = _Level7Color;
        else if (IN.worldPos.z > _Level6)
            o.Albedo = _Level6Color;
        else if (IN.worldPos.z > _Level5)
            o.Albedo = _Level5Color;
        else if (IN.worldPos.z > _Level4)
            o.Albedo = _Level4Color;
        else if (IN.worldPos.z > _Level3)
            o.Albedo = _Level3Color;
        else if (IN.worldPos.z > _Level2)
            o.Albedo = _Level2Color;
        else if (IN.worldPos.z > _Level1)
            o.Albedo = _Level1Color;
        else
            o.Albedo = _Level0Color;

    }
    ENDCG
}
Fallback "Opaque"
}

```

Any suggestions would be greatly appreciated.

# Answer
> 3 votes
What you're finding here is that drawing the line based on your height above/below the boundary gives inconsistent results: in places where the height changes quickly (steep slopes), the outline ends up being very narrow, or even disappearing at some zooms/camera angles. But in places where the height changes gradually, the outline gets thicker, because the surface hangs around that threshold level longer.

We can (approximately) correct for this by using screenspace partial derivatives to measure how quickly the height is changing from pixel to pixel in the neighbourhood of the pixel we're drawing, and use that to estimate how many pixels we are from the border. Then we can draw a cleanly antialiased line at a consistent pixel width, regardless of the slope, zoom, or camera angle.

I used a version of this trick to draw the topographical lines on the planetary maps in Starlink. :)

In Unity, the code would look something like this:

```
fixed4 frag (v2f i) : SV_Target
{
    // Compute how fast height changes between adjacent pixels,
    // horizontally and vertically on the grid of the screen.
    float2 rateOfChange = float2(ddx(i.height), ddy(i.height));

    // Compute how far we are above/below the nearest line interval.
    float fromLine = frac(i.height * _NumberOfLines + 0.5f) - 0.5f;

    // Divide by our rate of change to get our pixel distance from the line.
    float pixelsFromLine = abs(fromLine) / length(rateOfChange);

    // Instead of a bunch of ifs and colour parameters,
    // I just painted the colour bands into a texture to sample.
    fixed4 col = tex2D(_MainTex, float2(i.height, 0));

    // Blend between our colour and the line, based on thickness.
    col = lerp(_OutlineColor, col, saturate((pixelsFromLine - _Thickness * 0.5f) * 0.3f));

    return col;
}

```

This isn't 100% free of artifacts - it's still using just local information from the current shading quad, which can be misleading. And it's limited by the resolution of your height data - whether that's per-vertex or calculated per-fragment. (In the example above, I'm calculating height per-vertex, so you can see the line warble a little where the vertex resolution is too low to capture the subtlety of the curve) But it handles the bulk of cases quite well for just a few lines of code.

---
Tags: unity, shaders, fragment-shader, mesh, vertex-shader
---


# Question
Title: Avoiding Incredibuild error when building
Apparently the UE4 Installed Build script function is trying to use Incredibuild, but halting with an error.

I believe this is due to my Agent Services not running, due to the fact that I have none.

I don't have a license, and so I can't use Incredibuild.

How can I modify the scripts to not use Incredibuild? I downloaded FastBuild, and want to give that a try. I just need help in knowing which scripts to modify.

# Answer
To prevent Incredibuild being used... For certain, AllowXGE needs to be set to false, in ...\UnrealEngine-4.22\Engine\Source\Programs\AutomationTool\BuildGraph\Tasks\CompileTask.cs

I also set bAllowXGE to false (public bool bAllowXGE = false;), in ...\UnrealEngine-4.22\Engine\Source\Programs\UnrealBuildTool\Configuration\BuildConfiguration.cs, but I am not sure if this was necessary.

I am not sure if setting AllowParallelExecutor = false is necessary, as recommended by this answer, since I forgot to set that in CompileTask.cs, and the build went through, anyway.

I get errors with FASTBuild but I will play around with this at some later time, while building projects.
> 1 votes

---
Tags: unreal-4, build-process
---


# Question
Title: What does 'AlwaysResetOnEntry' do, and where would it be used?
---

In Unreal Animation Blueprints, each state has an option for `AlwaysResetOnEntry`.

The tooltip text for this is:

`Whether or not this state will ALWAYS reset its state on reentry, regardless of remaining weight`

---

**Question**

What does this do, exactly?

Additionally, what is a good example of where this would be used?

# Answer
I got this reply from someone outside of Stack exchange, so I'll post it here to help others

---

Searched the code for bAlwaysResetOnEntry, looks like its used for animation state machines.

Implies its possible to re-enter a state while it is still the active state, and the reset flag would cause the state to re-trigger, possibly re-calling the OnStateEntered events. Untitled

```
if ((!bAlreadyActive || bForceReset) && !IsAConduitState(NewStateIndex))
        {
            // Initialize the new state since it's not part of an active transition (and thus not still initialized)
            FAnimationInitializeContext InitContext(Context.AnimInstanceProxy);
            StatePoseLinks[NewStateIndex].Initialize(InitContext);
            // Also call cache bones if needed
            // Note dont call CacheBones here if we are in the process of whole-graph initialization as a 'never updated' counter
            // will not perform its 'minimal update guard' duty and every call will end up getting though, performing duplicate work
            // over Save/UseCachedPose boundaries etc.
            // This is OK because CacheBones is actually called before updating the graph anyway after whole-graph initialization
            if(Context.AnimInstanceProxy->GetCachedBonesCounter().HasEverBeenUpdated())
            {
                ConditionallyCacheBonesForState(NewStateIndex, Context);
            }
        }

```

bForceReset is assigned bAlwaysResetOnEntry earlier.
> 0 votes

---
Tags: 3d, animation, unreal-4, animation-states, animation-controller
---


# Question
Title: Unity Springjoint2d - how to put collider between anchors?
I want gameobjects to bounce off a line between 2 springjoint points. I placed boxcollider2d (with small Y scale) or edgecollider2d between two Joint points **and every frame put it in right place, set different x scale, and set different rotation**, but it doesn't work - other objects don't bounce on collision, they go through collider instead. I know that unity collisions work properly when objects move because of velocity instead of changing position every frame. Attaching collider to any of two objects connected by joint won't do what i want. Any ideas how to solve it?

# Answer
Solution \[very simple\]\[after hours\]: I added rigidbody2d to boxcollider object and set mass for highest possible, it turned out that when object is many times heavier than other, then other will be pushed out of it much harder, and collisions look normal (tested on slowly moving object, but works), there is no going through collider like when the mass is lower.

---

To make interaction between object colliding with mentioned boxcollider and objects connected with springjoint i wrote a script. (Useful when making spring joints bridge (that I m doing and didnt mention) and it should interact with heavy things driving through the bridge, change its shape depending on on which place of bridge the heavy thing is) Finally good effect Special thanks to DMGregory, the only person to comment till now!
> 0 votes

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


# Question
Title: Find new position of rotated by 10 degrees line
I have a line that goes to x (x1) of 300, and then I rotate the line by -10 degrees. How can I get the new x (x0) of the rotated line?

Here's a picture to show what I mean:

Are there any books that would help me learn this stuff?

# Answer
> 6 votes
You should learn trigonometry on Khan Academy. We didn't yet learn it in the school, but I believe it has to do something with sines and cosines and tangents. The basic idea is that when you do a thing like that, you get a right triangle, where the hypotenuse is the line from your standpoint to x1. If you do sin(a), you would get the length of your desired line divided by the hypotenuse, I'm not sure I never really got into this and no one thought me, so this might be false. Check on the internet (although it's obvious that you get a right triangle and need to use trigonometry).

# Answer
> 5 votes
you can easily use a rotation matrix of -10deg to find your answer. check wikipage to learn how to create a rotation matrix. after that you only need to multiply rotation matrix into (300,0).

If I'm not mistaken for your problem you also need height of rectangle to find intersection point;

here is a sudo code that computes x1 for you:

```
x0 = 0;
y0 = rectHeight;
teta = 10 * pi / 180;

x1 = cos(teta) * x0 - sin(teta) * y0;
y1 = sin(teta) * x0 + cos(teta) * y0;

ratio = rectHeight / y1;

x1 = x1 * ratio;
y1 = y1 * ratio;

result = 300 + x1;

```

# Answer
> 0 votes
If it is not on the line (which means the new line is not longer, just rotated), the x position is Length * sin (angle) and the y position is Length * cos(angle).

```
300 * sin (-10) = 52.09...
300 * cos (-10) = 295.44...

```

You must yourself switch the 52 to -52 as the sinus function doesn't do that.

So the answer should be (-52 , 295).

# Answer
> 0 votes
Here's my javascript solution. I needed to set limits on the amount of rotation allowed. HTH.

```
static findRotationPoint(startPoint: PointXY, endPoint: PointXY, degreeRotation: number, slope: number, reverse: boolean): PointXY {
    const distance: number = getDistanceBetweenPoints(startPoint, endPoint);
    const degrees: number = convertSlopeToDegrees(slope);
    const theta = (degreeRotation + degrees) * Math.PI / 180;

    if (reverse) {
        return new PointXY((Math.cos(theta) * distance) + startPoint.x, (Math.sin(theta) * distance) + startPoint.y);
    } else {
        return new PointXY((Math.cos(theta) * -distance) + startPoint.x, (Math.sin(theta) * -distance) + startPoint.y);
    }
}

static getDistanceBetweenPoints(pointA: PointXY, pointB: PointXY): number {
    return Math.sqrt(Math.pow((pointA.x - pointB.x), 2) + Math.pow((pointA.y - pointB.y), 2));
}

static convertSlopeToDegrees(slope: number): number {
    if (slope === Infinity || slope === -Infinity) {
        return 90;
    } else if (slope === 0 || slope === -0) {
        return 0;
    } else {
        return 360 * Math.atan(slope) / (2 * Math.PI);
    }
}

```

---
Tags: 2d, mathematics, graphics
---


# Question
Title: Using EntityManager from inside a system
I am using Entities v0.8

I am trying to build a Spawner, and this is the system

```
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;

public class ChunkSpawnerSystem : SystemBase
{
    protected override void OnUpdate()
    {
        Entities.ForEach((ref ChunkSpawnerComponent spawner) =>
        {
            if (!spawner.needsRender) return;

            EntityArchetype chunkArchetype = EntityManager.CreateArchetype(new ComponentType[] { typeof(Translation) });

            for (int id = 0; id < spawner.size; id++)
            {
                Debug.Log("Rendering chunk " + id);
                Entity entity = EntityManager.CreateEntity(chunkArchetype);
                EntityManager.SetName(entity, "Chunk " + id);
            }

            spawner.needsRender = false;

        }).Schedule();

    }
}

```

But I get the following error

> ChunkSpawnerSystem.cs(9,9): error DC0002: Entities.ForEach Lambda expression invokes 'get\_EntityManager' on a ChunkSpawnerSystem which is a reference type. This is only allowed with .WithoutBurst() and .Run().

Apparently I cannot seem to be able to use EntityManager inside the lambda function. Why is this?

# Answer
Check out this example of a system which has entities spawning more entities from Unity Technologies.

This comment explains the problem:

> Systems can schedule work to run on worker threads. However, creating and removing Entities can only be done on the main thread to prevent race conditions.

In other words, the EntityManager isn't thread-safe. So you can not safely use it from code which might run in parallel with other code. The same example also provides a solution to this problem:

> The system uses an EntityCommandBuffer to defer tasks that can't be done inside the Job.

So what you need to do in your system is to obtain a reference to the CommandBufferSystem. You can do this in `OnCreate` with

```
commandBufferSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();

```

in the OnUpdate-method of your system, you then need to

1. Obtain a commandBuffer from the CommandBufferSystem using `var commandBuffer = commandBufferSystem.CreateCommandBuffer().ToConcurrent();`
2. Write the ForEach lambda function to attach commands to the commandBuffer using `commandBuffer.Instantiate`, `commandBuffer.SetComponent` etc.
3. Schedule the ForEach job
4. Schedule the execution of the command buffer with `commandBufferSystem.AddJobHandleForProducer(Dependency);`
> 1 votes

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


# Question
Title: How to make a brightness-inverting shader?
I have a stone texture that looks great, except for one thing: it's very dark and I want white stone.

I don't want to mess with the texture, because it's used for other things in the same project. What I'd like to do is invert the brightness in a shader. Specifically, I want a custom shader that does everything exactly the same way as the Standard PBR shader, except that it inverts brightness.

By "inverting brightness", I mean:

* take albedo.RGB, convert to HSV
* V of HSV = 1 - V
* Convert back to RGB

I tried making a trivial custom shader that does exactly this, but it has two problems:

1. The result is completely flat, because the custom shader template didn't include the normal map and the height map.
2. The brightness didn't actually get inverted!

Not sure what's going on with point #2, but when I tried adding the additional textures to the custom shader, I discovered that the `SurfaceOutputStandard` struct doesn't have a field for outputting height map data to!

Does anyone know how to make this work? Here's what I've got so far:

```
Shader "Custom/Bright Stone"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _NormalTex ("Normal Map", 2D) = "white" {}
        _HeightTex("Height Map", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _NormalTex;
        sampler2D _HeightTex;

        struct Input
        {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
        // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
        // #pragma instancing_options assumeuniformscaling
        UNITY_INSTANCING_BUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

            float3 rgb_to_hsv_no_clip(float3 RGB)
        {
            float3 HSV;

            float minChannel, maxChannel;
            if (RGB.x > RGB.y) {
                maxChannel = RGB.x;
                minChannel = RGB.y;
            }
            else {
                maxChannel = RGB.y;
                minChannel = RGB.x;
            }

            if (RGB.z > maxChannel) maxChannel = RGB.z;
            if (RGB.z < minChannel) minChannel = RGB.z;

            HSV.xy = 0;
            HSV.z = maxChannel;
            float delta = maxChannel - minChannel;             //Delta RGB value
            if (delta != 0) {                    // If gray, leave H  S at zero
                HSV.y = delta / HSV.z;
                float3 delRGB;
                delRGB = (HSV.zzz - RGB + 3 * delta) / (6.0*delta);
                if (RGB.x == HSV.z) HSV.x = delRGB.z - delRGB.y;
                else if (RGB.y == HSV.z) HSV.x = (1.0 / 3.0) + delRGB.x - delRGB.z;
                else if (RGB.z == HSV.z) HSV.x = (2.0 / 3.0) + delRGB.y - delRGB.x;
            }
            return (HSV);
        }

        float3 hsv_to_rgb(float3 HSV)
        {
            float3 RGB = HSV.z;

            float var_h = HSV.x * 6;
            float var_i = floor(var_h);   // Or ... var_i = floor( var_h )
            float var_1 = HSV.z * (1.0 - HSV.y);
            float var_2 = HSV.z * (1.0 - HSV.y * (var_h - var_i));
            float var_3 = HSV.z * (1.0 - HSV.y * (1 - (var_h - var_i)));
            if (var_i == 0) { RGB = float3(HSV.z, var_3, var_1); }
            else if (var_i == 1) { RGB = float3(var_2, HSV.z, var_1); }
            else if (var_i == 2) { RGB = float3(var_1, HSV.z, var_3); }
            else if (var_i == 3) { RGB = float3(var_1, var_2, HSV.z); }
            else if (var_i == 4) { RGB = float3(var_3, var_1, HSV.z); }
            else { RGB = float3(HSV.z, var_1, var_2); }

            return (RGB);
        }

        float3 InvertBrightness(float3 albedo)
        {
            float3 hsv = rgb_to_hsv_no_clip(albedo);
            hsv.z = 1.0 - hsv.z;
            return hsv_to_rgb(hsv);
        }

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = InvertBrightness(c.rgb);
            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
            o.Normal = tex2D(_NormalTex, IN.uv_MainTex);
            // o.Height = tex2D(_HeightTex, IN.uv_MainTex);
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

If I'm going about this completely wrong and there's a better way to do it, feel free to point that out as well.

# Answer
> 1 votes
I think the conversion to HSL and back is wasteful if you have no intention of modifying H or S, only the L. ;) So instead I've used a simpler trick below to keep the chromaticity while flipping dark to light and vice versa.

I've used a simple & cheap parallax offset that's built into Unity to make use of the heightmap. You can also implement parallax occlusion mapping instead for a stronger sense of depth, at correspondingly greater expense.

```
Shader "Custom/LightnessInverter"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
        _BumpMap("Normal Map", 2D) = "bump" {}
        [MaterialToggle] _Invert("Invert Brightness", Float) = 0
        _ParallaxMap("Height Map", 2D) = "white" {}
        _Parallax("Height Scale", float) = 0.05
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _BumpMap;
        sampler2D _ParallaxMap;

        struct Input
        {
            float2 uv_MainTex;
            float3 viewDir;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        float _Invert;
        float _Parallax;

        // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
        // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
        // #pragma instancing_options assumeuniformscaling
        UNITY_INSTANCING_BUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            // Albedo comes from a texture tinted by color
            IN.uv_MainTex += ParallaxOffset(tex2D(_ParallaxMap, IN.uv_MainTex).r, _Parallax, IN.viewDir);
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex);

            if (_Invert > 0.0f) {
                float brightest = max(c.r, max(c.g, c.b));
                if (brightest < 0.0001f) {
                    c.rgb = 1.0f;
                }
                else {
                    float3 peakVersion = c.rgb / brightest;
                    c.rgb = (1.0f - brightest) * peakVersion;
                }
            }

            c *= _Color;
            o.Albedo = c.rgb;

            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;

            o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_MainTex));
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

---
Tags: unity, shaders
---


# Question
Title: 3D modeling: how to make a spaceship with interior and exterior
recently i wanted to try and model a spaceship. i want to make one with interior and exterior. (like spaceships in star citizen.) But i dont know how to start working on it. Do i first build the interior and thzn build the exterior around it ? or reversed ? also how does one design interior if there is already an exterior. my goal is to maybe implement this in a game engine so i can walk around inside of it. i tried looking for this on google but i only got results that show how to make a spaceship but withoud interior. or interiors alone. does someone know how to make this ? or does someone have a tutorial i can use to learn from ? thanks in advanced.

# Answer
> 1 votes
When you have two elements of any sort that rely on each other to make sense, whether they be interior and exterior of a spaceship, or the design of two opposing asymmetric factions, a standard way to do it is to build both things in parallel.

For a spaceship, that could be: block out the basic forms of a cool exterior in half an hour or something, then make space for the rooms inside. Notice that you forgot a restroom or a cargo compartment, add those, and reshape the exterior to match. See that the exterior doesn't look as cool any more, and adjust it. Then go back to the interior and squeeze things in. Go back and forth a few times, and then when you're satisfied with the layouts you can polish them each up with a lot of details. When you get more practice with how adjusting the exterior affects the interior, you won't need to go back and forth so many times to get something you're happy with.

Remember to make your interior and exterior meshes separate so you can render just the exterior for ships you're not in, and avoid wasting GPU time.

# Answer
> 1 votes
Often the interior and exterior will be separate models.

Splitting them this way improves rendering efficiency in our common use cases:

* If you're inside the sleeping quarters, you generally don't need to render the exterior - it's all occluded anyway.
* And vice versa: from the outside, you can't see the quarters. A low-fidelity model or shader trick might stand-in for glimpses of the interior you can see through the windows.

This also allows us to "Tardis" the ship - making the interior bigger or different in shape than the exterior. This is a common trick used in games to make the insides of buildings spacious and intricate, while making the outside easy to navigate by compressing the distance you have to travel to get around the building, or from one building to the next.

If you're new to modelling complex game assets and environments, this might be a good way to go: you can start modelling either the interior or the exterior, and switch back and forth between them as your work on one gives you ideas for what to do next in the other. The two don't have to match perfectly, just close enough that the player deems it plausible that they're the same structure, which gives you a lot of wiggle room to change your mind or make mistakes along the way.

The main spot they need to match up is wherever the player gets in & out of the ship. If that happens invisibly in your game (eg. via a teleporter, camera cut, or loading screen), you can avoid dealing with it at all.

If not, then you can create an airlock that fits both the interior and exterior, and ensure that at some point in its operation, the player's view of the opposite side is obscured, giving you an opportunity to swap their surroundings for the other version of the mesh.

If you need your interior and exterior to match perfectly - if Tardising it would be noticeable to the player, or just antithetical to your design direction - then I'd suggest not starting in modelling software at all. Start on paper, drafting a blueprint for your ship and its various requirements. Once you have a solid plan in place, then you can start modelling any part of it you choose.

---
Tags: 3d-modeling
---


# Question
Title: How to get button component in Unity 2019.3
I have a simple class attached to a button in Unity Canvas:

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

public class AudioButtonPlay : MonoBehaviour
{
    public Button button;
    void Start()
    {
        button =  gameObject.GetComponent<Button>();
    }
}

```

But on the line `button = gameObject.GetComponent<Button>();` I get the following message:

```
GetComponent requires that the requested component 'Button' derives from MonoBehaviour or Component or is an interface

```

How can I access the "Button" component?

# Answer
**You're using the wrong namespace.**

Instead of

```
using UnityEngine.UIElements;

```

do

```
using UnityEngine.UI;

```

Everything else should already work when you change that.
> 3 votes

---
Tags: unity
---


# Question
Title: Finding cells between two points (along line) to finding obstacles
My game is in 3D environment partitioned with 2D grids in 2 dimensioned array

So I can get any cell/node by passing row and col like `return _nodes[r][c]`.

When the an attacker attacks an enemy with ranged weapon, I want to check if there is any obstacle in between the two points.

Without using mesh collision methods, I want to achieve it by checking all the cells which falls between the source and target points and check if there are any obstacles.

I want to write this in a routine which will return false as soon as it finds an obstacle and returns true if it finds no obstacle in any of the cells between the source and target

From the above picture, I want to get yellow that falls between the two end points

Can some one suggest me the approach?

# Answer
> 7 votes
One of the popular ways to do this, as Doorknob says in their comment, is Bresenham's line algorithm. The example image of which looks nearly identical to you requirement example:

It's commonly used to draw lines on the computer screen deciding which pixels to use to represent that line. In your case, you'll use it to decide which grid spaces to check.

Essentially, you start at the fire location and step through the line generated by connecting the fire location and hit location. For each square the line enters, you check for obstacles.

The wikipedia page linked above has some pseudo code examples, and it should be simple to find examples in your language of choice.

You should also check this similar question.

# Answer
> 1 votes
I implemented the pseudocode from wikipedia for Bresenham's algorithm and got a result like this:

```
   0  1  2  3  4  5  6  7  8  9  10
0   0  0  .  .  .  .  .  .  .  .  .
1   .  .  0  .  .  .  .  .  .  .  .
2   .  .  .  0  .  .  .  .  .  .  .
3   .  .  .  .  0  .  .  .  .  .  .
4   .  .  .  .  .  0  .  .  .  .  .
5   .  .  .  .  .  .  .  .  .  .  0
6   .  .  .  .  .  .  .  .  .  .  .
7   .  .  .  .  .  .  .  .  .  .  .
8   .  .  .  .  .  .  .  .  .  .  .
9   .  .  .  .  .  .  .  .  .  .  .
10  .  .  .  .  .  .  .  .  .  .  .

```

As you can see the algorithm falls apart when `dy > dx`. It also is not tracing the line very well from (0,0) to (5,10). I implemented my own algorithm that plugs values into `y=mx+b`,rounds the result and uses that to modify the grid.

Python 2.7 code:

```
def get_grid_cells_btw2(p1,p2):
  x1,y1 = p1
  x2,y2 = p2
  dx = x2-x1
  dy = y2-y1

  if dx == 0: # will divide by dx later, this will cause err. Catch this case up here
    step = int(copysign(1,dy))
    pts =[]
    for y in range(0,dy,step):
      pts.append((x1,y))
    return pts

  m = dy/(dx+0.0)
  b = y1 - m * x1

  points = {}
  step = 1.0/(max(abs(dx),abs(dy)))
  steps = [x * step for x in range(int(x1 / step), int(x2/step + copysign(1,x2)), int(copysign(1,dx)))]
  for x in steps:
    y = m * x + b
    pt = (int(round(x)),int(round(y)))
    points["%d,%x"%pt] = pt #catch duplicates

  return points.values()

```

And a much simpler+faster version using Numpy

```
#function COPIED from stack overflow - https://stackoverflow.com/questions/31097247/remove-duplicate-rows-of-a-numpy-array
def remove_np_duplicates(data):
  # Perform lex sort and get sorted data
  sorted_idx = np.lexsort(data.T)
  sorted_data =  data[sorted_idx,:]

  # Get unique row mask
  row_mask = np.append([True],np.any(np.diff(sorted_data,axis=0),1))

  # Get unique rows
  out = sorted_data[row_mask]
  return out

def get_grid_cells_btw(p1,p2):
  x1,y1 = p1
  x2,y2 = p2
  dx = x2-x1
  dy = y2-y1

  if dx == 0: # will divide by dx later, this will cause err. Catch this case up here
    step = np.sign(dy)
    ys = np.arange(0,dy+step,step)
    xs = np.repeat(x1, ys.shape[0])
  else:
    m = dy/(dx+0.0)
    b = y1 - m * x1

    step = 1.0/(max(abs(dx),abs(dy)))
    xs = np.arange(x1, x2, step * np.sign(x2-x1))
    ys = xs * m + b

  xs = np.rint(xs)
  ys = np.rint(ys)
  pts = np.column_stack((xs,ys))
  pts = remove_np_duplicates(pts)

  return pts.astype(int)

```

And run it with

```
    from pandas import *
    cells = get_grid_cells_btw2((0,0),(5,10))
    grid = [['.' for row in range(11)] for col in range(11)]
    for pt in cells:
      x,y=pt
      grid[x][y] = '0'
    print(DataFrame(grid))

```

We get

```
   0  1  2  3  4  5  6  7  8  9  10
0   0  0  .  .  .  .  .  .  .  .  .
1   .  0  0  0  .  .  .  .  .  .  .
2   .  .  .  0  0  0  .  .  .  .  .
3   .  .  .  .  .  0  0  0  .  .  .
4   .  .  .  .  .  .  .  0  0  0  .
5   .  .  .  .  .  .  .  .  .  0  0
6   .  .  .  .  .  .  .  .  .  .  .
7   .  .  .  .  .  .  .  .  .  .  .
8   .  .  .  .  .  .  .  .  .  .  .
9   .  .  .  .  .  .  .  .  .  .  .
10  .  .  .  .  .  .  .  .  .  .  .

```

to (2,10)

```
   0  1  2  3  4  5  6  7  8  9  10
0   0  0  0  .  .  .  .  .  .  .  .
1   .  .  .  0  0  0  0  0  .  .  .
2   .  .  .  .  .  .  .  .  0  0  0
3   .  .  .  .  .  .  .  .  .  .  .
4   .  .  .  .  .  .  .  .  .  .  .
5   .  .  .  .  .  .  .  .  .  .  .
6   .  .  .  .  .  .  .  .  .  .  .
7   .  .  .  .  .  .  .  .  .  .  .
8   .  .  .  .  .  .  .  .  .  .  .
9   .  .  .  .  .  .  .  .  .  .  .
10  .  .  .  .  .  .  .  .  .  .  .

```

to (10,6)

```
   0  1  2  3  4  5  6  7  8  9  10
0   0  .  .  .  .  .  .  .  .  .  .
1   0  0  .  .  .  .  .  .  .  .  .
2   .  0  .  .  .  .  .  .  .  .  .
3   .  .  0  .  .  .  .  .  .  .  .
4   .  .  0  0  .  .  .  .  .  .  .
5   .  .  .  0  .  .  .  .  .  .  .
6   .  .  .  0  0  .  .  .  .  .  .
7   .  .  .  .  0  .  .  .  .  .  .
8   .  .  .  .  .  0  .  .  .  .  .
9   .  .  .  .  .  0  0  .  .  .  .
10  .  .  .  .  .  .  0  .  .  .  .

```

to (10,10)

```
   0  1  2  3  4  5  6  7  8  9  10
0   0  .  .  .  .  .  .  .  .  .  .
1   .  0  .  .  .  .  .  .  .  .  .
2   .  .  0  .  .  .  .  .  .  .  .
3   .  .  .  0  .  .  .  .  .  .  .
4   .  .  .  .  0  .  .  .  .  .  .
5   .  .  .  .  .  0  .  .  .  .  .
6   .  .  .  .  .  .  0  .  .  .  .
7   .  .  .  .  .  .  .  0  .  .  .
8   .  .  .  .  .  .  .  .  0  .  .
9   .  .  .  .  .  .  .  .  .  0  .
10  .  .  .  .  .  .  .  .  .  .  0

```

# Answer
> 0 votes
I tried the code and it seems working but I found some issues. For Example:
`[[97, 281], [96, 276]]` I received only
`[[96, 280]]`.
Decided to debug, but found Bresenham’s line drawing algorithm, which has python package. The code looks like this:

```
from bresenham import bresenham

cells = list(bresenham(96, 280, 95, 275))
print(cells)

```

I received `[(96, 280), (96, 279), (96, 278), (95, 277), (95, 276), (95, 275)]`

---
Tags: grid, line-of-sight
---


# Question
Title: Why is "collision" event needed when there is a "trigger" event?
The "trigger" event in unity is very flexible: it can be set to fire on both dynamic and kinematic bodies, as long as one of them has a collider with the "trigger" flag. On the other hand, the "collision" event is limited to only dymanic bodies.

My question is: why do we need "collision" events at all - why not just always use "trigger" events?

\[In other words: why does Unity include these two kinds of events and not just the "trigger"?\]

# Answer
The collision event represents a physics overlap that causes a **collision resolution**, altering the behaviour of one or both objects involved to make them bounce apart rather than pass through one another.

Collision resolution can only happen when one of the bodies involved is a dynamic Rigidbody. So this isn't a limitation of the collision event, this is simply the only time it's relevant or meaningful.

A static collider never moves, and a kinematic body overrides any collision resolution, so collisions between these colliders with no dynamic body involved don't produce any change in physics behaviour, and don't need to be processed by the collision resolution system that fires collision events.

Resolving a collision with a dynamic body requires additional information (and additional processing to generate it) that's not required for the simple overlap check of trigger events. This includes things like the contact points and normals making up the collision manifold, the physics materials of those contacting surfaces, the penetration/separation vector, the masses and momenta of each object, and the corresponding impulses to apply to each body to push them back apart.

The physics engine then exposes this information through the collision event in case user code needs to make use of it: say for spawning a dust cloud at each point of contact, or playing a sound based on the material at the hit location, or inflicting damage proportional to the resolution impulse, or altering the physics behaviour in response to the collision to simulate non-Newtonian objects, etc.

All this extra processing and data to pass makes the collision event a different beast than the trigger event, not just the same thing with a different name.

The separation also lets us distinguish between, say, a player entering the awareness trigger zone around an enemy, when we want to start its chase behaviour, versus the enemy colliding with the player, when we want to inflict damage. If both these applications used the same trigger message channel, we'd need to separate our scripts onto multiple objects to disambiguate which one happened.
> 11 votes

# Answer
Imagine you want a dent in a car or want to collide two cars into eachother. How will you determine impact/hit force ? Trigger doesn't return these functionalities
> 3 votes

# Answer
Perhaps you would like something akin to portal:

The cubes you can pick up have collision responses to everything to play scraping noises etc.

However the cubes only disappear when they pass through the blue light wall trigger volumes.
> 2 votes

---
Tags: unity, collision-detection
---


# Question
Title: How can I roll up a plane with a vertex shader?
I have **plane** that I want to roll up using a vertex shader, like this:

I found a math demo that shows the kind of curve I want my mesh to follow. I tried implementing this in my shader code, but the results don't form a roll as expected:

```
Shader " Custom/Rolling "
{
Properties
{
_MainTex ("Base (RGB)", 2D) = "white" {}
_Bend("Bend",Float) = 1
_Strength("Strength",Float) = 1
}

SubShader
{
Tags {"Queue"="Geometry" "IgnoreProjector"="true" "RenderType"="Opaque"}
Cull Off

Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

struct v2f
{
half2 texcoord  : TEXCOORD0;
float4 vertex   : SV_POSITION;
};

sampler2D _MainTex;
float _Bend;
float _Strength;

v2f vert(appdata_full v)
{
v2f o;

//I don't know what should I write here for rolling ,please help me.
//v.vertex.y *= ???
v.vertex.y *= exp(_Bend+(v.vertex.x*_Strength)); // something like this but this hasn't twist effect
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = v.texcoord;
return o;
}

float4 frag (v2f i) : COLOR
{

float2 uv = i.texcoord.xy;
float4 tex = tex2D(_MainTex, uv);

return tex;
}
ENDCG
}
}
Fallback Off
}

```

Instead of a neat roll, the end of my plane shoots up into the sky!

# Answer
Here I'm going to assume your geometry is set up like so:

* It's a ribbon of quads extending from z = 0 to z = end
* The z = 0 line will be the outer lip of the roll, and z = end will be the part tucked deepest inside the spiral
* Each quad in the ribbon will span an equal angle when coiled in the roll (but not an equal length of ribbon: the quads in the tightest part of the roll will be smaller) - this gets us a consistent resolution for drawing our curves, and we'll correct for the texture stretching in the shader
* The ribbon is 1 unit wide along the x axis
* The UVs are set up with u/x running across the ribbon, and v/y pointing down the ribbon
* The origin of your object represents the point where the roll should contact the floor
* The roll will be centered somewhere above this point (depending on how many windings are left on it), and the unwound portion will extend in the local -z direction.

We can draw this with a shader like so, using the formula for arc length along an archimedean spiral that I explain in this answer:

```
Shader "Custom/Roll"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
        _StartAngle("Start Angle (Radians)", float) = 60.0
        _AnglePerUnit("Radians per Unit", float) = 0.2
        _Pitch("Pitch", float) = 0.02
        _UnrolledAngle("Unrolled Angle", float) = 1.5
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        Cull Off

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows vertex:vert

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input
        {
            float2 uv_MainTex;
            float3 viewDir;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        float _StartAngle;
        float _AnglePerUnit;
        float _Pitch;
        float _UnrolledAngle;

        // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
        // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
        // #pragma instancing_options assumeuniformscaling
        UNITY_INSTANCING_BUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

        float arcLengthToAngle(float angle) {
            float radical = sqrt(angle * angle + 1.0f);
            return _Pitch * 0.5f * (angle * radical + log(angle + radical));
        }

        void vert(inout appdata_full v) {
            float fromStart = v.vertex.z * _AnglePerUnit;

            float fromOrigin = _StartAngle - fromStart;
            float lengthToHere = arcLengthToAngle(fromOrigin);
            float lengthToStart = arcLengthToAngle(_StartAngle);

            v.texcoord.y = lengthToStart - lengthToHere;

            if (fromStart < _UnrolledAngle) {
                float lengthToSplit = arcLengthToAngle(_StartAngle - _UnrolledAngle);
                v.vertex.z = lengthToSplit - lengthToHere;
                v.vertex.y = 0.0f;
                v.normal = float3(0, 1, 0);
            }
            else {
                float radiusAtSplit = _Pitch * (_StartAngle - _UnrolledAngle);
                float radius = _Pitch * fromOrigin;

                float shifted = fromStart - _UnrolledAngle;

                v.vertex.y = radiusAtSplit - cos(shifted) * radius;
                v.vertex.z = sin(shifted) * radius;

                v.normal = float3(0, cos(shifted), -sin(shifted));
            }
        }

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;

            o.Normal *= sign(dot(IN.viewDir, o.Normal));
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

Note that the arc length to the start and arc length to the split/unwinding point are constant for all vertices in a frame, so for efficiency you can pre-compute these in a script and pass them in as uniforms instead.

Here's an example of it working on a single 10x10 Unity plane. Obviously, to have a longer ribbon/tighter spool, you'll need more triangles to represent it smoothly like in the example above. You can get that by assembling multiple planes, or generating your own mesh exactly to your specifications with the Mesh class. If you go this route, you can even bake-in the `arcLengthToHere` as a texture coordinate, to eliminate more transcendental math from the vertex shader. :)
> 5 votes

---
Tags: unity, shaders, hlsl, shaderlab, vertex-shader
---


# Question
Title: How to add lighting to a 2D Tile-based game in JavaFX?
I'm making a 2D roguelike tile-based game with Java and JavaFX. I'm currently working on adding lighting and darkness to the dungeon, but whenever I try running it, it takes a very long time to load, and it eventually gives an out of memory error.

Here is Lighting.java:

```
package sample;

import static sample.World.worlds;

public class Lighting {
    public static void calculateLighting(int wn, int skyLighting) {
        Block[][][] world = worlds[wn];
        for (int z = 0; z < worlds[Player.cw][0][0].length; z++) {
            for (int y = 0; y < worlds[Player.cw][0].length; y++) {
                for (int x = 0; x < worlds[Player.cw].length; x++) {
                    Block b = world[x][y][z];
                    b.light = skyLighting;
                    if (b.embID == 1) { //test if a block has a torch attached to it
                        for (int distance = 0; distance <= 15; distance++) {
                            for (int x1 = x - distance; x1 < x + distance; x1++) {
                                for (int y1 = y - distance; y1 < y + distance; y1++) {
                                    for (int z1 = 0; z1 < worlds[Player.cw][0][0].length; z1++) {
                                        try {
                                            world[x1][y1][z1].light += 1;
                                        } catch (ArrayIndexOutOfBoundsException ignored) {

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        for (int z = 0; z < worlds[Player.cw][0][0].length; z++) {
            for (int y = 0; y < worlds[Player.cw][0].length; y++) {
                for (int x = 0; x < worlds[Player.cw].length; x++) {
                    Block b = world[x][y][z];
                    if (b.light > 15) {
                        b.light = 15;

                        //If your number X falls between A and B, and you would like Y to fall between C and D, you can apply the following linear transform:
                        //Y = (X-A)/(B-A) * (D-C) + C
                        //https://stackoverflow.com/questions/345187/math-mapping-numbers
                        //(worlds[Player.cw][x][y][z].light-0)/(15-0) * (1-0.5) + 0.5
                        if (b.sprite != null) {
                            b.sprite = ImgManip.darken(b.sprite, (worlds[Player.cw][x][y][z].light) / (15d) * (1 - 0.5) + 0.5);
                        }
                    }
                }
            }
        }
    }
}

```

What this is doing is that it first finds torches in the world, and then increases the brightness of each block around it, depending on how far away the torch is. Then, it takes each block's sprite and makes it darker with the `darken()` method. This is what is causing it to take so long. When I just comment that out, it performs just fine, but the lighting isn't there.

Here is the `darken()` method:

public static Image darken(Image image, double amount) {
        PixelReader pixelReader = image.getPixelReader();
        WritableImage writableImage =
                new WritableImage(
                        (int)image.getWidth(),
                        (int)image.getHeight());
        PixelWriter pixelWriter = writableImage.getPixelWriter();

        for(int y=0; y<image.getHeight(); y++){
            for(int x=0; x<image.getWidth(); x++){
                Color color = pixelReader.getColor(x, y);

                color = color.deriveColor(0,-amount/2d,-amount,0);

                pixelWriter.setColor(x, y, color);
            }
        }
        return writableImage;
    }
```

# Answer
first of all, if you want to apply effects like lighting to your scene/canvas then `PixelWriter` is a terrible idea, because of the unevitable O(n^2) created by the nested loop for traversing every pixel. This loop will perform on your CPU since it is located in your Java code and thus performs slow.
This is the reason why "shaders" exists. To perform heavy weight graphical operations on your GPU, which is optimized for transforming pixels. Though shaders are not directly accessible from JavaFX.

The closest thing you have in JavaFX are `Effect`s and blending mechanisms. For your use case you should definetly try to implement your lighting effects with JavaFX Effects Objects or blending. I once had the same issue. Blending on a canvas improved the performance a lot. But there is only so much you can do with JavaFX. It is very limited.

If you don't want to deal with such low level problems all the time, try using FXGL. It might be lightweight framework compared to others, but it is based on JavaFX.
> 1 votes

---
Tags: java, 2d, lighting, image, javafx
---


title: Finding Endpoint of line in Unity

text:
# Question
Title: Finding Endpoint of line in Unity
I have a startpoint, magnitude(length) and direction and want to find endpoint to construct the line here is the code to make question more clear

```
private Vector2 GetEndPoint(Vector2 startPoint, Vector2 direction, float magnitude) {
    Vector2 endPoint = //some stfuff with parameters
    return endPoint;
}

```

And this is the visualization of what I want

Hope I am clear enough, any suggestions is welcomed

# Answer
This would be simply:

```
Vector2 endPoint = startPoint + direction.normalized * magnitude;

```

Though you can omit the `.normalized` if you can guarantee your input direction is a unit vector already (ie. it is exactly 1 unit in length)

You can also do this with the `Ray` type, if you find that clearer:

```
Ray ray = new Ray(startPoint, direction);
Vector2 endPoint = ray.GetPoint(magnitude);

```
> 1 votes

# Answer
This is simple vector math.

```
return startPoint + direction.normalized * magnitude;

```

If the direction is already normalized (it has a magnitude of 1.0), you can of course omit the `.normalized`.
> 1 votes

---
Tags: unity, c#, vector, geometry
---


# Question
Title: How to fix collision detection with fast moving objects in 2D?
I was making a simple Pong game and it worked fine until I tried to increase the speed of the ball. With increased speed, the ball moves across the walls occasionally. I've set no rigidbody for the walls and dynamic rigidbodies for players and the ball. Surely, all of them have colliders. I check collision with `OnTriggerEnter2D` and all colliders are triggers. How can I solve this problem besides just hard coding collisions?

# Answer
I found a solution! In order to get a proper collision detection you should use `Kinematic` body type in Rigidbody2D properties and move the ball with Rigidbody2D.MovePosition in `FixedUpdate` instead of `transform.Translate` in `Update` method.
> 1 votes

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


# Question
Title: How to add ingame tutorial for first time?
I want to know how to show tutorial when player playing for First time. Only once

# Answer
> 1 votes
You can use the class PlayerPrefs to store persistent data on the user's device.

In order to decide whether or not to play the tutorial, find out if the player already completed the tutorial with

```
if (PlayerPrefs.GetInt("Tutorial_Completed") == 1) {

```

After the player completed the tutorial, set the variable with:

```
PlayerPrefs.SetInt("Tutorial_Completed", 1);
PlayerPrefs.Save();

```

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


# Question
Title: Unity Material Override Video is too dark
I have made a TV in Blender, UV Wrapped a material and applied a video on it in Unity. But the picture is too dark, and I would like to make it brighter.

How could I solve this problem?

The left one

# Answer
> 1 votes
Click on the Material. Shader -\> Unlit -\> Texture

---
Tags: unity, blender, materials, video
---


# Question
Title: How can I tell if a Gameobject is currently touching another Gameobject with a specific tag?
I've seen similar questions to this here on Stack Exchange — Game Development, but none of the answers to them have helped my problem. I am working in Unity 2019.2.18f1 with Visual Studios 2019 Community.

What I want to know how to tell when one Gameobject (the player) is currently touching another game object with a tag name of "Block". When the player collides with a "block" I want it to set: `jumpPossible = true;` But when it leaves the block (by jumping or falling off) `jumpPossible = false;`

What I currently have in my `PlayerController` script (the important stuff anyways):

```
private void OnCollisionEnter(Collision collision) {
    if (collision.gameObject.CompareTag("Block")) {
        jumpPossible = true;
    }
}

private void OnCollisionExit(Collision collision) {
    if (collision.gameObject.CompareTag("Block")) {
        jumpPossible = false;
    }
}

```

The problem I am having is when the player is currently on a block and then touches another block. When it leaves the one of the blocks, it will set: `jumpPossible = false;` and so you can't jump.

What I want for this script to do is whenever the player is touching *any* Gameobject with a tag of "Block" it should allow it to jump.

# Answer
> 1 votes
To solve this particular problem, I would store a reference to the objects in a list, instead of setting a variable. In this case, I am using a HashSet, because it is faster than using a list, can only contain each entry once and we do not want to access the objects inside.

```
private HashSet<GameObject> touchingObjects = new HashSet<GameObject>();

public bool CanJump => touchingObjects.Count > 0;

private void OnCollisionEnter(Collision collision) {
    if (collision.gameObject.CompareTag("Block")) {
        touchingObjects.Add(collision.gameObject);
    }
}

private void OnCollisionExit(Collision collision) {
    if (collision.gameObject.CompareTag("Block")) {
        touchingObjects.Remove(collision.gameObject);
    }
}

```

Aside from that: Look into the link *DMGregory* provided. It could have better approaches to the problem that you are facing.

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


# Question
Title: How to make controlled exchanges in an online-game?
There is an online game in which you can collect things of different values: ordinary, epic, legendary. The cheapest things are ordinary, the more expensive are epic, and the most expensive are legendary.

If you have collected 10 things of the same value, then you can exchange them for one thing with a value higher. For example, if you collected 10 things of epic value, then you can exchange them for one legendary thing.

After such an exchange, the user can go into minus or plus, because 10 things with a value lower can total be worth more than one thing with a value higher or vice versa. The user can drop a thing worth 25% to 400% of the exchange value.

How can I make such exchanges controlled so that someone can get a good profit from these exchanges, someone stay at zero, and someone go minus? But the most important condition is that, as a result, the online game is in plus with exchanges.

# Answer
This looks like a job for expected value!

* Take all the epic items in your game.
* For each one, compute its value, and its probability of dropping / being acquired by the player.

This second one can be a bit tricky to calculate, depending on your game systems.

+ If you all items are equally likely, or you have one master drop table with probabilities for each item, it's easy.
    + If there are lots of different ways of getting an item, and they depend on what actions the player is choosing to pursue, then you may need to estimate it using a "typical" or "optimizing" model player, or a Monte Carlo simulation.

    If this is a game that's already live or in playtesting, you can use telemetry data from real players to see how often an item is appearing, as-played, which can often differ in subtle or dramatic ways from what we predicted on paper.

As long as you get a decent approximation of relative frequency though, this technique will still lead you to useful results, even if they're not exact to the last decimal point. ;)
* For each item, **multiply its value by its probability**, and sum up the total across all epic items.
* Divide by the probabilty of getting an epic at all.

What you've just calculated is the **expected value of one epic item**. That is, if you played for a long time and got 1000 epic items, we'd expect the total value to be about 1000 times this representative average value.

Now do the same for the legendary items that you award from the trade-in.

Subtract ten times the expected value of an epic from the expected value of a legendary. The number you have left is your **expected profit on the trade**.

* If it's positive, then even if some individual trades might lead to a loss, when iterated across many trades players would still expect to make about this much profit per trade on average.
* If it's negative, then a rational player will expect to lose on the trade, and will probably avoid using this system.

Now you can tune your values and probabilities until the expected profit is in a range that looks right for your target experience. Just keep in mind loss aversion: players feel the sting of a bad trade more intensely than the elation of a good one, so you often need to tip the scale a little extra in the player's favour for it to "feel" fair or profitable.

One other wrinkle to watch for here: if the value of the legendary you award has no connection to the value of the epics that were sacrificed, then players will notice, and they'll save up only the low-value epics to use for this trade, and spend their high-value epics elsewhere (assuming some alternative use exists, like selling it to an NPC/shop or another player). This will shift the expected value of an epic-that-gets-traded, so it will be lower than the expected value for an epic overall, increasing the expected profit for players who go this route.

You can either factor that into your calculations, and balance for both a player who trades everything and a player who picks only the duds to trade, or you can bias your legendary selection so that you preferentially choose low-value legendaries for low-value sacrifices, and vice versa, so players perceive trading high-value epics as worthwhile for the better shot at high-value legendaries.
> 1 votes

---
Tags: c#, java, mathematics, javascript, python
---


# Question
Title: Is it possible to implement Steamworks functionality in a Java game? How?
I have a basic game that I want to eventually turn into something better. The game is all Java as of right now, but I want to implement the Steamworks SDK into my game (so it can have achievements, and the Workshop, and so on). But Steamworks requires C++. Is it possible to have my full Java game implement the Steamworks SDK without rewriting it in C++? I am currently using the jMonkey Engine 3 for my game.

# Answer
> 11 votes
It's definitely possible, you would just need to create a thin layer wrapping the Steam SDK (or part of it) to java via the Java Native Interface

I'm not aware of any efforts to have an opensource library for this.

# Answer
> 7 votes
JNI is a way to go if you want full access, but the Steamworks Web API might be an easier way to go. It's basically an HTTP/HTTPS-based channel to the Steamworks functions, designed to be instantly compatible with access from Java, Python, Ruby, and really anything that isn't intrinsically C/C++.

Of course you know that the issue with JNI is that you would need to compile it seperately for each available OS, which kind of defeats the purpose of any of those languages. Getter methods can be run with basic HTTP; setters (like setting an achievement), as I understand it, require HTTPS, and a unique developer identifier; but the interface is still relatively simple.

# Answer
> 4 votes
Today there exists a ready-to-use wrapper on github:

https://github.com/code-disaster/steamworks4j

This could be what you are looking for!

# Answer
> -3 votes
Use Steam SDK and U can use Jar if they provide. check them issue and API. and after think about implementation. http://steamcommunity.com/dev/

---
Tags: java, steam
---


# Question
Title: One pixel lines flash on tile map when camera moves
I'm writing a simple game using Phaser 3.5.1. I made a 20X20 over world tile map for my hero to walk around on with the camera following the hero. I was able to implement tile based movement using tweens. This works but whenever the camera moves 1 pixel lines flash on the tile map perpendicular to the direction I move. Example uses a static map layer:

As you can see I was also getting some weird artifacts on my sprite even when the camera wasn't moving, but after reading about rounded pixels I was able to eliminate that on my sprite by setting `roundedPixels: true` in my game config, but now the sprite jitters when the lines appear. Example uses static map layer with rounded pixels:

I also experimented with static vs dynamic layers for my map. When I have a dynamic map layer without rounded pixels the result is the same as my static map layer without rounded pixels.

When I use rounded pixels on a dynamic map everything gets really jittery. Interestingly when the camera doesn't move the map shakes, and when the camera does move the sprite jitters.

Regardless of the map type or rounded pixels setting, the longer the tween's duration the worse the problem gets. In my examples I used 2 second tweens to emphasize the problem.

How do I fix this problem? In a perfect world I'd like to keep using tweens for tile based movement, keep a static map, and just update some config value. If that isn't going to work what approach should I take?

---

I'm happy to add code to my question if people think it would be helpful.

# Answer
I was able to fix the problem by setting following a point instead of following my hero sprite. **The core problem was the camera wasn't moving in round pixels.** By making that point move in round pixels the problem was solved for both static and dynamic map layers. That combined with setting the round pixels parameter for the game cleaned up the jitter, lines, and artifacts around the sprite during motion. I got the idea from an old forum post. My solution is just an extremely simplified version of lewster32's suggestion.

My initial code in the create method looked like:

```
create() {
    // Create and display the overworld map.
    this.map = this.make.tilemap({ key: "overworld" });
    this.tileset = this.map.addTilesetImage("dragTilesSmall", "tiles");
    this.activeLayer = this.map.createStaticLayer("overworld", this.tileset, 0, 0);

    // The hero of the game
    this.hero = new Hero({ scene: this, key: "playerSprites", x: 16 * 5, y: 16 * 4 });

    // Setup the camera
    this.cameras.main.startFollow(this.hero);
    this.cameras.main.setBounds(0, 0, this.activeLayer.width * this.activeLayer.scaleX, this.activeLayer.height * this.activeLayer.scaleY);

    // Setup the inputs
    this.input.keyboard.on("keydown", this.handleKey, this);
}

```

The only thing that changed in the create function was I made the camera section follow a point instead of the hero. To update the location of the point I added an update function with two lines of code.

```
// This is the new "Setup camera section"
this.cameras.main.setBounds(0, 0, this.activeLayer.width * this.activeLayer.scaleX, this.activeLayer.height * this.activeLayer.scaleY);
this.cameraDolly = new Phaser.Geom.Point(this.hero.x, this.hero.y);
this.cameras.main.startFollow(this.cameraDolly);

// This is the update function I added
update() {
    // Move the camera dolly in round pixels
    this.cameraDolly.x = Math.floor(this.hero.x);
    this.cameraDolly.y = Math.floor(this.hero.y);
}

```

To set the `roundPixels` property you just need to add it to the game config. here's what mine looks like:

```
const config = {
    parent: "GameContainer",
    width: 160,
    height: 160,
    pixelArt: true,
    roundPixels: true,
    scene: [BootScene, MainScene],
    zoom: 5
};

const game = new Phaser.Game(config);

```
> 3 votes

# Answer
For me, nothing that I've found online worked so far. But I've managed to find a solution though. The difference is that my game was fully controlled by the backend, so no physics involved on the frontend. Only a dummy change of position.

Using the solution Erik mentioned made my character move jittery which is not nice but might work for some games.

The solution that worked for me on Phaser3:

```
this.camera.startFollow(hero, true); // second parameter sets roundPixels to true on camera

```

Nothing new so far. I bet most of the answers that you found said this.

The trick is actually in the movement. There is a term called Sub-Pixel rendering. The thing is that if you move the character by fractions of pixels, you will have render issues somewhere. ( This is especially on elements that are followed by camera )

Just use Math.round(newX), Math.round(newY) when changing position for your hero.
> 1 votes

---
Tags: camera, movement, phaser
---


# Question
Title: Fix Unity Line Renderer for pointer drawing a jaggy line
I think I'm using the standard Oculus setup from the SDK using the OVRCameraRig. I've also got a LaserPointer.

But inside VR on my Rift the line looks like this.

Any idea what I'm doing wrong? It used to be straight. Now it's not. I don't know what I changed.

# Answer
> 1 votes
Found it. Somehow "monoscopic" was checked in the OVRManager

No idea how that happened. Found it by looking through git diffs. **Unchecking** it fixed it.

Of course that brings up the question, what is that setting for if it messes up the rendering? I get it means you'd no longer get stereo 3D but I'd still expect lines to render straight!??!?

---
Tags: unity, virtual-reality, oculus
---


# Question
Title: Jump when the screen is tapped, rather than when the space key is pressed
I am trying to make my character jump when the player taps the screen.

At the moment it jumps when I press space bar, but how can I change the code to make him jump when the screen is tapped?

This code works as the character then jumps up:

```
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.gravityScale *= -1;
    }
}

```

This code using touch does not work: the character just stays where he is when I click the screen on my computer.

```
public void Update()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        rb.gravityScale *= -1;
    }
}

```

# Answer
I changed the code to the following by adding a TouchPhase.Began to the if statement:

```
public void Update()
{

    if (Input.touchCount == 1)
    {
        if (Input.GetTouch(0).phase == TouchPhase.Began)
        {
            Touch touch = Input.GetTouch(0);

            rb.gravityScale *= -1;

        }
    }

}

```

Then testing it on a device using unity remote.
> 1 votes

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


# Question
Title: Drawing outlines around 2D objects OpenGL
I am trying to draw an outline around any arbitrary object using OpenGL and shaders with a different color than the original object, while also retaining compatibility with alpha values \<1. I am currently trying to get this working with just a rectangle. I tried using points to determine x, y, width, and height, but these would then fail to be transformed by view and projection matrices. Using triangles renders a regular rectangle, but I can't figure out how to create an outline around it. While I am making a 2D engine, being able to transform into 3D (ex: spinning the object on all 3 axes while retaining the outline, but not actually rendering 3D objects) is important to me.

Here is my current vertex array:

```
float vertices[8] = {
    0.5f,  0.5f,
    0.5f, -0.5f,
   -0.5f, -0.5f,
   -0.5f,  0.5f
};

```

Here is my vertex shader:

```
#version 330 core

layout (location = 0) in vec2 inPos;

uniform mat4 transform;
uniform mat4 view;
uniform mat4 projection;

uniform vec4 vsColor;
uniform float vsOutline;
uniform vec4 vsOutlineColor;

out VS_OUT {
    vec4 color;
    vec4 outlineColor;
    float outlineWidth;
} vs_out;

void main() {
    gl_Position = projection * view * transform * vec4(inPos, 0.0, 1.0);
    vs_out.color = vsColor;
    vs_out.outlineColor = vsOutlineColor;
    vs_out.outlineWidth = vsOutline;
}

```

Here is my geometry shader, which currently just acts as a passthrough:

```
#version 330 core

layout (triangles) in;
layout (triangle_strip, max_vertices = 3) out;

out vec4 fsColor;

in VS_OUT {
    vec4 color;
    vec4 outlineColor;
    float outlineWidth;
} gs_in[];

void main() {
    // Draw main triangle (passthrough)
    fsColor = gs_in[0].color;
    gl_Position = gl_in[0].gl_Position;
    EmitVertex();
    gl_Position = gl_in[1].gl_Position;
    EmitVertex();
    gl_Position = gl_in[2].gl_Position;
    EmitVertex();

    // ===UNKNOWN===
    // Outline the object (WIP)
    fsColor = gs_in[0].outlineColor;

    EndPrimitive();
}

```

Finally, here is my fragment shader:

```
#version 330 core

in vec4 fsColor;

out vec4 fragColor;

void main() {
    fragColor = fsColor;

    if (fragColor.a == 0) discard;
}

```

I am unsure if I need to do outlining in the geometry or fragment shader. I would like to have an implementation that could work with non-regular shapes (such as sprites), but that is not required at this time. However, it does have to work with other shapes such as circles and triangles.

Here is an image of the current state of my engine, with the pink rectangle needing to be outlined:

The box texture shows how objects may be transformed in the game, as well as the necessity of alpha compatibility.

**UPDATE 1**

Here is my render function:

```
void c2m::client::gl::Sprite::render() {
    // Set shader uniforms if the shader is initialized
    if (shader != nullptr) {
        if (outlineWidth > 0) {
            glStencilFunc(GL_ALWAYS, 1, 0xFF);
            glStencilMask(0xFF);
        }

        applyTransforms();
        shader->useShader();
        shader->setMat4("transform", trans);
        shader->setVec4("color", color.asVec4());
    }

    // Rebind the VAO to be able to modify its VBOs
    glBindVertexArray(vao);

    // Reset vertex data to class array
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // Bind texture
    tex->bind();

    // Draw
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

    // If the outline width is 0 return
    if (outlineWidth == 0) {
        return;
    }

    // Draw outline
    if (outlineShader != nullptr) {
        glStencilFunc(GL_NOTEQUAL, 1, 0xFF);
        glStencilMask(0x00);
        glDisable(GL_DEPTH_TEST);
        outlineShader->useShader();

        outlineShader->setVec4("color", outlineRGBA.asVec4());
        // Temporary transform matrix to prevent pollution of user-set transforms
        glm::mat4 tempTransform = trans;
        tempTransform = glm::scale(tempTransform, glm::vec3(outlineWidth + 1, outlineWidth + 1, outlineWidth + 1));
        outlineShader->setMat4("transform", tempTransform);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        glStencilMask(0xFF);
        glEnable(GL_DEPTH_TEST);
        glStencilFunc(GL_ALWAYS, 1, 0xFF);
    }
}

```

And here is the result of the function:

**UPDATE 2**

Here is my initialization and clear code:

Init:

```
// Enable various OpenGL functions
// Enable depth testing/z-indexing
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// Stencil
glEnable(GL_STENCIL_TEST);
// Disable stencil writing by default, to be enabled per draw cycle
glStencilFunc(GL_NOTEQUAL, 1, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
// Alpha
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

Clear code (run every draw cycle):

```
// clear the buffers
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

```

The only other code related to stencils is in the `render()` function shown above.

# Answer
> 1 votes
It turns out that the library I was using (SFML) has the stencil buffer **disabled** by default. All I had to do was pass a `sf::ContextSettings` object with the stencil buffer argument set to 8 to a `sf::RenderWindow` constructor to fix everything.

# Answer
> 1 votes
A possible solution for your problem might be using stencil testing. Here is a link that explains it. It also describes how object outlining is done.

You basically need to populate the stencil buffer while rendering your object. Then you render your object slightly scaled up a second time while using a simple single color fragment shader. During the second rendering process, you discard every fragment where the stencil buffer was set during the first rendering call. Have a look at the link for the details.

---
Tags: opengl, c++, glsl
---


title: AI Conversation

text:
# Question
Title: AI Conversation
I am trying to create a conversation system for a crowd simulation AI. The way I am currently approaching this is by doing a check if bot1 sees bot2, than I pick a point for them to meet and they meet at that point. Start a conversation. The problem is that not many times two agents happen to see each other. I want to introduce a sociability level for each bot which represents how sociable (how much he wants to get engaged in conversation) he is. The problem is that I try to make use of this variable by adding a variable `sociabilityLevel` which varies from 1 to 10. Whenever two bots see each other I pick a random integer value between 1 and 10, call it `randomValue`.

If `randomValue <= sociabilityLevel`, for both of the agents, than they actually meet. For example: bot1 has sociability level of `9(high)` and bot2 has `5(medium)`, assuming they both see each other in this frame,I pick a random value which happens to be `4`. This means that the meeting is possible,otherwise for a random value of say '8' than the meeting will be cancelled because it does not satisfy bot2 requirement.

My goal is to make the agents with high sociability level talk with each other very probable, and agents with low sociability level talk with each other very unlikely. And any other combination with medium etc.

The problem is that with my current approach is that the `sociabilityLevel` variable does not reflect the actual chance of that agent of talking. The reason is because the condition of the agents to see each other is much more powerful than the `randomValue <= sociabilityLevel` condition.

Furthermore, if two agents come from direct opposite directions they will see each other on several frames, which means that the check `randomValue <= sociabilityLevel` will be executed as long as they see each other. This results in picking several random numbers pretty fast and it is quite likely that an agent with a level of `2` sociability will agree to the meeting.

I thought of introducing a 0.25 let's say delay for the agent to check if he sees another agent and vice-versa. This does not seem the right way to solve the problem.

Let's I remove the check for them to see each other and create a sort of event (like in this post : Design pattern for AI cooperation), where bot1 asks "Do you want to meet me?", and bot2 answers "Yes, I do". The issue is that how can I get the meeting point right? Because they have to face one each other and I am not pretty sure how to do this. Moreover, I only need to send the "Do you want to meet me?", only to a close bot, otherwise will mean a disaster, one agent wait hours for the other agent to come up.

# Answer
> 0 votes
How I would have done is to add a circle on every agent. The more sociable have a bigger zone so more chance to see an other one. If two zone touches, you make a probability check,

example: Bot1 have a sociability of 3 and bot2 have a sociability of 7. You make the average like "(ShiestBotSociability + SociableBotSociability) / 2" = meeting chances that give a result between 0 and 10. Then you get a random value between 0 and 10 and do "if random number \< meeting chances ..." If the don't meet, you add the bot1 an array of bots to ignore of bot2 and do the same for the array of bots to ignore of bot1. Then you remove them from the array under a certain condition (ex: after 1 minute they could meet again).

If you don't want to do that: I'm not sure if thats possible in the case of your game, but you could use a raycast as the bot view (if you're not already doing it) that have a certain length of like 10 meters. If a bot see an other one, you can do a probability check based on his social level to determine if he will talk to the other bot, then if he do the other bot either turn toward him or ignore him, based on his sociability.

However I think the best way is still to compare both bots sociability is to make an average, but thats up to you. I hope this helps you !

---
Tags: unity, animation, algorithm, ai
---


# Question
Title: How to avoid material copying error message in Edit-mode?
I created a component called "AphaGroup" (an analog of the existing CanvasGroup for UI) which should be able to change `alpha` of the whole game object tree. My component finds all the `MeshRenderer` components, takes their `material.color` and changes its `alpha`. It should work both in play- & edit- modes. When it's run in edit-mode there is an error in the console when the material is copied for the first time:

> *Instantiating material due to calling `renderer.material` during edit mode. This will leak materials into the scene. You most likely want to use `renderer.sharedMaterial` instead.*

I've read most of the similar questions on the Internet but still haven't found the answer on how to manage this situation properly. **How to avoid both: this error message and memory leaks?**

I tried Renderer.material, Renderer.materials and Renderer.GetMaterials, but all they cause the same error.

# Answer
My original goal was to create a component similar to CanvasGroup in the UI system that would work for Sprites. Then I needed it to work with MeshText components as well - that's where I encountered the error described in my question.

Given my original goal, *the code was tested on those components (sprites & text)* and I can't guarantee that it works correctly with any other materials. For example, transparency of some materials wouldn't be changed if their *RenderingMode* is not `Fade` or `Transparent`, or their shader is not *"Transparent/Diffuse"* (it can be changed with `material.shader = Shader.Find("Transparent/Diffuse");` or in the Inspector).

> AlphaGroup.cs

```
using System.Linq;
using UnityEditor;
using UnityEngine;

/// <summary>
/// Controls the transparency of the entire object (including all children) as `CanvasGroup` does in the UI system.
/// Executes both in play- & edit- modes.
/// </summary>
[DisallowMultipleComponent]
[ExecuteAlways]
public class AlphaGroup : MonoBehaviour
{
    [Range(0f, 1f)]
    [SerializeField]
    private float _alpha = 1f;

    private float _prevAlpha;
    private Renderer[] _renderers;

    private void Awake()
    {
        _renderers = GetComponentsInChildren<Renderer>();
    }

    private void Update()
    {
        UpdateAlpha();
    }

    private void UpdateAlpha()
    {
        if (_prevAlpha == _alpha)
            return;

        for (int i = 0; i < _renderers.Length; i++)
        {
            var renderer = _renderers[i];

            if (renderer is SpriteRenderer spriteRenderer)
            {
                var color = spriteRenderer.color;
                color.a = _alpha;
                spriteRenderer.color = color;
            }
            else if (renderer is MeshRenderer meshRenderer)
            {
                IsCopyMaterial isCopy = renderer.gameObject.GetComponent<IsCopyMaterial>();
                Material[] materials;

                if (isCopy)
                {
                    materials = meshRenderer.sharedMaterials;
                }
                else
                {
                    materials = meshRenderer.sharedMaterials.Select(m => Instantiate(m)).ToArray();

                    for (int j = 0; j < materials.Length; j++)
                    {
                        var material = materials[j];
                        material.name = meshRenderer.sharedMaterials[j].name + " (copy)";
                    }

                    meshRenderer.sharedMaterials = materials;
                    meshRenderer.gameObject.AddComponent<IsCopyMaterial>(); // Create a copy of the renderer materials only once.
                }

                foreach (Material material in materials)
                {
                    if (!material.HasProperty("_Color"))
                        continue;

                    var color = material.color;
                    color.a = _alpha;
                    material.color = color;
                }
            }
        }

        _prevAlpha = _alpha;
    }
}

```

> IsCopyMaterial.cs

```
/// <summary>
/// An indicator that the material has been copied.
/// </summary>
[DisallowMultipleComponent]
public class IsCopyMaterial : MonoBehaviour
{
}

```
> 0 votes

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


# Question
Title: How to sort scores and assign positions based on the scores?
I have three game objects each with an individual score. I was wondering how I should go about sorting these scores in ascending order. I want to also give these objects a position based on their score. Any help would be appreciated.

For example:

```
object1.score = 1300,

object2.score = 3000,

object3.score = 2200

```

What I'm looking for is:

```
object1.position = 3,

object2.position = 1,

object3.position = 2

```

Game Object code:

```
SGameObject
{
    int cp = 0;
    int lap = 0;
    int score = 0;
    int position = 0;
}

```

# Answer
> 1 votes
Put your objects into a `std::vector` (or even `std::array`) and then use `std::sort` with a custom comparator. After that, if necessary, you can assign the indices in the list to the corresponding objects.

```
std::sort(objects.begin(), objects.end(), [](const auto& a, const auto& b) {
    return a.score > b.score; });

```

Now `objects` contains the items sorted by their scores. To assign the positions, just loop over the objects again and assign their index to the position:

```
for (std::size_t i = 0; i < objects.size(); ++i)
    objects[i].position = i;  // Zero indexed, add one for one indexed.

```

---
Tags: c++, mathematics, game-mechanics, leaderboards, sorting
---


# Question
Title: Making sense of the positions of gameObjects
**Project files:** https://github.com/Sebastian-Nielsen/makingSenseOfPositions

**Note:** There are no scripts running, all I am doing in between each picture is manually changing the x-coordinate in the inspector of the given gameObject.

**See the problem:** Gif

Here we got my lovely little scene

Now, take note on the x-position of the tile the dark soldier is standing upon; it's -13.78.  Take a look at the Dark Soldier's x-position now. There is a difference of 3 between those two on the x-axis!

Now, look what happens when I change the x-coordinate of the Dark Soldier to -13 to match that of the tile. (I expect the Dark Soldier to now be precisely on top of the tile he was standing on in the first picture -- maybe he was a little off in that pic).

Wait what? He moved away from the tile at position x=-13.

Why is that?! I think I'm going crazy! Please make sense of this, why is this happening?

# Answer
> 1 votes
You've done a few things here that are making this appear more confusing than it needs to.

First: your tiles are all children of a parent object - which can be good for scene organization - but it means you're not comparing apples to apples when you look at the transform values (which show you the `localPosition`, `localEulerAngles`, and `localScale` properties):

* Your Dark Knight has no parent, so its position/rotation/scale values are relative to your world coordinate system.
* Your tiles are children of the Tiles game object, so their position/rotation/scale values are relative to their parent.

Again, this isn't bad, but it introduces an extra step: you have to consider the parent's transform too. And you've shifted the Tiles parent object by (-2, 1, -45)

That means the tile that's at (-13.78, 3.87, 44.517) relative to this parent is actually at

```
(-13.78, 3.87, 44.517) + (-2, 1, -45) = (-15.78, 4.87, -0.483)

```

in the world.

If you want to do easy apples-to-apples comparisons in worldspace between objects in different containers, it can help to keep the container at (0, 0, 0) and default scale & rotation.

This won't be a problem in scripts, of course, since you can just ask an object for its `transform.position` (not the `.localPosition` you see in the Inspector), which automatically factors in the whole parent/grandparent chain and reports back the value in world space.

You can get a similar effect in editor by kicking the object of interest out of the parent - Unity will automatically adjust its local transform values to try to keep it at the same location/orientation/scale, baking its world transform down into its local transform for you to read. Then you can reverse the operation to put it back in its original place in the hierarchy.

The next funny thing we can reveal by putting the scene transform gizmo toggles at the top toolbar into "Pivot" mode:

We can see the transform gizmo arrows cross at the pivot of the object, right in the center of the tile, where we'd intuitively expect to find it.

But when we position the Dark Knight at the location we calculated above to adjust for the parent offset, we see this:

As we wanted, the pivot is positioned perfectly on top of the tile. But the visible sprites are shifted significantly from this pivot point!

It looks like you've set up this asset so all the body parts are down and to the right of the parent's origin/pivot point.

Usually we want to set up our characters so the root transform's origin is either at their center of mass, or at the base of their feet (for ease of positioning characters of different heights on the same ground level).

If there are no animations on the object, we can usually fix this with a trick similar to the one above: kick all the child objects out of the parent, move the parent to the location where we want it relative to the children, then add the children back into the parent, so they take on new local positions inside it.

But with animations this is tricky: the first frame the animation plays, it will usually shove everything back to its recorded position in the animation, which was the old offset we wanted to remove! So you may need to remake your animation on this asset to get the pivot where you want it.

A cheap trick you can use to avoid this work is to create a new parent object at the place where you want the pivot, then parent your whole prefab to the new parent, and then overwrite your prefab with the new parent. You deal with one extra layer of transformation this way, but it lets you quickly correct for an unwanted transformation on the child objects.

---
Tags: unity, transformation
---