# Question
Title: A-star algorithm after 2D tilemap 90-degree rotation
I am learing Unity and for now trying to implement a simply pathfinding alogorithm in a simply 2D isometric diamond-shaped tilemap.

Recently I learned a way how to rotate tilemap and I already have a question.

My rotation algorithm works as follows:

1. I create a Dictionary `Dictionary<Vector3Int, TileBase>` for storing tiles.
2. Then I iterate through my tilemap and implement a 90-degrees rotation operator as `(x, y) --> (-y, x)`. And save new tiles position in a Dictionary.
3. Then I **clear all tiles** by calling `tilemap.ClearAllTiles()`
4. And then set tiles again from Dictionary.

f

```
foreach (var item in tilesPositions)
{
tilemap.SetTile(item.Key, item.Value);
}
tilemap.CompressBounds();

```

Honestly I am worry a little about implementation of the pathfinding. As I understand, this algorithm receive **start position** and **end position** and made some calculation for mob's to move from start to end

Let imagine I rotate my tilemap making `(x, y) --> (-y, x)` for all tiles Will this procdeure broke a pathfinding algorithm?

And most of all, is the rotation of tilemap which maded with recalculation position for all tiles the best way to do 90 degree rotation for an isometric game?

# Answer
> 1 votes
You need to decouple/disconnect different parts of your application.

Ideally, you want to have some object representing the board in memory which only deals with gameplay-specific concerns (placing pieces, movement, etc).

Whilst it's possible to use a `Dictionary<Vector3Int, TileBase>` for this, it's not actually a very useful format for finding (or reasoning about) adjacent tiles.

You might be better off creating a 2-dimensional array of TileBase...

```
var board = new TileBase[10,10];

```

Then you can refer to the tiles by coordinate (0-indexed) `board[0,0]`, `board[8,9]`, etc.

This will make it a *lot* easier to find the next tile when path finding.

---

Entirely separate to that, you have a requirement to display that board in the UI.

If possible, you can just pull the data directly from the board to recreate the UI elements as needed.

If you absolutely *must* have it in the form of a `Dictionary<Vector3Int, TileBase>`, you can convert from the board to your dictionary format.

If you do that step using a couple of nested loops as shown below

```
var dictionary = new Dictionary<Vector3Int, TileBase>();

for (int x = 0; x < board.GetLength(0); x++)
{
    for (int y = 0; y < board.GetLength(1); y++)
    {
        if (board[x, y] != null)
        {
            dictionary[new Vector3Int(x, y, 0)] = board[x, y];
        }
    }
}

```

Then it becomes trivially simple to rotate/flip the board by tweaking the values written to the dictionary (or even by playing with the loop order/variables)

All your path finding is now working on `board` alone, so doesn't have to worry about rotation or any other UI-level concerns.

p.s. There's a `Vector2Int` if you only need 2D coordinates.

---
Tags: unity, tilemap, path-finding, isometric
---


# Question
Title: How to create a Unity Editor box grouping with a header and vertically stacked content inside?
I am trying to do something like this with Unity Editor for my window but I am not sure how it is done.

So it is basically a box ( a wrapper ) with a title at top. Beneath the title there are boxes or "cards" where you add text to it.

Any help is appreciated!

# Answer
Just use `GUILayout.BeginVertical` with style `window`.

```
GUILayout.BeginVertical("Card Title", "window");
GUILayout.Button("button 1");
GUILayout.Button("button 2");
GUILayout.Label("some text");
GUILayout.Label("more text");
GUILayout.Label("still text");
GUILayout.EndVertical();

```

Result:
> 2 votes

# Answer
To comment from @zwcloud If you want that GUILayout.BeginVertical("Card Title", "window"); not to fill all the free area to the bottom of editor you can add this line after GUILayout.EndVertical() : **GUILayout.FlexibleSpace();**
> 0 votes

---
Tags: unity, gui
---


# Question
Title: Programming Singletons vs Static classes
I've been developping a 3D app for some time and I remember at some point I started to need to pass data arround in unrelated areas of the program, where it wouldn't make much sense to pass them through update functions (stuff like screen resolution or cursor position). My solution at the time was to implement a "Ressources" singleton class that would hold and manage all that data. But now looking back at my code I don't intuitively see the difference between a singleton and a static class. I'm tempted to switch to static implementation, since it would mean I wouldn't have to fetch the singleton eveytime I want to use it, but I'm curious what more experienced programmers have to say about this.

I did look a bit arround for other's opinions, but what's been surfacing is that the very minute differences used in very corner-cases implementations are emphasized everywhere and overall I can't find a general preference for one or the other. Add to that that Java coders tend to hate non-OOP programming and they tend to just say: global variables are bad, period. So I'm left a bit confused here.

Is there really an advantage to use one or the other in my general case, or is it just functionaly the same? Are there performance benefits? Are there code structure benefits?

# Answer
In Game Programming Patterns, Robert Nystrom lays out that there's a few common reasons we like to reach for singletons:

* Ease of global access
* Only takes resources if used (if no one uses the singleton in a given run, we can avoid instantiating it)
* You can control when it's instantiated, and it can be customized with runtime information (e.g. instantiating a different subclass or initializing it with a different configuration depending on information only known after launch)
* Enforced uniqueness (no risk of different bits of code each trying to spin up their own version and conflicting with each other)

He points out that several of the problems we run into singletons mostly arise when we only want *some* of those traits, but we reach for a solution with *all* of them and end up fighting.

Here, you don't care about points #2 and 3. You're always going to need information about the cursor, so there's no benefit to lazily instantiating this, and you don't need to decide between polymorphic cursor behaviours at runtime.

So, a singleton is overkill here, and a static class gets you the traits you care about (global access and uniqueness) more simply.

Yes it's introducing mutable global state, but so is a singleton, so there's no particular encapsulation win by making this an instance. You can arrange your interface so that data is accessed through getters to limit the ways it can be mutated to the correct pathways.

Using static classes this way is not unusual in game development. Most of the Unity API for example is accessed this way, through static classes for `Time`, (legacy) `Input`, `Screen`, `SceneManager`, etc.
> 5 votes

---
Tags: java, architecture, software-engineering
---


# Question
Title: Bullet Physics Multi-threading Rigid Body transform jittering issues across threads
I've been working on a game using Bullet Physics for C++ as well as SDL for the windowing (with OpenGL)

I've recently threaded the game, so that a separate while loop runs the Physics Simulation, whilst the rendering runs independently *(Right now I've got a Car driving around a Heightfield, which worked perfectly without jitter, prior to thread it)*

The reason was, because I wanted to de-coupled physics simulation with rendering *(So low FPS could still have the same Physics simulation speed, which would inevitably cause choppiness)*

**Problem**: at FPS greater, or lower than 60 FPS *(pretty much if it isn't synced with the 60 Hz Physics Timestep)* there will be jittering of the vehicle, and physics objects in general...

The `btTransform = vehiclePhysics.GetTransform()` is the Vehicle's motion state. Right now it's a `btDefaultMotionState`, so this would deal with some bit of interpolation, but below 50 fps, it's still very jittery.

When I activate the `lerpVec3` transformation on my Camera's `lookAt`, the vehicle at low FPS jitters less, but the entire scene starts to jitter. And when I don't the scene is LERP'd and camera movement is smooth, but the vehicle jitters, and the Debug Drawing of the vehicle also jitters, so it's clearly the transform of the vehicle or in general, physics objects that are wonky due to the threading...

### Render Thread Code (essentials)

This is the code within my rendering loop (main thread) that will get the transforms from the shared Resource, and get it ready for rendering *(As well as Debug Drawing code for `BulletDebugDrawer`)*

```
  vehiclePhysicsInfo vI = sharedPhysicsRessource.GetVehiclePhyInfo();
    btTransform vehicleTransform = vI.transform;

    if (isFirstUpdate) {
        lastVehicleTransform = vehicleTransform;
        isFirstUpdate = false;
    }

    btVector3 vehiclePosition = vehicleTransform.getOrigin();
    btVector3 lastVehiclePosition = lastVehicleTransform.getOrigin();

//... Redacted trials at interpolation (On or off, I still get the problem, so it's useless anyways)

//Tried manual LERP & SLERP interpolations for positional and rotational data, and it's togglable with the If stmt below, still doesn't change much at all..

    if(interpolated_transforms){
      vehiclePosition = interpolatedPosition;
      vehicleRotation = interpolatedRotation;
    }

    glm::quat glmVehicleRotation = glm::quat(vehicleRotation.w(), vehicleRotation.x(), vehicleRotation.y(), vehicleRotation.z());
    if(interpolated_transforms){
        glmVehicleRotation = glm::quat(interpolatedRotation.w(), interpolatedRotation.x(), interpolatedRotation.y(), interpolatedRotation.z());
    }

    //Position Translation
    glm::mat4 translation = glm::translate(glm::mat4(1.0f), glm::vec3(vehiclePosition.x(), vehiclePosition.y(), vehiclePosition.z()));

    glm::mat4 rotation = glm::mat4_cast(glmVehicleRotation);
    glm::mat4 rotate90DEG_Adjustment = glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f));

    vehicleModelMatrix = translation * rotation * rotate90DEG_Adjustment * glm::scale(glm::vec3(0.75f));
    // WheelMatrix = translation * glm::scale(glm::vec3(0.25f));

    //! PROTOTYPING: VEHICLE RENDERING CODE

    // Specify the color of the background
    glClearColor(0.07f, 0.13f, 0.17f, 1.0f);

    // Clean the back buffer and depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    // Tell OpenGL which Shader Program we want to use
    shaderProgram.Activate();

    // Assigns a value to the uniform; NOTE: Must always be done after activating the Shader Program
    // brickTex.Bind();
    glUniform1i(useTextureLocation, GL_FALSE);
    //debugDrawer->setDebugMode(btIDebugDraw::DBG_DrawWireframe);

    if(show_debug_draw) {

        physicsWorldPTR->debugDrawWorld();
        debugDrawer->flushLines();

    }
    glUniform1i(useTextureLocation, GL_TRUE);

  //* ###### CAMERA #######

    camera.DEBUG = false;

    if(!camera.DEBUG) {

      auto targetVec = glm::vec3(vehiclePosition.x() + 1.0f, vehiclePosition.y() + 3.0f, vehiclePosition.z() - 5.0f); //* Camera Offset
      auto dirVec = targetVec - camera.Position;

      if (glm::distance2(targetVec, camera.Position) > 0.02f)
        camera.Position += dirVec * 0.03f;

      glm::vec3 lookAtPosition = glm::vec3(vehiclePosition.x(), vehiclePosition.y(), vehiclePosition.z());

      //camera.LookAt = lookAtPosition; //Naive Approach

      camera.LookAt = lerpVec3(camera.LookAt, lookAtPosition, 0.35f);

    } else { camera.Inputs(Window); }

    camera.Matrix(45.0f, 0.1f, 1000.0f, shaderProgram, "camMatrix"); //! IMPORTANT

  //*############## OpenGL - Draw Calls ################

```

## This is the Physics Thread Code (essentials)

```
auto lastTime = std::chrono::high_resolution_clock::now();
    double accumulator = 0.0;
    const double physicsTimestep = 1.00 / 60.0;

    if (debugDrawer) {
            physicsWorld->dynamicsWorld->setDebugDrawer(debugDrawer);
            sharedRSRC->UpdatePhysicsWorld(physicsWorld->dynamicsWorld);
    }

    while (running) {

        auto currentTime = std::chrono::high_resolution_clock::now();
        double frameTime = std::chrono::duration_cast<std::chrono::duration<double>>(currentTime - lastTime).count();
        lastTime = currentTime;
        accumulator += frameTime;

        uint8_t input;
        while (playerInputQueue.TryPop(input)) {
            //... input handing, works fine (Thread Safe Queue)

            // Process and print the input command
        }

        while (accumulator >= physicsTimestep) {

            // Step the physics simulation
            physicsWorld->dynamicsWorld->stepSimulation(physicsTimestep, 2, physicsTimestep);

            // Get the latest vehicle transform and update shared resource
            btTransform vehicleTransform = vehiclePhysics.GetTransform();
            if (sharedRSRC) {

                vehiclePhysicsInfo vInfo;

                vInfo.transform = vehicleTransform;

                for (int i = 0; i < vehiclePhysics.vehicle->getNumWheels(); i++)
                {
                btWheelInfo wheelinfo = vehiclePhysics.vehicle->getWheelInfo(i);
                vInfo.wheelVec.push_back(wheelinfo);
                }

                sharedRSRC->UpdateVehiclePhyInfo(vInfo);
                sharedRSRC->SwapBuffers();
            }

            // Decrease the accumulated time
            accumulator -= physicsTimestep;
        }

        btVector3 vehiclePosition = vehiclePhysics.GetTransform().getOrigin();

        //player positions (vehicle)

        btScalar pXpos = vehiclePosition.getX();
        btScalar pYpos = vehiclePosition.getY();
        btScalar pZpos = vehiclePosition.getZ();

        terrainChunkManager.update(pXpos, pZpos);

        // std::cout << "Thread is running..." << std::endl;
        // Sleep or wait logic can be added here to control update rate
    }

```

And here is the shared resource, used to communicate between threads, basic header file, and these functions have `Thread_guards` that lock and update mutex

```
class SharedPhysicsResource {

public:
    void UpdateVehiclePhyInfo(const vehiclePhysicsInfo& data);
    vehiclePhysicsInfo GetVehiclePhyInfo();

    void SwapBuffers();

    void UpdatePhysicsWorld(btDiscreteDynamicsWorld* physicsWorld);
    btDiscreteDynamicsWorld* getPhysicsWorld();

private:
    vehiclePhysicsInfo playerVehicleBuffer[2];
    int rI = 0; //Read
    int wI = 1; //Write

    std::mutex mutex_;
    btDiscreteDynamicsWorld* physicsWorld_;
};

```

**I've tried**:

* Manual linear interpolation (and spherical as well for rotations)
* Using `btMotionState` instead of getting the RigidBody transforms *(This helps a lot for when the FPS is a constant 60)*
* Double buffering the shared resource that contains the `btTransform` for the rendering of Vehicle
* Unsuccessfully tried to build my own `btMotionState`, but I don't think this is the problem, as at 60 FPS, the default motion state works great

---

I've briefly looked at some other Bullet setups and they use different different constraint solvers & generally other components that seem inherently multi-threaded.

For instance, here's my dynamics world setup *(that I'm running in an independent thread)*

```
PhysicsWorldSingleton::PhysicsWorldSingleton() {

    broadphase = new btDbvtBroadphase(); //uses QuadTree Data Structure to minimize expensive collision checking

    collisionConfiguration = new btDefaultCollisionConfiguration();
    dispatcher = new btCollisionDispatcher(collisionConfiguration);

    solver = new btSequentialImpulseConstraintSolver();

    dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0.0f, -13.81f , 0.0f));

};

```

I'd be very grateful to hear any advise, wisdom, or things I might potentially be doing wrong with my setup, as I know games that fluctuate between 30-144 FPS, with smooth physics simulation...? Also please let me know if you need clarification on anything, or additional code snippets

# Answer
"The final touch" segment from this blogpost seems to address this.

You've tried interpolation, but since I don't see any reference to the "accumulator" variable in the rendering code or in the shared resources, I gather you didn't interpolate using that specific variable - which is required for the accurate desirable interpolation.

From the blog post:

> Any remainder in the accumulator is effectively a measure of just how much more time is required before another whole physics step can be taken. For example, a remainder of dt/2 means that we are currently halfway between the current physics step and the next. A remainder of dt\*0.1 means that the update is 1/10th of the way between the current and the next state. We can use this remainder value to get a blending factor between the previous and current physics state simply by dividing by dt. This gives an alpha value in the range \[0,1\] which is used to perform a linear interpolation between the two physics states to get the current state to render.

So, my suggestion is:

* Add the accumulator to the shared resources.
* Read it in the render thread.
* Divide it by the physics timestep.
* Use the result as the interpolation value between the previous physics state and the current one.

Hope this helped!
> 0 votes

# Answer
consider this as a naive answer from a non bullet specialist,just some thoughts about the process:

### Physics

Firstly, physical simulation should not be impacted by multi threading, if it worked before, no reasons it doesn't anymore. If it is not the case, perhaps consider rendering physics in your physic thread again to debug it.

Thread of the the physical simulation should work on its own. It should do the job, then copy(or swap if possible) its last simulated state to share : so we get:

```
LastSimulatedState at LastSimulated_t with lastSimulatedMotion as speed vector

```

available for the render thread.

### Rendering at time t = now()

Obviously, Rendering should not lock the Simulation thread

Rendering world is in the state of the last rendering, say `LastRenderState` The new wanted rendering state should be the LastSimulatedState extrapolated by physical motion to (t - LastSimulated\_t)

```
ExtrapolatedRenderState = LastSimulatedState + (t - LastSimulated_t) * lastSimulatedMotion

```

Render it like, would probably cause jittering, (extrapolation problem)

So you'd have to interpolate from your lastRenderState to ExtrapolatedRenderState by a ratio:

```
NewRenderState = LERP(LastRenderState,ExtrapolatedRenderState,ratio)

```

You would never render the physical world but would constantly try to approach it gently.

Hope this helps, if it is not just, trash it ;)
> 0 votes

---
Tags: c++, sdl, multithreading, bullet-physics, simulations
---


# Question
Title: How to setup gradient lighting in OpenGL shader?
I setup simple single light source lighting around campfire object. However, as can be seen, the transition between lightened area and unlighted one is sharp.

The GLSL fragment shader code:

```
uniform vec2 screenSize;
uniform vec2 lightSourceSize;
uniform vec2 lightSourceCoords;
uniform float lightIntensityCap;
uniform sampler2D textureSample;

void main(void)
{
    float horizontalDiff = -lightSourceSize.x / 2;
    float verticalDiff = lightSourceSize.y;

    float lightSourceX =
    (lightSourceCoords.x - horizontalDiff) / screenSize.x * 2 - 1;

    float lightSourceY =
    (-lightSourceCoords.y - verticalDiff) / screenSize.y * 2 + 1;

    vec2 lightSourcePos = vec2(lightSourceX, lightSourceY);

    float lightIntensity = 1.0/distance(lightSourcePos, pos.xy);

    if (lightIntensity >= lightIntensityCap) {
        lightIntensity = lightIntensityCap;
    }

    if (lightIntensity <= 1) {
        lightIntensity = 1;
    }

    if (distance(lightSourcePos, pos.xy) > 0.3) {
        lightIntensity = 1;
    }

    vec4 lightCol = vec4(lightIntensity, lightIntensity, lightIntensity, 1.0);
    fColor = texture(textureSample, fragmentUV).rgba * lightCol;

    if (fColor.a <= 0){
        discard;
    }
}

```

If I will remove

```
if (distance(lightSourcePos, pos.xy) > 0.3) {
    lightIntensity = 1;
}

```

the lightened area will expand and the transition will be much smoother. How do I interpolate light intensity and achieve smooth transition for smaller area?

# Answer
> 0 votes
I managed to do it. The key is to use diffusion and ambient light values. If the distance is less than radius of target lightened area, the light should be diffused and combined with ambient.

In case of fragment being too far away from light source, ambient is used to set default light value.

```
vec2 lightSourcePos = vec2(lightSourceX, lightSourceY);

vec3 ambient = vec3(0.8, 0.8, 0.8);

float dist = distance(lightSourcePos, pos.xy);
float lightIntensity = 1.0/dist;
float targetRadius = 0.3;
float diffuse = 0;

if(dist < targetRadius) {
    diffuse = 1.0 - abs(dist / targetRadius);
}

if (lightIntensity >= lightIntensityCap) {
    lightIntensity = lightIntensityCap;
}

if (lightIntensity <= 1) {
    lightIntensity = 1;
}

vec4 fragColor = texture(textureSample, fragmentUV).rgba;
vec3 lightCol = vec3(lightIntensity, lightIntensity, lightIntensity);
fColor = vec4(min(fragColor.rgb * ((lightCol * diffuse) + ambient), fragColor.rgb), 1.0);

```

---
Tags: opengl, glsl, lighting
---


title: how to import uv maps into unity?

text:
# Question
Title: how to import uv maps into unity?
Im trying to create a model using blender and import it to unity. I can import the model and get the texture working but the texture uv map is not correct. I have a uv layout map file I exported but not sure if there is some way to apply it in unity. Any help would be appreciated.

blender:

unity:

# Answer
> 0 votes
I don't know why but .obj seems to work while .fbx does not, no matter what I try. I guess the main difference between file types is .fbx supports animations. I have no plan to work on animations any time real soon so I'm not going to use .fbx format.

Blender:

Unity:

There are so many posts about this issue in Unity forums going back several years. Many people are not happy about it.

It's not all roses though. For posterity these are my .fbx export settings:

Setting path to **copy** seems important based on forums but it doesn't seem to do anything. It supposedly copies the texture into the obj. However after importing to Unity I had to still do several things:

* I pack then unpack the file in Blender which creates a textures folder.
* Then I copy the textures to unity. I have to select my obj and click export materials.
* Then manually copy the textures directly to the materials. Its rubbish and no idea if it will work for all models. Too much information to explain every step without a video.

---
Tags: unity, blender, uv-mapping
---


title: How do real time cutscenes work?

text:
# Question
Title: How do real time cutscenes work?
I want to code a real time cutscene editor in my engine but I couldn't find any pdf documents or websites explaining it in detail. Is the cinematic scene file loaded with instructions like `Camera::Up()` for example?

And how then do real time seamless no cut gameplay to cutscene editors work? I heard for God of War 4 they used handheld cameras so I'm wondering how they imported that data into the engine and then used in a gameplay to cutscene.

# Answer
> 0 votes
The simplest set of steps when a in-engine cutscene triggers is:

1. disable player control
2. move the camera to where it needs to be
3. start playing all the required animations and sound files. These are likely custom animations for that cutscene and would have the same format as any other animation used for gameplay like the walk and run cycles, except they only run once.
4. after the cutscene is done revert back to normal gameplay controls.

For doing a handheld camera you would use some kind of motion tracking system (which game studios will have access to, and you can DIY with a basic VR setup) and in the cutscene replay the tracked motion on a invisible object and mount the camera to it.

You might need to do some smoothing on the motion, either by using a heavy prop for the camera stand-in used in the motion tracking studio, or in a post processing step.

---
Tags: c++, animation, camera, directx12
---


# Question
Title: Best way to create a 2 player networked game
I've been dabbling in Unity. I learned the basics and I've created a few small games and one larger one. All of them were single player games. Now I want to create a game that's a 2 player - pretty much "Catch" with extra steps (two players, each competing to collect as many collectibles as possible while trying to get the other to drop their collectibles.)

I've been trying to understand what the best tool would be to handle the networking and such but all the tutorials speak of creating multiplayer games. I want only 2 players, and no tutorial I've seen explains HOW exactly one player can create a host and invite a certain one other player to the session. It's shown nowhere I've seen, and I'm getting frustrated by the multitude of "create a multiplayer in 5 minutes" tutorials that show how to add a network component but say nothing of how it's supposed to work over multiple computers.

I just need an explanation of how it all works. Thank you.

# Answer
> 1 votes
Hey **Kaiannae** if you're considering venturing into multiplayer game development, a convenient approach is to utilize established network frameworks such as **Mirror** or **Unity's Netcode for GameObjects**.

In essence, these frameworks offer a tool known as the **NetworkManager**. This versatile component efficiently manages the transmission of data. Simply attach the NetworkManager to an object within your project, and you gain access to its streamlined methods. This allows you to effortlessly either host your own game or seamlessly join an existing one. It's a refined solution that streamlines the complexities of multiplayer networking.

```
// example using mirror
// this is everything you need in terms of hosting and connection
NetworkManager.singleton.StartHost();
NetworkManager.singleton.networkAddress = IpInput.text;
NetworkManager.singleton.StartClient();

```

**Note: From here on Mirror is the example framework**

When it comes to moving and animating characters in Mirror, you've got handy tools like **NetworkTransform** and **NetworkAnimator**. These let clients take control of their own character's movement and animations without waiting for the server's approval. So, you can see your character walking and moving around the game world right away.

But, when you want to add features like picking up coins, things get a bit trickier. You'll need to understand how information is sent between the server and clients.

In our example, imagine you're both running the server and playing the game. This gives you a good sense of how information flows back and forth between your game and the server.

```
// Use a ClientRpc to synchronize coin pickup across all clients and the server
[ClientRpc]
void RpcPickupCoin()
{
    // Destroy the coin GameObject for all clients
    Destroy(gameObject);
}

// Use a command to execute on the server to destroy the coin
[Command]
void CmdPickupCoin()
{
    // Execute the RPC to destroy the coin for all clients
    RpcPickupCoin();
}

// Detect when a player interacts with the coin
private void OnTriggerEnter(Collider other)
{
    // Check if the object colliding with the coin is the player
    if (other.CompareTag("Player"))
    {
        // Only allow the local player to send the RPC
        if (isServer)
        {
            // Execute RPC to destroy the coin for all clients
            RpcPickupCoin();
        }
        else if (isOwned)
        {
            // Call the RPC on the server to destroy the coin
            CmdPickupCoin();
        }
    }
}

```

I hope you find this helpful, but remember, there's a lot more to learn about making multiplayer games. It's a good idea to dig deeper into the topic before you start creating your own.

Greeting :)

---
Tags: unity, unity-networking, peer-to-peer, hosting
---


# Question
Title: Using an InputField to enter a distance and then move an object to a location based on the input: object returns to old position
I have attached a script (1) to the `InputField` for ease and it displays `HA` changing when I alter it during run time in the script. I have created another script (2) and attached it to the object I would like to move in order to retrieve this value and upon pressing of the space bar change the object's location.

No errors come up when running this and the object does change position, however for some reason it seems to always return the object to the same place (even after inputting a new value) with the `Debug.Log` returning 20 in the consoles...

I am fairly new to Unity so any help in explanations would be much appreciated.

(On another note: I would prefer to use enter rather than space so that after clicking enter for the input field it activates, but "KeypadEnter" doesn't seem to work. Any ideas?)

Script 1

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.RuleTile.TilingRuleOutput;

public class PointValHA : MonoBehaviour
{

    [SerializeField] private float HA;
    [SerializeField] private TransformerFW connect1;

    public void HAgrab(string inputHA)
    {

        HA = float.Parse(inputHA);

    }
    private void Start()
    {
        connect1.Transformer1(HA);
    }
//how I edited section
  public void Update()
  {
      connect1.Transformer1(HA);
  }

//end of edit
}

```

Script 2

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Unity.VisualScripting;
using UnityEngine;

public class TransformerFW : MonoBehaviour
{
    public float HACheck;

    private float HA;

    public void Update()
    {

        if (Input.GetKey(KeyCode.Space))
        {
            HACheck = 1;
            UnityEngine.Debug.Log("Hellofailure");
            Transformer1(HA);
        }
    }

    public void Transformer1(float HA)
        {

            if (HACheck == 1)
            {

                HA = Mathf.Cos(HA) * 5;
                transform.position = new Vector3(HA, HA, 0);
                UnityEngine.Debug.Log("Hellofailure2" + HA);
                HACheck = 0;
            }

        }
    public void Start()
    {
        if (HACheck != 1)
        {
            UnityEngine.Debug.Log("Hellofailure2" + HA);
        }
    }

}

```

# Answer
> 0 votes
If you want to pass a reference to a live-updating value, it needs to be inside a reference type like a `class` that has its own independent lifetime:

```
[System.Serializable] // Makes this visible in Inspector.
public class LiveValue<T> {
    public T value;
}

```

```
public class Publisher : MonoBehaviour {
    [SerializeField] LiveValue<float> myFloat;
    [SerializeField] Subscriber subscriber;

    void Start() {
        subscriber.SubscribeTo(myFloat);
    }

    public void ParseNewText(string text) {
        if (float.TryParse(text, out float newValue) {
            myFloat.value = newValue;
        }
    }
}

```

```
public class Subscriber : MonoBehaviour {

    LiveValue<float> subscription;

    public void SubscribeTo(LiveValue<float> floatValue) {
        subscription= floatValue;
    }

    void Update() {
        // Do stuff with subscription.value
    }
}

```

But a more conventional/idiomatic way to set up this kind of pub-sub relationship is via the Observer Pattern, which is mostly a fancy name for events:

```
Using UnityEngine.Events;

public class Publisher: MonoBehaviour {
    public UnityEvent<float> OnFloatChanged;

    [SerializeField] cachedFloat;

    public void ParseNewText(string text) {
        if (!float.TryParse(text, out float newValue)
            return; // Not a float; abort.

        if (cachedFloat == newValue)
            return; // No change to report; abort.

        // Remember the latest value.
        cachedFloat = newValue;

        if (OnFloatChanged == null)
            return; // No listeners subscribed; abort.

        // Tell all listeners to update / act on the new value.
        OnFloatChanged.Invoke(newValue);
    }
}

```

```
public class Subscriber() : MonoBehaviour {

    public void OnValueChanged(float value) {
        // Do something with value
    }
}

```

The `Publisher.OnFloatChanged` event will show up in the inspector, just like click/text input events for UI components. You can use that to wire up `Subscriber.OnValueChanged` to listen to this event and receive calls when it fires. You can also add a listener through code if either party needs to be spawned dynamically.

The advantage of this approach is that it reduces coupling between these clases: note that `Publisher` no longer contains any reference to `Subscriber` or vice versa. That means you can re-use the same classes in many different combinations. Say you have a dozen different input fields that all need to convert text into a number then trigger a dozen different changes. Instead of writing a dozen copies of your text-to-number-and-forward script, you can write one, and just instantiate it once for each input, then wire the appropriate subscribing scripts to each one.

That does also come with a downside, in that the control flow is less explicit in your code: now it depends on the data of which subscribers are listening to which events. This can make debugging and reasoning about code more challenging in complex situations, but this scenario is straightforward enough that this should not be an issue.

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


# Question
Title: How do I prevent buffered image size fluctuation when rotating?
As you can see in the GIF, as the car rotates, as the Car rotates, the size appears to change to fit the determined height and width, what would be the best way to change these in conjunction with the rotation. I have rotation saved as a variable from 0 to 359. I am using affine transform and a buffered image in Graphics2D. Is there an easy way to fix this in affine transform or when rendering?

rotator

```
public BufferedImage rotateImageByDegrees(BufferedImage img, double angle) {

        double rads = Math.toRadians(angle);
        double sin = Math.abs(Math.sin(rads)), cos = Math.abs(Math.cos(rads));
        int w = img.getWidth();
        int h = img.getHeight();
        int newWidth = (int) Math.floor(w * cos + h * sin);
        int newHeight = (int) Math.floor(h * cos + w * sin);

        BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = rotated.createGraphics();
        AffineTransform at = new AffineTransform();
        at.translate((newWidth - w) / 2, (newHeight - h) / 2);

        int x = w / 2;
        int y = h / 2;

        at.rotate(rads, x, y);
        g2d.setTransform(at);
        g2d.drawImage(img, 0, 0, null);
        g2d.dispose();

        return rotated;
    }

```

rendering

```
        g.drawImage(handler.rotateImageByDegrees(img, Direction), (int) x, (int) y, (int) width, (int) height, null);

```

# Answer
> 1 votes
The following code fixed my problem:

        int newHeight = (int) Math.floor(height * Math.abs(Math.cos(Math.toRadians(Direction))) + width * Math.abs(Math.sin(Math.toRadians(Direction))));

        g.drawImage(handler.rotateImageByDegrees(img, Direction), (int) (x - ((newWidth - width) / 2)), (int) (y - ((newHeight - height) / 2)), newWidth, newHeight, null);```
</code></pre>

# Answer
> 0 votes
The code you posted calculates the new height and width of the image after rotation, and then draws the image at a position adjusted by half the difference in size. This adjustment ensures that the image remains centered at its original position after rotation.

what your code does:

1. `Math.abs(Math.cos(Math.toRadians(Direction)))` and `Math.abs(Math.sin(Math.toRadians(Direction)))` calculate the absolute values of the cosine and sine of the rotation angle, respectively. These values are used to calculate the new dimensions of the image after rotation.
2. `(int) Math.floor(height * Math.abs(Math.cos(Math.toRadians(Direction))) + width * Math.abs(Math.sin(Math.toRadians(Direction))))` calculates the new height of the image after rotation.
3. `(int) (x - ((newWidth - width) / 2)) and (int) (y - ((newHeight - height) / 2))` calculate the new position at which to draw the image. This position is adjusted so that the image remains centered at its original position after rotation.
4. `g.drawImage(handler.rotateImageByDegrees(img, Direction), (int) (x - ((newWidth - width) / 2)), (int) (y - ((newHeight - height) / 2)), newWidth, newHeight, null);` draws the image at the calculated position and with the calculated dimensions.

# Answer
> 0 votes
```
BufferedImage rotatedImg = handler.rotateImageByDegrees(img, Direction);
g.drawImage(rotatedImg, (int) x, (int) y, rotatedImg.getWidth(), rotatedImg.getHeight(), null);
```

---
Tags: java, graphics
---


# Question
Title: Is it possible to add new waypoints to Dolly Track in Unity CinemachineVirtualCamera on the go?
I'm making a racing game "on rails" that utilizes generated map (similar to outrun). The map is made out of chunks that appear every time player crosses a Trigger area on the chunk that is 3 chunks away from the end. To make camera go steady through designed path I need something like Dolly track. The problem with using it is that it uses an Array to store all the waypoints of the track. Which means I cannot simply add another element to the Array end because it will replace the old array with a new one. (I tested it and indeed - Only the last chunk has any dolly points)  Do I need to write a new dollyTrack or is there a simpler way to have newly generated points added to DollyTrack ? Is there a better camera package for it ?

# Answer
> 1 votes
While I did not test it's usefulness in terms of smooth transition I made a version of dolly track that uses list and seems to add/subtract waypoints progressively.

The working solution to the problem of smooth transition ended up being simple replacement of one point array with another. It didn't work for me at first because of dolly camera "dumping" variables. The dumping caused the camera to glitch-teleport to the end of the new track and then slide back to the beginning. When you set it to 0 the transition itself is smooth.

However there seems to be other problem arising. The generated path sometimes folds itself in places where the distance between points is not roughly divisible by the `CinemachineSmoothPath` "resolution" variable. It mainly affects camera on track. So I simplified the system by using 3rd person camera that follows a cart on a dolly track instead of having a camera also being confined to a dolly track.

---
Tags: unity, camera
---


# Question
Title: Unity UI Buttons not working (not clickable)
Buttons Easy, Medium and Hard can not be clicked even though Restart Button was clickable from the start. All of the buttons have interactable checkbox on and raycast target on. Shadow panels and Bacground - Game Menu also have raycast target on.

# Answer
To confirm which button the system thinks is available do this:

* Run the game.
* Find your EventSystem in the hierarchy and expand it.
* Move your mouse/pointer over each button and look for pointerEnter changing.

Do this on the button that works and the ones that don't. What do you see?
> 1 votes

# Answer
The problem was the Hearts Panel, I resized it, added Graphic Raycaster to Background, Buttons and Shadows and it started working!
> 0 votes

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


# Question
Title: C# class works in Unity, but not in Android build
I am using Unity to program a simple Android game in C#. Right now, all the game does is to randomly load one of 196 flags upon startup (view: https://hastebin.com/suxonayoce.cs or code below). This class file is currently the only class file there is. When I play the game in Unity everything works as expected (i.e. each time the game is started a random flag is displayed). However, when I build and run the game on my Android phone only the placeholder flag is displayed and never a randomly chosen one.

So far I've tried relaunching Unity, re-importing all assets, and recreating the game in a new project. Nothing of this has resolved the problem.

```
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
  private int _flagCount = 196;

  private string[] _ccTlds;
  private void GenerateCctldsArray()
  {
    _ccTlds = new string[_flagCount];
    _ccTlds = File.ReadAllLines(@"Assets\ccTLDs.txt");
  }

  private void DisplayRandomFlagSprite()
  {
    // Randomly gets the file name of a flag.
    int flagArrayPosition = Random.Range(0, 195);
    string flagImageName = _ccTlds[flagArrayPosition];

    // Gets the sprite of the flag called "flagName".
    Sprite sprite = Resources.Load<Sprite>(@"FlagSprites\" + flagImageName);

    // Loads the image associated with "flagName".
    FlagImage.GetComponent<Image>().sprite = sprite;
  }

  [SerializeField]
  private GameObject _flagImage;
  public GameObject FlagImage
  {
    get { return _flagImage; }
    set { _flagImage = value; }
  }

  private void Awake()
  {
    GenerateCctldsArray();
    DisplayRandomFlagSprite();
  }
}

```

Does anyone have any ideas why the games stops working when it is run on the phone and how this can be fixed?

# Answer
Disclaimer: I don't have an Android test setup at present, so the following is speculation.

I suspect this has to do with how you're trying to read your text file.

The file exists at `{ProjectPath}\Assets\ccTLDs.txt` *on your development machine*, but that's not necessarily where the file gets packed into an Android build. In fact, if Unity can't detect anything referencing that text file, it might not include it in your game build at all (since it tries to prune unused assets)

So, instead of trying to load it from a path using File IO APIs, I'd recommend assigning the asset file to a `public TextAsset ccTLDs;` member variable you configure in the Inspector.

This ensures you have a portable reference to it that will work on any platform, and that Unity can see the reference so it doesn't try to prune it out of your build.

Then you can replace these lines:

```
_ccTlds = new string[_flagCount];                  // <-- This line does nothing useful
_ccTlds = File.ReadAllLines(@"Assets\ccTLDs.txt"); // (since it's immediately replaced)

```

with

```
_ccTlds = ccTLDs.text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

```
> 0 votes

# Answer
I too believe there is something wrong in reading the file.

First things, first.Debug it. When you read succesfully the file, show a text in the screen , etc.

Secondly use this for the applications path in Android.

```
 Application.persistentDataPath

```
> 0 votes

# Answer
`_ccTlds = File.ReadAllLines(@"Assets\ccTLDs.txt");`

The reason this works in Unity is because Unity has all the folders, however, when you build the game, everything is compiled into smaller files and the assets folder as well as all other project folders get lost. There is no longer an assets folder when you build the game so it can't read it.

Instead you can use `Application.persistentDataPath` which will get the games data directory no matter what operating system you're using. For example on Windows it's typically: `C:/Users/(username)/AppData/LocalLow/(company name)/(game name)`

Note: company name and game name can be set inside the project settings.

Example: `_ccTlds = File.ReadAllLines(Application.persistentDataPath + "/ccTlds.cld"`

Also, you dont have to to use a txt, something more random may help to make the file look less generic, if you care which you may not. If this file is important though you should probably look into a BinaryFormatter. Otherwise anyone can just edit the text file and break the game basically.

Note: BinaryFormatter is obselete and has some security flaws, it may work for basic data but you may also want to consider some of the alternatives listed on the BinaryFormatter docs page.
> 0 votes

# Answer
It could be because you need to set a random seed before using the random range, **considering this similar problem.**

Although I think that UnityEngine.Random's seed is deprecated after 5.3, so maybe use the System.Random?

**Example with UnityEngine.Random:**

```
public class Example : MonoBehaviour
{
    public float bias;

    public void GenerateRandom()
    {
#if !UNITY_EDITOR
        Random.seed = Input.acceleration.magnitude * (1f + bias); /// Maybe you could use the accelerometer to get the seed.
#endif

        float randomNumber = Random.Range(0.0f, 100.0f);
        Debug.Log(randomNumber.ToString());
    }
}

```

**Example with System.Random:**

```
public class SystemExample : MonoBehaviour
{
    public int maxRange;

    public void GenerateRandom()
    {
        /// Maybe you could use the accelerometer to get the seed.
        int seed = (int)(Input.acceleration.magnitude * (1f + bias));
        Random rng = new Random(seed);

        /// Returns a non-negative random integer that is less than the specified maximum.
        int randomIndex = Random.Next(maxRange);
        Debug.Log(randomIndex.ToString());
    }
}

```

**To know more about random seeds**. Hope it helps.
> -2 votes

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


# Question
Title: How to securely retrieve game stats from clients in a p2p game network?
I'm working on a P2P game and I know I should never trust the clients. I my architecture, there is a "Master Server" that stores game room (host) informations. Players can create their own rooms (hosting) and play with together.

There is another server that is "Info Server", it stores character informations like inventory, level etc. Now, I need to make a stats table with kills/deaths and I have to get these kill/death events from host player (host player \>\> \[event\] \>\> master server). But I think host player can send a lot of kill events because it is authoritative, so master server will process/handle all events from the host player.

How can I trust these events? Can't a server just send fake kill/death events?

# Answer
As you already guessed, you can't trust any server or client you do not have under your control. So you can't send processed results. You have to send requests to the server, indicating the actions that lead up to these results, and verify these requests against the master server's knowledge of the rules of your particular game.

Even then, someone could hack the client and e.g. create aim-bots or whatever to make the game easier for them.

If your users run the servers, you can guarantee even less. The person hosting the server (or "master client" or whatever) could be running a hacked server, you can't know. So if that's your approach, you have to decide how much you want to trust them.

What is your motivation behind this P2P approach?

If the objective is that friends can play and have fun without having to do it online with others, or in more privacy, then it's probably fine, because a friend who runs a hacked server will get reprimanded by his friends. You just can't take any results from these off-line games and use them on your official server.

If the objective is to make it easy to find other players nearby for multi-player matches, you can just make the finding of the partners P2P, and then have each player send the unique ID of their team to the central server. You get easy discovery of P2P, *and* less cheatable gameplay of a central server.

If the objective is to save yourself from having to run a huge server, you could try to split up the operations across all users that are logged in. I.e. send out little units of calculation, maybe even unrelated to the game of the player whose machine is processing them. That way, nobody can predict *who* will benefit from any hacks they do, and if you have several computers perform the same calculation, you can find hacked servers because their results don't match.

Or you could simply forget about it, like many single-player games on iOS do. They simply let the user play the game, and then send the result to a high score server. Anyone can send their own fake result there (in fact, many iOS games these days have the first bunch of top high score spots taken up with ridiculously huge hacked numbers). But since the high score is mainly an encouragement to users and doesn't really affect gameplay or rewards you might get, it's OK in that case.
> 1 votes

# Answer
Is this question still active after nine years?

If so, ensuring that only the server is initiating these calls is **good**.

To further enhance trust, consider implementing authentication on the receiver's end to **verify the legitimacy** of the source.
> 0 votes

---
Tags: unity, networking, security, peer-to-peer
---


# Question
Title: Sort an array of Node3Ds by distance with closest first
I am working on kart racing game. I have created a series of respawn points (Node3Ds) for when a player falls off of the track. Currently, I am trying to get the closest respawn point to the player and place them at this location when they enter a Boundary (Area3D). However, I can't seem to sort the list of respawn points. Below is my code I am using to try sort my points, however when I print my points, they are always printed in order they appear in the tree and I do not get the closest point.

Is there a better way to sort and get the position of the closest Node3D?

```
@onready var respawn_points: Array[Respawn_Point]

var player_location:Vector3

func _on_body_entered(body: Node3D) -> void:
    if(body.is_in_group("Player")):
        player_location = body.position
        var sorted_respawn_points = sortNodesByDistance(respawn_points)
        for point in sorted_respawn_points:
            print(point)
        player.position = sorted_respawn_points[0].position

#Sort Respawn Points by distance
func sortNodesByDistance(nodes: Array) -> Array:
    nodes.sort_custom(compareDistance)
    return nodes

func compareDistance(a: Node3D, b: Node3D) -> int:
    var distance_a = a.position.distance_to(player_location)
    var distance_b = b.position.distance_to(player_location)
    if distance_a < distance_b:
        return -1
    elif distance_a > distance_b:
        return 1
    else:
        return 0

```

# Answer
Here's a version that finds the node closest to a given position, without sorting the whole array, calculating any distance more than once, or using any square roots, so it should be substantially faster than the sorting approach.

I don't work in GDScript often, so I may have made small syntax errors, but the general idea of iterating over the array, keeping track of the closest option you've found so far, should be clear:

```
func findClosestNode(nodes: Array, position: Vector3D) -> Node3D:
    var closestSquaredDistance = INF
    var closestNode = null
    for node in nodes:
        var squaredDistance = node.global_position.distance_squared_to(position)
        if squaredDistance < closestSquaredDistance:
            closestSquaredDistance = squaredDistance
            closestNode = node

    return node

```
> 2 votes

---
Tags: gdscript, godot-4, sorting
---


title: Error converting singles and floats

text:
# Question
Title: Error converting singles and floats
I have a custom data type I made called a point.

It has implicit operators to easily convert between a Vector3 and a float\[\], the reason being Vector3 and Vector2 types are not `System.Serializable` meaning they cant be converted to binary, before I would use a simple method like this:

```
public static void Vector3ToFloatArray(Vector3 v)
{
    return new float[] {v.x, v.y, v.z};
}

```

And another for `float[]` to `Vector3`

Here is the code I made for my custom point data type:

```
using System;
using UnityEngine;

[Serializable]
public struct Point {
    public float x, y, z;

    public Point(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public static implicit operator Vector3(Point p) => new(p.x, p.y, p.z);

    public static implicit operator float[](Point p) => new float[] {p.x, p.y, p.z};

    public static implicit operator Point(Vector3 v) => new(v.x, v.y, v.z);

    public static implicit operator Point(float[] f)
    {
        if (f.Length != 3) throw new ArgumentException("Float array must have exactly 3 elements for point conversion.");
        return new Point(f[0], f[1], f[2]);
    }

    public bool IsZero
    {
        get {
            if (x == 0 && y == 0 && z == 0) return true;
            return false;
        }
    }
}

```

As you can see I have an operator for converting from Point to float array and the other way around. Yet in Unity it says:

It claims a `Single[]` can't be converted into a 'Point' even though I have the implicit operator in place.

The 'position' variable it's referring to is inside my SaveData script:

```
using UnityEngine;

namespace Game.Save
{
    [System.Serializable]
    public class SaveData
    {
        public int MusicIndex { get; set; } = 0;
        public Point position;

        // TEMPORARY
        public SaveData(Vector3 pos, int musicDex)
        {
            position = pos;
        }
    }
}

```

As you can see inside the constructer I'm able to set position to a Vector3 due to that implicit operator, so I should be able to convert a float array into it and I don't understand why it's throwing this error.

Edit: I forgot to mention the reason the error is for "point" and the struct is called "Point" is because after the error threw I also did some code optimization like making point capitalized. The new error looks like this:

# Answer
I figured it out, it's kinda stupid.

The reason was because before I created the data type I was using a float\[\], but when I updated it to Point, I still had the old files with float elements in them. After deleting the cache files and remaking them, the error disappeared.
> 0 votes

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


# Question
Title: Calculating velocity to reach the jump height while the player presses the jump button
The height of the jump depends on how long the player presses the jump button. There are only two parameters - height and time. Gravity is constant.

Let's say that the height has three units, and the time is set to a second.

There are fixed time-segments during which velocity must be added. If the player presses the button for the entire second, they will reach the three units height, taking into account the fact that gravity is pulling them down.

When I tried to solve this problem, I was trying to use `v = sqrt(2gH)` formula which was perfect to calculate instant velocity for fixed-height jumps.

Not for this case! My code may look like this:

```
private float jumpHeight = 3f;
private float jumpTime = 1f;

private const float GRAVITY = -10f;

...

private float timer = jumpTime;

public void FixedUpdate(float fixedDeltaTime) {
    if(timer < 0) {
        return;
    }
    timer -= fixedDeltaTime;

    var deltaTimeNormalized = fixedDeltaTime / jumpTime;
    var deltaHeight = jumpHeight * deltaTimeNormalized;
    var jumpVelocityY = CalculateJumpSpeed(deltaHeight, Math.Abs(GRAVITY));

    character.rigidbody2D.velocity.y += jumpVelocityY;
}

private float CalculateJumpSpeed(float height, float gravity) {
    return Math.Sqrt(2 * height * gravity);
}

```

The controlled character skyrockets, and I don't quite understand the reason for this behavior.

I clearly see that the speed is gaining rapidly, but I cannot understand why the original idea does not work, and what other solutions there might be that would take the same two parameters.

# Answer
Your math is not mathing.

sqrt() is not a linear operation. This is what the slope of a sqrt(x) looks like:

This is what a linear operation would look like

If I want to jump up 1 unit of height with a gravity of 10 units/s then the velocity I Need is sqrt(2 * 10 * 1) = 4.47214... If I want to jump up 3 units of height then the velocity I need is sqrt(2 * 10 * 3) or 7.74597... Which is not 3 * 4.47214.
> 0 votes

# Answer
You're adding to the speed in every FixedUpdate with this line. `character.rigidbody2D.velocity.y += jumpVelocityY;`

What I'd do is treat it like a regular instant velocity, fixed-height jump. Then, if the jump button is released, gravity would increase to end the jump earlier.
> -1 votes

---
Tags: unity, physics
---


# Question
Title: How do i put an entities x,y and z coordinates to a variable(?) in Blitz3D?
I'm making a TEST 3d platformer where the camera follows the player from above. Normally I would make the camera move at the same time when the player moved, for example:

```
If KeyDown(17) Then TranslateEntity player1,0,0,0.1
If KeyDown(17) Then TranslateEntity camera,0,0,0.1

```

But this doesn't work with my "gravity" code which is just:

```
If Not Keydown(57) Then TranslateEntity player1,0,0,-0.1

```

I cannot use the same code with the camera, otherwise, the camera will infinitely go down if the player didn't press space(57)

I want to put player1's coordinates to an entity(?) so that the x and z of the camera would be the same as player1's, but the y coordinates would be y+30

I've tried to do:

```
x = EntityX(player1)
y = EntityY(player1)
z = EntityZ(player1)

camera = CreateCamera
PositionEntity camera,x,y+30,z

```

But when I run the program, it shows the Entity does not exist error

If it does help, I will post the entire code. The game isn't completed yet as I'm still making it, and I will try to improve it

```
;-------------------------------------------
Graphics3D 640,480,32,2
SetBuffer BackBuffer()

view = CreateCamera()
CameraClsColor view,5,10,255
PositionEntity view,x,y+30,z
RotateEntity view,75,0,0

x = EntityX(player1)
y = EntityY(player1)
z = EntityZ(player1)

type_map = 1
type_player = 2
type_player2 = 3

light = CreateLight()

player1 = CreateCube()
PositionEntity player1,0,0,10
EntityColor player1,255,75,0
EntityType player1, type_player

player2 = CreateCube()
PositionEntity player2,-5,0,10
EntityColor player2,10,20,30
EntityType player2, type_player2

map = LoadMesh("drinks.b3d")
PositionEntity map,0,-8,130
ScaleEntity map,4,4,4
EntityType map, type_map

While Not KeyDown(1)

Collisions type_player, type_map,2,2
Collisions type_player2, type_map,2,2
Collisions type_player, type_player2,2,2
Collisions type_player2, type_player,2,2

If KeyDown(17) TranslateEntity player1,0,0,0.1
If KeyDown(31) TranslateEntity player1,0,0,-0.1
If KeyDown(30) TranslateEntity player1,-0.1,0,0
If KeyDown(32) TranslateEntity player1,0.1,0,0

If KeyDown(17) TranslateEntity view,0,0,0.1
If KeyDown(31) TranslateEntity view,0,0,-0.1
If KeyDown(30) TranslateEntity view,-0.1,0,0
If KeyDown(32) TranslateEntity view,0.1,0,0

If Not KeyDown(57) Then TranslateEntity player1,0,-0.1,0
If KeyDown(57) Then TranslateEntity player1,0,0.1,0
If KeyDown(57) Then TranslateEntity view,0,0.1,0

RenderWorld
UpdateWorld
Flip

Wend

End
;-------------------------------------------

```

# Answer
moving camera with player by two if-statements isnt very good solution, use EntityParent() function (`EntityParent(view,player1)`), so "view"-entity (camera) will always follow it's parent (player) without other code.

also you are trying to get player1 position (`x=EntityX(player1)`...) BEFORE it got created, so function trying to get position of entity that does not exists.

```
; fixed example:
player1=CreateCube()

x=EntityX(player1) ; ...

```
> 0 votes

---
Tags: 3d, camera, movement, coordinates, position
---


# Question
Title: How can I store a list of instances of different classes?
I am making a customizable save system for Unity. In my previous save systems, since they aren't designed to be modifiable, I already know what each save is going to contain.

However, when making this new system, I want to create some kind of attribute like `[Savable]` that allows that class to be serialized into the save file.

I figured the attribute would just store a list of classes, structs, etc, and then they would all be stored in some file, along with some other data. But how would I contain a list of class instances from these different classes?

I'm not talking about a list of instances of a specific class like:

`public List<MyClass>;`

I need some way to store a list of different class instances. Or perhaps a way to store a list for each class instance. Something like this:

`public List<SavableClasses>;`

Is there any way I can do this?

# Answer
It turns out, you can do this half-decently with Unity's \[SerializeReference\] attribute. Here's a quick demo:

You can see I have a list containing more than one different type, but they're all directly inspectable in the Unity interface.

Click the three-dot ⋮ context menu in the top-right of the "Mixed Serialized (Script) component inspector to test out the following actions:

* **Add Mixed Types**: Adds one instance of each class `ObjectA`, `B`, and `C` to the data list.
* **Serialize to JSON**: Updates the `json` field to contain a string representation of the `data` object.
* **Deserialize from JSON**: Uses the text in the `json` field to replace the `data` object with the saved version.

You can write that JSON to a file directly as a somewhat human-readable save file (good for debugging and modding), or apply compression or encoding to it if you want it obfuscated.

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

public class MixedSerializer : MonoBehaviour
{
    // Unrelated types with different data storage.
    [System.Serializable]
    public class ObjectA {
        public string a = "apple";
    }

    [System.Serializable]
    public class ObjectB {
        public int b = 42;
    }

    [System.Serializable]
    public class ObjectC {
        public float c = 3.14159f;
        public bool toggle;
    }

    // Containter type.
    [System.Serializable]
    public class SaveData {

        // SerializeReference allows the contents to be serialized
        // separate from the list, with their own type information.
        [SerializeReference]
        // Every reference type can be cast to/from System.Object.
        public List<System.Object> list;
    }

    // Structured data to save.
    public SaveData data;

    // Serialized version as text.
    [TextArea(5, 20)]
    public string json;

    // API method for other code to add stuff to be saved.
    public void AddDataToSave(System.Object serializableData) {
        if (data.list == null) data.list = new();

        data.list.Add(serializableData);
    }

    // API method to extract loaded data of a given type.
    public int GetSavedData<T>(List<T> output) where T: class {
        if (data.list == null) return 0;

        int count = 0;
        foreach (var item in data.list) {
            var cast = item as T;
            if (cast == null) continue;

            output.Add(cast);
            count++;
        }

        return count;
    }

    [ContextMenu("Add Mixed Types")]
    void AddMixedTypes() {
        if (data.list == null) data.list = new();

        data.list.Add(new ObjectA());
        data.list.Add(new ObjectB());
        data.list.Add(new ObjectC());
    }

    [ContextMenu("Serialize to JSON")]
    void ToJson() {
        json = JsonUtility.ToJson(data, true);
    }

    [ContextMenu("Deserialize from JSON")]
    void FromJson() {
        data = JsonUtility.FromJson<SaveData>(json);
    }
}

```

Note how the information about individual instances saved with `[SerializeReference]` get stored in a new field called "references" in the JSON version. That means the type you're saving cannot have its own field named "references" or you'll get errors when trying to deserialize.

When reading this data back, you'll have to inspect each item's type to figure out what to do with it. You can do so something like this:

```
    void ReportContents() {
        if (data.list == null || data.list.Count == 0) {
            Debug.Log("Save data list is empty.");
            return;
        }

        Debug.Log("Save data list contains...");
        foreach (var item in data.list) {
            switch(item) {
                case ObjectA objA:
                    Debug.Log($"- Object A with a = {objA.a}");
                    break;
                case ObjectB objB:
                    Debug.Log($"- Object B with b = {objB.b}");
                    break;
                case ObjectC objC:
                    Debug.Log($"- Object C with c = {objC.c} and toggle = {objC.toggle}");
                    break;
                default:
                    Debug.Log($"- Unknown type {item.GetType().Name}: {item.ToString()}");
                    break;
            }
        }
    }
}

```

But note that the method iterating over the contents needs to know about each type to be able to decide what to do with it. If you want this to work with arbitrary types without modifying this part, then this is where Zibelas's suggestion to look at interfaces may help:

You can make an `ISavable` interface that implements an `OnLoad()` method, then make your list of type `List<ISavable>`. On load, you can iterate over the list's contents and call `OnLoad()` on them, without knowing their concrete types. Each newly-added `ISavable` type can then implement its own logic for what should happen to it after loading, and have that logic fired from the save system without modifying the core save system code for each new type.

Or you can use the methods I labelled `// API method` above for external code to add and read back data to be saved / data that was loaded of a particular type, without this class knowing all those types.
> 1 votes

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


# Question
Title: How to serialize data from C# in a non-human-readable way?
How can I serialize a C# object (class, struct, etc) to a file without that file being easy to read?

---

**Binary Formatter**

First I used the Binary Formatter, which worked really well, but there were a lot of warnings about data security and many said it's a bad idea.

**JSON & XML Serialization**

This wouldn't work for obvious reasons, these languages are designed to be easily read and easily modified by humans, therefore it's biggest strength is also it's biggest weakness in this case.

**Encrypted JSON/XML**

Not sure how well this would work, and how easy it would be to tell its JSON or XML, but the main reason I couldn't use it was because I couldn't figure out an easy method or way to work it. And most posts said its extremely complicated since it's designed to be hard to decrypt.

---

For some reason there seem to be almost no posts on this topic, even though nearly every game records the players progress and needs to do this. What other methods are there? I don't need top level security here, just something gibberish enough to put off your average Joe trying to skip half the game.

# Answer
Is this gibberish enough?

This is just the JSON generated by my answer to your previous question, which I then compressed to a zip file (reducing its size by half as a bonus), and renamed so it's not so obvious that it's just a zip.

That is, I started with this text in a file called `data1.save`:

```
{
    "list": [
        {
            "rid": 1000
        },
        {
            "rid": 1001
        },
        {
            "rid": 1002
        }
    ],
    "references": {
        "version": 2,
        "RefIds": [
            {
                "rid": 1000,
                "type": {
                    "class": "MixedSerializer/ObjectA",
                    "ns": "",
                    "asm": "Assembly-CSharp"
                },
                "data": {
                    "a": "apple"
                }
            },
            {
                "rid": 1001,
                "type": {
                    "class": "MixedSerializer/ObjectB",
                    "ns": "",
                    "asm": "Assembly-CSharp"
                },
                "data": {
                    "b": 42
                }
            },
            {
                "rid": 1002,
                "type": {
                    "class": "MixedSerializer/ObjectC",
                    "ns": "",
                    "asm": "Assembly-CSharp"
                },
                "data": {
                    "c": 3.141590118408203,
                    "toggle": false
                }
            }
        ]
    }
}

```

So the compression does a good job of hiding the obvious/familiar structure seen above.

Someone with good knowledge of the zip format would be able to recognize its signature by peeking at the bytes, but "your average Joe" would likely already assume this is not a human-editable file and give up.

(Fun fact, MS Office docs use this trick too: if you rename a .docx Word document or .pptx PowerPoint slideshow to .zip, you can unzip it to find human-readable files and folders inside. If you never though to do that with a document, most of your players will never think to do it with a save file either)

You can make this a little bit harder by running a different compression algorithm that's not so readily built-into every PC's OS, but the general point is: compressed data is no longer very human-readable, and will probably put off the type of user you're trying to deter.

You get diminishing returns if you try to add more obfuscation than this. Even if you put in high-security grade encryption, your game necessarily has to include the encryption key to be able to read and write the save files. So if you have a computer-savvy adversary, you've handed them both the lock and the key. With enough determination, they can always extract your game's decryption routine and use it themselves to modify the data, unless you do all your saving on a server you control, so the key never touches the player's device. Maybe do that if you have real money involved, like gambling applications. But for most games you're likely to be making, it's not worth that effort.
> 0 votes

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


# Question
Title: What causes some web game engines work in "slow mo" mode instead of reducing FPS but continuing to show the true time/tick state of things?
I used game engines that are capable of cross-platform export: Cocos Creator, Godot, Unity, others.

Some game engines have this thing, called "physics update" or "fixed update". Those are methods where the "true" calculation should occur. Meaning if your game domain logic says - this bullet should fly with this precise speed and not less not more - you put this code into the "physics update" method of object. So even when FPS of game is low, bullet will change position as it should.

I assume there is some time/tick calculation done inside those methods to ensure expected behaviour.

But some engines lack this feature. Like Cocos Creator. There is only "update" method. And when game runs on slow machines in browsers - game goes into this "slow mo" mode instead of "true but low fps" mode.

Why does this happen? Some people say that it's impossible to gain "true physics process" method in the browser, but I saw one in Godot 3.5 web export. You have low FPS but everything moves with the speed designed in the editor, not the speed browser allows. FPS is low of course, but not slow moving stuff. That is, if you put your important code into this "physics process" method, of course.

# Answer
One simple way to get this slow-mo effect is if you have a variable rate update and no delta time correction to make it "framerate independent". For example if each update you say:

```
position.x += 1

```

Then you're moving right one pixel or unit per frame. The more frames per second, the more movement happens in that time, so action speeds up (though you can limit this by sleeping some excess time away instead of updating/rendering as fast as the hardware will go). If the frame rate dips down below your target pace, the action goes into slow-mo.

So most games scale their movement by elapsed time (`position.x += speed * deltaTime`), or implement a fixed time step like the "fixed update" you describe, which are decoupled from rendering speed.

But you can get this slow-mo even with a fixed update based system, if that fixed step gets sufficiently overloaded.

In Unity for example, if computing a single frame takes longer than Time.maximumDeltaTime wall clock seconds, that elapsed time is clipped down to the given max. At that point, even code in `FixedUpdate` will start to run behind real time, and the simulation doesn't just render more choppily: game state updates start getting that "slow mo" effect you describe.

I explain this in more depth in this older answer.

You can imagine the engine's game loop being implemented something a bit like this pseudo-code:

```
Tick() {
    now = GetCurrentTime()
    deltaTime = Min(now - startOfLastFrame, maxDeltaTime)
    startOfLastFrame = now

    accumulator += deltaTime

    while (accumulator >= fixedTimeStep) {
        // Run zero or more game state updates back-to-back,
        // each representing a consistent slice of simulation time.
        gameTime += fixedTimeStep
        FixedUpdate(fixedTimeStep)
        accumulator -= fixedTimeStep
    }

    // Tick anything that's not gameplay/physics sensitive
    // (like UI) just once per rendered frame, scaling
    // their animation progress by the full time elapsed.
    VariableRateUpdate(deltaTime)

    // Compute interpolation ratio - how much progress
    // have we made from the last FixedUpdate to the next?
    // This can be used to draw objects in an intermediate
    // state to hide judder from fixed ticks being mismatched
    // to the frame rate.
    alpha = accumulator/fixedTimeStep
    Render(alpha)
}

```

As long as we can complete all those steps - potentially multiple `FixedUpdate()` ticks, a `VariableRateUpdate()`, and issuing commands to `Render()` the frame - in less than `deltaTime` wall clock seconds, the displayed state of the simulation keeps up with real time. The faster we do it, the better our framerate, but we have a range in which we can soak differences in hardware/code performance without changing gameplay simulation outcomes and the speed things move relative to real time.

But once there's enough load anywhere in this system - in `FixedUpdate()`, `VariableRateUpdate()`, or `Render()` \- to cause a single frame to take longer than our `maxDeltaTime`, we clip away the excess real time to keep the execution time bounded, using something like this:

```
deltaTime = Min(now - startOfLastFrame, maxDeltaTime)

```

Now we're simulating fewer seconds in the game than actually occurred out in the real world over the same interval, and the game appears to go in slow mo.

Without this, you can get a snowballing effect, where one long frame means we need to run more `FixedUpdate()` ticks in the next frame to catch up to real time. But running more `FixedUpdate()` ticks takes more time, so that frame gets longer too, so we need to run more ticks again... This can cause the framerate to get worse and worse, and transform a momentary hitch (like a loading spike) to stretch into a long period of sluggishness until the game finally manages to catch up to where it should have been without that hiccup.

Enforcing a `maxDeltaTime` means that we "make the best of a bad situation" after such a loading spike. We accept discarding some time, so our simulation is now "in the past", but then we keep ticking it forward at a normal rate from there, turning that snowballing sluggishness into (hopefully) just a momentary hitch.

This kind of slow-mo will eventually happen to any engine, if you put enough workload into `FixedUpdate()` (or their equivalents) that the time spent processing it all nears or exceeds the duration of the fixed time step. At that point, there's no way to catch up to real time: every time you try, you just dig yourself even deeper into time debt.

So, it could be that each of these engines is managing its fixed time steps in very similar ways, and it's just that some of them sit closer to this edge of inevitable slowdown - either because of...

* differences in efficiency of their internals (a slow game engine, running in a slow language like JavaScript in the browser, will naturally be easier to bog down this way than one that's better-optimized for the game you're making)
* or the engine/game's `maxDeltaTime` (or equivalent) is tuned more tightly or more loosely (say, based on different estimates of the target hardware/experience or the complexity of game code they're designed to support).
> 8 votes

---
Tags: godot, game-loop, webgl, cocos3d
---


# Question
Title: Best practice for Actor Components that require other Actor Component functionality
I struggle to understand best practices regarding composition and inheritance for Actor Components in Unreal Engine 5. Concretely, I want to build a base class, say `Interactable` that handles basic functionality of interactable items in the level. E.g. it detects collision, creates a prompt saying "Press \[E\] to interact", and then triggers an event or function when this happens. Subclasses can then implement this concretely.

Now, when I implement `Interactable` as an *Actor*, it's all easy. I can add a Box Collision to the scene root and listen to events triggered by it. However, this seems like a bad practice, because an Actor then always ever be either `Interactable` or, say, `Destructible`.

It occurs to me that `Interactable` should rather be an Actor Component instead. However, an actor component can neither *have* nor *be* a collision box. They cannot have a collision box because components cannot have components. I feel it should be possible that they can *be* a collision box, but at least for Blueprints I don't see a way to achieve that. It seems the superclass should be something like UBoxComponent. However, this is not available from the "New Blueprint" dialog. (Why?) The lowest ancestor is `PrimitiveComponent`, but that, too, cannot be selected as a blueprint parent class. (Why?)

The only ways out I see are:

* Require that any Actor who wants to use the `Interactable` component also define a collision box. Then, in the component code of `Interactable` I can look it up and register events with it. This puts needless burden on the user and seems very odd.
* When the `Interactable` component is constructed, add a collision box to the parent actor programmatically. This seems equally odd to me, and again is not user friendly because it will not be visible in the UI.
* Use C++ I guess? I'd be fine with that in principle, but it seems this task is so simple that it lends itself well to the Blueprint concept, and I'd be surprised if this really only works in C++.

Is there a better one?

# Answer
> 1 votes
ActorComponents have no transformation, so they can't have physical presence. SceneComponents, however, have a transformation, and PrimitiveComponents derived from SceneComponent have physical (collision) presence.

There are a few ways to use this in an object fashion:

* You could derive your Interactable from something like the Box collision component. This is classic "inheritance" OO. I don't like it much, but it's there.
* You could also have a reference that's set at construction time -- you don't make the component yourself, you get configured with the component to use for presence. That way, both Destructible and Interactable could use the same Box. This is modern "delegation" OO, and tends to lead to fewer "diamond inheritance" problems.
* Finally, you can scan your actor for collision components, and configure yourself to use those at runtime. This is the dynamic "dynamic discovery" flavor of OO, which is super flexible, but with that flexibility comes a much harder time to debug things when they go wrong.

---
Tags: blueprints, unreal-5
---


title: Shader FloodFill Alogrithm

text:
# Question
Title: Shader FloodFill Alogrithm
I'm new to openGL and shaders.

Is there a way to implement shader algorithms for floodfills?

Basically, I have a picture with outlines and i want to fill the insides of where the user touches it

# Answer
The above method was not only outdated for 2017, but extra-ordinarily slow. There are dedicated algorithms to do what you're talking about on the GPU that take maximal advantage of GPU parallelism.

There are several methods for filling an area on the GPU, but it greatly depends on your situation. Technically this is called "connected component labelling" unfortunately there's a huge disconnect between the game dev world and academia, so you likely aren't going to find this kind of information in the game dev space.

The idea is that you *label* each pixel in your image with an ID, figure out what is connected to it, and then label the whole thing as the parent ID. Then when you actually fill things, you just check each pixel with the ID you wanted to fill

When the user interacts with the image, the bucket tool touches some pixel, that pixel gets a connected components ID that corresponds with many pixels, and then you just check for each pixel whether it matches the bucket pixel, and set it to the bucket color.

The algorithm described in the below resources works via splitting the work up into row blocks that the GPU processes in parrallel.

First turn your image into a binary image (where your border is = 1, and where it isn't = 0). The algorithm then works via processing labels for each element in each row, calculated at the start via the actual linear address id (0,1,2,3...) only labelling starting segments. Then parent labels are created bewteen rows, each row taking the lowest linear address id that is connected to each contigous segment as it's parent id. Then this process repeats for borders between groups of rows.

Finally, now that the parent ID has been figure out for all rows for all segments, connected component labels can be flattened to only the parent ID.

There's a lot of "the rest of the owl" in what I just said, so you you'll need to read the paper to understand how it works fully, but the main thing to understand is this isn't an iterative image algorithm that only works in parallel on the frontier, it's completed in a discrete number of steps.

See this PDF for more details, there are several algorithms to look at as well, timing is shown below.

https://developer.download.nvidia.com/video/gputechconf/gtc/2019/presentation/s9111-a-new-direct-connected-component-labeling-and-analysis-algorithm-for-gpus.pdf

and this paper of the same thing:

https://hal.science/hal-01923784/document

Github https://github.com/DanielPlayne/playne-equivalence-algorithm

8 way version (cardinal plus diagonal connections between each pixel)

https://github.com/FolkeV/CUDA\_CCL?tab=readme-ov-file

While the examples are in cuda, with the proper feature set, this should translate rather directly to compute shaders. Note that to take advantage of this algorithm you're going to need access to subgroup operations, this requires vendor specific OpenGL extensions IIRC or enabling subgroup support in vulkan (since 1.1 ie 2018), in addition to atomic operations.
> 4 votes

# Answer
As Bálint noted in a previous answer, shaders are designed to be highly parallel, which makes them an awkward fit for flood-filling.

In parallel execution, the GPU's many cores are making decisions about what colour to paint each pixel for gobs of pixels all at once. Since these decisions happen at the same time, the outcome of one can't depend on the outcome of the other. If it did, the whole thing would grind to a halt and we'd use only a tiny sliver of its power computing a few pixels at a time in dependency order. Shader languages deliberately make it difficult to express this kind of dependency, so we get the most out of our graphics hardware.

But that's a challenge for algorithms like flood fill. Knowing whether the fill reaches pixel (x, y) depends on whether the fill reached at least one of its neighbouring pixels (x - 1, y) (x + 1, y) (x, y - 1) (x, y + 1). And each of those depends on their neighbours.... Usually on the CPU we plow through this recursively or with a queue/stack, but that's not an option for pixel/fragment shaders.

(Compute shaders let us break this rule a bit, but it's not exactly a free lunch there either - I'll let someone with more experience in compute explain how that style could be applied in this case. Thankfully, Krupip rose to that challenge and shared some more efficient algorithms that work with compute shaders, with some pre-processing steps to identify connected regions)

But even if you're not comfortable wading into compute shaders and academic papers just yet, all is not lost! Instead of trying to completely solve each pixel in dependency order, we can instead incrementally / partially solve a subset of the image in parallel, and iterate.

More sophisticated algorithms can work on bigger chunks of the image at a time, but here's a simple naïve method that does the job for small images without any pre-processing:

1. We define two temporary textures to track our fill-in-progress.
2. We draw a white pixel into the first temporary texture at the seed position of our flood.
3. We "blit" from this first temporary texture into our second temporary, with a shader that:

i. Reads the outline texture to decide if the current pixel being shaded is a line. If so, abort (return black / not-filled)

ii. Reads the corresponding pixel and its immediate neighbours from the first temporary texture. If any of them are white / filled, then return the same. Otherwise return black / not filled.

This is a kind of dilate filter, except it's limited by the outline texture. Run just once, it will bleed our initial seed pixel out into a diamond or square of pixels, depending on which neighbours you count.

3. Now we blit *back* from the second texture into the first one, using the same shader - we've just exchanged the input and output textures.
4. Keep blitting back and forth. Each blit spreads our fill a bit further until the area is filled.

To keep it simple you can set a maximum number of passes based on the size you expect your fill areas to be, and stop after that many. A more advanced solution could use GPU queries to identify the first blit where no new pixels are filled.

5. Lastly, render back into your outline texture, tinting it to the fill colour wherever the most-recently-updated temporary texture says should be filled.

Obviously all this iterative blitting takes time, which is why Bálint advised against doing it this way. But keeping this work GPU side isn't automatically wrong - sometimes you might choose to do it that way if the CPU is too busy with something else, or to avoid a stall when shunting the data back and forth.

(Animation by Finlay McWalter, via Wikipedia, CC BY-SA 4.0)

You can also make this blitting back and forth work for you, by spreading it over several frames and showing the player the colour spreading out from the location they chose. This both avoids a slowdown while you do all the blitting, and gives a neat-looking visual effect, if that works for your context. ;)

There are other things you can do to speed this up, like masking each execution pass to the portion of the image that could change, or downsampling and filling a smaller-scale image, then upsampling and running the full-res flood fill on hopefully just a few remaining gaps.

Performance is always contextual though, so I'd recommend trying it in a simple way first, then post a new question if it's not performing the way you want, and we can give customized feedback on how to improve it.
> 2 votes

---
Tags: android, shaders, opengl-es, fragment-shader
---


# Question
Title: How to implement rigidBody movement and collision in local axis X while moving the body automatically in local Z axis?
I'm making a very peculiar outrun clone. I need the player to move forward automatically while being able to change his position on the road in his local X axis.

I made infinitely generated road and placed dolly track in the middle of the road. The track is swapping waypoints for the new ones every 3 map chunks. Like here: Is it possible to add new waypoints to Dolly Track in Unity CinemachineVirtualCamera on the go?

For now I have made the effect you see above using transfrom.translation. The problem is that if I wanted to collide with something on the edge of the road (like a barrier) I couldn't do that. I go right through any collider. I checked the collision with Debug.Log and it certainly fires.
I think I need rigidBody related movement like AddForce etc.

Currently I have a cart attached to the dollyTrack. The track moves the cart along the path. Camera is looking at the cart and following it. I made "player" a child of the cart, however player didn't move with it for some reason, so I made a script that moves player to the point that is 8 units forward in relation to the camera. It uses RigidBody.Move().

**The problem:**
I don't know how to simultaneously move player forward and allow him for movement to the sides and be able to collide with lets say - a wall on the side. When I try to make the side movement use RigidBody instead of translation it stops working at all. My theory is that forward movement takes precedence and side movement just doesn't occur.

This is the code I tinker with for player movement:

```
void MoveV2(bool accelerate, bool brake, float turnInput)
    {
        turnInputView = turnInput;

        bool pastRightScreenEdge = Camera.main.WorldToScreenPoint(transform.position).x >= Screen.width;
        bool pastLeftScreenEdge = Camera.main.WorldToScreenPoint(transform.position).x <= 0;

        float accelerationCurveCoeff = 5;
        float maxSpeed = m_FinalStats.TopSpeed;
        float accelPower = m_FinalStats.Acceleration;

        float currentSpeed = Rigidbody.velocity.magnitude;
        float accelRampT = currentSpeed / maxSpeed;
        float multipliedAccelerationCurve = m_FinalStats.AccelerationCurve * accelerationCurveCoeff;
        float accelRamp = Mathf.Lerp(multipliedAccelerationCurve, 1, accelRampT * accelRampT);

        float finalAccelPower = accelPower;

        float finalAcceleration = finalAccelPower * accelRamp;
        bool wasOverMaxSpeed = currentSpeed >= maxSpeed;

        turnInput = turnInput / 2; // So it doesn't bounce back so hard ?

        if (!pastLeftScreenEdge)
        {
            if (turnInput < 0)
            {
                Rigidbody.AddRelativeForce(-transform.right * turnInput, ForceMode.Force);
                Rigidbody.velocity = -transform.right * turnInput *10;
            }
        }
        else
        {
            Rigidbody.velocity = -transform.right;
        }

        if (!pastRightScreenEdge)
        {
            if (turnInput > 0)
            {
                Vector3 fwd = transform.right;
                Vector3 movement = fwd * finalAcceleration * turnInput;

                //transform.Translate(turnInput, 0, 0);
                if (wasOverMaxSpeed)
                    movement *= 0.0f;

                Vector3 newVelocity = Rigidbody.velocity + movement * Time.fixedDeltaTime;
                newVelocity.y = Rigidbody.velocity.y;

                Rigidbody.velocity = newVelocity;
            }
        }
        else
        {
            Rigidbody.velocity = -transform.right;
        }
        //transform.Translate(turnInput, 0, 0);

    }

```

I tried different ways for left and right side movement but neither of them work. Is there a way to produce movement I need with RigidBody ? Alternatively just to make player collide with walls that might be on the sides of the road ?

# Answer
> 1 votes
While aleqzander's answer was useful it wasn't explicitly the solution.

What solved my problem was using Joints. I connected the player to the dolly cart that travels through `CinemachineSmoothPath` by customizable joint. It allowed the player to follow the cart while being able to move freely to the sides and collide with everything as rigidbody object.

# Answer
> 1 votes
Hey **SirResnick2** :)

Good news regarding your movement - you can keep your movement code.

Ensure that **isKinematic** is checked on your players rigidbody.

When the rigidbody isKinematic forces, collisions or joints will not affect the rigidbody anymore - but OnTriggerEnter will still be called!

This means:

1. Add the rigidbody to the player and enable isKinematic
2. Add a collider to any barrier and enable the isTrigger
3. Add a script to those barriers with following code

```
private void OnTriggerEnter(Collider other) { // damage player }

```

**When you want to move your rigidbody you go like this:**

```
// We execute this in our FixedUpdate-Method
// Create our move vector
Vector3 move = new(Input.GetAxis("Horizontal") * moveSpeed, 0, forwardForce);
// Apply our move vector
yourRigidbody.velocity += move; // use this
yourRigidbody.AddForce(move); // or this

```

---
Tags: collision-detection, rigidbody
---