# Question
Title: remaking Pong in Godot but the opponent AI cannot locate the ball's coordinate correctly
I'm following a detailed YouTube tutorial on remaking Pong in Godot 3.0 but I have ran into an issue regarding the way the AI opponent reacts to the incoming ball, what's happening is that the opponent can track the balls' location but for some strange reason the opponent always reacts to the incoming ball as if it's more below its actual location, here's a video that shows my issue , as you can see the opponent always moves way more down than it should which makes it impossible for it to hit the ball most of the time, the only time it can hit the ball correctly is when the ball is already heading down to the corner, so it just so happens to meet up with it

I have followed the tutorial closely and downloaded the source code for the Godot project and tried copy and pasting the opponent's (and even the ball's code) to my project and I double checked the variable names and the way scene tree is organized yet the issue is still present

Here's the current code for the AI opponent:

```
extends KinematicBody2D

var speed = 250 #tried changing this but the issue still occurs
var ball

func _ready():
    ball = get_parent().find_node("ball")

func _physics_process(delta):
    move_and_slide(Vector2(0,get_opponent_direction()) * speed) #i tried also multiplying the speed by delta but it doesn't fix it

#the issue is in this function probably...
func get_opponent_direction():
    if abs(ball.position.y - position.y) > 25: #I tried increasing\decreasing this but the issue's still present
        if ball.position.y > position.y: return 1
        else: return -1
    else: return 0

```

Here's the ball's code also (even though I don't think it has anything to do with it)

```
extends KinematicBody2D

var speed = 400 #tried increasing\decreasing the speed but the issue is still present
var velocity = Vector2.ZERO

func _ready():
    randomize()
    velocity.x = [-1,1][randi() % 2]
    velocity.y = [-0.8,0.8][randi() % 2]

func _physics_process(delta):
    var collision_object = move_and_collide(velocity * speed * delta)
    if collision_object:
        velocity = velocity.bounce(collision_object.normal)

```

I even checked if the project window size is correct and it is, I also double checked that me and the tutorial are both using Godot 3.2. It seems to me that the issue is that the opponent gets the coordinates for the ball but for some reason it increases the Y axis for the coordinates, this results in the opponent seeing the ball below its actual location, so yeah something with the Y coordinates...

# Answer
In the Godot editor, I made the silly mistake of placing the `Sprite` and `CollsionShape` nodes far away from the (0,0) origin point.

I simply dragged them over to the origin point and the problem was solved.
> 5 votes

---
Tags: ai, godot, coordinates, debugging, gdscript
---


# Question
Title: Is it possible to use the Unreal Engine as a big C++ library, without using the editor?
I want to write a game entirely in C++, but I would like to profit from the possibilities offered by the Unreal Engine, especially in terms of graphics and physics. Nevertheless, I strongly dislike its visual editor: I find it heavy, slow and unintuitive. Finally, it forces me to use Visual Studio instead of my favourite C++ IDE.

Is there a way to use the Unreal Engine as a big library that I could simply include in my C++ project, or am I forced to used the Unreal Editor?

*Related question for Unity: How can I build a game in Unity with minimum/no use of the visual editor?*

# Answer
> 4 votes
Breaking down what the editor provides and how you can side-step its usage:

## Compiling

Technically this is something that Visual Studio is providing but still important. Compiling Unreal is non-trivial and involves invoking the Unreal Build Tool to generate some code (supports things like reflection, blueprint interfacing etc...). Doing this without using Visual Studio is possible but largely undocumented. I guess the best place to start would be looking at how it builds on Linux and mimicking that.

## Building the game (i.e for distribution)

In theory this can be done via the command line, but I have had issues where I get weird build errors if I don't first run the editor. I suppose these can be resolved. But again, it will be undocumented and probably quite error prone.

## Map editor

The map format is binary so creating maps would be a problem. I believe Unreal Engine needs at least one map to run the game, so you'd probably have to create an empty map at the very least. Once it was created, you can spawn stuff from code.

In fact, interestingly, since the editor is actually included in the source, you could perhaps use the editor methods to create an empty map and save it out without using the editor. In theory, you could even write your own simple map editor, though at that point you are essentially re-implementing Unreal.

## Blueprints

Presumably you'd just not use any of the functionality. Though this is a shame as it is a nice separation of data from function.

## Materials

There are some basic materials that you could use but again this could be a major pain. I suppose you could write the shaders directly, but I'm not sure how you could then use them as a material.

I am sure I've missed some aspects of it, but to summarise: **probably, but you will run in to a lot of problems**.

Crucially, the editor functions can be accessed from code, so theoretically you can implement the parts of the editor that you need. However, all this begs the question, why don't you want to use the editor? You are probably much better off simply minimising the amount of time you use the editor.

# Answer
> 2 votes
Starting a rough answer for this old question as I learn more about this functionality myself, yes it seems this functionality has been available since at least Unreal Engine 4.27. However, it's currently Windows only.

Old docs: link. Newer docs: Link.

It looks like this is accomplished via targeting `UELibrary`, the API of which is documented at the link above. And you do have to define `UE_LIBRARY_ENABLED=1`.

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


# Question
Title: Motion Retargeting from a BVH File to a Rigged Mesh in Unity with Arbitrary Rest Pose
I want to perform motion retargeting from a .bvh file (from lafan2 dataset) to a rigged mesh in Unity (which is John Lemon in this tutorial resource).

I have overcome most of the problems, but this last one got me: I need to somehow calculate the rotation between John Lemon and lafan's rest poses. Now, these two rest poses look different, are in different coordinate systems, and it kills me to identify the orientation of each bones, especially in a .bvh file, since they don't have any meshes and the pose was positioned in a non-human manner, meaning that it was hard to tell what is the "twist" of each joint.

Here are the pictures of these "nice" rest poses:

FYI, these are what their T-poses look like, which are, sadly, not their rest poses:

What I have right now: the .bvh file data along with global orientation, location for lafan, and bone structures consists of gameObjects for John. I guess theoretically I can identify the bone orientation manually, but I am seeking for advices. Are there any easier ways to calculate the rotation between these two rest poses?

What I have tried: I first tried calculating the rotation between vectors. And later I learned that treating the bones as vectors is not cool, because I can only get the "swing" part of the rotation by that, and the "twist" part of the desired rotation was lost. As a result, my character's joints seem to be at the right position, but all his joints are twisted along the bone direction. You can see how Jonh's spine and limbs twist

# Answer
> 1 votes
I kinda fixed it myself. Solution is simple: I just hand-tuned all the required twist angles in Unity. There is a hidden problem though: the order of the 'twist' and 'swing' rotation matters. Result looks much better now: But as you can see, the head orientation is still a little off. I'll fixed it with IK, since it's more of a data problem than a bug.

Edit: Actually, it was a bug. Now its head is way better, even without IK.

Here are the formulars to explain what I was doing. I hate equations, but we will have to figure it out to solve the problem.

What I have is the global orientation, location (calculated) from a .bvh file, and a skeleton structure of gameObjects in Unity. At the end of the day, I want unity mesh (which is John) to pose exactly like what the .bvh file (which is lafan) is doing, so thier final **orientation** should align: $$ O\_{JL} = O\_{lafan} $$ Considering that these two skeletons have different rest poses in different coordinate systems, we have to transfer the data all into one coordinate system. In this case, we will put them into Unity's system.

After that, we need to face the aforementioned rest pose problem. Assume that we already know how to represent the rest pose of lafan in Unity, we have: $$ Q\_1 \times O\_{JL}^{rest} = Q\_2 \times O\_{lafan}^{rest} $$ where \\$Q\_1\\$ is what I wanted, \\$O\_{JL}^{rest}\\$ are all `Quaternion.identity`, \\$Q\_2\\$ is known by FK calculation, but \\$O\_{lafan}^{rest}\\$ was hard to calculate. So I made another assumption: assume that we know the rotation between two rest poses already, then I can just apply the ratation to \\$Q\_2\\$, and get \\$Q\_1\\$. How can I get the roation between two rest poses then?

Well, according to my question, I actually already knew the swing part of the rotation. I just need the twist part. Also, like I mentioned, given the fact that the twist part was probably a rotation just around one axis, it's not hard to tune it manually. If we have the swing and the twist rotation, then we have: $$ O\_{lafan}^{rest} = Q' \times O\_{JL}^{rest} = Q\_t \times Q\_s \times O\_{JL}^{rest} $$

where \\$Q'\\$ is the roation between, and is composed of \\$Q\_s\\$ and \\$Q\_t\\$, multiplied in that order. Put that back into the equation above, we have: $$ Q\_1 = Q\_2 \times Q\_t \times Q\_s $$ meaning that with \\$Q\_s\\$ and \\$Q\_t\\$, we have \\$Q\_1\\$. Be careful, the order counts. Other then that, we are good to go.

I may make mistakes here, so feel free to point them out...

---
Tags: unity, rotation, motion
---


# Question
Title: Using the boids algorithm for multidirectional boids
I have some difficulties with my basic collision system in croweded places as it is based on simple box to box or radius detection. Sometimes characters are stuck to something or stopped because there is no way to go around. I'm trying to see if the boids algorithm can help, specifically using the separation behavior. In my simulation the boids are going in random directions. The problem I have is that boids are supposed to go in a similar direction. Indeed what I see is some boids moving the opposite of their direction to avoid others which is not nice. So is it possible to modify the separation function to maintain the moving in the correct direction.

Alternatively maybe there is a better algorithm for that purpose.

# Answer
I have developped a small MFC dialog app to study the problem. Below is the code and a screen picture. What does this demo do: It moves 20 boids in the limit of a 700x700 window with 3 ranbom obstacles in green. boid 0 red and boid 1 blue have a target position to reach. When a boid hit someting it turns according to its current direction and hit face. If there is no hit the boid try to recover its general direction (or target direction for b0 and b1). Putting too many boid makes the target search longer. 20 is fine. I have adapted this to my regular project. A problem I see is when a character moves according to a defined path (AStar or predefined positions). Turning around other characters until no hit can led to the character moving too far from its current path and possibly loosing it. I currently managed this by some priority checking, e.g. character using a AStar check only obstacle, other character being in charge of avoinding the one using the Astar. Not the best but easy to mananged.

The code below test just boids, obstacles and window. No AStar or predefined positions.

```
typedef struct _BOID
{
DWORD   Index;//as in for loops counter
FLOAT3  Pos;
FLOAT   RotY;//general angle
FLOAT3  Dir;//general direction from general angle (random or to End)
FLOAT   Angle;//current angle
FLOAT3  Vel;//current direction from current angle
FLOAT3  End;//target pos if any
FLOAT3  Close;//accumulation parameter
RECT        Rect;//rectangle define by XZ volume on screen
BOOL        bStopped;//force stop if too many hits. optional
DWORD   Neighbor;//index of closest boid hit found otherwise 0xFFFFFFFF
DWORD   Count;//as in for loops counter
FLOAT   Turn;//amout of rotation if hit found
}BOIDS, *LPBOIDS;

// MaxBoid defines the number of boids we want (20 in the picture)
//RECT Obstacle [3] define the 3 random obstacles in green
// BOIDS B[MaxBoid] define moving boids
//On the picture boid0 (red) and boid1 (blue) want to reach their colored targets.

Void OnTimer()
{
    for (DWORD b1 = 0; b1 < MaxBoid; b1++)
    {
        LPBOIDS pB1 = &B[b1];
        CheckBoidToWorld(pB1);
        for (DWORD b2 = 0; b2 < 3; b2++)
        {
            CheckBoidToObstacle(pB1, &Obstacle[b2] ,45);
        }
        pB1->Angle += pB1->Turn;
        if (pB1->Turn == 0) //no obstacle and no window limit
        {
            //boids 0,1 want to reach a target
            if (b1 < 2) ReorientToTarget(pB1);
            //other boids want to have a global direction
            else ReorientToGlobalDir(pB1);
        }
        else pB1->RotY = pB1->Angle;
        //update changes
        //to stay in the range [0..2PI]
        if (pB1->Angle < 0)pB1->Angle += PI2;
        if (pB1->Angle > PI2)pB1->Angle -= PI2;
        //could be x=sin and z=cos depending on left or righthand matrix.
        pB1->Vel.x = cosf(pB1->Angle);
        pB1->Vel.z = sinf(pB1->Angle);
        pB1->Close.x = pB1->Close.z = 0;
        pB1->Close.y = 1e6; //maxdistance in close.y to find closest boid
        pB1->Neighbor = 0xFFFFFFFF;//no closest neighbour at start
        pB1->Rect.top = pB1->Pos.z - 10;//update rect for moving boids
        pB1->Rect.left = pB1->Pos.x - 10;
        pB1->Rect.bottom = pB1->Pos.z + 10;
        pB1->Rect.right = pB1->Pos.x + 10;
        pB1->Count = 0;
        pB1->bStopped = false;
    }
    for (DWORD b1 = 0; b1 < MaxBoid; b1++)
    {
        LPBOIDS pB1 = &B[b1];
//the b2 loop can be optimized by b2=b1+1 to MaxBoid
//if the check is symmetrized from b1 to b2 and b2 to b1 in the     CheckBoidToBoid function
        for (DWORD b2 = 0; b2 < MaxBoid; b2++)
        if (b1 != b2)
        {
            CheckBoidToBoid(pB1, &B[b2]);//search closest one
        }
    }
//finalize the movement
    for (DWORD b1 = 0; b1 < MaxBoid; b1++)
    {
        LPBOIDS pB1 = &B[b1];
        if (pB1->Neighbor < 0xFFFFFFFF) UpdateBoidToBoid(pB1);
        pB1->Pos.x += pB1->Vel.x;
        pB1->Pos.z += pB1->Vel.z;
    }
}
Some modifiable parameters
FLOAT AvoidFactor = 0.02f;
FLOAT AreaClose = 40*40;//not necessary to sqrt the distance
FLOAT AreaFar = 100*100;
FLOAT MaxSpeed = 3.0f;
FLOAT MinSpeed = 1.0f;
FLOAT TurnBoid = 0.001f;
FLOAT TurnBloc = 0.1f;
FLOAT RotFactor = 0.1f;
FLOAT Speed = 0.5f;
//the window size is 700x700. I consider a limit=40 for starting to turn.
BOOL CheckBoidToWorld(LPBOIDS pB1)
{
    pB1->Turn = 0;
    FLOAT3* pP1 = &pB1->Pos;
    FLOAT3* pD1 = &pB1->Vel;
    FLOAT K;
    if (pP1->x < 40)
    {
        K = 4-pP1->x/10;
        pB1->Turn = (pD1->z<0) ? TurnBloc*K : -TurnBloc*K;
    }
    if (pP1->x > 660)
    {
        K = 4 - (700 - pP1->x) / 10;
        pB1->Turn = (pD1->z>0) ? TurnBloc*K : -TurnBloc*K;
    }
    if (pP1->z < 40)
    {
        K = 4 - pP1->z / 10;
        pB1->Turn = (pD1->x>0) ? TurnBloc*K : -TurnBloc*K;
    }
    if (pP1->z > 660)
    {
        K = 4 - (700 - pP1->z) / 10;
        pB1->Turn = (pD1->x > 0) ? -TurnBloc*K : TurnBloc*K;
    }
    return pB1->Turn!=0;
}

Void CheckBoidToObstacle(LPBOIDS pB1, LPRECT pR, FLOAT Limit)
{
    FLOAT3* pP1 = &pB1->Pos;
    FLOAT3* pD1 = &pB1->Vel;
    FLOAT TurnZ = 0;
    FLOAT K = 0.99;
    if (pP1->x >= pR->left - Limit)
    if (pP1->x <= pR->right + Limit)
    if (pP1->z >= pR->top - Limit)
    if (pP1->z <= pR->bottom + Limit)
    {
        if ((pP1->x > pR->left - Limit) && (pP1->x < pR->left))
        {
            pB1->Turn = (pD1->z<0) ? -TurnBloc : TurnBloc;
            TurnZ = fabs(pD1->x);
        }
        else
        if ((pP1->x > pR->right) && (pP1->x < pR->right + Limit))
        {
            pB1->Turn = (pD1->z>0) ? -TurnBloc : TurnBloc;
            TurnZ = fabs(pD1->x);
        }
        else
        if ((pP1->z > pR->top - Limit) && (pP1->z < pR->top))
        {
            pB1->Turn = (pD1->x>0) ? -TurnBloc : TurnBloc;
            TurnZ = fabs(pD1->z);
        }
        else
        if ((pP1->z > pR->bottom) && (pP1->z < pR->bottom + Limit))
        {
            pB1->Turn = (pD1->x>0) ? TurnBloc : -TurnBloc;
            TurnZ = fabs(pD1->z);
        }
        //use TurnZ as an amplifier effect based on perpendicular direction
        //to hit obstacle face. 0.25f is an arbiray non-zero value
        pB1->Turn *= 0.25f + TurnZ*0.9f;
    }
}

Void CheckBoidToBoid(LPBOIDS pB1, LPBOIDS pB2)
{
    FLOAT3 XZD;
    XZD.x = pB1->Pos.x - pB2->Pos.x;  XZD.z = pB1->Pos.z - pB2->Pos.z;
    XZD.y = XZD.x*XZD.x + XZD.z*XZD.z;
    if ((XZD.y < AreaClose) && (XZD.y < pB1->Close.y))
    {
        pB1->Neighbor = pB2->Index;
        pB1->Close = XZD;
        //can be stopped if too many neighbors
        pB1->Count++;
        if (pB1->Count > 2) pB1->bStopped = true;
    }
}

Void UpdateBoidToBoid(LPBOIDS pB1, INT Sign)
{
    if (pB1->bStopped)
    {
        pB1->Vel.x = 0;
        pB1->Vel.z = 0;
    }
    else
    {
        pB1->Vel.x += pB1->Close.x*AvoidFactor*Sign / pB1->Count;
        pB1->Vel.z += pB1->Close.z*AvoidFactor*Sign / pB1->Count;
    //normalize new velocity
        FLOAT DD = sqrt(pB1->Vel.x*pB1->Vel.x + pB1->Vel.z*pB1->Vel.z);
        if (DD > 0)
        {
            pB1->Vel.x /= DD;
            pB1->Vel.z /= DD;
        }
        pB1->Angle = atan2f(pB1->Vel.z, pB1->Vel.x);
    }
}

Void ReorientToTarget(LPBOIDS pB1)
{
    pB1->Dir.x = pB1->End.x - pB1->Pos.x;
    pB1->Dir.z = pB1->End.z - pB1->Pos.z;
    float NewRot = atan2f(pB1->Dir.z, pB1->Dir.x);
    float DRot = pB1->Angle - NewRot;
    if (fabs(DRot)  > PI) pB1->Angle += DRot*0.01f; else  pB1->Angle -= DRot*0.01f;
    pB1->RotY = pB1->Angle;
    pB1->Dir.x = cosf(pB1->Angle);
    pB1->Dir.z = sinf(pB1->Angle);
    pB1->Vel = pB1->Dir;
}

Void ReorientToGlobalDir(LPBOIDS pB1)
{
    float DRot = pB1->Angle - pB1->RotY;
    if (fabs(DRot)  > PI) pB1->Angle += DRot*0.01f; else  pB1->Angle -= DRot*0.01f;
    if (pB1->Turn != 0) pB1->RotY = pB1->Angle;
    pB1->Dir.x = cosf(pB1->Angle);
    pB1->Dir.z = sinf(pB1->Angle);
    pB1->Vel = pB1->Dir;
}

```
> 0 votes

# Answer
You can make the friendly forces weaker when the neighbor's alignment deviates enough from the target direction.

This essentially treats boids that go in the opposite direction as predators to avoid.
> 0 votes

---
Tags: algorithm, movement-prediction
---


# Question
Title: Can I convert a Unity file with the extension ".asset" to ".prefab"?
I am using a Unity asset to combine many meshes of many objects in my scene to one object. The name of this asset is "**Mesh Combiner**", and here is the link to the asset: https://assetstore.unity.com/packages/tools/modeling/mesh-combiner-157192

After this tool combines the meshes, it creates and saves a file with the extension ".asset". But, this is not a prefab that I can drag-and-drop to a scene.

My question is: Can I manually change the extension of this file from ".asset" to ".prefab", and use it as a prefab in my new scene ?

# Answer
> 4 votes
You do not "convert" an asset to a prefab. These are different things that serve different purposes. A prefab is a game object that can exist in your scene. An asset is the raw data that a game object might reference, but it cannot exist in a scene on its own. You never have a "mesh asset" in your scene, you have game objects with rendering components that *reference* the mesh asset they want to render. This indirection is helpful - it allows you to share one set of mesh data among many instances, without needing to store many copies of it (flyweight pattern).

What you can do is *create* a prefab that references the combined mesh asset this way:

1. Create a new Empty GameObject.
2. Add MeshFilter and MeshRenderer components to it. The MeshFilter selects the mesh to be rendered, and the MeshRenderer handles rendering it and configuring the materials and settings for that rendering.
3. Set the MeshFilter to use the mesh asset generated by the combiner tool.

Now you have a GameObject that renders this mesh, and you can populate its materials as desired.

Drag that GameObject into your Project tab to create a prefab of that new object.

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


# Question
Title: When should I call the physics simulation within the game loop?
I am thinking about where to call the physics simulation. The current situation is that I first update the entities and then the physics immediately before rendering. As you can see in the following example:

```
// Only an example, my loop uses not true :)
while(true) {
  this.UpdateScene();
  this.ProcessPhysics();
  this.RenderScene();
}

```

Is this the correct order?

# Answer
I'd recommend running the physics step before your other update code. That gives code in your `UpdateScene` function a chance to react to things that changed in the physics step.

Maybe you have an object whose sprite should change to face the direction it's currently moving in, or you're using velocity to control squash and stretch on a cartoony character. If that code runs before the physics step, the velocity might have changed by the time you render the scene, leading to these visual changes appearing to lag a frame behind.

As noted in the comments, many games will also implement a fixed timestep, where physics and other gameplay-sensitive code is run with a constant amount of game time elapsing in each tick, decoupled from the current rendering framerate. This can be good for consistency across a range of hardware. That pattern usually looks something like this:

```
while (ShouldRun()) { // Handle quitting
    float deltaTime = GetTimeSinceLastFrame();

    accumulator += deltaTime;

    while (accumulator >= fixedDeltaTime) {
        // Handle simulation updates that need to be ticked at a constant
        // rate (0, 1, or more times) to catch up to real-time.
        ProcessPhysics(fixedDeltaTime);
        ProcessGameSystems(fixedDeltaTime);
        accumulator -= fixedDeltaTime;
    }

    // Handle visual updates that need to be ticked exactly once per frame.
    // Doing this after the sim update lets us react/fix-up visuals just in time.
    VariableRateUpdate(deltaTime);

    // Render the scene - potentially interpolating between the two
    // most recent simulation steps for smoothness.
    float interpolation = accumulator / fixedDeltaTime;
    RenderScene(interpolation);
}

```
> 1 votes

---
Tags: physics, software-engineering, game-loop, bullet-physics
---


# Question
Title: How to calculate rotation needed to cancel out perspective shift
I have a direction vector that's pointing to (0,0,1) in local object space. How can I calculate rotation needed to rotate it on Y axis so that from camera's point of view it would look as if it's pointing up, while in world space it would stay projected on (0, 1, 0) plane.

When object is directly in front of camera, it behaves as I want to, however, moving it elsewhere changes the appearance due to perspective effects. It seems like I need to cancel out the perspective shift by rotating the direction vector.

In the attached screenshot, orange lines show the desired behaviour.

**Edit 1:** Some context on why I'm trying to do this. I'm working on a puzzle game and want to add support for joystick controls. Each controllable object has handles above that should get activated dependent on the joystick input. I found that because of the perspective shift, selecting appropriate handle is a bit awkward. For example, in the screenshot, input is (0, 1) - directly pointing up, however, input translated to object space (yellow ray) is not hitting the expected handle (highligted in orange)

# Answer
There's probably a neat mathematical way to do this, but here's the kludge I've used when I needed this in the past:

1. Project the object position to a screen position using `Camera.WorldToScreenPoint`
2. Increase the y coordinate to get a point on screen above the object
3. Turn this point into a ray with `Camera.ScreenPointToRay`
4. Use `Plane.Raycast` to see where this ray hits the object's ground plane
5. Subtract the object's position from the hit point to get a vector in the ground plane that's vertical from the perspective of the camera - you can use `Quaternion.LookRotation` to rotate in that direction.

(If the ray misses the plane, you can fall back on facing directly away from the camera instead - this only happens if you're looking up from under the object, or exactly edge-on along the plane)

Note that this rotation cancels out the perspective shift and the opposite only. The horizontal direction should not be shifted at all - so really you're dealing with a shear, not a rotation. If you need to map all joystick directions to "on-screen" directions, you can use a shear matrix, or use the current joystick direction as the screen-space shift in step 2 before firing the ray.
> 0 votes

---
Tags: unity, mathematics, vector
---


# Question
Title: How to use Unity ECS without URP or HDRP?
Finally, DOTS is completely released with Unity's 2022 version, so I decided to learn it using the latest tutorial by code monkey. He is using URP for this project.

My question is, URP or HDRP necessary to run Unity ECS? Or especially the SubScene?

I ask because, after following the 15-minute tutorial, I am not able to render my simple cube object in the game view under the sub-scene. **Note:** I am not using EntityGraphics Pacakge.

When I searched for this, I found an issue on the issue tracker that says that SubScenes will work with URP.

Is there any way to use Unity SubScenes with a built-in render pipeline? Or are SubScenes only compatible to use with URP/HDRP?

# Answer
> 1 votes
I have successfully used entities with the regular render pipeline in one project. I did this by creating a MonoBehavior I called "EntitySurrogate". Its Update-method queries the entity manager to retrieve the components with the position and rotation of the entity (In my case, a custom component called `MovementComponent`) and use their values to set the position and rotation of its own transform component. This allows to create traditional game objects which mimic the movement of specific Entities in the ECS world.

```
using UnityEngine;
using Unity.Entities;

public class EntitySurrogate : MonoBehaviour {

    public Entity entity;
    private EntityManager manager;

    void Start() {
        manager = World.DefaultGameObjectInjectionWorld.EntityManager;
    }

    void Update() {
        var movement = manager.GetComponentData<MovementComponent>(entity);
        transform.SetPositionAndRotation(
            new Vector3(movement.pos.x, 0.0f, movement.pos.y),
            Quaternion.Euler(0f, movement.rotation, 0f)
        );
    }
}

```

However, if you do this for all the entities in your game, you will probably not benefit a lot from the ECS performance gains. I only did this because in my specific use-case there was a background simulation involving tens of thousands of entities, but less than a hundred of them visible at any time. So the overhead of doing this wasn't so bad, because I only needed these "Entity Surrogates" for a very small subset of all entities. But in most situations it would probably be better to bite the bullet and use either HDRP or URP where you can use the Entity Graphics package.

# Answer
> 0 votes
At 4:10 of the tutorial you linked, Code Monkey says:

> The other \[package\] that we need in order to be able to render things is the Entities Graphics. You only need this one if you actually want to render entities, meaning you can just use entities without any entities visual.
>
> ...
>
> Now one more note related to this Entities Graphics: this one only works either URP or HDRP. It does not work with the built-in render pipeline.

The description for this package says it provides the "systems and components for drawing meshes using DOTS".

So you can use DOTS entities without this package / without URP or HDRP, you just won't be able to directly draw meshes with those entities.

What good is an entity you can't draw? Consider off-screen simulation. Imagine you're making a city management sim. You want to be able to update the simulation of the whole city all the time, even if not every agent/process in the city is a mesh currently visible on-screen. And you want to do that as efficiently as possible, without impacting framerate. So farming out that simulation to DOTS entities that can distribute work among background threads and benefit from burst compiling makes a lot of sense.

Then, if a subset of those entities correspond to pedestrians / vehicles / buildings / props / animals visible in the current camera frame and zoom level, you can spawn conventional game objects, particle systems, or VFX to render just that subset, without rendering a whole sub-scene of entities directly.

We used a technique similar to this in the game Starlink: Battle for Atlas (not in Unity) to handle updating the behaviour of allied and enemy factions on the other side of the planet or on other planets from where the player was currently playing. When the player came in-range of one of these background "SimUnits", we up-rezzed it to a fully-realized game object with a display mesh and full AI behaviour, then when they went out of range, de-rezzed it back to a SimUnit in the pool for efficient batch simulation.

If your application requires rendering many entities, then you'll need to switch to URP/HDRP and install the Entities Graphics package to enable this.

---
Tags: unity, unity-dots
---


title: Strange shiny reflection on terrain

text:
# Question
Title: Strange shiny reflection on terrain
So I'm trying to figure out, what's causing this strange reflection on my terrain. I've tried almost everything to get rid of that shiny circle, but to no avail. It follows me wherever I go, so it's not static either. I'm using Realtime lighting at the moment. I tried changing the Alpha Source on my grass texture to None, tried bringing to specular down, tried creating a different terrain material, regenerated the lightmap but nothing seems to work. (I'm using URP, Unity 2021.2.1f1)

The problem:

My settings:

# Answer
What @Marc-Diprose said worked for me.
Follow these steps to remove the shiny blot:

1. Locate your texture in Unity's File Explorer.
2. Click on the texture that is giving you an issue.
3. In the Inspector the 4th option down is **Alpha Source**; use the drop down and select **From Gray Scale**.
4. Click **Apply**.

Scene should update the texture on the terrain and fix the lighting issue.

Before the fix:

After the fix:
> 2 votes

# Answer
On the texture import settings, make the Alpha 'From grayscale' and if that alone doesnt fix it, change the format to RGB 24 BIT to discard the alpha channel - the alpha channel is what causes the specularity.
> 1 votes

---
Tags: unity, shaders, terrain, unity-urp
---


# Question
Title: Displaying Precisely Scaled Images With URP Decal Projector
I am using Unity's URP Decal Projector to display an oval shaped blob shadow texture.

The image's dimensions are 227 x 70. However, when I use it as a base map for my Shader Graphs/Decal material, it just displays as a small circle. The only scaling options I see are Width and Height, which work similar to a Transform's X & Y scale. These can be adjusted to "estimate" the correct size, but it seems very far from precise.

Is there anyway that I can preserve the texture's aspect ratio/native size so that I can display it properly?

# Answer
Textures are mapped in normalized coordinates, so 1.0 is the far side of the texture, no matter whether it's 2 pixels wide or 2000.

But you van easily achieve an exact aspect ratio by scaling the with:height values to have the same 227:70 ratio as your base map.

Any multiple of 227/70 = 3.2428571428571:1.0 will work.
> 1 votes

---
Tags: unity, unity-urp, decal-system
---


# Question
Title: C# syntax for "This button is interactable"?
What should be the C# syntax for the condition **if (This Button is interactable)**?
I have a script attached to the button, Which has to run only if the button is interactable.

Thank you in advance!

# Answer
Once you have reference to a `Button`, you can use `Button.interactable` to determine if the button is interactable. `interactable` is a member of the `UI.Selectable` class; `Button` inherits from `Selectable`, and thus, has access to `interactable`.

The below script takes a `Button` reference, and runs logic if the button is selectable. When you intend to "run the script", simply call `Run()`. The logic will not run, if the `Button` is not interactable.

```
public Button button;

public void Awake()
{
    if(button == null)
    {
        button = GetComponent<Button>();
    }
}

public void Run()
{
    if(button != null && button.interactable)
    {
        // run your logic, here.
    }
}

```
> 3 votes

# Answer
Checking `button.interactable` checks only if the button itself is interactable, completely ignoring the possible existence of Canvas Groups.

The correct check should use `IsInteractable()` instead of `interactable`:

```
public Button button;

public void Awake()
{
    if(button == null)
    {
        button = GetComponent<Button>();
    }
}

public void Run()
{
    if (button != null && button.IsInteractable())
    {
        // run your logic here.
    }
}

```
> 1 votes

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


# Question
Title: Unity Canvas on Quad blocking mouse click sometimes?
I'm working on a card game that has quads with world space canvases on them. I've been using `OnMouseOver()` and `Input.GetButtonDown(0)` for detecting mouse clicks on the quad, but sometimes it seems the mouse click doesn't work when I'm over the quad. Now, I've checked multiple posts detailing different possible solutions to this question, but many of the raycast settings on the canvas and its children haven't produced results.

# Answer
> 0 votes
I noticed the card hitboxes were working fine in the hand. The reason it wasn't working on the play field was because of the perspective; the card was being partially blocked by the slots in the playfield itself because of the perspective.

---
Tags: unity, unity-ui
---


# Question
Title: Should we have multiple scripts doing only one thing, or one large script?
I'm currently working to make a game, and it's a first for both of us.

We are at the point where we are starting to have a lot of scripts pile up, and are wondering about the resource management & resource impact on having a lot of small scripts running.

Is there any drawback to having multiple scripts only doing one thing, as opposed to one large script?

For example, one of our scripts only contains this following code, and is likely to not change, but all it does is destroy the object after it's hit twice;

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

public class PartsController : MonoBehaviour
{
    int collisionCounter;
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Projectile")
        {
            collisionCounter += 1;
            if (collisionCounter >= 2)
            {
                Destroy(gameObject);
                Destroy(other.gameObject);
            }
        }
    }
}

```

Would we be better off trying to nest things like this into a larger script, instead of running several small ones?

# Answer
Scripts take up some space in memory, but a larger script covering the same job would generally take up the same amount or more. So you don't save anything that way.

If you have many instances of different scripts and you combine them into a single instance of a master script, you reduce the memory overhead of each individual instance, but this is normally not something that breaks the bank. And you might increase the complexity and potential for bugs by combining many different responsibilities into one script this way.

Scripts with an `Update` (or `FixedUpdate`, `LateUpdate`, etc.) need those methods called every frame, and that method call cost adds up even if those methods don't do anything. But the example you've shown doesn't have such a method, so that doesn't apply here.

**For the script example you've shown, its main runtime cost is in invoking its collision handler.**

If you replaced this script with a different script that also does the same job, you'd still have to invoke that collision handler, so that cost would not decrease.

(Technically it's *possible* to get a savings here if the needed part of the larger script was already in the instruction cache, so you don't need to go fetch a new version of it from a different script. But if you have a project with lots of different behaviours used a few times each, then it's not especially likely that the needed snippet will reliably be in cache the next time you use it - so I don't expect that will benefit your case).

If that new larger script does other things in its collision handler, then you'd need to add some extra logic to check whether it should do those other things, or do just the things that this smaller script does. That extra logic could *increase* the runtime cost.

**So, refactoring this into a bigger script is likely to be a pessimization.**

If you want to optimize this script, there are two things you can do:

1. Invoke the collision handler less often
2. Do less work each time you invoke the collision handler

You can get both of these at once by using physics layers instead of tags to separate your projectiles. Create a "Projectile" physics layer, and a "Projectile Detector" physics layer. Put all your projectiles on the projectile layer, and this script's object on the detector layer. Set the collision flags so that the detector layer collides *only* with the projectile layer.

Then you can remove the tag check (which should have been using `CompareTag()` anyway, but that's beside the point). *Only* projectiles will be able to invoke this collision handler, and every other object will be ignored automatically.

So, fewer invocations, and less work checking inside each invocation.

---

In terms of general practice advice: I would say ***favour* small scripts that do just one job**. Small scripts with a simple defined purpose (Single Responsibility Principle) tend to be easy to reason about and maintain, and less prone to developing bugs than massive scripts that try to do a lot.

Profile your game regularly, and use that evidence to find whether there is a particular script that has an outsized impact on your performance, rather than being suspicious of scripts overall.
> 7 votes

# Answer
Yes, having fewer **components** in the scene (which might or might not correlate with how many distinct script files you have) means that Unity has less management overhead, so reducing components by integrating multiple features into one can be a performance optimization.

**But** performance is not all that matters. Unity favors a software design approach called composition over inheritance. The idea behind this design approach is that having many small classes which each do exactly one thing is better than having few large classes which handle everything a specific entity does. The main argument for this component-based approach is flexibility: Each entity is the sum of its components. Which means that it is very easy to create a new type of entity by simply combining existing components in a different way. For example, when you have a `Hitpoints` component which you put on anything that can be attacked and destroyed, then you can make any object in your game destructible just by adding that `Hitpoints` component to it.

In the end it's a trade-off between performance and design clarity. And whenever you stand in front of such a trade-off decision, remember a well-known mantra in software development: **Premature optimization is the root of all evil**. It is very difficult to predict in advance which parts of your code will be the biggest performance hooks. So sacrificing code readability and maintainability for performance when you don't even know yet if the player is even going to notice that performance optimization is counter-productive.

So what you should usually do is prioritize design clarity until you *actually* have a perceivable performance problem and you used the profiler to find out which part of your code causes those problems.
> 7 votes

# Answer
"It depends", as always in software development.

Unity has a component approach, and if you look at the built-in stuff, it generally follows the philosophy of having several scripts instead of one. So you have a collider component and a Rigidbody component instead of one "Physics Object" component - because it is possible that you want one but not the other.

One approach is to start with a general design principle of using scripts doing one thing, but watching out for indications that scripts should be lumped together into one, such as:

* two different scripts communicating more than once with each other (via direct calls or messages)
* one script accessing data stored on another script
* two different script manipulating the same object data (such as position or rotation)
* code starting to be duplicated between scripts, either exactly or very similar (i.e. something you could merge with an if or two)
* two different scripts listening to the same input, be it player input, physics interactions (collisions, triggers, etc.) or messages from other scripts.

All of these and a few more are *signs* that this maybe should be one script instead of two, but there can still be good reasons to keep them separate, so it's always a case-by-case decision.

Note that some methods do indeed have a performance impact. Running `Update` on ten scripts is more expensive than running it on one, and that is true for many more functions. For objects you have once in your scene like the player object, that essentially doesn't matter, but on objects that can be in the scene hundreds of times, it can have an impact on performance.
> 2 votes

# Answer
## The short answer:

It's better (in my opinion) to use lot's of small scripts, having looked through lot's of decompiled games from professional game dev companies, this seems to be the way to go. The reason is pretty simple, if you have lots of small scripts it's easy to find what you're looking for without having to take a deep dive into one large script.

However, it may not be that simple for you.

Let's break it down into 2 key points: **preference** and **efficiency**.

**Preference:**

Obviously, it's up to you to decide which you prefer, research what benefits you get out of both options (although I'll tell you there aren't many benefits or drawbacks to either approach)

Find which method suits you best, feels good, and just feels right. If you have a higher efficiency writing it in separate scripts, but it makes it less enjoyable, use one large script. Over the years I've spent doing game development, the biggest thing I've realised, is that it doesn't matter how you do something, as long as it works, and is enjoyable to write. That being said, usually the more efficient solution *is* more enjoyable, as you get a faster, more satisfactory result.

**Efficiency:**

If you find yourself wasting time looking for the right script in a folder that contains hundreds, you have a low efficiency. When it comes to Game Dev, having a high efficiency is key. Alternatively, if your struggling to find a function inside your 10000 line giant file. That would also be inefficient.

Since you're using Unity having the scripts interact with each other is simple, since Unity automatically compiles all scripts into the same assembly and some other stuff I'm not so sure about, compared to something like C++ which can get really annoying when trying to include different files, Unity makes it really easy. If that weren't the case, then it may be worth using larger scripts.

I hope this answers your question clearly.
> 1 votes

# Answer
I don't have any experience with game development, especially not with Unity, but... code is code, and I'm very well familiar with C#, so I think I can add my 2 cents.

In my opinion, this is a matter of taste. This same question - "fewer large files vs more small files" comes up in all sorts of programs. Performance is usually minimally affected, but readability and maintenance is a different story.

I've seen examples of both extremes. A project where no code file has less than a 1000 lines, and a project where almost every function has its own file. And I must say, both were hard to work with.

For large files, you often get lost in them and need to spend time finding your way back. Large files also tend to breed large methods which are also hard to keep in mind when reading code.

On the other hand, if you split your code into 1000 small pieces, that's also a challenge to comprehend. You only ever see a small part of the overall process you're investigating, and you need to keep jumping back and forth between files, trying to remember 1000 tiny pieces and how they all relate to each other.

It's a matter of taste, of course, but if I have to choose between these two extremes, I'd rather do the large files than the 1000 breadcrumbs.

Ideally though you want to strike a balance. Not too big, not too small.

Split and group functionality together so that each piece makes sense logically, not worrying too much about file size. This way, when you need to work on a certain piece, you can think about it in isolation, forgetting most of the rest of the system. And all the code for it should be close together, so that you don't need to travel far and wide trying to round up a zillion miniature particles.

And in turn when you use it, you don't need to think about how it does what it does - you can just treat it like a "black box of magic" that can do certain things.

Note that it's pretty difficult to judge these things while *writing* code. Writing code is easy, no matter how you split or merge it. When you have freshly written it, it's all in your mind and all seems easy. But come back to it after a year (or ask a colleague to look at it) and you'll start to get a sense of how well written it is. If it's well written and well split/grouped, you'll easily remember (or understand) what is what and where to look for the lines you're interested in.
> 0 votes

# Answer
You will probably be more productive if initially you just write back to back, and then worry about taking out the common functions and organizing it into smaller scripts later on. I would say write it so it works then consider refactoring it later.

Use `ctrl``f` to jump to parts of the script that need your attention, rather than fumble with open tabs.
> 0 votes

# Answer
As has been often noted, efficiency-wise it's not going to matter. Spreading your code into X many scripts comes down to readability.

But making many small scripts, like that collision thing, is a pain. Looking through a Cow script that does everything Cows need isn't too bad. But with a small script for each Cow ability, having to remember the name of the script that does X to them is a pain; and having all of those scripts open in your editor is too many to fit.

It also makes communication more complicated. With one big script you can use "class globals" -- if 3 other Cow functions need to use your `collisionCounter` variable they can read it as-is. With lots of small scripts you need to find the other script with things such as `GetComponent<BrickCollision>().collisionCounter`.

So, in practice, make a large script for each type of gameObject, use #region, and when that gets messy split it into 2 or more.
> -2 votes

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


title: Momentum of a ball on a moving platform

text:
# Question
Title: Momentum of a ball on a moving platform
I'm seeking information on how to implement something. I have a ball on a moving platform. The ball has a position and momentum.

Here's a gif illustrating the situation:

So the way it works is, the ball detects when it touches a specific platform, and "childs" itself to that platform. When the platform moves, it will go through all its children and move them by the same amount.

My problem is, when the ball moves on a platform, it should accumulate momentum from the motion of the platform-- which should be visible when the platform slows down (or in some cases stops abruptly)

I've tried several things but always end up with an accelerating ball that zooms off in the direction of the platform. I've tried subtracting the component of the ball's momentum from the momentum that is going to be added but I still get an accelerating effect. In fact everything I try gives me acceleration in the direction of the platform's motion.

Can anyone explain to me what the right way is to deal with this problem?

* + - Edit to add some clarification:

In the interests of making this run on slower devices, the ball's physics are not complicated. The ball's main loop is a glorified version of mPosition+=mMomentum, with the player able to change the momentum.

When a ball is on a platform, all that happens is, the platform says "I moved n, therefore Ball-\>mPosition+=n" ... but I would be interested in hearing the "right" way to do this so that I can try to adapt it in such a way that it doesn't require a full hardcore physics simulation to run.

# Answer
Other than the mentioned friction on the sphere body you could try looking into matrix multiplication. Transform the sphere matrix with the platform matrix then setting the resulting velocity vector to whatever it was before that matrix multiplication. You could also try simply adding the velocity vector of the platform to the sphere when it detects that it no longer collides. Good luck with your game.
> 1 votes

---
Tags: physics, 3d, moving-platforms
---


# Question
Title: How do I make a hitbox for a sword in a top-down game?
Context: I'm using Box2D through LibGDX in Java. The sword and the player are in separate classes. Both extend LibGDX's Sprite class.

I've got a sword attached to my character that swings when I press 'X' on the keyboard, but I'm having trouble defining its hitbox. I want the hitbox to cover the area that the sword currently is, acting as an extension of my character so it doesn't push him around or slow down his movement. However, when the hero slashes his sword on a wall, I want it to push him back.

**The animation:**

I want the hitbox to appear only for the duration of the animation (there are only two frames in the animation), then disappear until the sword is swung again.

Would I have to set the hitbox's position to certain coordinates for each frame of the animation in a long switch-case? How could I easily find these coordinates, or is it just trial and error?

# Answer
A switch case would be a great start. And you could try looking at the use of an overlap function of the axis-aligned bounding box of the sword to that of the wall, then push the difference from the player.
> 0 votes

---
Tags: java, libgdx, animation, box2d, rpg
---


title: Hide Horizon Line with Small Terrain?

text:
# Question
Title: Hide Horizon Line with Small Terrain?
I'm drawing a sky plane with an atmosphere fragment shader in front of my terrain. It looks pretty much fine at sea level, but if you move above the sea level, the illusion is quickly broken, as you can see from the image.

Looks fine:

Illusion is broken as you move higher up:

I've googled this, and either I've heard either 1. you can make the render distance really large to compensate for this which is not an option, or 2. mix the fog colors with the sky plane colors, which also does not work, because my sky plane is not a single color and mixing fog with the color below the horizon line wouldn't look good or make sense.

Is there any way to get around this? Can fog even be used here to cover the horizon line? Or am I forced to resort to a solid color sky plane, or at least one that doesn't have a horizon line?

# Answer
First of all, any sky whatsoever will look wrong when you are far above a tiny level and can see the level clearly sitting in empty space below you. The difference between a smooth background and complex geometry is immediately obvious to the eye. You'll never be able to make the perspective in your second picture look *good*, especially in motion. To avoid this problem, pick a solution:

* Don't let the player fly that high.
* Choose your “fog” to be strong enough that by the time you can easily see the edges of the world below you, it's thoroughly fogged out. That is, if your level geometry is small, make the fog close to match it.

---

But we can do the sky better too.

It looks to me like you're calculating a simulated atmosphere, but not accounting for what's *behind* that atmosphere. Abstractly, pixels below the horizon should not just be colored by the atmosphere, but also colored by the ground that they strike after passing through the atmosphere. Of course, you don't want to have infinitely large geometry, but you can pick an average color for your distant ground, and use that in your sky calculation. Here's what that looks like, using an extremely simple sky (no atmospheric simulation, just an upper and lower color) I happen to have recently programmed:

Now, obviously there is an edge to the geometry here. But it blends into the sky visually, because the lower half of the sky is calculated as equal to the color of the grass lit by the color of the upper half of the sky. Thus, the bottom half *looks like* an infinite plane similar to the ground plane in the foreground.

If you are simulating a spherical world (or, in general, finite size rather than an infinite plane), then the horizon line below which the ground is visible should naturally move down as the viewpoint moves higher up. This is fine — everything works out as long as the actual level geometry doesn't end up sticking up *above* the portion of the sky rendering that is ground-colored, which should always be true if your calculations are physically-based. Here's an exaggerated diagram of how that should work out (presented as a 2D slice through the 3D space that passes through the viewpoint):

You probably still won't want the player to actually fly this high, so the angles will be smaller.

> or 2. mix the fog colors with the sky plane colors, which also does not work, because my sky plane is not a single color and mixing fog with the color below the horizon line wouldn't look good or make sense.

What is fog?

* Physically, fog is just the part of the atmosphere between you and objects. It's not different from what's happening in the sky.
* In rendering, fog is how we make very different stuff gradually fade out rather than being abruptly cut off.

**You can and should make your “fog color” be the sky color**. Render your sky to a texture, then when drawing your geometry, in the fragment shader, sample the texture and use that as the fog color. This will make distant objects fade into matching the sky (at any angle), and thus be completely invisible once they are finally clipped. If you use any other color, there will be visible clipping.
> 1 votes

---
Tags: 3d, graphics, fragment-shader
---


# Question
Title: How do you manage shared assets and tools across a team and projects?
As my team grows I'm trying to better manage shared assets in an organized way across the team. These assets include:

* Brushes and Alphas for Substance, Blender, Krita, etc
* Custom Plugins for Maya
* Trim Sheets and tiling textures
* Reference meshes and images
* Useful configs for content creation softwares that maintain consistency and adherence to our asset policies
* In-House tooling that simplifies certain workflows
* ... and so much more...

The nature of these assets is that they're not tied to any specific programs and all have their own structures. As such, it's not enough to just integrate with an existing engine's marketplace.

These are assets that may sometimes be updated, or expanded upon- and they may have dependencies on other assets, though probably not often.

Our team composition includes around 20 individuals with a diverse set of skills from the deeply technical to the aesthetic and visual (i.e. Software devs, artists, and technical artists). As an example of where we're at with our tooling- we've been able to onboard everyone onto git for version control, including our artists. However, this was only possible with the use of Github Desktop and Sourcetree git clients. We're using a self-hosted Gitea instance to store all of our repositories. We use Notion for process documentation, discord for team communication, and build primarily for Unity. We have a private npm package registry for Unity specific packages, *and all other assets we share either through attachments in Notion or just by sending it directly when asked.*

It's that last part that is woefully insufficient and I'm hoping to get advice on. How do other gamedev teams of similar size to ours handle syncing assets and tools across their teams. What we're doing now is not scalable and the discoverability of these tools and assets is so bad that often people are redoing work when they don't have to.

What workflows and processes are used to support this need? Are there solutions out there that are easy to onboard for people of less technical skillsets?

# Answer
I worked at a studio of about 400 people and there was a central team managing the Unity plugins. I had to send them an email to get access to a unity asset for example. I dont remember much but I think they were also managing other types of assets. There was also a central tooling team who was providing tools to extend Unity capabilities. If I rembember correctly, we had to clone a SVN repository to get those tools. So maybe you could also provide your assets in one or more Git repositories. Specific roles could clone repos interesting to them and by doing so would get access to all your up to date internal tooling.

In another company of about 20 people, artist assets were simply put and organized into google drive. At least with Notion like you currently do, you can put context and visually organize your assets.

I've never seen this, but another option I guess would be to make your own artifact registry. For example using Azure you could easily create a NuGet or a npm registry: https://learn.microsoft.com/en-us/azure/devops/artifacts/start-using-azure-artifacts You can even create a "universal package" registry. But I think this might be overkill.
> 1 votes

---
Tags: tools, asset-management, project-management, teamwork
---


# Question
Title: "Loaded resource as image file, this will not work on export" - what does this mean
I'm sure it is something unrelated is why my program won't work, but I still want to know:

`core/image.cpp:1746 - Loaded resource as image file, this will not work on export: 'res://ball.png'. Instead, import the image file as an Image resource and load it normally as a resource.`

What does this actually mean!? What is it telling me to do?!

# Answer
> 5 votes
I'm not deeply familiar with Godot, but here's my interpretation based on reading the docs:

Many game systems include a concept of "baking" data. The authoring tools might accept a wide range of "raw" asset formats — like png or jpeg — but these are often not ideal for use in the game runtime for various reasons:

* Their data layout is different than what the game uses internally (eg. GPUs use specialized compressed formats for rendering)
* The workload of converting/recompressing the assets in-game would bloat the runtime and slow down loading the game / levels
* Pre-digesting the data lets the game load faster, say by breaking the data into chunks to load only what's needed, or batch loading a group of needed assets in one pass
* The raw formats lack metadata information that the game needs to use them as intended

So the authoring tools accept a reference to these raw asset files, and then "bake" them into a form that's efficient for use in the published game. This means the files your game uses at runtime might not be the exact same source files you provided originally.

In Godot specifically, the docs say:

> In Godot 3+, image files are no longer native resources and they must be imported. The reason behind this is the large amount of configuration parameters that image files can be imported with.

So, it looks like that's what's happening here. The engine wants to used a baked asset ("imported resource") here, and you're giving it a raw asset ("native resource") like a png.

The error warns you that while this might work in the editor, it won't work in the exported game because the game only knows how to handle baked assets like imported resources;

> core/image.cpp:1746 - Loaded resource as image file, this will not work on export: 'res://ball.png'. Instead, import the image file as an Image resource and load it normally as a resource.

So, you can follow this guide to import your image to be able to use it as an imported resource, which should fix the error.

# Answer
> 2 votes
The answer by DMGregory is correct, though the solution given is not complete.

The most common cause is the project including `icon.png` as a default setting. For running on the web, you should convert this to `icon.icns`. You can use this free converter page to do that.

Once you have the converted icon, go to Project/Project Settings/Application/Config/icons and select your new `icon.icns`. This doc page may help.

# Answer
> 0 votes
For C# (.net) you should use someting like this:

```
var image = ResourceLoader.Load<Image>("res://ball.png");
var texture = ImageTexture.CreateFromImage(image);

```

---
Tags: godot, export, importing
---


# Question
Title: White noise on my material after import to UE5 from Blender
Please have a look at the 2 screenshots attached. The first one is from Blender. The second one is UE 5.3.

1. My first question is why my model in Unreal looks brighter than in Blender?
2. Do you see kind of “white noise” on tongue and lips on the second screenshot from UE? What could be a root cause of that?

I would be really appreciated for your help

# Answer
> 1 votes
Solutions.

1. Regarding to the first one. My BaseColor had disabled sRGB, so I’ve enabled it. Additionally, I’ve changed strategy to export my textures from Substance Painter and import them in Unreal. The way is:

a. Template should be Unreal Engine 4 (PAcked). 8bits. png or jpg

b. Exported textures import to Unreal.

c. One of the maps contains Metallic, Roughness and AO. I enabled sRGB for this map in Unreal.

d. Then created node and connected R with AO, G with Roughness and B with Metallic.

e. Other textures are self-explanatory for connection.

It is as expected now.

2. Disabling r.Lumen.ScreenProbeGather.ShortRangeAO in Unreal Engine helped to get rid of that issue. Actually antialiasing TSR and MSAA helped too. I don’t know yet what is better for me. Will see

Thanks

---
Tags: rendering, blender, materials
---


title: Approach to rendering a planet texture

text:
# Question
Title: Approach to rendering a planet texture
I'm making a space game using Godot 4, and I need to capture the "hugeness" of planets. I figured I'd use spheres with textures on them for planets. The textures have identifiable landmasses on them, because that's consistent with what planets have. You should be able to recognize the same landmass when you see it again.

The planets all need to spin, as planets are wont to do. I figure I'd just rotate the mesh itself while the player space ship is still far enough away.

My difficulty begins with approaching the planet closely enough. I don't want to land on any planet, but I do want to be able to achieve a low enough orbit that gives the sense of a horizon. The little picture should illustrate it well enough.  I figure I could "squash" the sphere into basically a flat circle when the ship gets close enough to the planet, and you wouldn't notice. I'd point this flattened sphere at the player's position, so it would function like a billboard in that sense. This flattened sphere could then be scaled up in the right directions, to give the sense of a vast circular plane almost.

I figure I could do *some* kind of trickery with UV offset and scale to keep the texture "in the right place", but i don't have any idea where to start, especially because it would need to be scaled up when you get close to it AND it would need to be in the same place as it was when you were further away from it AND...the uv would need to be offset by the rotation of the planet constantly because when the mesh is squashed, you can't rotate the mesh itself anymore. truthfully, i don't have much experience with uv shenanigans, nor with optical perspective. This whole approach is just an intuitive attempt, but i have to do SOMETHING because just "really big spheres" doesn't give a good enough impression of the hugeness of planets and stars and moons, and I don't know any of that shader black magic that could do the sphere-imposter trick on a quad (especially one you could freely orbit around).

The textures don't need to be super sharp: maybe i could stylize them somehow to be acceptable, but they DO need to have those recognizable landmasses which you can revisit, hence the difficulty.

Does anyone have any pointers for how to do this? Alternatively, does anyone know of a better solution for giving that "vastness of planets" feeling that emerges seamlessly once you get close enough to a planet?

# Answer
One way to approach this would be to generate the surface of the planet procedurally, using weighted octaves of noise;

Start with a noise function like Perlin or Simplex that takes an x/y\[/z\] coordinate and returns a value (usually 0-1) for that position.

By scaling the sample coordinates, you can generate different "octaves" of noise.

Blending those together with different weights can give a texture that works very much like a height map, except it can be sampled at arbitrary levels of detail...

Pick a cutoff height as a water level and you now have randomly shaped, but deterministic/repeatable continents with mountainous features.

If you want to go a step farther, you can also calculate erosion and other effects. It'll give you a more realistic result, but it'll be a lot more compute intensive and may require pre-calculating.

For more info on the approach see:

You can either use a 2D noise function and map a 2D coordinate system to your sphere's surface (but you'll get the usual spherical wrapping quirks) OR use a 3D noise function and just sample the points in space for the surface of the sphere, then treat that as a surface height.

Add a random offset to the coordinates for each planet and you'll get unique (but deterministic) results.
> 0 votes

---
Tags: textures, geometry, scale, perspective, planet
---


# Question
Title: encapsulation, structs and global variables?
I have worked on creating a gameloop and so far all of the code was inside a main.cpp file and I want to separate it into different files.

Which caused several problems:

My code is separated into 3 main functions in main(); which are input simulate and render.

I was able to separate the input code into its own file, however I ran into 2 problems I had to fix:

```
#include <iostream>
#include <SDL.h>
#include "input.h"

extern bool isMainLoopActive;
extern bool isMoveRightPressed;
extern bool isMoveLeftPressed;
extern bool isMoveUpPressed;
extern bool isMoveDownPressed;

struct detected_keys {
    bool right = true;
    bool left = true;
    bool up = true;
    bool down = true;
};

detected_keys movement_keys;

void input() {

    // player control of box
    const Uint8* currentKeyStates = SDL_GetKeyboardState(NULL);

    if (currentKeyStates[SDL_SCANCODE_RIGHT]) {
        isMoveRightPressed = true;
        movement_keys.right = true;
    }
    if (currentKeyStates[SDL_SCANCODE_LEFT]) {
        isMoveLeftPressed = true;
        movement_keys.left = true;
    }
    if (currentKeyStates[SDL_SCANCODE_UP]) {
        isMoveUpPressed = true;
        movement_keys.up = true;
    }
    if (currentKeyStates[SDL_SCANCODE_DOWN]) {
        isMoveDownPressed = true;
        movement_keys.down = true;
    }

    return;
}

```

The 2 problems are:

1. While I was coding in one large main.cpp file I was able to have a lot of functions and variables at the top of the file which were all global. Now that I moved the input() to a new file I lost direct access to the global variables.

So what I did first was use

```
extern bool isMainLoopActive;
extern bool isMoveRightPressed;
extern bool isMoveLeftPressed;
extern bool isMoveUpPressed;
extern bool isMoveDownPressed;

```

to simply get access to these variables back. However I read somewhere that one should avoid relying on global variables.

So I looked for a way to transfer the 4 key presses represented as boolean variables from one function to another as a struct.

However if I want to use a struct of the type "detected\_keys" then I would have also declare that type in the other files, which would be the same as just using extern variables all over.

So what is the best approach here if global variables are supposedly to not be used?

Is all code in videogames basically functions passing values over to each other in large packages? And if so, is there a data type that is better for that than struct?

# Answer
> 2 votes
The only difference between a class and a struct is that members within a struct are automatically public.

You could just create a class for all the input:

```
class Input
{
public:
    static bool isMainLoopActive;
    static bool isMoveRightPressed;
    ...
}

```

but a struct would also work, e.g.

```
struct Input
{
    static bool isMainLoopActive;
    static bool isMoveRightPressed;
    ...
}

```

The more important part is that they are static, since that would mean modifying them anywhere would change the values everywhere. Similar to global variables, also see Static keyword in c++.

The main difference between this and your method is that they are no longer global, but they do essentially the same thing. Instead of grabbing them normally, you would use something like Input::isMainLoopActive. This can also help code become more clean and understandable, as anyone can see its part of input, but thats just an example, you can change it to work with your scripts, and create multiple structs/classes if you need.

---
Tags: c++, sdl
---


# Question
Title: Sanity Check on my Idea for an Event System for game
So, I recently started making a small game from scratch, with no engine used(I'm a beginner at this) and I want to create an event system of my own. I want to check if my general idea for it is okay(any suggestions to improve it will be nice too). For reference(if this helps) I'm coding this in C++.

My idea:

We have a class named NewEvent, which holds several virtual functions for setting event flags, getting the name, etc.

For more specification, we have a function getting the name of the event, a function setting the flag of it, another function getting the flag, another function finding which 'category' of event it is.

Outside of this class, we also have an enumeration of events that I will detect for so that we don't record everything, just the specific ones we want. Examples would be keypresses, key releases, mouse clicks, window movement, window closing, window scaling, and mouse movement. Not exhaustive, just a few.

We have derived classes from NewEvent that share the enumeration names, like 'class KeyPress: public NewEvent', 'class KeyRelease : public NewEvent', and so forth.

Then we have an event dispatcher class, which compiles these new events that have been detected into a static queue so that we don't create a queue every time we create another dispatcher. This is then fed into a static dispatch function which will run on a different thread and then the resulting information on what to do will be fed back into the main thread, which will then run what we want it to. The threading is mostly so that if events buffer and slow down for some reason, it won't slow down the actual main application.

I'll try to answer clarifying questions as best as I can, and if anyone has any suggestions on making this idea more robust or expandable, that'll be greatly appreciated as well.

# Answer
First of all, there is no "right" or "wrong" in software development. Only "works for you" or "doesn't work for you". So any advise about your software architecture that is only about one part of it in isolation without having access to the big picture or the exact requirements for your engine should always be taken with a grain of salt.

But a few things I notice here:

* Why is the base-class for your events called "New" Event? That's a weird naming convention. I would rather call it something like `EventBase` to communicate that it is a base-class for all events or something like `AEvent` to communicate that it is abstract. I would also find it a lot more orderly if all the specific event classes would either have "Event" in their name or be in a `event::` namespace, so they can be immediately recognized as events. But there are only two difficult problems in software development: Cache invalidation and naming things. So this isn't something we should argue about.
* Are you sure you want only one global, static event queue? It can often make sense to have separate event queues for sub-systems that are isolated from the global event queue. If you still want the convenience of accessing these statically, you can create a bunch of static getter-functions on your EventQueue class to retrieve a *specific* event queue.
* *This is then fed into a static dispatch function which will run on a different thread \[...\] The threading is mostly so that if events buffer and slow down for some reason, it won't slow down the actual main application.* Are you sure this is a good idea? First of all, the mere dispatching of events without reacting to them is rarely going to become a performance bottleneck. If you generate so many events that it does, then either something is going very wrong resulting in unnecessary event spam or you are communicating stuff via events that probably shouldn't be an event at all. And when it does, it's going to become a big issue. The possibility that the delivery of certain events could be delayed by a couple frames for unpredictable reasons sounds like a great generator for impossible to reproduce bugs.
* *"the resulting information on what to do will be fed back into the main thread"* I just hope that what you actually mean with that is that the events will be stored in thread-safe buffers, which the main thread will then process at designated points within the game loop. And not that you are just having the dispatcher thread write into the data model without any concerns for thread safety. Because one thread changing data while another thread operates on that data is another great generator of impossible to reproduce bugs.
> 2 votes

---
Tags: c++, architecture, events
---


title: Destructible Terrain like worms

text:
# Question
Title: Destructible Terrain like worms
I have to develop a game with a dynamic destruction of the map, I searched the internet and even looked at some questions regarding this topic on this Website, but they did not help me much out.

I made the map with tiled and used box2d to make collision between the game objects. As a game engine we have to use Libgdx, but I dont know how to start as I had never develeped a game before, can someone give me any tipps how I could start?

with regards,

# Answer
> 8 votes
Okay, the naive approach is this: construct your terrain up of rectangles that are 1 pixel by 1 pixel (or, in the case of one of the 3D worms, of cubes). If you have a bullet, or an explosion, or any other source of destruction, then what you want to do is as simple as applying collision detection, and removing all of the rectangles/cubes that collide with the source of damage. The problem is, this is slow.

But, we can still use the idea behind this, if we're clever about it. The trick is: model the terrain as a larger rectangle. Then, when that rectangle collides with a source of damage, segment it into four smaller rectangles. And apply this recursively until you reach a necessary level of precision (i.e. 1 pixel, 2 pixels, 4 pixels, etc.) When you reach that level, remove all of the rectangles that are still in contact with your source of damage.

Here is an example of how it would look:

Note, that for more complex terrain, you could expand this into other polygonal shapes. However, consider also, that with some thought, you can model the shape of your 2D terrain using procedurally generated rectangles. But that would be a bit of a different discussion to have.

# Answer
> 5 votes
Old Worm games did use the pixel by pixel approach, but this was a bit more understandable in that era. Pixels weren't as dense and per-pixel collision was easy and fast (you could check whether two sprites collided during drawing). Modern Worms actually use something called marching squares or marching cubes. Instead of actual pixels, the map is made out of values between 0 and 1 in a specific density, then the algorithms take this and convert it to a mesh.

# Answer
> 4 votes
You don't need quadtrees for this. If you're not used to recursion, I would suggest an RLE approach like Minecraft uses, because it's simpler to understand: for every vertical column of pixels, store ranges saying where that column starts and ends, in vertical pixel coordinates. Multiple ranges then allow for multiply-fragmented terrain, or what is known in voxel lingo as "overhangs". For example:

`0-255`

Assuming your space is 256 units high, this means *this* entire column is solid ground, from end to end. *Other* columns nearby might not be, such as:

`0-115,121-167,170-255`

which is a column that's been fragmented. We have a solid volume from the "sea level" `0` to `115`, then there is a space of air between `115` and `121`, then we have another solid range from `121-167`, another air space, then we conclude the solid from `170` to the max height of `255`.

Why use only values `0-255`? Because that's the range a single 8-bit byte can support, making transfer of such information cheaper (across system bus, across network, etc.). You could also go for unsigned `short` `int`, @ 16 bits with range up to `0-16384`. Bytes and shorts also make more efficient use of limited CPU cache / line space, meaning you can increase CPU throughput.

Your world consists of these columns, each of which are made up of the ranges described above.

```
struct World
{
    List<RLEColumn> columns; //running left to right
}

struct RLEColumn
{
    List<Range> ranges;
}

struct Range
{
    byte min; //unsigned
    byte max; //unsigned
}

```

or maybe, if you're willing to limit the amount of vertical fragmentation to make it more efficient:

```
struct RLEColumn
{
    Range[] ranges; //could make this length 4, 8, 16 or what have you
}

```

# Answer
> 1 votes
By following the answer from Chris Qu, I've implemented a Phaser 3 + Typescript helper library for Destructible Terrain. Using Quad-Tree algorithm for creating/erasing terrain, collision detection and rendering.

It's on Github: https://github.com/xjxxjx1017/Destructible-Terrain-With-Phaser

Originally, I've tried using pixel by pixel approach, but it didn't get far until I found its limitations. Aside from performance, the approach seems to limit the bullet to be a point. (e.g. a line or a block shape bullet will be hard to achieve due to performance reasons).

# Answer
> 0 votes
The simplest option is to implement a quad tree. Here is how it looks like:

Here is my implementation: https://github.com/hesmeron/Destructible2DTerrain

I went into detail on how it works on my medium tutorial https://medium.com/@hesmeron/2d-destructible-terrain-in-unity-using-quadtrees-09e99a161b96

But, basically you use spatial partitioning to effectively construct a mesh and access necessary data.

---
Tags: physics
---


# Question
Title: Creating a new camera in 2D mode sets it as default, despite not being the main camera
I created a new camera in Unity's 2D mode, and for some reason it's being set as the main camera, despite not being tagged as such. The original main camera is in fact tagged as "main camera" but it will only display if the other one is disabled. Why do the cameras behave this way?

Here's the `MainCamera`, which is **no longer** the default:

Here's the `BattleCamera`, which for some reason **is** the default:

# Answer
Unity uses the `depth` property to determine the order that cameras are drawn in. If two cameras have the same `depth`, there's no guarantee which camera will be drawn first.

Unity will render any camera that is currently active and enabled, even if only one of those camera views is currently visible to the player. To avoid performance issues, it is very important to deactivate any camera that isn't currently being used (with `camera.enabled = false` or `camera.gameObject.SetActive(false)`). Properly managing your cameras will also prevent confusion about which camera should currently be visible to the player.
> 6 votes

---
Tags: unity, 2d, camera
---


# Question
Title: How to to make KeyListener do an action only once per press, even if the button is held down?
I'm trying to make a turn-based game where my character is allow to move in any direction, but only by as much as the dice rolled allows him.

My problem is with how I'm using `KeyListener`: the character will keep moving while the button (let's say 'W' for up) is held down. It's almost impossible to move him by one increment per press.

How can I do the action just once even if the button is held down?

Here's my implementation:

```
package main;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyHandler implements KeyListener {

public boolean upPressed, downPressed, leftPressed, rightPressed;

@Override
public void keyTyped(KeyEvent e) {
}

@Override
public void keyPressed(KeyEvent e) {

    switch(e.getKeyCode()) {

        case KeyEvent.VK_W:
            upPressed = true;
            break;

    }

}

@Override
public void keyReleased(KeyEvent e) {

    switch(e.getKeyCode()) {

        case KeyEvent.VK_W:
            upPressed = false;
            break;

    }

}

```

And here's the KeyHandler logic:

```
package entity;

import main.GamePanel;
import main.KeyHandler;
import java.awt.*;
import java.util.concurrent.ThreadLocalRandom;

public class Player extends Entity {

GamePanel gp;
KeyHandler keyH;

public Player(GamePanel gp, KeyHandler keyH) {

    this.gp = gp;
    this.keyH = keyH;
    setDefaultValues();

}

public void setDefaultValues() {

    x = 100;
    y = 100;

}

public void update() {

    if (keyH.upPressed) {

        y -= 16;

    }

    else if (keyH.downPressed) {

        y += 16;

    }

    else if (keyH.leftPressed) {

        x -= 16;

    }

    else if (keyH.rightPressed) {

        x += 16;

    }

}

```

# Answer
Here is the most common and likely easiest method:

```
// Store a boolean for the previous frames keydown value
private bool upPressedPrev;
private bool downPressedPrev;
...

public void update() {
    if (keyH.upPressed) {
        if (upPressedPrev == false) { y -= 16; upPressedPrev = true }
    }
    else { upPressedPrev = false; }
    // Repeat for all keys...
}

```

This works because after pressing down up (or any other key using this method), upPressedPrev would be false, so it would run the code once, then it sets upPressedPrev to true, meaning on the next frame, nothing would happen until the key is released. You could also implement a keyUp syntax using this method. Like this:

```
// Store a boolean for the previous frames keydown value
private bool upPressedPrev;
private bool downPressedPrev;
...

public void update() {
    if (keyH.upPressed) {
        if (upPressedPrev == false) { y -= 16; upPressedPrev = true }
    }
    else {
        if (upPressedPrev == true) { // Do something when the key is up; upPressedPrev = false; }
    }
    // Repeat for all keys...
}

```

This checks if the key isnt currently pressed, but was pressed the previous frame.

Hope this helps.
> 1 votes

---
Tags: java, input, keyboard
---


title: Topological sorting optimization

text:
# Question
Title: Topological sorting optimization
I'm creating a 2d isometric game that uses topological sorting to correctly depth sort all of the oddly-shaped isometric objects. I spent a lot of time writing this from scratch, and it works great. However, it has to sort every object every frame since there are moving entities. Once I get a couple hundred objects in the list, it begins to lag significantly. I'm wondering, does anyone know a way to save on these computation costs?

My intuition is to sort immobile objects once, store this, and then only sort moving objects from then on. However, I fear that this may not be possible with something complex like a DAG.

Edit:

I used this video as a starting point, so it's a good example of what I'm sorting exactly.

# Answer
> 2 votes
For anyone who is coming back to this thread in the future, here is my solution:

While topological sorting does seem to be less hands-on after the initial set up, the computation cost didn't seem to be worth it. Especially when adding a lot of instances that move, running the computation every frame is slow.

So, I decided to use the tried and true method of sorting by y-coordinate and breaking up any non-square objects into tile-sized chunks and sorting respectively. Since I already have width and length defined, it's easy to tell which objects are non-square. However, to avoid manually breaking up every sprite by hand, I had to write some code that does this automatically during runtime.

In Gamemaker, there's a draw function (draw\_sprite\_part) that draws only a part of the sprite. With this function, I can break non-square objects into multiple chunks, separate those chunks into different objects, and draw only that chunk.

In the end, this solution is faster and easier than topological sorting in my case. It probably has less graphical glitches too. Thanks everyone for your help!

# Answer
> 3 votes
The video you linked already shows the solution I would suggest: split large objects into a standard tile size. This increases the overall number of objects, but allows you to use more standard sort. That would make it easier to explore updating just the moving objects. Traditional sorts tend to have n\*log n performance which can beat linear (n) performance under some circumstances. Performance is mostly dependent on a smaller n, but the nature of the data can also be a factor. Some sorts perform very well on data that's mostly sorted. If most of the objects aren't being moved, you could use the previously sorted data as starting point and update the moving objects.

If you want to stick with a topological search, there's been some research on dynamic topological sorts. I noticed that some of the work by David J. Pearce and Paul H.J. Kelly has been used in Tensor Flow and is open source, so that might be a good place to start.

I personally haven't seen it discussed much in the game development related research I follow and I wonder if the Computer Science Stack Exchange community might have better answers regarding topological search. There's also some topological sort question on Stack Overflow, so that might also be a consideration. If you do ask another site, please tailor your question to that community - asking the same question across multiple Stack exchange sites (also known as cross-posting) is generally not allowed & will typically result in having your question closed.

There's also been some research on GPU based topological sorting. D. Svantesson and M. Eklund found thier GPU implementation was only better for large, shallow graphs (pseudo code available). The other paper I looked at by Rahul Saxena, Monika Jain and D.P. Sharma also had some graph restrictions. As such, I'd try other solutions before exploring GPU implementations.

Lastly, consider if there's a game design or game mechanics solution instead of an algorithm solution. It's not uncommon for games to limit things (number of sprites, simultaneous sound effects, ...) based on engine or computational constraints. This could be a hard limit on the number of objects that can be spawned or using something like special foreground objects (clouds or foliage maybe) to quickly exclude some objects from the topological sort via a bounding box. We would need to know more about the specifics of your game to give specific applicable recommendations.

---
Tags: game-maker, isometric, sorting
---


# Question
Title: Implementing framerate independent friction with linear deceleration
I'm implementing friction into my game, and I'd like it to be framerate-independent. Here's my first solution, in Lua style pseudo-code:

```
local pos = 0
local vel = 100
local deceleration = 80

function Game:update(dt)
    vel = move_toward(vel, 0.0, deceleration * dt)
    pos = pos + vel * dt
end

```

with `move_toward` being identical to the way it works in engines like Godot. Here's the implementation just in case but it's not that relevant.

```
function move_toward(from, to, delta)
    if math.abs(to - from) <= delta then
        return to
    else
        return from + sign(to - from) * delta
    end
end

```

Now, this seems to work fine but I noticed that there's still some very small disparities when I try to run this at different framerates: video link (top is 60 FPS, middle is 30 FPS, bottom is 15 FPS). I can't seem to figure out why that is.

I'm not trying to make a perfect or realistic simulation, just one that's good enough for games. I'm familiar with algebra and analysis, but I'd like something that is simple to implement, it's better if I can avoid complicated formulas or bits of code.

# Answer
> 1 votes
The problem you're running into is that you're performing numeric integration with a varying step size. In all but the simplest case (movement at a constant speed), this produces results that vary depending on the step size. There are two ways to fix this:

1. The most common (and usually the easiest) is to decouple your physics framerate from your drawing framerate. In a single-threaded program like you appear to have, that means figuring out how many physics frames have taken place since you last drew the screen, and running the physics loop that many times. Keep in mind that this is more than just "divide delta by 1/framerate", because you might have a partial physics frame left over from a previous drawing frame.
In a multithreaded situation, you'd have a dedicated physics thread running at a constant framerate, and the rendering thread would pick up the results of the most recent physics frame whenever it needed to draw something.
2. The less common option is to symbolically integrate, giving a formula that is independent of framerate. For example, deceleration would have the formula "position = initial\_position + initial\_speed * t - 0.5 * deceleration * t * t", where "t" is the time since deceleration began. This is usually harder than separating physics from drawing, and for more complex motion, isn't even always possible -- but when it is, it's more accurate than going with option 1.

# Answer
> 0 votes
This is my best guess on how you would achieve something like this:

Since code is run frame by frame there is no way to create a truly independent loop that runs separately from the regular loop (that I know of). However, you can use a sneaky trick to calculate how many of these passes have happened each frame, here is an example:

Lets say we want the code to run 100 times a second, we need to calculate the distance in fixed delta time between each seperate pass.

```
// This is in C# by the way so use whatever you would use for a floating point number
float fixedDeltaTime = 1/100;

```

Now we would need to calculate how many of these passes have happened using normal delta time, or the time between the current frame and the previous frame. For our example we're updating fixed timestep 100 times a second, or every 0.01 seconds. So lets say it has taken 4 seconds to render, that means that 400 fixed time loops have passed. So we can multiply this by whatever you normally use in the fixed timestep.

Lets say you want to move a player using this "framerate independent" timestep, instead of `player.x += 1 * deltaTime` you would use `player.x += 1 * deltaTime / fixedDeltaTime`

Hopefully this helps you to create a fixed timestep.

# Answer
> 0 votes
Imagine a graph of velocity over time, descending toward zero in a linear ramp.

In any given time slice, the area under that curve is the resulting position displacement over that interval.

In the bulk of the ramp, this is just the average of the velocity at the start and end of the interval times the duration.

At the toe of the ramp where it hits zero, we just need to make sure we're not counting the plateau at the end after the object stopped moving. So we can calculate time the object is actually decelerating in the interval, and use that.

Here's what that would look like in code:

```
decelTime = min(abs(vel)/deceleration, dt)
vel_end = move_toward(vel, 0.0, deceleration * dt)

pos = pos + 0.5 * (vel + vel_end) * decelTime
vel = vel_end

```

Note that while this will look smoother, it still doesn't guarantee perfect framerate independence, because we're working with finite precision numbers: rounding and accumulating errors with each operation. So running at a high framerate, you'll take smaller steps and encounter more of this rounding error, while a low framerate will move in larger chunks, and round less often.

---
Tags: physics, lua, love2d
---


# Question
Title: Issue with Goal Oriented Action Planning (GOAP) and multiple preconditions
So I am working on an AI for my game using GOAP. I've been researching it for the past few days and while implementing it on my own I've ran into a problem. Here is a diagram of what I am doing.

* The square is the goal and the circles are the actions.

Currently, I am following a path similar to what is shown in the GDC presentation. In the presenter's demonstration, a melee weapon was already equipped. So when deciding child actions for Melee Attack, it will attempt to add on for each precondition. This causes a incorrect path to be created in my case. The red highlighted path is the path it should hypothetically take with the other being incorrect.

Any ideas how I could make it choose the Goto Player first or make it so the left-most path is invalid?

I've thought about doing it by priority but both paths would end up having the same priority.

# Answer
> 0 votes
Assuming you have a class for nodes (which contains parent and children) and that you are working backwards from the action that satisfies the overall goal,then you can artificially add a precondition to the node class

Order preconditions so that one has to be solved first

Then once you find an action that solves the first precondition move the other preconditions into that action's node

---

for example:

O: Melee Attack -----\> at player, has knife(remove from melee attack node after finding go to player action) | O: Go To Player -----\> has knife (added artificially) | O: Get knife -----\> No preconditions

---

That way the AI will never consider paths that get the knife AFTER going to the player.

---

This can help prevent excessive branching too if you have a lot of actions, good for performance

The downside to this is that the AI can get "set in its ways" and become more predictable so only do this for actions a certain depth into the graph

---
Tags: unity, c#, game-design, ai, graph
---


# Question
Title: Turret following the player in the opposite side
i have tried using lookout method then flipping it by 180 degress but it gives me the same result as the problem i had before. my turret turns left when i move right and vica verse. To fix this i used my trigonometry skills to get how much it need to turn on the x and y axis.but i still get the same trouble so i the result negetive but this in turn flips my character. here is the code,i have modified it a bit so it wont look as nice as i am tired:(

```
 Vector3 distance = Trunk.GlobalPosition - TrackedObject.GlobalPosition;
 float rotatx = Mathf.Atan2(distance.Y , distance.Z);
 float rotatey=Mathf.Atan2(distance.X, distance.Z); //doing the opposite pattern
 Vector3 rot=Trunk.Rotation;
 Vector3 newrot =Trunk.Rotation;
 newrot.Y = rotatey;
 newrot.X = rotatx;
Trunk.Rotation = rot.Lerp(newrot, 0.1f);

```

here is a video to show the problem: Video (dont mind the clear trigonometry problem,i was tired and mixed up pi/2 with 90)

# Answer
This is the solution i came up with:

```
Vector3 TargetDirection = Trunk.GlobalPosition - TrackedObject.GlobalPosition;
TargetDirection = TargetDirection.Normalized();
Basis temptrunk = Trunk.GlobalBasis;
temptrunk.Z = TargetDirection;
temptrunk.Y = TargetDirection.Cross(temptrunk.X);
temptrunk.X=TargetDirection.Cross(temptrunk.Y);
Trunk.GlobalBasis = temptrunk;

```

The reason why it works is becouse the vector from the trunk to the target is the direction the trunk should be pointing. I then normalize it so that i only get the direction. Then i set the z basis\[think of the z basis as the face of the object,y basis as the angle in space of the object and the x axis as the side of the object\] so it has the same direction. Then i cross my y & x axis as i want my trunk to be scaled properly. This can also be applied on the different basis,it is important to know what you want to face what.
> 0 votes

---
Tags: c#, rotation, godot
---