# Question
Title: How to make a Unity slider sit over evenly spaced points?
I'm working on a timeline UI element in Unity, that looks like this:

I generate the bottom ticks by instantiating a number of times over the length of the parent RectTransform, and offsetting them on both sides inside the rectangle. This snippet is the general idea of how the ticks are instantiated:

```

// Take the 4 corners of the RectTransform.
// Think of the vertices of the Rectangle being spaced clockwise
// from BottomLeft (i.e. [0]) to BottomRight (i.e.[3])

float length = vertices[3].x - vertices[0].x;

// Because I want to inset the ticks by an amount
// I subtract the offset twice to keep my length correct
length = length - offset * 2;

// The number of ticks is an integer that is the count of a list.
// In order to make sure the spacing is even and stays within the boundaries
// of the timeline, we can identify the spacing between the ticks as follows:
// Visually represented below as well
float lengthBetweenTicks =  length / (ticks.count - 1)

```

The formula here for `a` is: `a = 20 / 16 - 1`

Anyway, the ticks are then created at the position:

```
Instantiate(tick, new Vector3(vertices[0].x + offset
    + lengthBetweenTicks * index, vertices[0].y,
    vertices[0].z),Quaternion.Identiy, transform);

```

This all is well and good, and the ticks sit where I want them to. This is all to say that the formula for spacing the ticks is reliant on an initial offset, and a distance between them calculated as the desired length divided by the number of ticks minus one.

**Backstory Over**

The next thing I would like to implement is to have a slider go to each tick as time passes, or a button is pressed skipping to the next tick. I don't care about tweening the value or anything pretty, I just need it to jump to the next position. I have tried using an Image component and a Mask component, but had issues and started using a Slider component with almost perfect success. The problem is that the slider seems to drift as it goes over the timeline:

The code I have use to adjust the slider is as follows:

```
float minimum = offset;
float maximum = length;
float increment = length / ticks.count + offset;

// Update slider value by increment
// For testing I just add the increment on Spacebar
// But it should be more like this
slider.value = increment * tickIndex;

```

*What would be the correct formula for the slider value to hit the center of a given tick, regardless of the index?*

Importantly, the value of a Slider is not a 0-1 range like Unity's Mask component, so that makes life a bit easier by not having to convert position back to percentages.

EDIT: Further testing has revealed to me the distance that the slider drifts changes on the screen resolution. I no longer think the formula is the problem, but I don't have a solution yet.

# Answer
> 3 votes
This solution sets the dots the same way as the rectFill of the slider with the anchors and should be reactive to the size of the slider. This script is currently placed on the slider. It is independent of the max slider value and the component displayed is the default slider with the slider knob deleted.

```
//offset in pixel
public float offset = 150f;
public int ticks = 3;
//your cicle icon
public GameObject tick;
public int tickPosition = 2;
//this is the fillArea of the slider
public Transform dotParent;

void Start() {
    float totalWidth = GetComponent<RectTransform>().rect.width;
    float offSetAmount = offset / totalWidth;
    float anchorDistance = (1f - 2 * offSetAmount) / (ticks - 1);
    for (int index = 0; index < ticks; index++) {
        GameObject spawnTick = Instantiate(tick, dotParent);
        spawnTick.GetComponent<RectTransform>().anchorMin = new Vector2(anchorDistance * index + offSetAmount, 0);
        spawnTick.GetComponent<RectTransform>().anchorMax = new Vector2(anchorDistance * index + offSetAmount, 0);
    }
    SetSpinner(tickPosition);
}

public void SetSpinner(int index) {
    float totalWidth = GetComponent<RectTransform>().rect.width;
    float maxValue = GetComponent<Slider>().maxValue;
    float offSetAmount = maxValue * offset/totalWidth;
    float lengthBetweenTicks = (maxValue - offSetAmount * 2) / (ticks - 1);
    GetComponent<Slider>().value = index * lengthBetweenTicks + offSetAmount;
}

```

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


title: Naming convention for loop modules

text:
# Question
Title: Naming convention for loop modules
Question about game engine object oriented design.

Let’s say I have an engine with a main loop, and many handlers that will be executed by the main loop every time on next iteration of main loop. So every handler will be invoked frequently, and can do necessary game logic that needs to be run in a loop.

Having many handler of the main loop, I can implement modular system, and separate different concerns in different handlers.

Every of this modules not necessary will have a visual representation on the scene, it just any process that should run in main loop.

What is name convention for such classes. I need to give some suffix for class. What is industry standard for naming class prefixes like that?

——

I saw few examples like:

```
while(true) {
   update(…)
   render(…)
}

```

Instead I would like to do something like:

```
loopHandler = [
  new UpdateGamePlayerPosition(),
  new UpdateAiPosition(),
  …
  new RenderScene(),
  new SendNetworkUpdates()
]

while(true) {
   for(loopHandler in handlerCollection) {
      loopHandler.execute(gameLoopEvent)
   }
}

```

——

The reason why I needs suffixes, it came from my web/enterprise experience. Let’s say I have a Player in the game, now I need to have a PlayerLoop to refresh his PlayerEntity state, also PlayerSceneObject for rendering, also I may need to transfer it over network, so I will have PlayerTransferObject, also I might want to save into save game file PlayerSaveObject.

# Answer
> 1 votes
Although all game loops have the same purpose, they're not all written in the same way; the way you're coding your loop is not an industry standard.

Thus, there is no industry standard for naming those classes.

The "typical" industry standard in this case is naming those classes in a way that you and your team easily and rapidly recognize and understand their purpose and intention.

---

If you think you need a suffix to organize your classes, you might as well consider using the concept of "namespace" and move all the classes that are intended for the same purpose into this namespace.

# Answer
> 0 votes
I didn’t find any naming convention yet, but I’ve used Loop as a suffix:

* UserInputLoop
* PlayerLoop
* AiBotsLoop
* RenderingLoop

---
Tags: architecture, software-engineering, game-loop, terminology
---


# Question
Title: Inheritance in Unreal C++. "GetOwningActor" doesnt return type "AMyPlayer"
```
void UAnimInstance_Player_PnC::NativeUpdateAnimation(float DeltaSeconds)
{
    Super::NativeUpdateAnimation(DeltaSeconds);

    APlayer_PnC* owningActor = GetOwningActor();

    if (owningActor != nullptr)
    {

    }
}

```

I realise this is more of a C++ type question than game dev specific, however I have noticed when I ask on Stack Overflow I get a C++ answer which is often not compatible with Unreal Engine way of doing C++.

I may be wrong, but I thought a child class has an "is a" relationship with its parent classes. So I thought that if I have `APlayer_PnC : public ACharacter` (which ACharacter is of course extending APawn , and then AActor), I would be able to 'find' it using the `GetOwningActor` function.

It gives the error `AActor* cannot be used to initialize type APlayer_PnC*` . I get it that I can just change that to AActor, but I need a variable that is part of the APlayer class.

What can I do to get access to a public variable in my `APlayer_PnC` instance.

The function I posted above is located in my custom AnimInstance class, which I have set my Player Blueprint to use and have re-parented the Anim Blueprint to my AnimInstance, but the variables do not show up.

I can post the full code if that will be of use, let me know.

Thanks

# Answer
The GetOwningActor returns an Actor. You need to cast to your specific class.

In this case: APlayer\_PnC\* owningActor = Cast\<APlayer\_PnC\>(GetOwningActor());
> 1 votes

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


# Question
Title: Is there a way to blend an opacity overlay in a "mix" like nature without using an FBO?
I have done this many times whilst using FBO's, but in this unique case i would prefer not to use an FBO.

I have tried a multitude of `gl.BlendFunc()` and `gl.BlendFuncSeparate()` variations and none of them comes close to the desired result. The color of the background and the overlay are the same, so basically all i want to do is to paint over the already drawn with the overlay texture.

When using `gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)` it works as expected for the text and button, but also makes makes the background darker, which i don't want.

I am not sure whether or not this is actually possible without using an FBO. I have a few rather complicated ideas of how to fix this, but i thought i would ask here in case there is a simple `gl.BlendFunc()` combination or something equivelant.

I have two things i would like "blended" together and provide the following results:

Before overlay:

Overlay:(alpha 1 in top and alpha 0 in bottom)

The desired result:

# Answer
> 0 votes
In order to get the effect you want, you need to provide *the background color* as one of the inputs — on a pixel-by-pixel basis, the blend function has no idea itself what is the text and what is the background, so you need to provide the background.

Use either your fragment shader, or the overlay texture's color channels, to produce the dark background color as the color that is being blended, together with the alpha ramp you already have. Then, a `(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)` blend, the same as you'd use for any texture-with-alpha, will get the result you want.

---
Tags: opengl
---


# Question
Title: Character rotation jitters when looking around
I want my character to walk around sphere like a planet, so in my script I rotate it according to the normal of a raycast and I also rotate my character on the Y axis when I look around with the mouse. When press play, I can look in any direction in front of me, left and right, but when my characters Y rotation gets closer to 180, the X and Z rotation start jittering.

```
    RaycastHit hit;
    Vector3 rayStart = new Vector3(0,-1,0) + transform.position;
    if (Physics.Raycast(rayStart, -transform.up, out hit, Mathf.Infinity))
    {

        Vector3 rotation = new Vector3(Quaternion.LookRotation(hit.normal).x,0, Quaternion.LookRotation(hit.normal).z);
        transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
        transform.eulerAngles = new Vector3(rotation.x,transform.eulerAngles.y,rotation.z);
    }

```

I also tried `transform.rotation = Quaternion.Euler(rotation.x,transform.eulerAngles.y,rotation.z);` but it changes nothing. If I remove the 3rd line, it works, so i'm guessing i'm assigning the rotation the wrong way ? Both the line to rotate the character according to the camera and the one to rotate it around the planet work individually, but not together.

# Answer
> 1 votes
This line extracts just 2 imaginary components out of a 4-dimensional quaternion:

```
Vector3 rotation = new Vector3(
                          Quaternion.LookRotation(hit.normal).x,
                          0,
                          Quaternion.LookRotation(hit.normal).z
                   );

```

In general, it is not safe to extract individual components of a quaternion like this. They're not angles like Euler angle triplets. They're individual components of a point on a unit sphere in 4 dimensions, so they don't really make sense without all 4 components.

Each quaternion component ranges from -1 to 1, so it's not really sensible to use as an angle in degrees here:

```
transform.eulerAngles = new Vector3(rotation.x,transform.eulerAngles.y,rotation.z);

```

It looks like instead you want to do something like this - using a trick I've covered in several past answers:

```
// Helper function to make an orientation whose local y+ direction matches "exactUp"
// and whose local z+ direction points as close as possible to "approximateForward".
Quaternion TurretLookRotation(Vector3 approximateForward, Vector3 exactUp)
{
    Quaternion zToUp = Quaternion.LookRotation(exactUp, -approximateForward);
    Quaternion yToZ = Quaternion.Euler(90, 0, 0);

    return zToUp * yToZ;
}

// ...

// Start your raycast below your position relative to your current orientation.
Vector3 rayStart = Transform.TransformPoint(Vector3.down);
if (Physics.Raycast(rayStart, -transform.up, out RaycastHit hit, Mathf.Infinity))
{
    // Match our vertical orientation to the surface under us, while
    // preserving our forward facing direction as best that allows.
    Quaternion matchSurface = TurretLookRotation(transform.forward, hit.normal);

    // Compute the rotation about our vertical axis according to mouse movement.
    Quaternion twist = Quaternion.Euler(0, Input.GetAxis("MouseX") * sensitivityX, 0);

    // Compose these two rotations to get our resulting orientation.
    transform.rotation = matchSurface * twist;
}

```

---
Tags: unity, 3d, quaternion, euler-angles
---


# Question
Title: Getting cameras from World to set up a static camera only game
I'm trying to use `ACharacter` for my characters, but the game uses ONLY static cameras (ie. they shouldn't even logically be attached to the mesh of the characters). But it seems Unreal's `ACharacter` will always have a camera spawned, there doesn't seem to be a way to disable it.

I've butchered code from this tutorial. It uses `SetViewTargetWithBlend` to change between the character's camera and the static one.

When I used that code, it crashed Unreal, and the reason I found was because he hard-coded '0' element of the found array. I added a check to see if array is empty and this stops the crash. Of course this means it is empty and hence the line inside the if block doesn't fire.

But it seems to me I have done exactly what they did in the tutorial. I have ensured that in the character BP I set the variable `fixed_camera_classtype`:

.h:

```
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "Camera/CameraComponent.h"

#include "Player_PnC.generated.h"

UCLASS()
class VOLCANOTOWN_API APlayer_PnC : public ACharacter
{
    GENERATED_BODY()

public:
    // Sets default values for this character's properties
    APlayer_PnC();

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

    UPROPERTY(EditAnywhere, BlueprintReadWrite)
    TSubclassOf<ACameraActor> fixed_camera_classtype;

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

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

    int movement_state = 0;
};

```

.cpp

```
#include "Player_PnC.h"
#include "Components/SkeletalMeshComponent.h"
#include "Camera/CameraActor.h"
#include "Runtime/Engine/Classes/Kismet/GameplayStatics.h"

// Sets default values
APlayer_PnC::APlayer_PnC()
{
    // Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

}

// Called when the game starts or when spawned
void APlayer_PnC::BeginPlay()
{
    Super::BeginPlay();

    //Cast to Player Character's PlayerController

    if (APlayerController* PlayerCharacterController = Cast<APlayerController>(GetController()))
    {
        //Array to contain found Camera Actors
        TArray<AActor*> FoundActors;

        //Utility function to populate array with all Camera Actors in the level

        UGameplayStatics::GetAllActorsOfClass(GetWorld(), fixed_camera_classtype, FoundActors);

        if (FoundActors.Num() != 0)
        {
            //Sets Player Controller view to the first CameraActor found
            PlayerCharacterController->SetViewTargetWithBlend(FoundActors[0], 0.0f, EViewTargetBlendFunction::VTBlend_Linear);
        }

    }

}

```

# Answer
> 0 votes
Ok well I did find a related question that has led me to almost fix my issue. https://stackoverflow.com/questions/39406118/why-getallactorsofclass-returns-empty

It appears I needed the `fixed_camera_classtype` to be ::StaticClass() somehow.

So far I have done this to get around it , but now I can no longer use my BP version of the camera.

```
if (APlayerController* PlayerCharacterController = Cast<APlayerController>(GetController()))
    {
        //Array to contain found Camera Actors
        TArray<AActor*> FoundActors;
        TSubclassOf<AFixedCameraActor> classToFind;
        classToFind = AFixedCameraActor::StaticClass();
        UGameplayStatics::GetAllActorsOfClass(GetWorld(), classToFind, FoundActors);

        if (FoundActors.Num() != 0)
        {
            //Sets Player Controller view to the first CameraActor found
            PlayerCharacterController->SetViewTargetWithBlend(FoundActors[0], 0.0f, EViewTargetBlendFunction::VTBlend_Linear);
        }
        else
        {
            UE_LOG(LogTemp, Warning, TEXT("foundactors.num is zero"))
        }

    }

```

# Answer
> 0 votes
As long as you've set your Subclass in your APlayer\_PnC Blueprint then you already have access to it in code. You don't need to get all actors of class.

Try this instead:

```
    if (APlayerController* PlayerCharacterController = Cast<APlayerController>(GetController()))
    {
        // Check a Subclass has been set in the Blueprint
        if (fixed_camera_classtype)
        {
            PlayerCharacterController->SetViewTargetWithBlend(fixed_camera_classtype, 0.0f, EViewTargetBlendFunction::VTBlend_Linear);
        }
    }

```

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


title: ue4editor.exe GPU selection

text:
# Question
Title: ue4editor.exe GPU selection
Even though I set ue4editor.exe to use integrated graphics on my laptop, it somehow ends up using the discrete nvidia gpu; is there a way to set the preferred gpu with the unreal suite?

# Answer
> 1 votes
there is a console variable for that: r.GraphicsAdapter

you can set in Engine.ini or DefaultEngine.ini

# Answer
> 1 votes
You need to set the `r.GraphicsAdapter=1` ( Choosing device 1 ) to `<Your Unreal Projects Folder>\Unreal Projects\MyProject5\Config\DefaultEngine.ini` inside the section `[/Script/Engine.RendererSettings]`.

Eg.:

##### Unreal Projects\MyProject5\Config\DefaultEngine.ini

```
[/Script/HardwareTargeting.HardwareTargetingSettings]
; quality settings
TargetedHardwareClass=Desktop
AppliedTargetedHardwareClass=Desktop
DefaultGraphicsPerformance=Maximum
AppliedDefaultGraphicsPerformance=Maximum

[/Script/Engine.RendererSettings]
r.GraphicsAdapter=1
; exposure control and tone mapping settings
r.Tonemapper.Sharpen=2
r.TemporalAA.Upsampling=True
...

```

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


# Question
Title: How to temporarily set additional system environment variable only in 'play' mode inside godot editor?
I'm learning godot with a laptop that has AMD discrete GPU. My OS is Arch Linux so if I want to use discrete GPU I have to set system environment variable `DRI_PRIME=1` temporarily. This can be easily done with **pygame**, just add following code:

```
import os

os.environ['DRI_PRIME'] = '1'

```

The game will launch using discrete GPU.

But if I want to do that in godot, I have to run it fully in discrete GPU, which means I have to use command `DRI_PRIME=1 godot` to launch it. It's now using discrete GPU to run game, but it takes 4-5 seconds to react to my input when I switch back from tutorial webpage from browser. That's because the discrete GPU will hang when switching out of godot, and I have to wait for it to respond. It will waste a lot of time if I frequently switch between godot and browser.

Is there any configuration to temporarily set system environment variable only in 'play' mode inside godot editor?

# Answer
Seems the solution that works so far is to write my own shell script.

Here's the script:

```
#!/bin/sh

export DRI_PRIME=1

if [[ $# -ge 1 ]]; then
    if [[ -f 'Scenes/'$1'.tscn' ]]; then
        godot -d Scenes/$1.tscn --position 400,300;
    else
        echo 'File doesn'\''t exist!';
    fi;
else
    echo 'Please specify main scene!';
fi

```

I wish godot team to provide cmdline feature inside editor ( / \__ \ )
> 2 votes

---
Tags: gpu, linux, godot-3
---


# Question
Title: Unreal Engine - Materials Import as Gray
I imported the .fbx files from here: https://www.cgtrader.com/3d-models/industrial/other/big-warehouse-pack into an Unreal Engine 4.27 project. All the meshes load in properly, but the materials are all gray. So I just have a bunch of gray shelves, boxes, etc...

Any thoughts on what I could be doing wrong?

# Answer
> 0 votes
I'm not exactly sure what happened, but I found a bunch of png files in a different folder, and some more fbx files in another one. I then combined the contents of all the folders, and imported them altogether at once, and it worked. I think the png files are used as textures for the materials associated to the meshes, which makes the models have their proper appearance.

---
Tags: textures, unreal-4, models, 3d-meshes, materials
---


# Question
Title: How to spawn the cubes on the terrain surface even if there is a hill on the terrain then spawn the cubes on the hill surface?
I have the following pieces of code:

```
void Update()
{
  SpawnThroughPlane();
}

```

And:

```
public void SpawnThroughPlane()
{
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (plane.GetComponent<MeshCollider>().Raycast(ray, out hit, Mathf.Infinity))
        {
            GameObject cube = Instantiate(prefabToSpawn);

            cube.transform.position = hit.point;

            Vector3 pos = cube.transform.position;
            pos.y = Terrain.activeTerrain.SampleHeight(cube.transform.position);
            cube.transform.position = pos;

            cube.transform.localScale = new Vector3(50, 50, 50);
        }
    }
}

```

This spawns cubes all around the terrain at position `0` on the Y-axis. But I want it to position the cubes at a height depending on the terrain elevation.

I'm not sure if I need another raycast, and how to use it for the cubes before positioning them.

I tried this but it's still not working:

```
public void SpawnThroughPlane()
{
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (plane.GetComponent<MeshCollider>().Raycast(ray, out hit, Mathf.Infinity))
        {
            GameObject cube = Instantiate(prefabToSpawn);

            cube.transform.position = new Vector3(hit.point.x,
                hit.point.y + 25, hit.point.z);
        }
    }
}

```

# Answer
> 3 votes
You don't really need the `Terrain.SampleHeight()` function, since `hit.point` already contains the information (i.e. the position on the Terrain) you're looking for.

```
public void SpawnThroughPlane()
{
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (plane.GetComponent<TerrainCollider>().Raycast(ray, out hit, Mathf.Infinity))
        {
            GameObject cube = Instantiate(prefabToSpawn);
            cube.transform.position = hit.point;
        }
    }
}

```

I used `TerrainCollider` instead of `MeshCollider` because I assumed you were working with Terrains, but the same criteria apply to Mesh colliders as well, provided some minor code edits.

The previous function places cubes on the terrain without applying an offset to `hit.point`, and this results in cubes penetrating the Terrain after positioning:

You can solve this new problem in different ways, but the main idea is moving the cube towards a certain direction for a certain distance so that it touches the Terrain without intersecting it.

### Offset-based approach

When a cube is placed, its bottom half is "inside" the Terrain but its top half is actually visible. Then, we can move it upwards for half its height with respect to the `hit.point`. To do so, just add an offset value when setting the `cube.transform.position`:

```
...
cube.transform.position = hit.point + 0.5f * Vector3.up;
...

```

We multiply `0.5` to a vector to define a distance along a given direction in space. Rather than hard-coding values, you can also compute object heights programmatically by using `Mesh.bounds` and then `Vector3.Scale()` to account for scaling as well.

This small tweak improves the final result, although polygons still penetrate each other when slopes are steep:

You could even use `hit.normal` in place of `Vector3.up` and apply the offset along a direction perpendicular to the hit surface. Rotating the cubes will look nice as well (I don't know if this is what you're looking for though):

### Intersection-based approach

Instead of positioning the cubes and adjust their position, you may use a different approach:

* Raycast onto the Terrain, and find out the `hit.point` of interest
* Assume a "safe" height from the terrain, e.g. 10 units, and consider the new position `Vector3 dropFrom = hit.point + 10f * Vector3.up`;
* Use the `Physics.BoxCast` function, with starting position `dropFrom` and direction `Vector3.down` (or a Ray pointing downwards).

This way, you are "dropping" a cube from atop of the Terrain and casting a geometric proxy downwards until a collision occurs. The cast results in a position a cube can be placed in without intersecting the Terrain:

# Answer
> 2 votes
SampleHeight method returns a value relative to the terrain space, more details can be found here

try this:

```
pos.y = Terrain.activeTerrain.SampleHeight(cube.transform.position) + Terrain.activeTerrain.transform.position.y;

```

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


# Question
Title: Should I dispose a NativeArray on application quit?
I have a `NativeArray` which stays alive during the whole game, using the `Persistent` allocator. Should I dispose it inside an `OnApplicationQuit` callback?

In the editor, Unity gives me the following leak detection error after I restart Play Mode:

```
A Native Collection has not been disposed, resulting in a memory leak. Allocated from:...

```

I don't understand how I can be causing a memory leak after my application quits. Is the OS not reclaiming everything already?

# Answer
> 2 votes
Yes, the OS releases leaked memory on exit. At least, this is what happens when a new application starts and the OS manages memory allocation for execution.

On the other hand, Unity's Play Mode happens within the IDE itself, which is already running when Play Mode starts. This is different from other engines (such as GameMaker Studio), which compile and run your game as an independent executable every time you need it.

I suppose the OS is dealing with actual memory management for Unity. And Unity is only managing memory for Play Mode at a high level. This allows Unity to provide a useful `NativeLeakDetectionMode` and memory leaks detection. Allocator types include `Temp`orary and `Persistent` allocation modes. Unfortunately, the related documentation is poor. One can find more information about `NativeArray`s on the Unity Forums, although that information will be coming from users rather than Unity devs.

In this forum thread, user **recursive** describes how different allocator types work. They say that `Temp`orary allocators will trigger warnings after few frames, whereas `Persistent` ones give more freedoms to the developers. This is likely due to Unity monitoring memory in Play Mode.

However, the IDE can make no assumptions on memory usage when an allocator works in `Persistent` mode. It doesn't know if that memory is needed for 10 frames or 10 minutes. Then, it delegates control to the developers, who aren't annoyed by warning messages but are in charge of disposing of memory when not needed anymore.

Leaked memory is still leaked memory − the longer an application runs, the more it keeps leaking. That's why Unity still triggers the warning. Better use `NativeArray<T0>.Dispose()`.

---
Tags: unity, c#, unity-dots, unity-job-system
---


title: Make a rigidbody walk around a planet

text:
# Question
Title: Make a rigidbody walk around a planet
I have my character with a rigidbody and attracted by the planet. I am trying to move it with its velocity. I tried this script:

```
    Vector3 x = Input.GetAxis("Horizontal")*transform.right*speed;
    Vector3 z = Input.GetAxis("Vertical")*transform.forward*speed;
    rb.velocity = new Vector3(x.x + z.x,rb.velocity.y,x.z+z.z);
    rb.AddForce(-transform.up * GravityForce);

```

and I have also tried with `transform.TransformDirection` but the result is the same. Everything goes well until I get to the middle of the planet, then my character stop going forward. Also, it sometimes stop sticking to the planet as if my character sometimes start going straight instead of going straight relative to its rotation around the planet.

# Answer
> 0 votes
As mentioned in the comments, this line:

```
rb.velocity = new Vector3(x.x + z.x,rb.velocity.y,x.z+z.z);

```

...always replaces the global x and z components of your velocity with this frame's input, so gravity can only ever accumulate freely on the global y axis, and player input in the direction facing global y is discarded.

It looks like you meant to do something like this, capturing the amount of velocity parallel to the *character's* y axis, and passing that through unchanged, while applying input parallel to the *character's* x and z axes.

```
float verticalSpeed = Vector3.Dot(transform.up, rb.velocity);

rb.velocity = transform.right   * Input.GetAxis("Horizontal") * speed
            + transform.up      * verticalSpeed
            + transform.forward * Input.GetAxis("Vertical")   * speed;

```

---
Tags: unity, 3d, rigidbody
---


# Question
Title: How can I get correct coordinates from a diamond isometric map created in Tiled?
I am rendering a diamond isometric map created in Tiled using `Monogame.Extended.Tiled` package.

Here is where I'm trying to spawn a player with an object at coordinates `224,224` on my map

Here is where it actually spawns within the game world.

I have some debug info at the top of the screenshot. `0, 0` in the gameworld is where the first tile is in the middle of the screen.

I understand how to get the correct coordinates when it is a staggered map. I know for a diamond it involves something with the halving the screen size and height but I'm personally stuck and have tried searching for this answer somewhere.

I just want to be able to convert the coordinates Tiled puts out, into the world space. If it comes to it, I will just use my own map renderer and go back to staggered but I would prefer not to.

My tiles are 64px wide, 32px tall

As usual, any help is appreciated and will provide any extra information.

---

# Edit

Here are updated screenshots with regards to the comment. I hope they're correct.

Below are tiles with the coordinates + origin. These are objects in Tiled where I wish to place something.

Here is where they are actually rendered.

I am confused as to why the origin is offset on the Y coordinate like that but this is rendered using `Monogame.Extended`.

# Answer
It looks like you want something like...

```
pixelY = tileHeight * (tileX + tileY)/2 + tileHeight;
pixelX = tileWidth  * (tileX - tileY)/2;

```
> 0 votes

---
Tags: monogame, isometric, coordinates, tiled, monogame-extended
---


title: Collision Resolution for Height Maps

text:
# Question
Title: Collision Resolution for Height Maps
GameDev StackExchange!

I've written height map collision detection into my game, but I've been struggling on how to get the resolution step to work well with player movement. (This is in 3D, by the way.)

The player is represented in the physics engine by a capsule, and the height map is essentially just a series of y-positions (heights) in a grid (2D array) representing (x,z) positions. When testing for a collision, I take all of the rectangular grid spaces that the player intersects with, then test the capsule for intersections against the two triangles that make up each grid space. (These triangle-capsule tests use the Separating Axis Theorem.) This approach allows the player to have multiple collision points, one with each triangle (e.g. one with a "ground" triangle below, keeping him from falling, and one with a "wall" triangle ahead, keeping him from walking farther forward).

However, this approach has issues. For example, if the player falls from a high place and lands on the boundary between two triangles, penetrating some distance into their faces, the direction of minimum penetration will be parallel to the ground rather than along the triangle normals. This causes the player to be pushed parallel to the ground and fall through the terrain instead of being caught.

I tried to solve this by constraining the triangles to force resolution to occur along the triangle's normal. This solves the floor-fall problem, but introduces new problems. (There's programming for you, huh?) For example, if the player jumps at a ledge but doesn't make it, the triangle at the top of the ledge will still force the player upwards, causing them to be pulled up above the terrain.

Note that, since I'm using a heightmap, I don't have any true walls and need a solution that works for slopes of any steepness. For example, the following case would also be problematic using the triangle normals as the sole basis of resolution:

At this point, I don't know how to best take the raw collision resolution data and modify/filter it to work as I would like. How can I get these collisions to work in a sensible manner for player movement?

(It may or may not be useful to note that I currently also have a modifier on the capsule that "flattens" the resolution directions to be either parallel or orthogonal to the capsule's local vertical direction, vertical being "from sphere to sphere." This facilitates things like allowing the player to walk up a ramp at angle without forcing them to input a diagonal direction to compensate for being pushed to the side.)

# Answer
So, it turns out that I was able to solve this satisfactorily just by reverting to resolving exclusively on normals, but then ignoring the collision entirely if the penetration depth was beyond a certain threshold. Since the objects can't move too far in a single time step, this led to the desired results.

If entities started moving too quickly, I would have to start breaking down the time steps into smaller chunks, but with that addition, I imagine that this would generalize well to any physics engine.

The bounty expires in eighteen hours, so if anyone has any last-minute ideas, I'd still love to hear them! Otherwise, I'll go ahead and accept my own answer on my own question on which I myself provided the bounty... which feels... really weird...
> 0 votes

---
Tags: movement, collision-resolution, heightmap
---


# Question
Title: How can I make a button active when all the items of my array have been displayed? (for a dialogue scene)
I've coded something in Unity using C# (see below) for a dialogue scene separate from the actual game. On the click of a button from the game, the player is taken to this dialogue scene where the dialogue starts playing. After the dialogue has finished playing, a new button, called "Return Button" appears and takes the player back to the game. However, I am having trouble with displaying the Return button. When I run this in my Unity project, it is able to go through all the dialogue correctly, but the Return button does not appear, thus the player is unable to return back to the game. How can I make it appear at the end of the dialogue?

This code is attached to an empty GameObject in the scene.

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

public class Dialogue : MonoBehaviour
{

    public TextMeshProUGUI textDisplay;
    public string[] sentences;
    private int index;
    public float typingSpeed;

    public GameObject continueButton;
    public GameObject endButton;

    void Start()
    {
        StartCoroutine(Type());
        endButton.SetActive(false);
    }

    void Update()
    {
        if (textDisplay.text == sentences[index])
        {
            continueButton.SetActive(true);
        }

        if (index == sentences.Length)
        {
            endButton.SetActive(true);
            SceneManager.LoadScene("Maze minigame");
        }
    }

    IEnumerator Type()
    {
        foreach(char letter in sentences[index].ToCharArray())
        {
            textDisplay.text += letter;
            yield return new WaitForSeconds(typingSpeed);
        }
    }

    public void NextSentence()
    {
        continueButton.SetActive(false);
        if(index < sentences.Length - 1)
        {

            index++;
            textDisplay.text = "";
            StartCoroutine(Type());
        }
        else
        {
            textDisplay.text = "";
            continueButton.SetActive(false);
        }
    }

    public void Return()
    {
        SceneManager.LoadScene("Maze minigame");
    }
}

```

Any help will be much appreciated!!

Thank you in advance!

# Answer
From the content of NextSentence the value of the index will never be over sentences.Length - 1. you have to check that index is equal to sentences.Length - 1 not sentences.Length inside the Update method
> 1 votes

---
Tags: unity, c#, 2d, unity-ui, scenemanager
---


# Question
Title: How to handle two player-programmed robots attempting to enter the same discrete grid cell in one game tick
I am making a game with discrete block positions (something like minecraft) where you can program robots with instructions to move around, the robots are the size of one block, and they can execute one instruction per game "tick".

There is a problem when two robots want to move to the same cell in the next game tick (the green squares are robots):

I can see three possible solutions, but all of them are not satisfying:

* The robots have an order in which their instructions are executed, so one robot will always have priority to move over the other -\> difficult to tell which robot has the priority, unless each robot have a number displayed on it
* The instructions are run in a random (or seeded pseudo-random) order, forcing the player to avoid these interlocked states -\> not consistent or not clear enough for the player
* Only one robot can move at a time -\> not interesting gameplay wise

As this is a programming game, the behavior of the programmed robots should be deterministic and predictable by the player. What would be the best way to handle this?

Some games don't handle this at all, in minecraft for example red stone behavior is non-deterministic and depends on factors the player cannot reason about.

# Answer
Some ways I've seen this solved:

## Treat a collision as a failure state

Zachtronics games like SpaceChem and Opus Magnum commonly go this route. The player is challenged to create a program that does *not* lead to a conflict or collision, and causing one immediately halts execution. The player can then observe the problem, modify the program/machine to avoid it, and re-run the execution from scratch.

An alternative version of this is to self-destruct robots that are in conflict, or turn them into permanent obstacles, but then allow the rest of the execution to continue if it can, rather than treating it as automatic failure. So there may be times when it makes sense to "sacrifice" robots this way, ending their execution while the rest of the distributed program marches on.

## Assign "right of way"

You can introduce a simple rule that if two (or more) robots' instructions for a given tick conflict, then one is deterministically given priority to execute, in a way that the player can easily work out which one that is without identifying characteristics on the robot.

One such rule is "The robot furthest to the east has priority. If two robots in the same east-most north-south column are in conflict, then the one furthest to the south has priority".

For any cluster of interacting robots, one column of them will always be furthest in the "east" direction of your map, and one robot in that column will always be furthest "south".

The rest of the robots in the conflicting cluster wait, effectively executing a no-op. You can decide whether they continue trying to execute the same instruction on the next tick, effectively delaying their program, or if the wait causes the instruction to be skipped and they resume at the *next* instruction after the conflict.

Other robots not in that conflicting cluster still execute their actions simultaneously, so you're not limited to only one robot moving at a time, which you'd raised as an issue with one of the potential solutions you identified.

## Sub-step in a predictable order

You could also allow all robots to act, but have them execute their actions consecutively within the tick rather than simultaneously when there's a conflict.

You'd use a rule similar to the right of way rule to assign an order of execution, like proceeding west to east, north to south. So the west-most robot on the north-most row of the conflict acts first, then the next one acts (possibly pushing the earlier one out of the way or destroying it) etc.

(This is equivalent to Ryan1729's suggestion in the comments)

## Conflict = wait

You could also choose to treat a conflict as "no move". The robots detect that they cannot all execute their action this turn, and the conflicting robots wait a tick instead to see if they can continue executing next frame.

(This is equivalent to Zibelas's proposal to execute the conflicting moves, then rebound and undo them, politely saying "after you")

Here you're hoping that another robot not in conflict, or some other change in the map like a moving conveyor/cycling door, results in a new state next tick that can resolve the conflict for at least one of the robots, giving them a chance to recover and continue. If the player has not arranged things so that the conflict is recoverable in this way, then this becomes a deadlock, similar to the "obstacle" variant of the failure state approach described above.

As with the "right of way" approach, you can decide if the stalled robots re-try the same instruction on the next tick, or skip it and advance to the next instruction instead.

## Fast forward

When there is a conflict, all conflicting robots immediately skip the conflicting instruction and try the next one. This might produce a new conflict, causing a subset of those robots to skip forward again.

You'd want to introduce a maximum skip depth, or detect when you've looped back around to the original conflict to prevent an infinite loop when trying to advance a single tick. If you exceed such a limit or discover such a loop, then you can fall back on any of the approaches above.

## Stacking robots

When two or more robots enter the same space, they stack! You can use a rule like the "sub-step" approach to decide the order in which they stack and which robot ends up on the bottom/on top.

Just what a stack means, you can determine:

* Robots that get driven over are destroyed, and only the robot at the top of the stack remains to continue executing its program next tick.
* Stacked robots continue executing their programs, and can be carried along with robots under them if they stay still, or can drive off the stack to un-stack themselves if they move.
* Stacked robots' programs are paused until an outside force un-stacks them (like the robot at the base of the stack driving under a bridge or past a magnet)
* Stacked robots merge, making the robot at the bottom of the stack more powerful (eg. able to push heavier objects or resist being pushed because it's heavier)

(The mobile puzzle game Trainyard implements a clever version of this that I'll avoid spoiling completely here. )
> 4 votes

# Answer
I think you can solve such a problem by introducing simple priority rules or additional gameplay elements. You may see these as instances of suggestions by DMGregory, so I'm just building up additional ideas on top of his answer.

### Collision as a failure, by design

> Who goes first? **Nobody.**

When two robots attempt to move into the same cell, a race condition occurs, and this can lead to a collision. Games such as RGB Express integrate collisions in their mechanics: puzzles must be solved by entangling actor paths without causing car accidents. This aspect prevails when trying to solve puzzles with a perfect solution (i.e. minimum distance possible).

If your game implements this mechanic, the player will always know what happens when crossing paths and will be required to avoid these scenarios. As a consequence, you must design puzzles accordingly.

**Edge cases:** None (I can think of), since this can also be considered a safe fallback case.

### Collision as a failure, with a loophole

> Who goes first? **Nobody, unless...**

Before thinking about priority rules, we let players solve possible collisions on their own. Since robots are programmed by players, they could get access to a **TryMove** command (as opposed to the base **Move**):

* **Move:** moves robots towards a direction, without further checks
* **TryMove:** IF the next cell is *going to be free next step* THEN move there ELSE perform actions

Example: the same scenario described in your question, the top robot (T) moves with **Move** and the left one (L) with **TryMove**. T is going to move from `(1,2)` to `(2,2)` no matter what; L is smarter: it knows that it can't move to `(2,2)` right away, then it does something else.

Possible *something else*s:

* Pause execution for the current step, then continue from the current **TryMove** instruction (wait until the cell is free/untargeted next step)
* Pause and wait, but **TryMove** switches to **Move** (only one chance to avoid collisions)
* Pause and wait up to *n* steps, then:
    + Switch **TryMove** to **Move** as above
    + Declare failure and halt execution

**Edge cases:** Two or more robots with a **TryMove** command meet each other: they could all halt or crash into each other.

### Crossroad priority

You could assume that robots perform commands provided by players, but have a certain degree of freedom when it comes to decision-making and conflict resolution. Their "firmware" may contain instructions to solve order execution when meeting other fellow robots along the path. These are similar to common driving rules that apply to drivers.

> Who goes first? **Major path first, minor path last.**

If paths aren't totally arbitrary, and your levels feature well-defined pathways, robots moving along main routes are entitled to go first. Then, robots crossing roads or merging to the main routes shall give priority to others before moving or turning.

**Edge cases:** Robots may attempt to move against the flow. Two robots try to perform the same action one opposite to another.

> Who goes first? **Oncoming traffic first, emerging traffic last.**

Similar to above, but priority goes to robots that didn't turn recently. Working with your example: if robot T turned around 5 cells from North before meeting robot L, which previously turned and moved for 10 more cells, then L goes first. This is because L was already travelling when it bumped into T.

**Edge cases:** If two robots previously moved for the same distance, this may cause a conflict (collision) or require a different fallback criterion.

> Who goes first? **Relative left/right first.**

In such a case, priority must be given to robots coming from one's left or right side. In your example, T goes first if priority is given to left-coming traffic; L goes first otherwise.

**Edge cases:** Four robots simultaneously approach the same cell from the four directions.

> Who goes first? **Heavy first/last, light last/first.**

If there're different types of robots, you can define priority based on their weight, size, role or any trait of choice. Heavy-duty machines may need to move first, or lightweight drones may have priority since they move faster and can disengage the crossroad first.

**Edge cases:** Two vehicles of the same type bump into each other: their priority can be determined by the next trait in the hierarchy, but for identical machines, priority may not be well-determined.

### Priority flags

> Who goes first? **Y'all don't, I DO.**

Players can mark certain units with a control flag which guarantees priority over any other robot. While priority flags are an added mechanic and a limited resource, they become useful when it comes to resolving conflicts amongst multiple robots:

* Three robots bump into each other from North, East and West
* Unit N is flagged for priority, while others aren't: N goes first
* Units E and W wait for N to move over, then resolve their mutual conflict by applying a different criterion

This is a variation of "Collision as a failure, with a loophole", but the game mechanic involved is a property rather than a different command for the robots.

**Edge cases:** A priority-flagged robot goes first, but its movement is effectively obstructed by the mere presence of another robot. Multiple priority-flagged robots are involved in the conflict.

---

Depending on your design needs, you may consider using one or more of the above solutions. They don't conflict with each other and can be also arranged in a hierarchy of criteria, where an always-safe fallback solution is reached when other measures have failed.
> 2 votes

---
Tags: game-design, game-mechanics, grid
---


# Question
Title: Generating consistent terrain chunks with unpredictable per-chunk seeds
I am working on an automatically generated (theoretically) infinite 2D world. The grid would be separated in chunks made of thousands of world tiles.

We plan to use a Perlin noise function to generate the islands and biomes within a chunk, so that the chunk is completely deterministic. It means that you need no other data than the chunk seed to know exactly how the terrain look like.

But some biomes would be really rare and we don't want people to be able to predict where they are going to appear. This is why we would like to use a randomly generated chunk seed everytime a player enters a new chunk.

We however have a problem:

What if a biome ends at the border of a chunk and the other chunk has a completely different generation? How could we avoid that?

# Answer
> 2 votes
For this answer, I'm going to assume that the inputs to your biome-selection process are just the elevations (or other measures like temperature/moisture) output from your Perlin noise function. If you're generating your biomes in a different way, be sure to edit your question to walk us through your current generation rules.

---

Perlin noise and similar functions are what's called gradient noise: they pseudo-randomly select a gradient at each lattice point, using the point's location and some seed information, and then interpolate a value between those gradients to fill the lattice cell between those corners.

So, as long as two chunks can agree on the gradients at those lattice points, then the rest will blend seamlessly. I show this in a couple of previous answers, for making a wrapping world and hexagonal tiles.

One way we can do this is to establish which chunk "owns" each lattice point. Say, a chunk owns every lattice point in its interior, and those lying exactly on its south and west edges. Its north and east edges are owned by the neighbouring chunk though - they're their south and west edges, respectively.

When we want to generate a pseudorandom gradient for a lattice point, we first check which chunk it's in, and use that chunk's seed in the pseudorandom selection. If we've never generated a seed for that chunk before, then we generate it now, on the fly, and save it. (That means you may have seeds stored for some chunks you've never visited, if they're immediately adjacent to one that you have)

And that's all - as long as the chunk you're in has access to the seeds of the neighbouring chunks, then you can generate it in a way that will be seamlessly consistent with them, even if you've never generated their interiors yet.

You may also be interested in Deterministic Procedural Wave Function Collapse for another way of approaching this chunk consistency problem, through different procedural tools, but with the same core approach: make sure they agree about the inputs to the generation function at the edges where they meet, and the output will match up seamlessly.

---
Tags: 2d, procedural-generation, terrain, maps, noise
---


# Question
Title: Detect what object was dropped onto, rather than the object being dragged
I want to make a simple drag and drop system in 2D in Unity.

When the user drags the object to a position, I want to check if the position is valid. As in I want the user to drag an object onto another object with a specific tag of my choice. If it's anything other than that, the dragged object should return to its original position.

My problem is that my current code for detecting the object I've dropped onto always detects the object I dragged instead. How can I modify this code to detect the object under it?

```
// The plane the object is currently being dragged on
Plane dragPlane;

// The difference between where the mouse is on the drag plane and
// where the origin of the object is on the drag plane
Vector3 offset;

Camera myMainCamera;

Vector3 originalPos;

void Start()
{
    myMainCamera = Camera.main;
    Physics2D.queriesStartInColliders = false;
    originalPos = gameObject.transform.position;
}

void OnMouseDown()
{
    collideCheck = false;
    dragPlane = new Plane(myMainCamera.transform.forward, transform.position);
    Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);

    float planeDist;
    dragPlane.Raycast(camRay, out planeDist);
    offset = transform.position - camRay.GetPoint(planeDist);
}

void OnMouseDrag()
{
    Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);

    float planeDist;
    dragPlane.Raycast(camRay, out planeDist);
    transform.position = camRay.GetPoint(planeDist) + offset;
}

private void OnMouseUp()
{
    //check if there is something at that position
    Collider2D hitColliders =
    Physics2D.OverlapCircle(transform.position, range);

    Debug.log(hitColliders);
    if (hitColliders.gameObject.tag == "p1")
    { transform.parent = hitColliders.gameObject.transform; }
    else
    { transform.position = originalPos; }
}

private void OnDrawGizmosSelected()
{
    Gizmos.color = Color.red;
    //Use the same vars you use to draw your Overlap SPhere to draw your Wire Sphere.
    Gizmos.DrawWireSphere(transform.position, 1);
}

```

# Answer
Use `OverlapCircleAll` to detect not just the dragged object's collider, but ALL colliders overlapping the circle, then check whether one of them has the target tag.

```
    Collider2D[] hitColliders = Physics2D.OverlapCircleAll(transform.position, range);
    foreach (Collider2D hit in hitColliders)
    {
        if (hit.gameObject.tag == "objectTaghere")
        {
            check = true;
            if (check)
            {
                transform.parent = hit.gameObject.transform;
            }
            break;
        }
    }

    if (!check)
    {
        transform.position = originalPos;
    }

```
> 0 votes

# Answer
Note that you can write the code from your answer much more cleanly as:

```
void OnMouseUp() {
    foreach (var hit in Physics2D.OverlapCircleAll(transform.position, range))
    {
        // "CompareTag" is more efficient than "tag =="
        if (hit.CompareTag("objectTaghere"))
        {
            transform.parent = hit.gameObject.transform;
            return;
        }
    }

    // We can get here only if no match was found.
    transform.position = originalPos;
}

```

No extra "check" variable needed.
> 0 votes

---
Tags: unity, collider, user-interface
---


title: Firearm magazine ejection

text:
# Question
Title: Firearm magazine ejection
I am playing around with a VR game where the player can fire a hand gun. When the magazine is empty they can press a button on the controller to eject the magazine from the gun. As its VR, I would like to have the player be able to pick up the magazine again, if they need to.

Currently when the eject button is pressed, the rigidbody of the magazine is enabled and it falls from the gun.

My question : The player can hold the grip side pointing up and the magazine will drop through the gun or hold the gun sideways and the same will happen.

If the player hold the gun in any of these orientations, the magazine needs be released but stay in the grip and only slide out as the gun is turned so that gravity pulls it.

My first instinct was to use code to animate the magazine and only enable the rigidbody when it leaves the gun. Another way to use 5 box colliders to emulate the walls of the grip and that way contain the movement.

I was just wondering if there was a better way to do this.

# Answer
> 2 votes
A Configurable Joint seems what you're looking for, as pointed out by DMGregory in this previous question.

I tried to implement a sliding magazine in a gun using the following setup:

* The `Weapon` GameObject is an entity with a `RigidBody` component (needed for configuring the Joint)
* The `Magazine` GameObject is a different GameObject and has a `RigidBody` as well

I made the following assumptions to make this system work:

* `Weapon`'s `RigidBody` has its property `isKinematic` set to True when being held by players - you attach it to their hand for interaction purposes. If dropped or thrown, `isKinematic` is set to False so that gravity can do the work
* `Magazine` behaves as follow:
    + **When inserted:** it is parented to `Weapon` and its `isKinematic` property is set to True. This way it will be integral with the weapon and move/rotate accordingly
    + **When reloading:** its parent is removed and its `isKinematic` is set to False, actually behaving as a generic physics-driven GameObject. However, its physics behaviour is influenced by a Configurable Joint that only allows sliding movement along a single direction

I managed to configure the Joint as follows:

Actual values depend on your actual `Magazine` dimensions. The main idea is to enable movement along the ejection direction only. By assigning a *Connected Body*, you can work in local coordinates.

I defined the `Connected Anchor` (the centre of the "track" the magazine moves along before being ejected) at a position such that, given an appropriate `Linear Limit` distance (in my case it's half the magazine's height), one end is the starting position of the magazine (same position as when inserted) and the other end is when the magazines starts falling:

Via script, when the magazine reached the bottom end, you can disable/remove the Joint to let the magazine free.

---
Tags: physics, rigidbody, collider
---


# Question
Title: Pygame : problem with calculating an angle between two points
I've been struggling to calculate the angle `alpha` between an object and a certain point M so that I can move that object to M.

To calculate alpha, I'm using trigonometry and more precisely the `atan2` function from the python math module :

```
class Obj:
...
    @property
    def alpha(self):
        return atan2(self.center[1] - my, self.center[0] - mx)

```

The problem I'm struggling with is that alpha, the calculated angle is not accurate. Take a look at this image :

So as the representation shows, in a situation where the obj and the point M are aligned, and that obj is on top of M, alpha is equal to 90 degrees !!

I can't understand why this happens. I know in math that a straight line is 180° or pi radians but not 90° !

Furthermore, if the point M was situated on top of the object on the screen, alpha will be negative.

What I want to do, is to suppose that the center of the obj is center of an 'imaginary' circle. Then, calculate the angle between the obj and M just like the image below shows :

This means that I want `alpha` to be equal to zero degrees if `M` is on the right of the `obj` forming a horizontal line, and I want it to be equal to 90° if M is on top of the obj forming a vertical line and so on ..

# Answer
> 0 votes
The problem turned out to be caused by flipped values in the `atan2` function's parameters.

So the alpha angle should be calculated by this expression :

```
atan2(self.center[1] - my, mx - self.center[0])

```

This will fix the flipped location of the axes. Now, the only issue that remains is that there are negative values that we need to get rid of. This can be done by this simple calculation as @DMGregory mentionned :

(alpha+360) % 360

---
Tags: mathematics, pygame, angles, trigonometry
---


# Question
Title: How to prevent blurry pixel art when the camera is following a character?
I'm developing a top-down pixel-art game and previously I was having the camera follow the player like this in the camera's update function (called every frame):

```
this.x = playerPos.x;
this.y = playerPos.y;

```

And that worked to have the camera follow the player. It would directly stick onto the player and cause no blurry visuals.

However, I read online that lerping the camera to make its movement smooth is often more desirable to the player. I found this excellent answer by DMGregory and implemented it like so:

```
let followSharpness = 0.1;
let blend = 1 - Math.pow(1 - followSharpness, Globals.deltaTime * 30);

let xOffset = playerPos.x - this.x;
let yOffset = playerPos.y - this.y;

this.x = Helpers.lerp(this.x, playerPos.x + xOffset, blend);
this.y = Helpers.lerp(this.y, playerPos.y + yOffset, blend);

```

Which *also* worked. The issue though is that now the character looks very blurry when the camera is following it. I'm not sure what is causing this, or even how to debug it. Some things I've noticed:

* When the camera catches up to the player sprite, the sprite is no longer blurry
* The player sprite seems more blurry than every other entity on the screen
* If the player stops moving, he is no longer blurry
* The player sprite only seems blurry when moving
* All entities have float positions, and so did the camera previously, so I don't think it has to do with that.

Anyone have any clue on why this might be happening, or how to solve it?

Edit: I've tried to take videos showing the difference:

Lerping: https://streamable.com/i7gxbe

Instant: https://streamable.com/n6awlz

Basically, the lerping video is using the aforementioned code in the post, and the instant code just does this:

```
this.x = playerPos.x;
this.y = playerPos.y;

```

My lerping function:

```
function lerp(a, b, t) { return a + (b - a) * t; }

```

My shader for drawing the sprite looks like this:

Vertex Shader:

```
void main() {
  gl_Position = vec4((u_cameraMatrix * u_transformMatrix * vec3(a_position, 1)).xy, 0, 1);

  v_texcoord = (u_textureMatrix * vec3(abs(u_flip - a_texcoord.x), a_texcoord.y, 1)).xy;
}

```

Fragment Shader:

```
void main() {
  outputColor = texture(u_texture, v_texcoord) * u_tint;
}

```

Here's the code that loads the image texture:

```
// creates a texture info { width: w, height: h, texture: tex }
// The texture will start with 1x1 pixels and be updated when the image has loaded
static loadImage(gl: WebGL2RenderingContext, url: string): TextureInfo {
  var tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  // Fill the texture with a 1x1 transparent pixel.
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([ 0, 0, 0, 0 ]));

  // let's assume all images are not a power of 2
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

  let textureInfo = new TextureInfo(1, 1, tex);

  var img = new Image();
  img.addEventListener('load', function() {
    textureInfo.width = img.width;
    textureInfo.height = img.height;

    gl.bindTexture(gl.TEXTURE_2D, textureInfo.texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
  });
  img.src = url;

  return textureInfo;
}

```

And here's the code that binds the texture:

```
gl.activeTexture(gl.TEXTURE0 + 0);
gl.bindTexture(gl.TEXTURE_2D, texInfo.texture); // this binds tex to TEXTURE0+0
gl.uniform1i(attribs.textureLocation, 0);

```

# Answer
> 0 votes
The blurry visual artefacts you are experiencing may be caused by how the rendering stack treats floating-point numbers when it comes to drawing sprites: world positions are floating-point numbers, pixels on the screen are not.

As a (blind) attempt to solve this issue, I suggest to change your interpolation function from this:

```
function lerp(a, b, t) { return a + (b - a) * t; }

```

To this:

```
function lerp(a, b, t) { return (1 - t) * a + t * b; }

```

The latter version guarantees to return `b` when `t = 1`, whereas the former doesn't due to floating-point arithmetic error.

In your particular case, `b` is the player position which the camera is trying to reach; small decimal differences may lead to rounding errors when rendering on the screen, which is the alleged cause of your current issue.

---

### EDIT

The external answer you included in your question refers to a piece of code which contains a comment:

```
// No need for the "if" - we'll practically never reach exactly 0 distance anyway.

```

This is an expected behaviour for two reasons:

* Interpolation, from a mathematical perspective, converges to a constant value after an *infinite* number of steps. I mean an *exact* value convergence, which can never be reached after a finite number of steps: 100000000000000000000000000000000 lerping steps are a huge amount, yet still finite. However, convergence occurs on computers due to machine error caused by the limited number of bits used to represent individual values
* Interpolation of a value towards another that changes over time (player is moving around) cannot really converge, since the target value changes more or less unpredictably each step

If you want to smooth your camera movement, you could fix its behaviour when it is close enough to the player, such as:

* Snapping camera position to the player's if the distance is smaller than a value such that it prevents undesired visual effects
* Taking explicit control of `t`, and change its value over time rather than over distance to make sure it equals `1`, and best follow the player object

---
Tags: javascript, camera, pixel-art
---


# Question
Title: Collision filtering in Box2D: running out of bits
I have a physical simulation on the streets of a city. The simulation is 2D but in a few points it could develop on multiple "layers": for instance bridges or underground tunnels. I may have up to 3 or very rarely 4 overlapping layers.

I think that using a 3D engine is overkill for this and could complicate things unnecessarily. A 2D engine like Box2D or similar should suffice. However Box2D and the other engines I checked out use a 16-bit mask for collision filtering.

If I divide those 16 bits in 4 submasks, one per each possible layer, I'm left with only 4 bits for filtering, which is not enough for my needs: I need more than 4 to implement other features.

Can you think of any solutions? Can I use those 16 bits in a smarter way? Should I use a 3D engine just for this? Can I tweak the filtering mechanism? Other solutions I could try?

# Answer
> 1 votes
If I'm not mistaken, Box2D also has the ability to store and simulate multiple independent Worlds.

So you could have one world for above-ground and a separate world for below ground, and transition objects from one world to the other at tunnel entrances/exits. This effectively means creating a new physics body for them in the new world, and destroying/recycling/disabling their old physics body. It's not as cheap as twiddling their collision filtering bits, so you'd want to choose where you split worlds carefully to minimize the traffic flux across the threshold.

You could also use one world with collision filtering for *most* traffic with up to 2 overlapping roads, and use the second world only for a tight vicinity around the rarer 3-4-way overlaps, and only for the least-travelled members of each cluster, to minimize the overhead this world-hopping introduces.

# Answer
> 1 votes
When I first used box2d I quickly reached the 16 bits limit :-)

Then I found a solution: you don't need to use all 16 bits, you need to categorize your objects.

For example, you have some grounds and solid platforms, you put them in the SOLID category.

You have many enemies, you put them in the ENEMY category.

...

An enemy is an enemy regardless of its abilities like size, speed... You will define those abilities upon creating them. For example:

```
if g_currentlevel == 1 then
    Nme_Flyer.new(xworld, {
        posx=xobject.x, posy=xobject.y,
        texpath="gfx/playable/Bob.png",
        animspeed=14, movespeed=8*0.6, jumpspeed=8*0.5, maxnumjump=2,
        density=1, restitution=0.5, friction=0,
        BIT=G_BITENEMY, COLBIT=nmecollisions, NAME=G_ENEMY,
        lives=1, nrg=1,
    })
elseif g_currentlevel == 2 then
    Nme_Flyer.new(xworld, {
        ...
        density=2, restitution=1, friction=0,
        BIT=G_BITENEMY, COLBIT=nmecollisions, NAME=G_ENEMY,
        lives=1, nrg=4,
    })
end

```

My complete set up looks something like this (please note **I am using Gideros framework, code is in Lua**):

```
-- here we store all possible objects name -- NO LIMIT
G_GROUND = 2^0
G_MVPLATFORM = 2^1
G_PTPLATFORM = 2^2
G_PLAYER = 2^3
G_PLAYER_BULLET = 2^4
G_ENEMY = 2^5
G_ENEMY_BULLET = 2^6
...
G_LADDER = 2^56 -- ;-)

-- here we define some category BITS (that is those objects can collide) -- 2^15 = MAX
G_BITSOLID = 2^0
G_BITPTPF = 2^1
G_BITPLAYER = 2^2
G_BITPLAYERBULLET = 2^3
G_BITENEMY = 2^4
G_BITENEMYBULLET = 2^5
G_BITSENSOR = 2^6

-- here is another trick (what can collide with what)
solidcollisions = G_BITPLAYER + G_BITPLAYERBULLET + G_BITENEMY + G_BITENEMYBULLET
playercollisions = G_BITSOLID + G_BITPTPF + G_BITENEMY + G_BITENEMYBULLET + G_BITSENSOR
playerbulletcollisions = G_BITSOLID + G_BITENEMY + G_BITENEMYBULLET
nmecollisions = G_BITSOLID + G_BITPTPF + G_BITPLAYER + G_BITPLAYERBULLET + G_BITENEMY
nmebulletcollisions = G_BITSOLID + G_BITPLAYER + G_BITPLAYERBULLET

```

This way you won't run out of bits **:-)**

**EDIT**: added the onBeginContact listener

```
function LevelX:onBeginContact(e)
    local fixtureA, fixtureB = e.fixtureA, e.fixtureB
    local bodyA, bodyB = fixtureA:getBody(), fixtureB:getBody()
    -- PLAYER1
    if (bodyA.name == G_PLAYER and bodyB.name == G_GROUND) or (bodyA.name == G_GROUND and bodyB.name == G_PLAYER) then
        if bodyA.name == G_PLAYER then bodyA.numfloorcontacts += 1
        else bodyB.numfloorcontacts += 1
        end
    end
    if (bodyA.name == G_PLAYER and bodyB.name == G_LADDER) or (bodyA.name == G_LADDER and bodyB.name == G_PLAYER) then
        if bodyA.name == G_PLAYER then bodyA.numladdercontacts += 1
        else bodyB.numladdercontacts += 1
        end
    end
    if (bodyA.name == G_PLAYER and bodyB.name == G_PTPLATFORM) or (bodyA.name == G_PTPLATFORM and bodyB.name == G_PLAYER) then
        if bodyA.name == G_PLAYER then bodyA.numptpfcontacts += 1
        else bodyB.numptpfcontacts += 1
        end
    end
...

```

---
Tags: collision-detection, box2d, layers, filtering
---


# Question
Title: Are there conventions on what exactly to log in a game?
I am currently developing a game in C++, using SDL2. For logging, I wrote this Log class:

*Log.h*

```
#ifndef LOG_H
#define LOG_H

#include "Singleton.h"

#include <fstream>
#include <string>

class Log : public Singleton<Log>
{
public:

    Log();
    ~Log();

    void regular_log(const std::string& msg); // writes to "file"
    void warning_log(const std::string& msg); // writes to "file", but adds [WARNING] prefix
    void fatal_log(const std::string& msg); // writes to "file", but adds [FATAL] prefix and throws runtime exception

private:

    std::string get_datetime(std::string format) const;

    std::ofstream file;

};
#endif

```

*Log.cpp*

```
#include "Log.h"

#include <chrono>
#include <ctime>
#include <filesystem>
#include <exception>

Log::Log()
{
    std::filesystem::create_directory("Logs\\");
    file.open("Logs\\" + get_datetime("%F %H-%M-%S.txt"), std::ios::out);
}

Log::~Log()
{
    file.close();
}

void Log::regular_log(const std::string& msg)
{
    file << "[" << get_datetime("%X") << "]" << " - " << msg << "\n";
}

void Log::warning_log(const std::string& msg)
{
    file << "[" << get_datetime("%X") << "]" << "[WARNING]" << " - " << msg << std::endl;
}

void Log::fatal_log(const std::string& msg)
{
    file << "[" << get_datetime("%X") << "]" << "[FATAL]" << " - " << msg << std::endl;
    throw std::runtime_error(msg);
}

std::string Log::get_datetime(const std::string format) const
{
    std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

    char buf[100] = { 0 };
    std::strftime(buf, sizeof(buf), format.c_str(), std::localtime(&now));

    return buf;
}

```

My problem is that I am not entirely sure what to log in my code. Is every little altering of the game state worth a regular log, things like "Object created", "Object moved from xyz to xyz", "Inventory opened by player 123"? Or should logging be reserved for more important causes? Where do I draw the line?

# Answer
> 4 votes
Logs serve a purpose, which is to help the developers detect, diagnose, isolate, and fix problems. When everything is running perfectly, you're probably not even reading the log.

So the question of what to log reduces to the question of *what helps you solve problems*.

## Stuff that definitely isn't right: Errors

As you code a system, you'll naturally encounter possibilities that should *never* arise at runtime - like calling the `Attack()` function with no target, or popping a game/UI/behaviour state off the stack and leaving it empty, or encountering an unknown/invalid message in an asset file or network packet. These are natural places to log an error to alert the developer to the problem (or, to halt on an assertion / throw an uncaught exception and crash the game on the spot).

## Stuff that looks suspicious, but might be OK for now: Warnings

Other scenarios might be more ambiguous. You're missing an important parameter, but you can carry on with a semi-reasonable default. Or you're over-budget for a particular asset class or performance metric, but it might be tolerable if it's just happening in a limited part of the game or while work is in progress.

These are good places to log a warning to highlight the presence of an issue that merits a closer look, especially if it might not otherwise be visible (because of sensible defaults or because it's just one of many cumulative issues that are only game-breaking if they pile up).

You might, however, want to add a flag that lets you check if you've already warned about this and skip repeating it, so that you don't spam the log with warnings about situations that are actually OK.

(As an aside: it's also important to be disciplined about fixing warnings that turn out to be real problems, and exempting the situations that are permissible, so that you don't get in the habit of ignoring warnings in your console/logs. Seeing the project go from 0 warnings to 3 will catch your attention and you'll find what changed. Seeing it go from 103 warnings to 106 might not be so alarming, letting bad code/content creep in unnoticed.)

## Stuff that helps you isolate a current or recurring class of problem: Logs

If it's not an error and not suspicious, then your default position should be: don't log it.

Logging has a cost, both in performance, and in attention. You might be surprised how easy it is to bog down a game by doing string processing and file IO in the middle of a reasonably hot loop somewhere. But also, excessive logging can actually make it harder to spot what's going on, because every system in the game is spamming the chat with conversations unrelated to the thread you're trying to follow.

So, if a current problem you're having would benefit from some logs to help you trace how the game state evolves into/through the problem case, add logs tactically to the places that inform that search. Once you're sure you've solved that problem, go back and remove / disable those logs.

If you find you have to come back to a system to re-add/enable logging repeatedly, that's a good sign those logs are useful for tracking down a class of recurring problems, and are worth keeping around more permanently.

For complex games, you might want to introduce a logging flag system, where via a launch argument or console command you can enable or disable specific subsets of log messages. So an AI programmer can launch with `-ai_log_enable` for their routine debugging, and the graphics programmer with `-gfx_log_enable`, and neither one is distracted by spam from systems they're not working on. Or even further, the AI programmer might want to enable `-ai_log_verbose` to get super granular logs of individual actions/transitions when tracking down a thorny issue, that are otherwise too spammy to keep on by default. You can filter as specifically as you want, like `EnableLog(Sound_Played_Events)`, if that helps solve the kinds of problems your game projects tend to have.

# Answer
> 1 votes
Years ago I had this exact same question, as I was trying to be proactive about it, as you are now.

In the end? No. You can't log specific categories of things, because these categories change from one game to the next, especially depending on where the complexity lies, but more importantly, they also change from one dev phase to the next - and of such phases, there may be hundreds or thousands before a game is released. As others have suggested, only you can know this about your current game under development.

It's more important to:

* make the *process* of selecting and logging specific categories as painless as possible, that is, make it as easy as you can to get a meaningful log entry for any given thing by inserting the minimum possible information at the necessary codepoint;
* make the logs as filterable as possible so you don't have to go about deleting / commenting former log statements just to be able to find entries pertaining to what is currently going on.

Existing systems can be a source of inspiration:

* Unity does an alright job, but uses only 3 categories: info, warn, and error. This is a single-level categorisation system that focuses on log entry criticality.
* Android, in conjunction with its IDEs, actually does a reasonable job of doing a multi-level categorisation by using tags in addition to criticality, which can be filtered through the IDE's UI, while the basic system within Android remains relatively conceptually simple - a Good Thing.

I'd suggest you write (or source) a suitable logging system based on ease of adding new lines to generate logs, and filtering. If it has support for logging via varied output streams, even better.

# Answer
> 1 votes
I think I may have something small to contribute. Other answers appear to cover more the development side of "logging". However, this:

> Inventory opened by player 123

...hints me that you might be in the process of developing a multiplayer game.

I unfortunately don't have first-hand experience with developing such games, but as I understand from multiple sources I've seen over the years, in this context, you should "log everything".

What is "everything"? It's mostly related to the information your devs and your GMs need to

* trace why quest X is buggy
* how could player Y scam player Z
* how could payer A duplicate item B
* how could player C illegally teleport from D to E
* assert that player F is actually a racist bully that ruins the game experience for everyone
* how guild G manages to win raids every weekend while never dying and making the server crash at the same time
* etc.

As it's been said before, you'll need to balance what you log and how you log it in a non-invasive way to not slow down your game servers, and in a practical way to help your devs and your GMs find quickly and easily the information they need. It's a nice challenge.

---
Tags: c++, debugging
---


title: How to prevent GameObject from moving?

text:
# Question
Title: How to prevent GameObject from moving?
I am making a pong game and here's the problem. The ball hits the enemy paddle and instead of reflecting the ball just takes the paddle with it.

**Ball Brains -**

```
using UnityEngine;

public class BallBrains: MonoBehaviour
{
    private int seedX, seedY;
    private Rigidbody2D rb;

    void Start ()
    {
        Random.InitState (69);

        seedX = Random.Range (0, 1);
        seedY = Random.Range (0, 1);

        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate ()
    {
        if (seedX == 0)
        {
            rb.AddForce (new Vector2 (0.5f, 0f) );
        }
        else if (seedX == 1)
        {
            rb.AddForce (new Vector2 (-0.5f, 0f) );
        }

        if (seedY == 0)
        {
            rb.AddForce (new Vector2 (0f, 0.5f) );
        }
        else if (seedY == 1)
        {
            rb.AddForce (new Vector2 (0f, -0.5f) );
        }
    }

    void OnCollisionEnter ()
    {

    }
}

```

**Enemy Movement -**

```
using UnityEngine;

public class EnemyMovement : MonoBehaviour
{
    private BallBrains ball;
    private Rigidbody2D rb;

    void Start ()
    {
        ball = FindObjectOfType<BallBrains>();
        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate ()
    {
        if (ball.transform.position.y > transform.position.y)
        {
            rb.AddForce(new Vector2(0f, 10f));
        }

        if (ball.transform.position.y < transform.position.y)
        {
            rb.AddForce(new Vector2(0f, -10f));
        }
    }
}

```

\**Player Movement - \**

```
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;

    private bool verticalMovementUp = false;
    private bool verticalMovementDown = false;

    void Start ()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update ()
    {
        verticalMovementUp = Input.GetKey(KeyCode.W);
        verticalMovementDown = Input.GetKey(KeyCode.S);
    }

    void FixedUpdate ()
    {
        if (verticalMovementUp) {
            rb.AddForce(new Vector2(0f, 10f));
        }

        if (verticalMovementDown) {
            rb.AddForce(new Vector2(0f, -10f));
        }
    }
}

```

Also, quick question - How do I set random seed for the direction the ball moves in at the start?

# Answer
For your first question, make your Rigidbody2D `Kinematic` for ignoring the forces acting on the paddle.

For your second question,

> How do I set random seed for the direction the ball moves in at the start?

```
  Vector3 randomDirection = new Vector3(Random.Range(0,360),Random.Range(0, 360),transform.position.z);
  transform.rotation = Quaternion.Euler(randomDirection);

```
> 1 votes

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


# Question
Title: Terrain Generation for Tile-Based 2D Platformer
I'm currently working on a tile-based 2D platformer similar to Terraria in some ways, although I'm having difficulty with the terrain generation. I have some basics done, although they do not come out as anything useful.

I have tried a few different techniques like Perlin Noise and read about some others such as Midpoint Displacement, although I'm not sure what one would be best, or a combination of different techniques to generate different areas. (Such as Midpoint Displacement for the general shape of the terrain and Perlin Noise for the caves.)

I have found an excellent explanation of how I could layer it up with the Accidental Noise Library, although it is in C++, and I do not know enough C++ to compile it into a DLL that I can use from C#. I have tried to copy this in C#, although, I do not know how I can merge two effects together (the gradient for the general base, and then the fractal for detail).

Currently I am using a Plasma Fractal and the results are extremely varied. For example it can generate terrain where there is hardly any surface, or it can generate terrain where there is no surface at all.

An example of an okay map, would be better with some more improvements, though. (Black is solid, white is air):

And an example of a terrible map. (Black is solid, white is air):

Basically, what I'm asking is, what would be a better way of generating the terrain, or forcing it to make sure that there is a reasonable amount of surface area, with the generation time as quick as possible. Or, alternatively, how I would be able to achieve the same result as the Accidental Noise Library, but in C#.

Any examples would be very much appreciated.

# Answer
I would try sticking with Perlin noise, but adding a weight to it based on height, to ensure a certain average density at certain altitudes. To quote part of Notch's post on Minecraft terrain generation:

> So I switched the system over into a similar system based off 3D Perlin noise. Instead of sampling the “ground height”, I treated the noise value as the “density”, where anything lower than 0 would be air, and anything higher than or equal to 0 would be ground. To make sure the bottom layer is solid and the top isn’t, I just add the height (offset by the water level) to the sampled result.

Essentially, you're taking a little slice of a Minecraft terrain. So generate 2D Perlin noise, but weight it so that anything above a certain point is *likely* to be air, and anything below a certain point is *likely* to be earth.

This will give you a good ground terrain, with some overhangs and interesting features, as well as some caves and floating islands. (If you don't want floating islands, you can test for them and remove them manually.) This method won't give you things like tunnels, so you'll want a method for adding those in after terrain generation, such as a random-walk.
> 9 votes

# Answer
You need some kind of coherent noise function, I would recommend go with Perlin or OpenSimplex noise, it is well known algorithm and there many implementation of same functions for different languages: C/C++, C#, Python, Java, JS etc...

Basically you just need to use noise function to generate value for x/y coordinate and apply math function on top of that to get desired effect.

Than you can can generate many map for different type of tiles, and mix them. For example every type of minerals can have separate map.

For example let's say you have mineral A and mineral B.

* Noise function with seed A for Mineral A, will give you certain value in point (x,y), and same way another noise value for Mineral B, and then you just choosing which mineral's have higher value.
* If all mineral bellow some threshold, than just using some common mineral like dirt.
* You can use it as binary so mineral is there or not, or you can use noise value, to generate mineral yield for that block.
* Another approach, you can take use noise function to map to different minerals. For example 0 - 0.5 is dirt, 0.5-0.7 dirt with stone, 0.7-0.85 stone with iron, 0.85-0.95 iron with gold, 0.95 - 1.0 pure gold.
* You may want to introduce some probability factor based on depth noise, so some mineral will be more often on certain height than other. I would recommend some kind of https://en.wikipedia.org/wiki/Binomial\_distribution, or any other function which plot looks like that.

---

I was searching similar thing for 3D terrain height generation recently, it is not exactly what you asking, but here is good xample how same noise function can be used for different variation. https://www.youtube.com/watch?v=lctXaT9pxA0

* He used same perlin for different things like: flat land, mountain range, biomes, geographical zones.

---

Also putted some analysis about noise functions: Enumerate list of noise algorithm for 3D terrain heighmap generation
> 1 votes

---
Tags: xna, 2d, procedural-generation, terrain
---


# Question
Title: Trying to access existing animator SetTrigger does nothing and returns error
First of all, I have a character with 2 armatures (Upper/Lower Body), where the Upper Body is the child of the Lower Body's root bone (Hip). *This is intended, and I really don't want to touch the hierarchy, as it would break a lot of other things.*

The thing is, that the animator of the Lower Body works like a charm and reacts to SetTrigger as expected (although in a different script, but on the same GameObject), while if I try to do the same for the Upper Body, it just throws me the following error and does nothing:

*Parameter 'Attack' does not exist. UnityEngine.Animator:SetTrigger (string)*

The Trigger does exist with the proper name (no typo), set up on the right animator with the right transitions. If I trigger it from the animator on spawn, it does play it, so the Trigger does exist.

Here is part of the code:

```
[SerializeField] GameObject goal;
[SerializeField] Transform stance;
[SerializeField] ParticleSystem projectileParticles;
[SerializeField] float targetRange = 10f;
[SerializeField] float attackRange = 5f;
[SerializeField] Transform enemy;

public GameObject Target;
public float maxDistance;

public NavMeshAgent agent;
public Animator animUpper;
public Animator animLower;

public void Start()
{
    animUpper = GetComponentInChildren<Animator>();
    animLower = GetComponentInChildren<Animator>();
}

void Update()
{
    FindClosestEnemy();
    AttackEnemy();
}

public void FindClosestEnemy()
{
    List<GameObject> nearestEnemies = new List<GameObject>();
    GameObject lastAddedEnemy = null;
    GameObject enemyTemp = null;

    float maxDistance = Mathf.Infinity;
    Vector3 position = transform.position;

    enemyTemp = FindNearestWithTag("RightBrute");
    if (enemyTemp != null && enemyTemp != lastAddedEnemy)
    {
        nearestEnemies.Add(enemyTemp);
        lastAddedEnemy = enemyTemp;
    }

    enemyTemp = FindNearestWithTag("RightRanged");
    if (enemyTemp != null && enemyTemp != lastAddedEnemy)
    {
        nearestEnemies.Add(enemyTemp);
        lastAddedEnemy = enemyTemp;
    }

    enemyTemp = FindNearestWithTag("RightArmor");
    if (enemyTemp != null && enemyTemp != lastAddedEnemy)
    {
        nearestEnemies.Add(enemyTemp);
        lastAddedEnemy = enemyTemp;
    }

    foreach (var enemy in nearestEnemies)
    {
        Vector3 diff = enemy.transform.position - position;
        float currentDistance = diff.sqrMagnitude;
        if (currentDistance < maxDistance)
        {
            enemyTemp = enemy;
            maxDistance = currentDistance;
        }
    }

    Target = enemyTemp;
}

public GameObject FindNearestWithTag(string tagName)
{
    GameObject[] enemies;
    enemies = GameObject.FindGameObjectsWithTag(tagName);
    GameObject closest = null;
    float maxDistance = Mathf.Infinity;
    Vector3 position = transform.position;

    foreach (var enemy in enemies)
    {
        Vector3 diff = enemy.transform.position - position;
        float currentDistance = diff.sqrMagnitude;
        if (currentDistance < maxDistance)
        {
            closest = enemy;
            maxDistance = currentDistance;
        }
    }

    return closest;
}

public void AttackEnemy()
{
    if (Target == null)
    {
        stance.LookAt(goal.transform);
        Attack(false);
        Move();
    }
    else
    {
        float maxDistance = Vector3.Distance(transform.position, Target.transform.position);
        stance.LookAt(Target.transform);

        if (maxDistance < targetRange)
        {
            Approach();

            if (maxDistance < attackRange)
            {
                Attack(true);
                animUpper.SetTrigger("Attack");
                //GetComponentInChildren<Animator>().SetTrigger("Attack");
            }
        }
        else
        {
            stance.LookAt(goal.transform);
            Attack(false);
            Move();
        }
    }
}

public void Attack(bool isActive)
{
    var emissionModule = projectileParticles.emission;
    emissionModule.enabled = isActive;
}

public void Move()
{
    NavMeshAgent agent = GetComponent<NavMeshAgent>();
    agent.SetDestination(goal.transform.position);
    animLower.SetFloat("Speed", agent.velocity.magnitude);
}

public void Approach()
{
    NavMeshAgent agent = GetComponent<NavMeshAgent>();
    agent.SetDestination(Target.transform.position);
    animLower.SetFloat("Speed", agent.velocity.magnitude);
}

```

As you can see I've tried using *GetComponentInChildren().SetTrigger("Attack");* but it resulted in the same error. I've been at it for days now and I'm completely out of ideas. I beg for some help, because the way I see it from other questions, it is a bug with Unity itself, in which case I would really like to get a workaround and a cold compress.

Reproduction steps with example character:

Yellow: Hierarchy; Orange: Script in question; Red: Properly assigned Animators;

Orange: Upper Body Animator; Red: Trigger set up properly; *Trigger is set up on two transitions for testing purposes. Changing it doesn't fix anything. I originally wanted it to come from Any State only.*

Animated character FBX files: https://we.tl/t-m8Yo1yMttS

Complete, simplified example project: https://we.tl/t-7P3FFwK8tv

To test the issue, just hit *Play*, go back into *Scene* and drag the *Cube* over the *character*. It gives the exact same results.

# Answer
> 1 votes
As I wrote in the comment, you are loading twice the same animator. While you do assign the correct ones in the inspector, in the code you are reloading the animators in the start method. Therefore in your case it would not matter at all what got assigned in the Editor for Upper/ Lower Body, it gets overwritten afterwards.

`GetComponentInChildren<Animator>()` returns you the first animator it finds. Calling it again returns the same again.

To fix your problem, either just delete the two lines (since you assign it over the inspector) or use a different loading. `GetComponentsInChildren` would return you all animators, you would need to know in which order they get returned.

On a side note, you might want to reconsider `FindGameObjectsWithTag` the way you use it right now for finding your enemies. It is likely that you are going to run into performance issues, it is not recommended to call it in Update and not even needed. In the example code you posted, you could load once at Start all enemies and just iterate over the list as you do now and compare to the tag.

---
Tags: c#, animation, animator, animation-controller, hierarchy
---


# Question
Title: What video settings make a game portable over different level computers?
I'm making a 3D video game, paying attention on optimization of my textures, materials, meshes, and so on. I've kept a good level of quality while having a relatively high and stable framerate, but I don't have the possibility to test it on lower level devices.

---

What settings should I let players change to make the game less resource-intensive? Of course, every setting could make the game perform better, but I would like to know what's the "*must-have*" performance settings.

Things like anti-aliasing, texture quality, framerate limit, VSync, etc.

# Answer
The obvious ones are:

* Anti-aliasing
* Texture resolution
* Maximum LOD level (if using LOD models)
* Post-processing effects/filters
* Vsync
* Shadows
* Shader quality (if your engine supports adjustable shader quality)
* Max particles onscreen

Profiling is a good way to determine bottlenecks, but if you're profiling on a high-end development rig and worried about how the game will run on a cheap laptop with integrated graphics, it can be difficult to determine where to optimize just from profiling. If you've been mindful of optimization, you probably already have some idea of where you should focus your efforts. For example, if your game uses low-poly style models with few textures, but has very complex real-time lighting, your efforts are probably better focused on tuning the lighting rather than tuning LODs and texture resolutions.
> 2 votes

# Answer
The only way to understand which settings should be adjustable in a 3d game is profiling it with different hardware and different combination of every option existing. Since there are many different video settings and they also have a different weight if considered in combination, this would require a lot of work done to answer the question.

Generally talking, there are a few options that always are good to have adjustable, according to wired but it also depends on what's your game require most. It's good to separate what's CPU-intensive from what's GPU-intensive and make sure that those settings causing one or the other to be the bottle-neck are adjustable.

Here a good article from *gamedeveloper.com* that talks about settings and video settings that a developer should considering while building a 3D video game, this article highlights how video settings also depend on what's the genre of video game, e.g. is good to have adjustable gamma if the game is a horror one.
> 0 votes

---
Tags: optimization, user-experience, settings
---