# Question
Title: How to stop Players and Enemies from pushing each other
I am developing 2D Top-Down RPG game. I have script that makes my enemy follow the player, and when they touch the player, the player will start to lose HP.

Everything works well, but when they touch each other, the enemy starts pushing the player and also I can push the enemy too.

I use a Rigidbody2D and BoxCollider2d for each of them.

Here is my enemy controller code:

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

public class EnemyController : MonoBehaviour
{
    private Animator myAnim;
    private Transform target;
    public Transform homePos;
    private Rigidbody2D myRB;

    [SerializeField]
    private float speed;
    [SerializeField]
    private float maxRange;
    [SerializeField]
    private float minRange;
    // Start is called before the first frame update
    void Start()
    {
        myAnim = GetComponent<Animator>();
        target = FindObjectOfType<PlayerController>().transform;
        myRB = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Vector3.Distance(target.position, transform.position) <= maxRange && Vector3.Distance(target.position, transform.position)>= minRange)
        {
            FollowPlayer();
        }

        else if(Vector3.Distance(target.position, transform.position) >= maxRange)
        {
            GoHome();
        }
    }

    public void FollowPlayer()
    {
        myAnim.SetBool("isMoving", true);
        myAnim.SetFloat("moveX", (target.position.x - transform.position.x));
        myAnim.SetFloat("moveY", (target.position.y - transform.position.y));
        transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }
    public void  GoHome()
    {
        myAnim.SetFloat("moveX", (homePos.position.x - transform.position.x));
        myAnim.SetFloat("moveY", (homePos.position.y - transform.position.y));
        transform.position = Vector3.MoveTowards(transform.position, homePos.position, speed * Time.deltaTime);

        if (Vector3.Distance(transform.position, homePos.position) == 0)
        {
            myAnim.SetBool("isMoving", false);
        }
    }
}

```

# Answer
> 0 votes
I fixed it when i add this codes to my enemy controller when enemy touch to player enemy's speed set to 0 and dont move more

 private void OnCollisionStay2D(Collision2D other)
    {
        if (other.collider.tag == "Player")
        {
            speed = 0f;
        }

    }

    private void OnCollisionExit2D(Collision2D other)
    {
        if (other.collider.tag == "Player")
        {
            speed = respeed;
        }
    }
```

---
Tags: unity, 2d, physics, collision-resolution, kinematic
---


# Question
Title: Part of model in Unity is inside out but not in Blender?
I've downloaded this asset and it looks perfectly fine in preview, and even in blender.

But when I import it in Unity, one of its shoulder is inside out, even after making all faces double sided.

I also tried switching the normal mode in the import settings to Calculate.

What causes this issue and how could I fix this?

# Answer
When you view the model in the Sketchfap viewer, click on the "Model Inspector" button and then enable "Vertex Normals", then you can see that the right shoulder of that character indeed has inward-facing normals. This is a mistake in the model, not with the way you import it. Such a mistake is easy to make, because many 3d modeling programs have two-sized rendering enabled by default (to improve usability), while most game engines do not (to improve performance).

You should be able to fix that in Blender by selecting the shoulder and flip the normals.

But if you really don't want to mess with the model and use it as it is, then another option is to use a shader which supports two-sided rendering. How to find/create such a shader depends on what render pipeline you are using.
> 2 votes

---
Tags: unity, blender, models
---


# Question
Title: How to replace if/else/switch with polymorphisim
For a long time Robert Martin has been advising against if/else/switch branching logic and instead rely on the polymorphic behavior of different types. `if/else/switch` should only be used in the factory creating the types with different behaviours. He describes the approach in a recent blog post. I feel I understand the thrust of his argument as applied in his example situation and I really like the concept as it pushes decision making to a single location, DRY & OCP.

However, I'm finding it difficult to apply the principle is some basic game dev situations.

e.g. consider this pseudo-code controlling a ball bouncing around a box (think 'Breakout')

```
void ball::update(){
  if(collideswith(leftWall))
    velocity.x= +speed;
  else if(collideswith(rightWall))
    velocity.x = -speed;
  else if(collideswith(topWall))
    velocity.y = -speed;
  else if(collideswith(bottomWall))
    velocity.x = +speed;
}

```

I am unsure what kind of polymorphic class I could build to replace the branching logic here.

Replacing the above code with an Uncle Bob solution might be over-engineering, but am interested in learning more about applying the principle in these *kinds* of contexts.

# Answer
*I'll just cover the `is_key_pressed` I proposed in comments.*

You could have a list of input handlers strategies. It would be a list of key-value pairs. Where they key is… well, a key, that could be pressed. And the value is what happens when the key is pressed.

You would have the type of the values be `IInputStrategy` (or `IHandleInput` using lolcat interface name convention). And you have multiple implementations, such as `JumpStrategy`, `RunStrategy`, `ShootStrategy`, and so on. Then you iterate over the list, for each one check if it the key is pressed, and call `Execute` on the value. Like this:

```
for ((key, strategy): strategies))
{
    if (is_key_pressed(key))
    {
        strategy.Execute(avatar);
    }
}

```

This has the advantage that we can easily add commands and change their binding in runtime. For example to configure the input we can just modify the key. Perhaps we can add or replace elements when the player unlocks a power up, or something like that. It also has the advantage of keeping the code for each command separate.

We could also wrap the calls to `is_key_pressed` in other objects. That could allow to configure inputs not based on a single key press. Then we can rewrite the code like this:

```
for (IInputStragy strategy: strategies))
{
    strategy.Execute(avatar);
}

```

That looks like a suitable replacement for a series of `if statements`. However, if we have a switch, we want to stop at the first one. So let us have `Execute` return `bool`:

```
for (IInputStragy strategy: strategies))
{
    if (strategy.Execute(avatar))
    {
        break;
    }
}

```

Well, that is not entirely disimilar to `sequence` and `selector` in behavior trees. That could be the path forward to continue to evolve this solution.
> 1 votes

# Answer
The OOP way to do this, would be to give the class `wall` a method `handleCollision(ball)` (although instead of `ball`, you might want to use the base-class of ball which represents any object which has a `velocity` and can bounce off of things).

And because you have both horizontal walls and vertical walls which do different things when a ball collides with them, you would create two classes inheriting from `wall`, namely `verticalWall` and `horizontalWall`. These classes would provide different implementation for `handleCollision`. One of them doing `ball.velocity.x *= -1;` and the other `ball.velocity.y *= -1`. `leftWall` and `rightWall` would be of type `verticalWall` and `topWall` and `bottomWall` would be of type `horizontalWall`.

You likely don't just want to limit yourself to 4 walls in your game but allow any number of walls, so it might be better to store those walls in an array. That allows you to write code like that:

```
for (wall w: walls) {
    if (collidesWith(w) {
        w.handleCollision(this);
    }
}

```

The array `walls` can contain any mix of horizontal and vertical walls, and the wonder of polymorphy will make sure that the correct `handleCollision` method is called for each of them within this loop.
> 1 votes

---
Tags: architecture, software-engineering, polymorphism
---


# Question
Title: Making a parent system with euler angles (gimbal lock problem)
I have a system where objects can be connected to each other - as the parent rotates the child objects will rotate too and child objects themself can rotate too. The system is already working, however, I am doing it with rotation matrices. I want to dynamically simulate angular physics and for that, I would need the angular velocity for which I thought the direct and easiest way would be to get the difference of the euler angles. I am still a beginner with those rotation maths like matrices, quaternions etc. The problem is that the rotation of the children would be local and currently I am just adding the euler angle values (which works fine if I only rotate around one axis). So when I rotate a child on the x axis by 90 degrees and then rotate the parent on the y or z axis the system breaks (y and z should be swapped in this scenario with 90 degrees x rotation)

As far as I have understood it the problem could be explained with "gimbal lock". Is there a way to calculate the local euler angles? Or is there in general a better way to achieve what I am trying to do here? I have heard that quaternions also don't save 360+ degrees, so that would be also a problem for angular velocity.

# Answer
> 0 votes
> I thought the direct and easiest way would be to get the difference of the Euler angles

No, this is definitely not a direct or easy way. This road leads only to suffering.

Euler angles are good for presenting an orientation to a human reader/editor, or for serializing an orientation to disc, or for a few special cases like camera control. But they are an absolute nightmare to use for general orientation computations or compositions. A combination of two Euler angle rotations is not the sum or any simple expression of the angles of the inputs, nor is there a simple expression for inverting them.

**Just use quaternions**. They don't have the axis bias or gimbal lock problems you've observed. You can compose two rotations in a chain (like a parent and child) as simply as doing a multiplication. And inverting a quaternion (eg. to undo a parent rotation and get into local space) is as easy as negating the x, y, and z components.

> I have heard that quaternions also don't save 360+ degrees, so that would be also a problem for angular velocity.

It's not a problem because you use quaternions to store orientations, not angular velocity.

Angular velocity can be stored as an axis and an angular speed, or as a single 3-component vector along the axis of rotation, whose length is the speed of rotation along that axis.

When you want to step forward your orientation by your angular velocity, you integrate your angular speed over the timestep to get a total angle of travel. Then you can construct a quaternion that rotates by that angle about the axis vector, and compose your previous orientation quaternion with this one.

---
Tags: physics, animation, euler-angles, gimbal-lock
---


title: HLSL defined render states

text:
# Question
Title: HLSL defined render states
As described in this article you can define render states such as ZFunc inside of the HLSL shader. You can also set these from application code. If you set the same state (e.g. ZFunc) in both application and HLSL, which one wins and gets used? Does it always use application over HLSL?

# Answer
**This article is specific to using HLSL with the Effects Framework; it's not general to HLSL**.

The Effects Framework is a high-level software wrapper over the Direct3D 9 (in this case) API. It has no functionality of it's own beyond ultimately making calls to the underlying Direct3D API, and providing some syntactic sugar over the API.

The documentation article I link describes how states specified using Effects interact with application states:

> When Begin is called, a stateblock is created and device state is saved (unless you specify otherwise). After a technique renders the passes that the application specifies to render, End is called to end the active technique. The effect system responds by automatically restoring the pipeline state that was captured in the state block (unless you choose to disable this save and restore functionality).

**It's important to realise that it's perfectly possible to use HLSL without using Effects** (in fact, one of the old DirectX SDK samples was named "HLSL without Effects" and demonstrated just that). You would just use (D3D9) SetVertexShader, SetPixelShader, SetRenderState, etc calls in your program code instead.

It's also important to realise that specifying render states is not part oif core HLSL; it's part of Effects. You cannot specify render states in HLSL outside of the Effects Framework.

Finally, Effects is deprecated and/or removed in newer versions of Direct3D.
> 2 votes

---
Tags: hlsl, directx9
---


# Question
Title: (Hitbox) OnTriggerEnter2D only work if enemy is moving
(UPTADE) I am developing a 2D Topdown Rpg Game. I have a problem with trigger colliders. I have button which make active an object and ı use it like Hitbox when i press button ı destroy enemy if it is touching hitbox but there is a problem about something. When i press button enemy is destroyed if only enemy is moving when it stop i cant destroy it

How can I fix this?

This is my hitbox's destroy script

 private void OnTriggerEnter2D(Collider2D other)
    {

        if (other.tag == "Enemy")
        {
            Destroy(other.gameObject);
        }
    }
```

# Answer
I fixed it. If anyone come across with same problem just add animation to collider because if you dont do that your collider wont be triggered
> 0 votes

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


# Question
Title: Resizing canvas to match screen size in Unity WebGL
I'm learning how to make a browser game with Unity. I have set up the screen display dimensions to 960 x 640 (I read that it's a safe resolution to use. Feel free to correct me). I created a Canvas and set it to match with width or height, and I set Reference Resolution to 960 x 640.

The problem is that the canvas doesn't match the screen properly and empty leaves bars at the top and bottom. I get the same result using both Render Modes for Camera and Overlay. I understand that the matching options choose either width or height, depending on the slider setting.

Can I somehow match the canvas to the display properly?

Screenshot of the Canvas

Screenshot of the Canvas setting

Screen as displayed in the browser

# Answer
I found the answer. I didn't realise I can set the game preview in Unity to specific a fixed aspect ration. The problem occurred because the Canvas were matching with the camera or screen size, and that preview window screen size did not match the desired 960 x 640. Apologies for a silly question. I haven't worked much with 2D games before.
> 0 votes

---
Tags: unity, 2d, webgl
---


# Question
Title: Apply multiple Shaders to one texture with DirectX
I'm beginning with DirectX development and I'm quite confused by the documentation about how to do the following:

**I have 1 image (Texture2D), I'd like to apply 2 independent HLSL, one after the other, and render it.**

For instance, one shader makes the texture semi-transparent, the other turns it to black and white. Also, I'm computing everything off-screen, so I don't have a SwapChain.

So far the output texture I get has the 1st shader applied but not the second. If I switch the order where the shaders are applied, then I'm seeing the 1st shader applied (in the new order) but not the second. In other words, both shaders work separately but not together. I'm using SharpDX and C#.

## Here is what I made

### Setup

1. Create D3D11 device.
2. Set Blend state

```
            BlendStateDescription blendStateDescription = new BlendStateDescription
            {
                AlphaToCoverageEnable = false,
                IndependentBlendEnable = false
            };
            blendStateDescription.RenderTarget[0].IsBlendEnabled = true;
            blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.One;
            blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            device.ImmediateContext.OutputMerger.SetBlendState(new BlendState(device, blendStateDescription));

```
3. Set Depth stencil state

```
            var depthStencilState = new DepthStencilState(device, DepthStencilStateDescription.Default());
            device.ImmediateContext.OutputMerger.SetDepthStencilState(depthStencilState);

```
4. Create a RenderTargetView and a texture
5. Create DepthStencilView and a texture
6. Set the RenderTargetView and DepthStencilView are targets of the output merger.

### Run

1. Load an image from the hard drive to a Texture2D
2. Create a ShaderResourceView from this texture.
3. For each effects I want to apply:
    * Load the shader from the bytecode into an Effect.
    * Create a vertice, then create a buffer from it.
    * Set this buffer as a vertex buffer in the Input Assembler: `deviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(myBuffer, Marshal.SizeOf(typeof(VertexPositionTexture)), 0));`
    * Set the input layout.
    * Get a `technique` from the shader and for each pass, I `effectPass.Apply` then do a `deviceContext.Draw`.
4. `deviceContext.Flush();`
5. Save the texture associated to the RenderTargetView as a PNG.

## Question

Is my approach correct or am I doing something wrong in that method?

I wonder if the issue could be in the blend state or depth stencil. Let me know if you'd like me to share more code to see my implementation details.

Thank you in advance for the help. :)

# \[UPDATE 3/8/21\]

Here is a simplified version of my code for insights:

```
var device = new Device(
                    DriverType.Hardware,
                    DeviceCreationFlags.BgraSupport | DeviceCreationFlags.VideoSupport,
                    FeatureLevel.Level_11_0);

            BlendStateDescription blendStateDescription = new BlendStateDescription
            {
                AlphaToCoverageEnable = false,
            };
            blendStateDescription.RenderTarget[0].IsBlendEnabled = true;
            blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.Zero;
            blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            device.ImmediateContext.OutputMerger.SetBlendState(new BlendState(device, blendStateDescription));

            DepthStencilStateDescription description = DepthStencilStateDescription.Default();
            description.DepthComparison = Comparison.LessEqual;
            description.IsDepthEnabled = true;

            device.ImmediateContext.OutputMerger.SetDepthStencilState(new DepthStencilState(device, description));

// [...]

            Texture2DDescription depthDesc = new Texture2DDescription()
            {
                Width = _outputTextureSize.Width,
                Height = _outputTextureSize.Height,
                Format = Format.D24_UNorm_S8_UInt,
                OptionFlags = ResourceOptionFlags.None,
                ArraySize = 1,
                MipLevels = 1,
                SampleDescription =
                {
                    Count = 1,
                    Quality = 0
                },
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                Usage = ResourceUsage.Default
            };

            DepthStencilViewDescription depthViewDesc = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format = Format.D24_UNorm_S8_UInt,
            };

            _depthStencilTexture = new Texture2D(device, depthDesc);
            _depthStencilView = new DepthStencilView(device, _depthStencilTexture, depthViewDesc);
            device.ImmediateContext.OutputMerger.SetDepthStencilState(
                new DepthStencilState(device,
                DepthStencilStateDescription.Default()));

// RENDERING

            context.ClearRenderTargetView(_renderTargetView, Color.CornflowerBlue);
            context.ClearDepthStencilView(_depthStencilView, DepthStencilClearFlags.Depth, 1f, 0);

            using ShaderResourceView shaderResourceView = new ShaderResourceView(device, inputTexture2D)

foreach (var effect in effectList)
{
    using ShaderBytecode shaderByteCode = ShaderBytecode.FromFile(effect.FilePath);
    var shaderEffect = new Effect(device, shaderByteCode.Data);

    using var verticesRectangle = new DataStream(
                Marshal.SizeOf(typeof(VertexPositionTexture)) * 4,
                true,
                true);

    // verticesRectangle.Write ...
    verticesRectangle.Position = 0;
    var buffer
                = new Buffer(
                    device,
                    verticesRectangle,
                    new BufferDescription
                    {
                        BindFlags = BindFlags.VertexBuffer,
                        CpuAccessFlags = CpuAccessFlags.None,
                        OptionFlags = ResourceOptionFlags.None,
                        SizeInBytes = Marshal.SizeOf(typeof(VertexPositionTexture)) * 4,
                        Usage = ResourceUsage.Default,
                        StructureByteStride = 0
                    });

    device.ImmediateContext.InputAssembler.InputLayout
                    = new InputLayout(
                        device,
                        shaderEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature,
                        elements: VertexPositionTexture.InputElements);

     device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
     device.ImmediateContext.InputAssembler.SetVertexBuffers(
                    0,
                    new VertexBufferBinding(
                        buffer,
                        Marshal.SizeOf(typeof(VertexPositionTexture)),
                        0));

    for (var i = 0; i < shaderEffect.GetTechniqueByIndex(0).Description.PassCount; ++i)
    {
                    using EffectPass effectPass = shaderEffect.GetTechniqueByIndex(0).GetPassByIndex(i);

                    if (effectPass.IsValid)
                    {
                        effectPass.Apply(deviceContext);
                    }

                    device.ImmediateContext.Draw(4, 0);
                }

                device.ImmediateContext.InputAssembler.InputLayout.Dispose();
                device.ImmediateContext.InputAssembler.InputLayout = null;
}

device.ImmediateContext.Flush();

```

My shader effects:

```
///
/// Shader effect that changes the opacity of a texture.
///

Texture2D Texture : register(t0);
SamplerState TextureSampler : register(s0);

float TargetOpacity;

struct ShaderParameters
{
    float4 Position : SV_Position; // vertex position input
    float2 TextureUV : TEXCOORD0; // first texture coordinate input
};

// Vertex Shader
ShaderParameters VS(ShaderParameters input)
{
    ShaderParameters output = (ShaderParameters) 0;

    output.Position = input.Position;
    output.TextureUV = input.TextureUV;

    return output; // Returns the position without any change to it.
}

// Pixel Shader
float4 PS(ShaderParameters input) : SV_Target
{
    float4 rgbaColor = Texture.Sample(TextureSampler, input.TextureUV);

    return float4(rgbaColor.rgb, rgbaColor.a * TargetOpacity);
}

technique10 OpacityTechnique
{
    pass P0
    {
        SetGeometryShader(0);
        SetVertexShader(CompileShader(vs_5_0, VS()));
        SetPixelShader(CompileShader(ps_5_0, PS()));
    }
}

```

And

```
///
/// Shader effect that converts a colorful texture to monochrome (gray).
///

Texture2D Texture : register(t0);
SamplerState TextureSampler : register(s0);

struct ShaderParameters
{
    float4 Position : SV_Position; // vertex position input
    float2 TextureUV : TEXCOORD0; // first texture coordinate input
};

// Vertex Shader
ShaderParameters VS(ShaderParameters input)
{
    ShaderParameters output = (ShaderParameters) 0;

    output.Position = input.Position;
    output.TextureUV = input.TextureUV;

    return output; // Returns the position without any change to it.
}

// Pixel Shader
float4 PS(ShaderParameters input) : SV_Target
{
    float4 rgbaColor = Texture.Sample(TextureSampler, input.TextureUV);
    float gray = (rgbaColor.r + rgbaColor.g + rgbaColor.b) / 3;

    return float4(gray, gray, gray, rgbaColor.a);
}

technique10 GrayscaleTechnique
{
    pass P0
    {
        SetGeometryShader(0);
        SetVertexShader(CompileShader(vs_5_0, VS()));
        SetPixelShader(CompileShader(ps_5_0, PS()));
    }
}

```

Thanks :)

# Answer
I finally fixed the issue!

There were 3 problems to my initial code.

1. The first effect I was applying was adding transparency to the image. My BlendState was configured in a way that the output texture would be completely transparent. Therefore, using a completely transparent texture for the next effect would just return something transparent too. I fixed the issue by making a blend state specific to each effect to apply.
2. I wasn't clearing the DepthStencilView and RenderTargetView between each effect. I thought I had to do it between each frame, not each effect.
3. As @DMGregory mentioned (and thanks to you :) ), I needed to make sure to reuse the output texture of the first shader as input for the next one.
> 0 votes

---
Tags: shaders, textures, directx
---


title: If statements on Update method

text:
# Question
Title: If statements on Update method
I want to disable axe collider when e is pressed and enable it again when e is pressed again. I have the bool "axeOnHand" so If statements can be called when needed. But when i press e, both If statements are called. I think the problem is they are called in the same frame. But i don't know how to solve this issue.

# Answer
both called because you set `axeonhand=false` therefore second `if` statement evaluate to `true`. change second `if` to `else if`.
> 0 votes

# Answer
Your first if-statement sets `axeOnHand = true`, so when the code execution reaches the second if-statement, that variable will have a different value than it had before.

I would structure the code like this:

```
if (Input.GetKeyDown("e") {
    if (axeOnHand) {
          axeOnHand = false;
          // toggle axe collider
    } else {
          if (axeCollided) {
              // toggle axe collider
              axeOnHand = true;
              pickUpAxe();
          }
    }
}

```

I omitted a couple lines. I would have included all the lines of your code if I had been able to copy&paste. Which I would have been able to do if you had included your code in text form instead of as a screenshot.
> 0 votes

---
Tags: unity
---


# Question
Title: How can I have the character come back to its full height after crouching?
I'm making a simple game and when the player crouches/slides I would want to make the character to change size. However when it changes to its smaller size it doesn't go back to its original size after you release the crouch button.

```
using UnityEngine;

public class advancedMovement : MonoBehaviour
{

    PlayerMovement basicMovementScript;
    public float sprint = 5f;
    public float slideSprint = 6f;
    public float deceleration = 0.5f;

    public CharacterController ccr_controller;
    public float ControllerHeight;

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift))
            basicMovementScript.speed += sprint;
        else if (Input.GetKeyUp(KeyCode.LeftShift))
            basicMovementScript.speed -= sprint;

        if (Input.GetKeyDown(KeyCode.LeftControl))
        {
            basicMovementScript.speed += slideSprint;
            ccr_controller.height = ControllerHeight;
            ControllerHeight = 7f;
        }

        if (Input.GetKeyUp(KeyCode.LeftControl))
        {
            basicMovementScript.speed -= slideSprint;
            ccr_controller.height = ControllerHeight;
            ControllerHeight = 14f;
        }
    }
}

```

# Answer
> 1 votes
The reason for your problem could be that you have just one variable `ControllerHeight` which gets both changed and used to restore the value of `ccr_controller.height`. This seems to cause a lot of confusion for you because you don't seem to always be aware of what value it has.

You might want to use two variables here with proper names:

* `float heightStand`: The height the character has when standing. The value of this variable should **never change** during the game.
* `float heightCrouch`: The height the character has when crouched. The value of this variable should also **never change**.

Use these two variables when you want to set the height of the character controller.

```
    if (Input.GetKeyDown(KeyCode.LeftControl))
    {
        basicMovementScript.speed += slideSprint;
        ccr_controller.height = heightCrouch;
    }

    if (Input.GetKeyUp(KeyCode.LeftControl))
    {
        basicMovementScript.speed -= slideSprint;
        ccr_controller.height = heightStand;
    }

```

When you have any situations where you need the *current* height of the character, use `ccr_controller.height`.

---
Tags: unity, c#, character-controller
---


# Question
Title: When using IK the player head is looking at down the ground instead looking at the object target up what can be the problem?
This script is attached to the player :

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

[RequireComponent(typeof(Animator))]

public class CharController : MonoBehaviour
{

    protected Animator animator;
    public bool ikActive = false;
    public Transform lookObj = null;
    public float lookWeight = 2f;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    //a callback for calculating IK
    void OnAnimatorIK()
    {

        if (animator)
        {

            //if the IK is active, set the position and rotation directly to the goal.
            if (ikActive)
            {
                // Set the look target position, if one has been assigned
                if (lookObj != null)
                {
                    animator.SetLookAtWeight(lookWeight);
                    animator.SetLookAtPosition(lookObj.position);
                }

            }

            //if the IK is not active, set the position and rotation of the hand and head back to the original position
            else
            {
                animator.SetLookAtWeight(0);
            }
        }
    }
}

```

When the lookObj is a sphere or a cube it's working fine but if the lookObj for example is a big spacecraft now the player head will look to the ground down and not to the spacecraft up :

The problem is that the center of the spacecraft is at the bottom this is a screenshot when it's showing the spacecraft at regular when it's in Pivot mode :

Now when I click on the Center button now the center of the object is at the bottom :

Is there any way to fix it maybe eve fix it ?

# Answer
> 0 votes
It appears that you imported a model which is not properly centered. The visible parts of the mesh appear to be far above the origin point.

Ideally you should fix that in a 3d modeling program by making sure that the 0:0:0 point is in the middle of the geometry. But when you don't want to mess with the asset, then you could fix that by wrapping the object in a parent and then changing the relative position of the object so its visual center is the position of its parent. Although it appears that the 3d mesh is already parented to the `Anim_Flyer` gameObject, so you might be able to change the relative position of the object(s) which are the children of that object.

Another option is to add a separate empty child to the flyer which serves as an IK target point for other objects. Adding objects like that can be useful when you want objects which look at another object to not center their view on the origin of the subject but on a specific eye-catching feature of the subject (like the yellow ring thing of this mesh), and perhaps even have multiple of such features and use them depending on context. It also plays well with animations, because you can parent those IK-targets to the sub-objects which are being animated.

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


title: How to do topdown collisions properly?

text:
# Question
Title: How to do topdown collisions properly?
I'm trying to achieve grid/tile based collisions like "a link to the past"; here is an article showing it off (sliding off the corners and such). I'm currently using this type of collision test. It's based on deepnight's implementation of tile collisions but modified a bit, you have your positionX/Y in the world, TileX/Y is the tile equivalent (my tiles are 16/16), and XRatio/YRatio which is how much into a tile are you so whenever you're moving into a tile you can clip into it for a certain amount which is nice for making it seem like the player is above stuff and to have more control over it but I'm really looking for someone to show me how I'd go about implementing this kind of collision testing properly I've been having so many problems (Getting stuck in 1 pixel in the corners, Snapping on one side while the other u don't, getting stuck in general/not being able to move when holding diagonals etc) If you could "Explain Like I'm 5" that'd be awesome I'd really like to learn this stuff properly.

TL:DR - Trying to achieve Topdown collision detection like a link to the past/stardew (Slide off corners of tiles) and being bug free (Not getting stuck / snapping)

# Answer
I'm assuming you're doing this:

```
var oldPos = position
position += velocity
if(collision):
    position = oldPos

```

the following method will fix the issues you're talking about

```
var oldX = position.x
position.x += velocity.x
if(collision):
    position.x = oldX

var oldY = position.y
position.y += velocity.y
if(collision):
    position.y = oldY

```
> 0 votes

---
Tags: c#, xna, collision-detection, mathematics, monogame
---


# Question
Title: stop previous audio from playing when starting a new one
I created a dialogue system with audio it works perfectly fine unless you start skipping the voice lines so then it all becomes a mess with all of the voice lines overlapping is there a way to make it so when you go to the next audio line the previous one stops playing?

Example of what is happening

as you can see in the video you can switch the text just fine and it doesn't show the previous one but for the audio, it just transforms into a jumbled mess, is there a way to fix this or to at least make it so people cant go to the next line until they finish hearing the current one?

DialogueManager Script:

```
public class DialogueManager : MonoBehaviour
{
public Door1Animation doorAnimation;

public Text nameText;
public Text dialogueText;
public Text changeText;

public AudioManager Sound;

public Animator textBoxAnimation;

public Queue<string> sentences;

public Queue<string> voiceLines;

void Start()
{
    sentences = new Queue<string>();
    voiceLines = new Queue<string>();
}

public void StartDialogue (Dialogue dialogue)
{
    textBoxAnimation.SetBool("Open", true);

    changeText.text = ("Aperte R para continuar");

    nameText.text = dialogue.name;

    sentences.Clear();

    voiceLines.Clear();

    foreach (string sentence in dialogue.sentences)
    {
        sentences.Enqueue(sentence);
    }

    DisplayNextSentence();

    foreach (string voiceLine in dialogue.voiceLines)
    {
        voiceLines.Enqueue(voiceLine);
    }

    PlayNextLine();
}

public void DisplayNextSentence()
{
    if (sentences.Count == 1)
    {
        changeText.text = ("Aperte R para fechar");
    }

    if (sentences.Count == 0)
    {
        EndDialogue();
        return;
    }

    string sentence = sentences.Dequeue();
    dialogueText.text = sentence;
}

public void PlayNextLine()
{
    if (voiceLines.Count == 0)
    {
        return;
    }

    string voiceLine = voiceLines.Dequeue();
    Sound.Play(voiceLine);
}

public void EndDialogue()
{
    Debug.Log("End of conversation");
    doorAnimation.openDoor = true;
    textBoxAnimation.SetBool("Open", false);
}
}

```

AudioManager Script:

```
using UnityEngine.Audio;
using System;
using UnityEngine;

public class AudioManager : MonoBehaviour
{
public Sound[] sounds;

void Awake()
{
    foreach (Sound s in sounds)
    {
        s.source = gameObject.AddComponent<AudioSource>();
        s.source.clip = s.clip;

        s.source.volume = s.volume;

        s.source.pitch = s.pitch;

        s.source.loop = s.loop;

    }

}

private void Start()
{
    Play("BackgroundMusic");
}

public void Play (string name)
{
    Sound s = Array.Find(sounds, sound => sound.name == name);
    s.source.Play();
}
}

```

Just the part of the interaction code so you can go to the next line/audio:

```
    public void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {

        PersonInteract();
        buttonInteract();

    }

    if (Input.GetKeyDown(KeyCode.R))
    {
        FindObjectOfType<DialogueManager>().DisplayNextSentence();
        FindObjectOfType<DialogueManager>().PlayNextLine();
    }
}

```

Inspector view of the dialogue manager:

# Answer
This is pretty trivial. Just remember which audio source you played most recently, and stop it before you play a new one.

```
AudioSource _lastPlayed;

public void Play (string name, bool cancelOnNextSound)
{
    if (_lastPlayed != null && _lastPlayed.isPlaying) {
        _lastPlayed.Stop();
    }

    Sound s = Array.Find(sounds, sound => sound.name == name);
    s.source.Play();

    if (cancelOnNextSound) {
        _lastPlayed = s.source;
    }
}

```
> 2 votes

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


# Question
Title: Can I have an Area affect the audio input of a Listener rather than the audio output of a speaker
Simple 3D use case: I have a Listener attached to my 3P character and a speaker attached to the environment, providing general background ambience (no attenuation).

When the character goes underwater, I'd like the environmental noise to be muffled and when they enter a building, I'd like echo, etc.

\[Edit\] In reality I have numerous AudioStreamPlayer3D objects attached to the environment (general ambience, sounds of a stream laid out along its course, sound attached to a NPC) so switching them all from one bus to another on `on_body_entered` and `on_body_exited` signals from the Area seems very inefficient, though I know I can probably achieve what I want that way.

# Answer
Don't move AudioStreamPlayer3D from an audio bus to another. Instead modify the audio bus on runtime. You should only have to modify one or two audio buses when leaving or entering an area. I remind you that usually we have the Master audio bus, and other audio buses routed to Master, but you can route a bus to another instead.

See AudioServer and Audio Buses.

---

You can get the index of a bus by name like this:

```
var bus_index = AudioServer.get_bus_index(bus_name);

```

*`get_bus_index` returns `-1` if the bus does not exist.*

You can change the volume of the audio bus like this:

```
AudioServer.set_bus_volume_db(bus_index, db);

```

You can set the effects you want in the audio bus from the editor, and then enable or disable them like this:

```
AudioServer.set_bus_effect_enabled(bus_index, effect_index, enabled);

```

---

I encourage to set the effects you want in the editor and simply enable or disable them. However, you can also add and remove effects with `AudioServer.add_bus_effect` and `AudioServer.remove_bus_effect` respectively. If you are adding and removing audio effects at runtime I suggest to only do one per audio bus, and take advantage of the routing.

Know that AudioEffects are resources. I suggest to export a resource variable from your script where you setup the audio effect:

```
export(AudioEffect) var audio_effect;

```

Then you can use the IDE to create the audio effect you want.
> 0 votes

---
Tags: godot, audio
---


# Question
Title: Problem with calculating velocity for a car with multiple gear ratios
I hope this is the right place for this but I have a problem with calculating velocity for my car game. The higher the gear, and therefore lower the gear ratio, the lower the top speed.

Given that

> Acceleration = Forward Force - Drag - Rolling Resistance

> Velocity += Acceleration * dt

and

> Wheel Torque = Engine torque * Gearbox ratio * Differential ratio

> Forward Force = Wheel Torque/Wheel Radius

I feel like I am missing something because if we decrease the gear ratio we decrease the torque and therefore the forward force causing lower acceleration so the car cannot gain additional velocity, and actually loses it due to resistive forces.

# Answer
> 0 votes
Let's assume your vehicle is travelling along at a given speed \\$v\\$ in metres per second - it may or may not be able to sustain this speed on its own, but we'll ignore that for now and use this as a stepping stone to determine the speed it *can* sustain.

In one second, the car moves forward \\$d = v \times 1 \text{s}\\$ metres.

That's \\$\frac d {2 \pi r}\\$ turns of a wheel with radius \\$r\\$, so the wheel is turning at a rate of \\$\frac {v \times 1 \text{s}} {2 \pi r} \text Hz\\$

For a combined gearing and differential ratio \\$g\\$, that means your engine is turning at: \\$g \frac {v \times 1 \text{s}} {2 \pi r} \text Hz = \frac {g v \times 1 \text{s}}{120 \pi r} \text{RPM}\\$

We can use this RPM rate to sample your engine's torque curve and compute the Forward Force as described in your question.

For very high initial values of the speed \\$v\\$, this force will be negative. At such high RPM, your engine offers too little torque to overcome the high drag at that speed.

So then you try a lower value of \\$v\\$ \- maybe the one corresponding to the RPM where your engine achieves its peak torque. At this lower speed, you get a positive value of Forward Force - your engine has enough surplus torque to not just maintain this speed, but accelerate beyond it.

So now we have two speed values, one that gives us a positive force, one that gives us a negative force. At some speed value between those two points, the force value must cross zero. At that specific speed, the torque our engine puts out and the resistance the car faces are exactly in balance, and we can maintain the speed but not accelerate above it. That's our maximum speed for this gear.

We can find this maximum speed by binary search: try the speed halfway between the two speed we've tried so far.

* If this new halfway speed yields a positive force, replace the previous speed that gave us a positive force by this one - we have a new lower bound.
* If this new halfway speed yields a negative force, replace the previous speed that gave us a negative force by this one - we have a new upper bound.

Each time we do one of these replacements, we reduce our uncertainty about the maximum speed by a half. Repeat until the lower and upper bounds converge to your desired precision.

---
Tags: physics, car, racing, vehicle
---


# Question
Title: How to retain gameobject in DoNotDestory objects when game is restart
I have an empty object which is not destroy after the game is restarted.

```
DontDestroyOnLoad(this.gameObject);

```

I have some gameobject references in the script

```
public GameObject leaderboardPanel;
public GameObject addPointsPanel;
public GameObject updateButton;

```

When the scene is reloaded then all the above objects in inspector shows

```
Missing(GameObject)

```

after game is reloaded

# Answer
> 1 votes
When you unload a scene, any object in that scene that was not marked `DontDestroyOnLoad()` (or not parented under a root object marked this way) will be destroyed. It doesn't matter whether another object still holds a reference to it. If you didn't tell Unity you wanted it exempted from the scene unload, then it will be destroyed just like everything else in the scene. That leaves a hole where it used to be - the "Missing (Game Object)" links you're observing.

The reason that you *seem* to still see the object in your scene is because you're reloading the same scene. So that spawns *new copies* of the leaderboard, etc. But the leaderboard that exists in the current scene is *not* the one your object was referencing.

If you have a cluster of objects that all depend on one another, then if you mark one as `DontDestroyOnLoad`, you'll probably want to mark *all* of them that way, to ensure they get preserved together. One simple way to do this is to put them under one root object.

* Persistent Objects (Marked `DontDestroyOnLoad()`, contains your script referencing the others)
    + Canvas
        - Leaderboard Panel
        - etc...

By marking the root object as not to be destroyed, the other objects under it won't be destroyed either.

Using `DontDestroyOnLoad` this way gets messy though, because when you re-load the same scene, you'll still get new copies of these objects, in addition to the surviving object that evaded destruction when the scene was unloaded. You can fix this by deleting the copies on scene load, or by moving these long-lived objects to their own scene that you load additively, and never unload/reload, so you never have to fuss with `DontDestroyOnLoad` in the first place.

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


# Question
Title: Efficient sprite animation display methods?
I'm making a game sprite, with animations for transitioning to different states, such as idle, sleeping, etc. I'm wondering what the most efficient way to play the animations is. As of now, I have a couple of ideas:

* store all frames as separate PNG images, and display only the frames for the current state (e.g. play frames 1-5 for idle, 5-10 for transitioning, 10-15 for sleeping)
* make the animations into GIFs and play the one corresponding to the current state.
* merge them all into a spritesheet.

Please let me know which would be the best approach, or if there's a better way to do things. I'm new to handling images and animation with code, so I'm not sure what the advantages and disadvantages are. Thanks!

In case the information helps anyone, I'm planning to use Python for this (although I could also do Java or C++, if there are good solutions in those languages), and the sprite image size isn't large, it's pixel art.

# Answer
> 0 votes
Storing all frames from every image as one large image allows for the hardware to use the same material/shader/texture for every animation and avoids context switching.

Then it's just a matter of calculating a frame's bounds in UV space (or pixel space if the graphics library you're using doesn't support UVs) given a frame index or its coordinates.

---
Tags: animation, sprites, python, spritesheet
---


# Question
Title: How to make my draggable object always on top and can move freely?
why my object is behind another object and also disappear when dragging around like this

as you can see the item or draggable object is always behind the second one, also behind all panel like this

this is my draggabe script :

```
public event Action<PointerEventData> OnBeginDragHandler;
public event Action<PointerEventData> OnDragHandler;
public event Action<PointerEventData, bool> OnEndDragHandler;
public bool FollowCursor { get; set; } = true;
public Vector3 StartPosition;
public bool CanDrag { get; set; } = true;

private Color backgroundColor;
[SerializeField] private Image backgroundImage;

public RectTransform rectTransform;
public Canvas canvas;

private void Start()
{
    rectTransform = GetComponent<RectTransform>();
    canvas = FindObjectOfType<Canvas>();
    backgroundImage = GetComponentInChildren<Image>();

    backgroundColor = backgroundImage.color;
}

public void OnBeginDrag(PointerEventData eventData)
{
    backgroundColor.a = .4f;
    backgroundImage.color = backgroundColor;

    if (!CanDrag)
    {
        return;
    }

    OnBeginDragHandler?.Invoke(eventData);
}

public void OnDrag(PointerEventData eventData)
{
    backgroundColor.a = 1f;

    if (!CanDrag)
    {
        return;
    }

    OnDragHandler?.Invoke(eventData);

    if (FollowCursor)
    {
        rectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor;
    }
}

public void OnEndDrag(PointerEventData eventData)
{
    backgroundColor.a = 1f;
    backgroundImage.color = backgroundColor;

    if (!CanDrag)
    {
        return;
    }

    var results = new List<RaycastResult>();
    EventSystem.current.RaycastAll(eventData, results);

    _DropArea dropArea = null;

    foreach (var result in results)
    {
        dropArea = result.gameObject.GetComponent<_DropArea>();

        if (dropArea != null)
        {
            break;
        }
    }

    if (dropArea != null)
    {
        if (dropArea.Accept(this))
        {
            dropArea.Drop(this);
            OnEndDragHandler?.Invoke(eventData, true);
            return;
        }
    }

    rectTransform.anchoredPosition = StartPosition;
    OnEndDragHandler?.Invoke(eventData, false);
}

public void OnInitializePotentialDrag(PointerEventData eventData)
{
    StartPosition = rectTransform.anchoredPosition;
}

```

## What I've tried

* I already using this `rectTransform.SetAsFirstSibling();` like Digiti said
* also using `gameobject.transform.SetParent(rectTransform)` onBeginDrag and using `gameobject.transform.SetParent(blankRectrasform)` onEndDrag but the draggable it cant move am I doing wrong

this script after adding those :

```
 public event Action<PointerEventData> OnBeginDragHandler;
public event Action<PointerEventData> OnDragHandler;
public event Action<PointerEventData, bool> OnEndDragHandler;
public bool FollowCursor { get; set; } = true;
public Vector3 StartPosition;
public bool CanDrag { get; set; } = true;

private Color backgroundColor;
[SerializeField] private Image backgroundImage;

public RectTransform rectTransform;
public RectTransform blankRectrasform;
public Canvas canvas;

private void Start()
{
    rectTransform = transform.parent.GetComponent<RectTransform>();
    blankRectrasform = GameObject.FindGameObjectWithTag("fp").GetComponent<RectTransform>();
    canvas = FindObjectOfType<Canvas>();
    backgroundImage = GetComponentInChildren<Image>();

    backgroundColor = backgroundImage.color;
}

public void OnBeginDrag(PointerEventData eventData)
{
    backgroundColor.a = .4f;
    backgroundImage.color = backgroundColor;

    if (!CanDrag)
    {
        return;
    }

    OnBeginDragHandler?.Invoke(eventData);

    gameObject.transform.SetParent(blankRectrasform);

    rectTransform.SetAsLastSibling();//Becomes last in parent
}

public void OnDrag(PointerEventData eventData)
{
    backgroundColor.a = 1f;

    if (!CanDrag)
    {
        return;
    }

    OnDragHandler?.Invoke(eventData);

    if (FollowCursor)
    {
        rectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor;
    }
}

public void OnEndDrag(PointerEventData eventData)
{
    backgroundColor.a = 1f;
    backgroundImage.color = backgroundColor;
    if (!CanDrag)
    {
        return;
    }

    gameObject.transform.SetParent(rectTransform);

    var results = new List<RaycastResult>();
    EventSystem.current.RaycastAll(eventData, results);

    _DropArea dropArea = null;

    foreach (var result in results)
    {
        dropArea = result.gameObject.GetComponent<_DropArea>();

        if (dropArea != null)
        {
            break;
        }
    }

    if (dropArea != null)
    {
        if (dropArea.Accept(this))
        {
            dropArea.Drop(this);
            OnEndDragHandler?.Invoke(eventData, true);
            return;
        }
    }

    rectTransform.anchoredPosition = StartPosition;
    OnEndDragHandler?.Invoke(eventData, false);
}

public void OnInitializePotentialDrag(PointerEventData eventData)
{
    StartPosition = rectTransform.anchoredPosition;
}

```

# Answer
UI RectTransfroms display in a top(behind) to bottom(front) order. Try to set up your draggable items panel in front of all others (last in hierarchy), and use rectTransform.SetAsLastSibling(); in OnBeginDrag();

```
public void OnBeginDrag(PointerEventData eventData)
{
  backgroundColor.a = .4f;
  backgroundImage.color = backgroundColor;

if (!CanDrag)
{
    return;
}

rectTransform.SetAsLastSibling();//Becomes last in parent

OnBeginDragHandler?.Invoke(eventData);
}

```

For further in-frontness, use an empty RectTransform panel as the last in your panels in heirarchy. Reference it in code, and parent the object to it while OnDrag() using transform.SetParent(frontPanel), and reset it to original parent OnEndDrag() using transform.SetParent(originalPanel);
> 2 votes

---
Tags: unity
---


# Question
Title: Weird blue shine on URP Lit shader Unity
I recently started to use URP and I am noticing a weird blue like tint on shiny objects that use the URP/lot shader and I can't understand what it is and how can i remove it.

# Answer
This appears to be colored light emitted by the skybox.

When you don't want the skybox to act as a light source with the color of its textures, then

1. Open the lighting window (Menu entry Windows-\>Rendering-\>Lighting)
2. Go to the "Environment" tab
3. Change the "Source" under "Environment Lighting" from "Skybox" to "Gradient" or "Color". You can then select the color of the ambient light. If you don't want any ambient light at all, set the ambient color to pure black.

It is also possible that this isn't actually ambient light, but actually a reflection of the skybox. This would explain why it only appears on "shiny" objects. When you want reflections on specular materials to reflect the actual environment around them, then make sure you scatter some reflection probes around your scene. But keep the performance concerns in mind.
> 3 votes

---
Tags: unity, lighting, unity-urp
---


# Question
Title: how to check previous scene in scene manager in unity 3d
I'm trying to make my first game using unity 3d and I'm trying to make a game over the scene that when you press the `try again?` button it should take you back to the previous scene, I was thinking of just making it with the code `SceneManager.GetActiveScene().buildIndex - 1));` then just place one after every level on the build index so that it takes to the previous level that the player was in, but I think this would just increase the file size (Idk if it actually does), so I was wondering if there is a more efficient manner on how to do this so that I could only have one Game Over Scene in the Build Index?

# Answer
> 2 votes
Presumably you considered storing your scene index just before loading the game over scene, and then returning to the stored index? Something like...

```
public class GameOver : MonoBehaviour {
    static int _lastSceneIndex;

    public static void GoToGameOverScene() {
        _lastSceneIndex = SceneManager.GetActiveScene().buildIndex;
        SceneManager.LoadScene("Game Over");
    }

    public void ReturnToLastScene() {
        SceneManager.LoadScene(_lastSceneIndex);
    }
}

```

Now code in any other scene can call `GameOver.GoToGameOverScene()` to transition to the game over scene while remembering the scene it came from. Your try again button can call `ReturnToLastScene()` to go back.

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


title: Why I'm getting null?

text:
# Question
Title: Why I'm getting null?
Not what is null but why I'm getting it if I'm adding first the LineRenderer component ?

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

public class DrawLines : MonoBehaviour
{
    // Apply these values in the editor
    public Transform target;

    private LineRenderer lineRenderer;

    void Start()
    {
        gameObject.AddComponent<LineRenderer>();
        lineRenderer.gameObject.GetComponent<LineRenderer>();

        // set the color of the line
        lineRenderer.startColor = Color.red;
        lineRenderer.endColor = Color.red;

        // set width of the renderer
        lineRenderer.startWidth = 0.3f;
        lineRenderer.endWidth = 0.3f;

        // set the position
        lineRenderer.SetPosition(0, transform.position);
        lineRenderer.SetPosition(1, target.position);
    }

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

    }
}

```

The null exception is on the line :

```
lineRenderer.gameObject.GetComponent<LineRenderer>();

```

Before adding the linerenderer component I tried to use the attribute :

```
[RequireComponent(typeof(LineRenderer))]

```

And then tried to get it as compoment in the Start but also it gave me null exception.

# Answer
```
gameObject.AddComponent<LineRenderer>();
lineRenderer.gameObject.GetComponent<LineRenderer>();

```

You haven't assigned a value to `lineRenderer`, so it's still null and you can't access its `gameObject` property.

Do this:

```
lineRenderer = gameObject.AddComponent<LineRenderer>();

```

Note that you do not need the `GetComponent<>()` line at all.
> 0 votes

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


# Question
Title: Why is my tessellation output failing to reach my geometry shader?
I'm attempting to render grass using GLSL tessellation and geometry shaders. For vertex input, I'm using position and normal. For reference, here's an image of the grassy field *without* tessellation (just vertex, geometry, and fragment shaders). The geometry shader transforms individual points on the underlying mesh to rotated quads.

So, on to the tessllation step. Here's the vertex shader I'm using:

```
#version 440 core

in vec3 vPosition;
in vec3 vNormal;

out vec3 hPosition;
out vec3 hNormal;

void main()
{
    hPosition = vPosition;
    hNormal = vNormal;
}

```

Next up is the tessellation control (TC) shader. I'm passing position and normal through unchanged. Tessellation levels are hardcoded for testing purposes.

```
#version 440 core

layout (vertices = 1) out;

in vec3 hPosition[];
in vec3 hNormal[];

out vec3 ePosition[];
out vec3 eNormal[];

void main()
{
    ePosition[gl_InvocationID] = hPosition[gl_InvocationID];
    eNormal[gl_InvocationID] = hNormal[gl_InvocationID];

    if (gl_InvocationID == 0)
    {
        gl_TessLevelOuter[0] = 3;
        gl_TessLevelOuter[1] = 3;
        gl_TessLevelOuter[2] = 3;
        gl_TessLevelInner[0] = 3;
    }
}

```

The next stage is tessellation evaluation (TE). Here's my shader:

```
#version 440 core

layout (triangles, equal_spacing, cw) in;

in vec3 ePosition[];
in vec3 eNormal[];

out vec3 gPosition;
out vec3 gNormal;

void main()
{
    gPosition = tessLerp(ePosition[0], ePosition[1], ePosition[2]);
    gNormal = normalize(tessLerp(eNormal[0], eNormal[1], eNormal[2]));
}

```

Where `tessLerp` is defined as follows (applying barycentric coordinates):

```
vec3 tessLerp(vec3 v0, vec3 v1, vec3 v2)
{
    return v0 * gl_TessCoord.x + v1 * gl_TessCoord.y + v2 * gl_TessCoord.z;
}

```

My goal, then, is to have the output of the TE shader feed into the geometry shader, at which point the geometry and fragment shaders are unchanged from the non-tessellated version above. As input, the geometry shader takes `layout (points) in;`. Instead, I'm getting nothing (the curved green mesh itself is rendered separately from the grass):

Some common answers I've found in similar questions that I'm confident are *not* the problem here:

* I'm calling `glPatchParameteri(GL_PATCH_VERTICES, 3);` before rendering.
* My draw call is already using `GL_PATCHES` rather than `GL_POINTS` (used for the non-tessellated version). The specific draw call is `glDrawElementsBaseVertex(GL_PATCHES, indexCount, GL_UNSIGNED_INT, (void*)0, 0);`, where `indexCount` is the number of indices bound in the element array buffer for the mesh.
* In the TC shader, I've tried `layout (vertices = 3) out;` rather than 1. My understanding is that using 3 causes indices to be computed (in order to form triangles), which I don't need for my purposes (since each tuft of grass is built from a single point).
* From the vertex shader through the TC and TE, vertex positions are left unmodified from the base mesh (rather than being transformed to clip space). Instead, it's the geometry shader that applies the view-projection matrix when emitting four vertices to form a quad.

My understanding is that by rendering in this way (indexed) and with `GL_PATCH_VERTICES` set to 3, OpenGL will group every three vertices (i.e. each triangle) into a patch. Each triangle's data (three vertices, each containing position and normal) is passed from the TC shader to the TE shader (with primitive generation in between), then the TE shader computes new data (position and normal) by multiplying each tessellated vertex against barycentric coordinates. This results in a series of vertices that are passed to the geometry shader. Clearly, either my understanding is wrong or I've configured something incorrectly.

**Why is my tessellated output not reaching my geometry shader?**

# Answer
> 0 votes
I solved it!

1. Rather than `layout (triangles, equal_spacing, cw) in;`, I used `layout (triangles, equal_spacing, cw, point_mode) in;` (note the fourth `point_mode` parameter). See the Khronos documentation at https://www.khronos.org/opengl/wiki/Tessellation\_Evaluation\_Shader (specifically sections 1.3 and 1.4 regarding primitive ordering and primitive generation).
2. By itself, this caused the grass to reappear, but only the first entry in the TE shader's input arrays was populated. This resulted in interpolated grass tuft positions (using the `tessLerp` function) to lerp from the origin, as pictured below (the origin in this screenshot is the top-center of the central pillar):

To fix this, I changed `layout (vertices = 1) out;` in the TC shader to `layout (vertices = 3) out;`, resulting in proper interpolation.

So, to summarize, the reason my tessellation output wasn't reaching my geometry shader seems to have been that **my geometry shader was expecting points, but the TE shader was outputting triangles.**

---
Tags: opengl, shaders, glsl, geometry-shader, tessellation
---


title: Octree Terrain Destruction and LODs

text:
# Question
Title: Octree Terrain Destruction and LODs
Meet my octree world:

My end goal is to have this world destructible, and I am having an issue warping my head around how this can be done when you have LOD. The basic principle of LOD (as I understand it) is to collapse nodes that are further away from the camera (removing them from RAM completely), and divide nodes that are closer (allocating new memory in RAM), by doing this you only have X amount of memory allocated at once.

The issue arrives when you think about how to generate the LOD back after collapsing the tree. The only way I can think of is to use the same Noise function to sample the tree at the node you are dividing (like in the initial generation of the world) and use that to figure out how the children of the tree need to look.

But what happens when a user has modified that node beyond the Noise function? How can you collapse the tree and then divide it down again while restoring the user's modifications?

(Is the only way to keep separate track of all voxels changed by the user?)

That's all folks, thanks :)

(Language: C++)

# Answer
The primary goal of LOD is to reduce the cost of *drawing* by not drawing unnecessarily fine detail. It is not usually about discarding information from RAM. In fact, in a conventional polygonal-model art style, it may mean using *more* memory to have low-detail and high-detail models ready to use as the camera moves.

In your case, since you have destructible terrain, you must either not use lower detail levels for modified areas, or *generate* low detail levels *from the modified terrain.* This is analogous to generating mipmaps automatically for a texture, only in 3D. Neither of these lets you discard the full-detail state from the octree — that is always needed, since players should be able to leave and come back to the same changes they made.

If you have a large modifiable world and you want to limit the amount of RAM used to a specific maximum, you must *save the modifications to disk and load them back* as the player(s) move about the world, like Minecraft does. This component of the system is entirely separate from rendering LODs.
> 3 votes

---
Tags: c++, voxels, octree, level-of-detail
---


# Question
Title: Scaling physics engines beyond single computational server
Currently working on a small home project of developing our own game. The game basics are just a straightforward space game, currently without any collision detection/resolution, just movement with position, velocity, and acceleration.

The game is an MMO(RPG), so currently designing & implementing the backend / server / platform side of things. So the only items we need to store right now for each object is linear and angular 3D vectors. we're doing this for the position, velocity, and acceleration. So far, so good.

The question now comes to scaling wise: let's say, a single container of the physics engine has the computational power to calculate 10 rooms of 1000 objects each. It continuously calculates the new velocity and positions of all the objects and that's about it. So what if we want to scale? I want to go to 20 rooms of 1000 objects, theoretically this seems straightforward: spin up another container and room 1-10 on container1, room 11-20 on container2.

However, what if one of those rooms in container1 suddenly goes to 5000 objects, this would mean container1 can no longer feasibly calculate this, so it should be moved (instantly) to container3.

The objects would all be stored on a redis in-memory database for purposes of speedily operations. The goal is to not have any limits to a single room or the amount of rooms, and just scaling the amount of containers based on the amount of total objects that are moving around in the whole game. Similarly, the scaling down should be handled as well, if 5 containers are each operating at 10% capacity, it should be moved to 1 container.

We were discussing things such as event bus where we insert a repeating event to "tick" on roomX, a container would take this event, look at the total amount of objects in the room, and then determine how much it can handle. The problem which we have here is that there's no guarantee the container will be done with tick\_0 when another container could be working on the same room for tick\_1.

Are there any other techniques we should consider doing to try and get this to figure out a scaling solution?

Other relevant things to mention:

* the rooms are unrelated to each other
* current programming language is Golang
* platform can be cloud agnostic (kubernetes with whichever pods are needed)
* client side will use an existing physics engine, as the client only has to draw the current room it's in
* physics engine is aimed to "tick" in between anywhere from 2-10/second, depending on the results and the computational cost of each item in the room

Looking for any help or pointers to get us underway with this issue! Places to discuss this would also be greatly appreciated.

Best regards

# Answer
You may follow the path of EVE Online and it's famous Time Dilation. The main idea is to slow physics down when there are too many objects.

Other less famous optimizations include clustering objects into bubbles: each bubble includes all objects that are close enough to interact. Consider a bubble to be an unit of containerization.

Another great issue of huge space battles is amount of network traffic. I'd look into deterministic physics and lock-step synchronization at early stages of development, before it's too late.
> 1 votes

---
Tags: architecture, design-patterns, physics-engine, scale
---


# Question
Title: Unity Editor extension to group scripts attached to an object
Let us suppose we have a game object which has hundreds of scripts attached. Now out of those hundreds we can pick out groups responsible for a specific functionality. E.g. there are 15 scripts responsible for moving on the ladder, there 20 scripts which control shooting, 10 scripts which control jumping, etc.

Now it becomes hard to navigate all the scripts when you want to see only a specific feature related scripts.

So, what I want to do is to add some kind of grouping separators in my Inspector view, which would separate groups of scripts from each other.

Of course I know about the following improvements:

* making the codebase structure reasonable by utilizing folders
* placing the scripts close to each other by reordering them in the Inspector view

But still I feel that having the separators would make my life easier.

E.g. as the red lines on screenshot separate script groups, I would like to have something similar in the editor:

I found some documentation related to my question: https://docs.unity3d.com/Manual/editor-PropertyDrawers.html. But it seems that I can only customize the look of a specific script or property, but not the Inspector view. Is it so?

# Answer
> 3 votes
I strongly recommend consolidating your scripts so that you don't have hundreds of components on one GameObject. There are many reasons not to get this carried away with components, some of which I mentioned in my comment. Breaking functionality into reusable components is good. Having 15 components for climbing a ladder and 10 components for jumping is getting carried away.

Property drawers are not the correct solution. What you want are custom Editor Windows.

```

class ShootWindow : EditorWindow {
    public static void  ShowWindow (GameObject target) {
        Assert.IsNotNull(target);
        ShootWindow window = EditorWindow.GetWindow<ShootWindow>();
        window.target = target;
    }

    private GameObject target;

    void OnGUI () {
        CShoot shoot = target.GetComponent<CShoot>();
        CShootMovement movement = target.GetComponent<CShootMovement>();
        //etc etc etc

        //Draw GUI for editing all of these components here
    }
}

```

You can display the window like this:

```
[CustomEditor(typeof(CShoot))]
private class CShootEditor : Editor {
    override void OnInspectorGUI() {
        base.OnInspectorGUI();
        if (GUILayout.Button("Show Editor Window")) {
            CShoot shoot = (CShoot)target;
            ShootWindow.ShowWindow(target.gameObject);
        }
    }
}

```

You can use a custom Editor Window for editing multiple components at once with a custom interface. However, if you have hundreds of components on each GameObject, expect to spend many many hours writing all of the relevant Editor Windows. Personally I think your time would be better invested consolidating some of your component scripts.

---
Tags: unity, editors
---


# Question
Title: Can I give prizes based on sharing a WebGL game link on Facebook?
I made a share to Facebook link for my WebGL Unity game and depending on when you share you get extra points. This is tied to a button which once pressed opens a new page to Facebook for sharing the link but at the moment when you press the button you get the extra points either way.

Is there a way to actually know when the content has been shared or not?

# Answer
> 1 votes
**You are not allowed to reward users for sharing**, since 2014, because it made for a completely awful experience for all of their friends. Before this rule, if you had a lot of gamer friends, all you'd ever see in your feed was these spammy incentivized share posts.

See https://webapps.stackexchange.com/questions/77969/is-rewarding-users-for-sharing-using-facebook-or-twitter-breaking-the-tos

# Answer
> 0 votes
1. Ask the player for their social media handle within your application
2. Open the window where they can share the content
3. Have the game contact a server you control
4. Have the server look up their social media account and confirm that they indeed shared the content

---
Tags: unity, unity-webgl
---


title: Unity Nav mesh lading data each frame

text:
# Question
Title: Unity Nav mesh lading data each frame
Hey all I had a question, I was looking into my game's performance and noticed this in the profiler:

Is there any way to optimize this such as pre-generating tiles so it doesn't have to do it each update :) ?

# Answer
> 1 votes
Your profiler hierarchy includes this entry:

```
Carving.ApplyResults

```

Carving is an optional feature where non-static obstacles can cut a hole into the NavMesh. Carving is expensive because it actually modifies the NavMesh, which is why Unity recommends only enabling Carving while an object is not moving.

If you have a moving `NavMeshObstacle` with Carving enabled and "Carve Only Stationary" *unchecked*, it's going to be carving and rebuilding part of the Nav Mesh frequently as it moves around (possibly every frame if the Move Threshold is low). That could explain the entries you're seeing in the profiler.

---
Tags: unity, performance, navmesh
---


title: How much is 2D geometry used in 3D?

text:
# Question
Title: How much is 2D geometry used in 3D?
I'm studying 2D geometry with eventual goal to study 3D geometry for building games - *very much looking forward to 3D!!*

Looking up on how to calculate hypotenuse of a right triangle in 3D I read that the the same 2D Pythagorean theorem can also be used in 3D right triangle to calculate the hypotenuse.

So now I'm curious on how much of the 2D geometry I'm learning right now will be reusable when I get to 3D?

By "**how much**" I mean

* Do devs throw away their 2D knowledge in 3D and use a whole new sets of formulas/theorems?
* Or almost all or at least 90% of 2D knowledge is reused in 3D?

# Answer
3D geometry is an extension of 2D geometry and a solid understanding of 2D geometry is useful in 3D development. Things can be more complex when shifting to 3D, but generally most things will remain familiar and can you can find the connections to their 2d counter parts. The Pythagorean theorem is a good example. In three dimensions, the distance between the points \\$(x\_1,y\_1,z\_1)\\$ and \\$(x\_2,y\_2,z\_2)\\$ is defined as:

$$d=\sqrt{(x\_1-x\_2)^2 + (y\_1-y\_2)^2 +(z\_1-z\_2)^2}$$

2D geometry is essentially 3D geometry restricted to a single Z plane. By restricted, we means all the z values must be fixed to some constant, \\$c\\$. And no matter what constant you choose, \\$c-c=0\\$, which means the distance formula simplifies as follows:

$$\begin{align} d&=\sqrt{(x\_1-x\_2)^2 + (y\_1-y\_2)^2 +(z\_1-z\_2)^2}\\ d&=\sqrt{(x\_1-x\_2)^2 + (y\_1-y\_2)^2 +(c-c)^2}\\ d&=\sqrt{(x\_1-x\_2)^2 + (y\_1-y\_2)^2 +0^2}\\ d&=\sqrt{(x\_1-x\_2)^2 + (y\_1-y\_2)^2} \end{align} $$ At the end, we arrive at the 2D version of the Pythagorean theorem that you've already seen.

On the other hand, rotations are one of the things that is significantly more challenging when moving from 2D to 3D. Not only are 3D Euler rotations messier than 2D, because of the additional degree of freedom they're not even a particular good way to represent general rotation in 3D.

Occasionally, you can get some nice optimizations by realizing that a particular 3D problem can be reduced to its 2D counterpart. And while somewhat anecdotal, every 3D game programming book I recall starts off 2D geometry summary before moving into 3D geometry. Most of your 2D geometry can be upcycled when moving to 3D.
> 1 votes

---
Tags: 3d, geometry
---


title: Duplicating actor in Unity

text:
# Question
Title: Duplicating actor in Unity
New to video game development and im working in unity on a Mac right now. I also have been using unreal on my pc figuring them both out. Im trying to (in unity) quickly copy prefabs by dragging them to different spots on mac? Basically the unreal engine equivalent to Alt + dragging your actor on windows. I've tried looking it up and shortcuts dont help and randomly pressing buttons and dragging is getting me nowhere fast

# Answer
> 0 votes
Ctrl+D (or Command-D on OSX) duplicates the selected objects/assets in-place.

You can then move the copies to a new location.

---
Tags: unity
---


title: How to perform right-angle pathfinding?

text:
# Question
Title: How to perform right-angle pathfinding?
I'm developing a procedural dungeon generator using pre-built rooms and currently I'm using A\* pathing to create corridors to connect one room's door to another room's door.

The problem with this is that the path is very jagged, like this:

whereas I'd prefer it to look like this:

It seems simple enough if only one turn is required, but say it has to connect to the bottom side of the 2nd rectangle, then another turn will be required. Is there any way to do some sort of pathfinding that prefers as straight of lines as possible?

# Answer
> 1 votes
The key idea is that A\* is a cost **minimization** algorithm. The standard use in path finding, seeks to minimize the total distance travelled.

In your case, you don't want to just get the shortest path, you want the shortest path with the *least number of turns*. You can accomplish that by including an additional cost for path decisions that introduce turns.

The most straight forward way to do this: when considering linking to a new node, compare its position to the node prior to the current node. If they differ in both x & y, there must be a turn, so a penalty is applied. If either the x or y is the same, no turn is added, so no additional cost would be applied.

For instance, say your path under consideration is: `... (5,7) (5,8)` and you are considering linking to the nodes: `(4,8)` `(5,9)` `(6,8)`.

The distance for each of these options is the same (it's 1). But `(4 8)` and `(6 8)` both require a turn whereas `(5 9)` maintains a straight path. So the *effective* distance for `(4 8)` and `(6 8)` would become `1 + penalty` and the *effective distance* would remain unchanged.

What value do you assign to the penalty? Usually you can simply set it to something a few orders of magnitude smaller than your unit distance and things will be fine. So for the example above, I might start with a penalty value of 0.0001.

There's a potential problem though: there's no way to differentiate costs that arise from actual distance as opposed to costs that arise from turns. By taking the simple approach, they're both just numerical values that get summed together. For most situations, this is just a theoretical problem. Using the values above, it would take 10000 turns to equal a unit distance.

A more robust solution would be to implement cost in a way that separated distance & turns. A 2d value, a tuple, a pair, a struct with 2 fields, etc. Then when comparing two values, you'd have something like this:

```
if(v1.d < v2.d)
 // v1 is less because it is less distance than v2
else if(v2.d < v1.d)
 // v2 is less because it is less distance than v1
else if(v1.t < v2.t)
 // v1 is less because it has the same distance, but fewer turns than v2
else if(v2.t < v1.t)
 // v2 is less because it has the same distance, but fewer turns than v1
else
 // v1 & v2 have the same distance & the same number of turns

```

Note that in either approach, we are never decreasing the final weights of the edges between nodes in the graph (they stay the same for straight connections or increase slightly for turns). This means that your A\* heuristic will still be admissible & doesn't require any changes. If instead of using a penalty for turns, we had tried to using a discount to straight connections, things wouldn't work out as nicely. We avoided that by working with rather than against the context of A\* - it's a minimization function, so we used it to minimize the total distance & number of turns.

---
Tags: javascript, procedural-generation, path-finding, tilemap, roguelikes
---


title: When should I publish my Steam page?

text:
# Question
Title: When should I publish my Steam page?
I developing my game, which still in alpha, and plan to sell it via Steam. I already applied to Steam partnership program and want to publish my 'coming soon' Steam page to start gather wishlists, but it on hold for now.

I don't have any promotional material yet, but people on social media positively reacting to gifs of my game. Is it good idea to publish Steam page right now with temporary thumbnail and screenshots of current version and then change everything later? Or should I make my page appealing first?

# Answer
Wait until what marketing materials you do have represent what the game will look like at launch. That way, people will be more interested in your game.

I also recommend reviewing the documentation for release and the review process, particularly Store Presence, Review Process and Release Process.

They explicitly state as part of the checklist that you need to have your store page (i.e. promotional materials) ready and approved before releasing and it must include images and/or footage of **actual gameplay available at launch**. You are discouraged from changing it later.

> (italizied emphasis mine)
>
> * **Your store page should only contain features and content that will be available at launch**
>
> You will need to remove screenshots, trailers, or features listed that contain content that are incomplete or planned to be implemented. *If you include content that's planned to be implemented later in your description section, it will need to be clear that the feature is currently not released*.
> * ...
> * **Your screenshots must only contain gameplay.**
>
> This means avoid using concept art, pre-rendered cinematic stills, or images that contain awards, marketing copy, or written product descriptions.
> 5 votes

---
Tags: marketing, steam
---


# Question
Title: Do we have events for +/- buttons for a serialized list?
Does Unity fire any events when the user clicks these buttons? Or is there a way how to hook up code to respond to these actions?

# Answer
> 3 votes
The answer is here - we can use OnValidate event - https://forum.unity.com/threads/do-we-have-events-for-buttons-for-serialized-list.1074768/

```
using System.Collections.Generic;
using UnityEngine;
public class TestListChangeEvent : MonoBehaviour
{
  private int previousCount = 0;
  public List<int> ints = new List<int>();
  private void OnValidate()
  {
    if (ints.Count != previousCount)
    {
      Debug.Log("change detected: " + ((ints.Count > previousCount) ? "more" : "less") + " items now.");
      previousCount = ints.Count;
    }
  }
}

```

Edit: To avoid an initial event, could serialize previousCount, or default that to -1, and in OnValidate if it's -1 just set it to the current count and return instead of checking.

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


# Question
Title: Are two non-exchangable currencies possible in an MMO?
Imagine an Adventure Coin and a Merchant Coin.

Adventure coins can be spent on training and equipment, at in-game shops, but cannot be transferred between players.

Merchant coins can be transferred between players, and are used for investing in land, ferries, mills, etc.

Do any existing MMORPGs have such a system?

How can this work in the face of "bad money drives out good"?

# Answer
> 1 votes
This is actually very common in MMORPGs. Lots of games use plenty of currencies which are not mutually exchangeable.

* There is usually only one general purpose currency which can be obtained very easily through various activities. It is usually used for player-player commerce and buying basic items and services from NPCs.
* When the game is free-to-play, then there is usually a currency which can only be obtained by investing real money and can then be used to acquire premium items which usually can not be acquired in any other way (at least not a feasible way).
* Some free-to-play games have a 3rd currency in between these two which can be achieved slowly (usually *very* slowly) through gameplay, isn't transferable and serves as an alternative way to pay for premium items.
* There are often a lot of auxiliary mechanics which reward the player with non-tradable tokens which can then be used to exchange them for unique items. These are often tied to time-limited events, rewards for PvP, faction loyalty activities or other activities in the game.

A good example to look at in this regard is the currently pretty popular Free-to-play title *Genshin Impact*. While it is technically not a massive multiplayer game, it borrows so many MMORPG mechanics that some people call it a "Single Player MMORPG". It has:

* *Mora*, the general purpose currency
* *Crystals*, the premium currency
* *Primogens*, the ingame-achieveable premium currency
* Two different flavors of *Fate* \- tokens for the gacha system of the game which can be bought with both *Crystals* and *Primogems*. There are also some very limited ways to acquire them ingame, making them another currency.
* *Stardust* and *Starglitter* \- consolidation prices for bad rolls in the gacha system which can be saved up and then exchanged for items.
* *Sigils*, reward tokens for exploration which can be exchanged for unique items at NPCs. Each region of the game world has its own sigils, and they are not interchangeable.
* *Resin* \- more of a resource than a currency. Replenishes over (real-) time and has to be paid for various ingame activities. Mostly a time-gate mechanic to slow down power-players and improve retention.
* Various tokens given out in time-limited events which can be exchanged for unique and not-so-unique rewards during those events.
* Probably a couple more I can not think of right now.

> How can this work in the face of "bad money drives out good"?

It works because the currencies are usually not interchangeable (at least not bi-directionally) and are used to pay for different things. When NPC A only accepts currency A, NPC B only accepts currency B, both NPCs have very different products and the currencies A and B can not freely be converted into each other, then both currencies have value.

---
Tags: game-design, mmo, economy
---


title: Unreal Engine Linux Support

text:
# Question
Title: Unreal Engine Linux Support
I use multiple game Engines, but havn't used Unreal engine for quite a while, Now with the recent changes in Unreal Engine there are quite some interesting features which would be interesting to use in games.

**However** I also recently heard that UE4 recently dropped build support for Linux. So my main 2 questions are 1. Did UE4 truly drop Linux build support? and if so 2. Is there a way to get Linux build support in the latest version of UE4?

I can check the first question myself but due to the large engine size and my slow network connection this would take very long, so I figured it would save a lot of time if someone who already has the newest version installed knew the answer.

# Answer
The Unreal Engine supports Linux OS. The official UE4 documentation contains a section that describes the installation procedure for Linux OS.
> 1 votes

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


title: Separating part of mesh facing upwards

text:
# Question
Title: Separating part of mesh facing upwards
I really hope you can help me fix this code:

```
List<Vector3> verticesToExport = new List<Vector3>();//vertices of the triangles facing upwards.
        List<int> trianglesToExport = new List<int>();//new triangle facing upwards.
        //meshToCut is the original mesh, then I just try to replace it with the new data.
        int[] triangles = meshToCut.triangles;
        Vector3[] vertices = meshToCut.vertices;

        for (int i = 0; i < triangles.Length; i += 3)
        {
            Vector3 corner = vertices[triangles[i]];
            Vector3 a = vertices[triangles[i + 1]] - corner;
            Vector3 b = vertices[triangles[i + 2]] - corner;

            float projection = Vector3.Dot(Vector3.Cross(b, a), Vector3.down);
            if (projection > 0f)
            {
                verticesToExport.Add(vertices[triangles[i]]);
                verticesToExport.Add(vertices[triangles[i + 1]]);
                verticesToExport.Add(vertices[triangles[i + 2]]);
                trianglesToExport.Add(triangles[i]);
                trianglesToExport.Add(triangles[i + 1]);
                trianglesToExport.Add(triangles[i + 2]);
            }
        }
        meshToCut.SetVertices(verticesToExport);
        meshToCut.SetTriangles(trianglesToExport, 0);//probably I'm doing wrong here!

```

It works great by retrieving the vertices facing up, and I guess the triangles too but when I put it into a mesh filter I believe the triangles are not in order...

1.The model I'm trying to separate; the triangles facing upwards.
2. This is what happens if I just take the vertices and triangulate them again. It proves that vertices are alright!
3. The result I get from the code above:

# Answer
> 0 votes
You're filling your `trianglesToExport` list with the indices these vertices had *in the original mesh*, rather than the indices they have in the new `verticesToExport` list.

A simple fix would be:

```
if (projection > 0f)
{
    // Fill the triangle index slots with the indices
    // where we're *about* to write our vertices.
    trianglesToExport.Add(verticesToExport.Count);
    trianglesToExport.Add(verticesToExport.Count + 1);
    trianglesToExport.Add(verticesToExport.Count + 2);

    // Then fill those slots with the vertices from the original mesh.
    verticesToExport.Add(vertices[triangles[i]]);
    verticesToExport.Add(vertices[triangles[i + 1]]);
    verticesToExport.Add(vertices[triangles[i + 2]]);

}

```

But note that the way you're doing this here, you're going to be copying any shared vertices multiple times.

We can solve this by adding a dictionary that stores the mappings between indices of vertices in the original mesh, and indices of those vertices in our new subset. When we encounter a vertex, we first check if we've already mapped it, and if so, return that mapping. If not, we add it to our new subset and store the mapping for when we revisit it next.

```
int GetNewIndex( Dictionary<int, int> oldIndexToNew, int oldIndex,
                 Vector3[] oldVertices,
                 List<Vector3> verticesToExport) {

    if (!oldIndexToNew.TryGetValue(oldIndex, out int newIndex)) {
        newIndex = vecticesToExport.Count;
        verticesToExport.Add(oldVertices[oldIndex]);
        oldIndexToNew.Add(oldIndex, newIndex);
    }
    return newIndex;
}

```

Prep an empty dictionary when you start the slicing process. Then your loop can look like...

```
if (projection > 0f)
{
    trianglesToExport.Add(GetNewIndex(oldIndexToNew, triangles[i],     vertices, verticesToExport));
    trianglesToExport.Add(GetNewIndex(oldIndexToNew, triangles[i + 1], vertices, verticesToExport));
    trianglesToExport.Add(GetNewIndex(oldIndexToNew, triangles[i + 2], vertices, verticesToExport));
}

```

Note that now we're not always adding three new vertices to the `verticesToExport` list for every triangle. Sometimes, some of the vertices are *already in the list*, and if so, we just re-use them by referring back to the existing index.

---
Tags: unity, c#, 3d-meshes
---


title: player teleporting into other levels

text:
# Question
Title: player teleporting into other levels
So I basically want to load another map once the player collides with a object, specifically a "Portal" in my game. Which is really making the player move onto other levels. I don't want to jumble up my code with a bunch of function like "go\_to\_level\_9" or something so I'm planning to use a list or dictionary or something. So how to those game devs out there do that? Code for main.py is here: https://pastebin.com/rpddq1MP. The part with the portal stuff, walls and a few others:

```
    for tile_object in self.map.tmxdata.objects:
        obj_center = vec(tile_object.x + tile_object.width / 2,
                         tile_object.y + tile_object.height / 2)
        if tile_object.name == 'player':
            self.player = Player(self, obj_center.x, obj_center.y)
        if tile_object.name == 'zombie':
            Mob(self, obj_center.x, obj_center.y)
        if tile_object.name == '#':
            Obstacle(self, tile_object.x, tile_object.y,
                     tile_object.width, tile_object.height)
        if tile_object.name in ['health', 'shotgun']:
            Item(self, obj_center, tile_object.name)
        if tile_object.name == 'portal':
            self.map = TiledMap(path.join(self.map_folder, tile_object.type))

```

how do you do it? I'm currently using Tiled and pygame so I'm also using pytmx.

Edit: When I run the code, it just gives me an error about my other file, tilemap.py.

Error: `File "D:\coding\my_coding_stuff\python\games\pygames\little rpg\tilemap.py", line 49, in apply return entity.rect.move(self.camera.topleft) AttributeError: 'TiledMap' object has no attribute 'rect'`

Tilemap.py:

```
import pygame as pg
import pytmx
from settings import *

def collide_hit_rect(one, two):
    return one.hit_rect.colliderect(two.rect)

class Map:
    def __init__(self, filename):
        self.data = []
        with open(filename, 'rt') as f:
            for line in f:
                self.data.append(line.strip())

        self.tilewidth = len(self.data[0])
        self.tileheight = len(self.data)
        self.width = self.tilewidth * TILESIZE
        self.height = self.tileheight * TILESIZE

class TiledMap:
    def __init__(self, filename):
        tm = pytmx.load_pygame(filename, pixelalpha=True)
        self.width = tm.width * tm.tilewidth
        self.height = tm.height * tm.tileheight
        self.tmxdata = tm

    def render(self, surface):
        ti = self.tmxdata.get_tile_image_by_gid
        for layer in self.tmxdata.visible_layers:
            if isinstance(layer, pytmx.TiledTileLayer):
                for x, y, gid, in layer:
                    tile = ti(gid)
                    if tile:
                        surface.blit(tile, (x * self.tmxdata.tilewidth,
                                            y * self.tmxdata.tileheight))

    def make_map(self):
        temp_surface = pg.Surface((self.width, self.height))
        self.render(temp_surface)
        return temp_surface

class Camera:
    def __init__(self, width, height):
        self.camera = pg.Rect(0, 0, width, height)
        self.width = width
        self.height = height

    def apply(self, entity):
        return entity.rect.move(self.camera.topleft)

    def apply_rect(self, rect):
        return rect.move(self.camera.topleft)

    def update(self, target):
        x = -target.rect.centerx + int(WIDTH / 2)
        y = -target.rect.centery + int(HEIGHT / 2)

        # limit scrolling to map size
        x = min(0, x)  # left
        y = min(0, y)  # top
        x = max(-(self.width - WIDTH), x)  # right
        y = max(-(self.height - HEIGHT), y)  # bottom
        self.camera = pg.Rect(x, y, self.width, self.height)

```

# Answer
> 0 votes
Sorry everyone for wasting your time, but I figured out I would just make new() take a extra parameter, map, and whenever player touches a portal, it will just load the map that's in the portal's type slot like this:

```
def new(self, map):
    # initialize all variables and do all the setup for a new game
    self.all_sprites = pg.sprite.LayeredUpdates()
    self.walls = pg.sprite.Group()
    self.mobs = pg.sprite.Group()
    self.bullets = pg.sprite.Group()
    self.items = pg.sprite.Group()
    self.map = TiledMap(path.join(self.map_folder, map))
    self.map_img = self.map.make_map()
    self.map.rect = self.map_img.get_rect()
    for tile_object in self.map.tmxdata.objects:
        obj_center = vec(tile_object.x + tile_object.width / 2,
                         tile_object.y + tile_object.height / 2)
        if tile_object.name == 'player':
            self.player = Player(self, obj_center.x, obj_center.y)
        if tile_object.name == 'zombie':
            Mob(self, obj_center.x, obj_center.y)
        if tile_object.name == '#':
            Obstacle(self, tile_object.x, tile_object.y,
                     tile_object.width, tile_object.height)
        if tile_object.name in ['health', 'shotgun']:
            Item(self, obj_center, tile_object.name)
        if tile_object.name == 'portal':
            self.new(tile_object.type)
    self.camera = Camera(self.map.width, self.map.height)
    self.draw_debug = False
    self.paused = False
    self.effects_sounds['level_start'].play()

```

---
Tags: collision-detection, python, pygame, levels
---


title: Skill button cooldown

text:
# Question
Title: Skill button cooldown
When a spell is on cooldown I display a "unfilling" black bar over the spell GUI until the cooldown is reached. Problem is when i have more than one second of cooldown the scale of the "unfilling" black bar getting strange outcome. I have found the calculation from this website https://gamedevelopment.tutsplus.com/tutorials/how-to-code-hud-cooldown-bars--cms-20983 at the article **Skill Buttons Cooldown**

```
float cooldownTime = 1000.0f; //milliseconds.
long elapsedTime = System.currentTimeMillis(); //This is called every second in the main loop
float cooldownEndTime = elapsedTime + cooldownTime;
guiTexture.scale.y = 0.06f; //The "unfilling" black bar over the sprite. 0.06 = cover the whole spell GUI
//When i try to change the scale of the "unfilling" black bar i use this code.
scale.y = (0.06f*(elapsedTime/1000)) - (((0.06f*(elapsedTime/1000))/cooldownEndTime) * elapsedTime);

```

I have tried to modify the calculation but I havent succeed. If anyone have tackle this problem before or can help me reache a soultion i would be grateful. Thanks

# Answer
Try this:

`elapsedTime` (current Java time always) over `cooldownEndTime` (predicted 1000ms in future) multiplied by maximum bar height 0.06f;

That is `scale.y = (elapsedTime/cooldownEndTime)*0.06f;` giving you a fraction scaled by a bar height.

Additionally \*- dividing elapsed time by 1000 or any fixed number is always going to give an unusual result, since System.currentTimeMillis() represents a number value of milliseconds since about 40 years ago today.
> 0 votes

---
Tags: java, mathematics, gui
---