# Question
Title: ECS - Lantern implementation / How does the RenderSystem determine which one to choose? Entity-Datastructure
I want to implement ECS in my game. The more I read the more insecure I get.

The current available Components for a Entity processed by the RenderSystem are:

* RenderComponent (mesh, texture, normalmap, etc.)
* TransformationComponent (position, scale, rotation)
* LightComponent (light color, brightness)
* CameraComponent (view Matrix)

Let's assume that my EntityManager has a methode: getEntitiesByComponents(Class\[\] components): List and is a singleton.

Here is my pseudocode with the issues I have:

```
cclass RenderSystem {

    EntityManager em = EntityManager.getInstance();
    Renderer renderer = new Renderer();

    update(float dt) {

        //This one contained only  RenderSystem related components
        RenderSystemComponents rsc = em.getRenderSystemComponents();

        // Try to get the Camera
        [CameraComponent,TransformationComponent][] cameraArray = rsc.getComponentByType(TRANSFORMATION,CAMERA);
        // Check if Camera is avaible
        if(cameraArray.length != 1) {
            // Do some error Stuff here
            // Not sure if I should allow more then one Camera
            // e.g. MiniMap
        }

        // lights
        [TransformationComponent,LightComponent][] lightArray = em.getComponentByType(TRANSFORMATION, LIGHT);

        // 'default' entities
        [TransformationComponent,LightComponent][] entityArray = em.getComponentByType(TRANSFORMATION, RENDER);

        renderer.render(cameraArray,lightArray,entityArray);
    }

    public enum ComponentType {
        RENDER, TRANSFORMATION, LIGHT, CAMERA
    }
}

```

This implementation could work if my method getEntitesByComponents is fast enough. But the floor is literally the floor. The Terrain has seen from the component's point of view no difference but the RenderEngine should know that it is processing an Entity ( box, tree, player, mob, ... ) or a terrain (different shaders). This isn't a only RenderSystem problem even the Collision detection has to know if it's a terrain or an entity.

---

This is my first problem understanding how I detect differences. The second problem is the method getEntitesByComponents. Current this peace of code doesn't exists in a way I would use it. The basic concept I current use is the one here. The Structure is a `Map<String, Map<Id, Component>>`. The String is the Component class, which maps to a Map with the EntityId as key and the actual component as value.

if you want to get the components from an entity you ask `map.get(Component.class).get(Entity#getId())` but you can't direct ask this structure to get all entities who refer to certain components without looping throw the map. So I need a proper management for the objects.

My first idea is to modify the entity class with a new attribute map and give each Component a unique static Id. So you can easily loop throw the entities and check with something like map.keySet().conatains(x) and y without checking one entity multiple times. But this seems not to be a common implantation. I often see a 'ComponentManager' but unfortunately the article I read doesn't describe the inner datastructure.

# Answer
By fetching entities in a system, you are working against the idea of ECS. ECS is more than just an alternative to polymorphism of game objects. It allows you to clearly define dependencies between Components (data) and Systems (actions), and store data in an optimized manner.

Systems should iterate over Components, not Entities. That way your render system only looks at components it needs (Render, Transformation, and Camera). Currently, there is nothing preventing a System from querying additional Components outside of its normal scope. Since the renderer likely only needs data in the components, accessing the entities violates the Law of Demeter.

How Entities are actually stored is a complex topic. Most of the optimizations are related to the layout of the entities in memory (Structure of Arrays vs Array of Structures). One of the benefits of iterate over Components is that all Components of a specific type can be stored in contiguous memory. Iterating over an array is way faster than accessing a Map. Either way, from your pseudo code it looks like you are using Reflection in Java, which is almost always slow.

Once you have systems with clear dependencies (which data it needs and which systems should be run in what order), you can start to do things like multithreading. For example, if you have two systems that work on two separate sets of components, there is no risk of conflicts or deadlocks when running them concurrently in different threads.

https://csherratt.github.io/blog/posts/specs-and-legion/ This article isn't a how-to on implementing ECS, but compares and contrasts two different ECS usable by the Amethyst. This its just two approaches to optimizing iteration over components, and they're definitely more. Optimizations are going to be tied to the language you are working in, and the level of control you have over memory.
> 0 votes

# Answer
Well, if system needs to distinguish something, you either have a setting in your component (`string ShaderOverride` / `enum RenderStyle`), or just use different components. Latter is preferable, as it's more *SOLID* (no scope bloat).

Here is an example with multiple components.

* `MeshComponent` simply points to a mesh file.
* `TerrainComponent` stores terrain data in-line, which may be modified within game editor.
* `RenderingOptionsComponent` provides additional parameters and overrides that are common for all mesh-like objects: shader override, shader parameters, visibility state, LOD bias and other performance filters.
* `LightComponent` provides light information.
* **`RenderingSystem`** asks *other* rendering sub-systems to provide data for rendering.
* `MeshRenderingSystem` knows how to provide data for all `MeshComponent`s on a map.
* `TerrainRenderingSystem` knows how to provide data for all `TerrainComponent`s on a map.
* `RenderingOptionsSystem` knows how to override already provided data for given entity.
* `LightRenderingSystem` provides light information from all `LightComponent`s on a map.
* **`PhysicsSystem`** asks *other* physics sub-systems provide data for simulation.
* `MeshPhysicsSystem` knows how to get collision data from all `MeshComponent`s on a map.
* `TerrainPhysicsSystem` knows how to get collision data from all `TerrainComponent`s on a map.

It's not necessary to split big systems into sub-systems, but makes mental model more clear, I hope.

ECS is pure database approach. There is no inheritance anymore, no OOP, just tables of data. Think like this: every aspect of every feature is either `Component` or `System`, sometimes both or even few of these. Want to render spline navigation for rendering purposes — ok, time to make `SplineComponent`, `SplineNavigationComponent`, `SplineNavigationDebugRenderingSystem` — or which of those you don't have yet.
> 0 votes

---
Tags: entity-component-system
---


# Question
Title: How do I ensure a piece of code runs only once?
I have some code that I only want to run once, even though the circumstances that trigger that code could happen multiple times.

For example, when the user clicks the mouse, I want to click the thing:

```
void Update() {
    if(mousebuttonpressed) {
        ClickTheThing(); // I only want this to happen on the first click,
                         // then never again.
    }
}

```

However, with this code, every time I click the mouse, the thing gets clicked. How can I make it happen only once?

# Answer
**Use a boolean flag.**

In the example shown, you'd modify the code to be something like the following:

```
//a boolean flag that lets us "remember" if this thing has happened already
bool thatThingHappened = false;

void Update() {
    if(!thatThingHappened && mousebuttonpressed) {
        //if that thing hasn't happened yet and the mouse is pressed
        thatThingHappened = true;
        ClickTheThing();
    }
}

```

Further, if you wanted to be able to repeat the action, but limit frequency of the action (i.e. the minimum time between each action). You'd use a similar approach, but reset the flag after a certain amount of time. See my answer here for more ideas on that.
> 43 votes

# Answer
Should bool flag not suffice or you wanted to improve readability\* of the code in `void Update()` method, you could consider **using delegates** (function pointers):

```
public class InputController
{
  //declare delegate type:
  //<accessbility> delegate <return type> <name> ( <parameter1>, <paramteter2>, ...)
  public delegate void ClickAction();

  //declare a variable of that type
  public ClickAction ClickTheThing { get; set; }

  void onStart()
  {
    //assign it the method you wish to execute on first click
    ClickTheThing = doStuff;
  }

  void Update() {
    if(mousebuttonpressed) {
        //you simply call the delegate here, the currently assigned function will be executed
        ClickTheThing();
     }
  }

  private void doStuff()
  {
    //some logic here
    ClickTheThing = doNothing; //and set the delegate to other(empty) funtion
  }

  //or do something else
  private void doNothing(){}
}

```

For simple "execute once" delegates are overkill, so I would suggest using bool flag instead.
However, if you needed more complicated functionality, the delegates are probably better choice. For example, if you wanted to chain execute more different actions: one on first click, other one on second and one more on third you could just do:

```
func1()
{
  //do logic 1 here
  someDelegate = func2;
}

func2()
{
  //do logic 2 here
  someDelegate = func3;
}
//etc...

```

instead of plaguing your code with tens of different flags.
\*at cost of lower maintainability of the *rest* of the code

---

I did some profiling with results pretty much as I expected:

```
----------------------------------------
|     Method     |  Unity   |    C++   |
| -------------------------------------|
| positive flag  |  21 ms   |   6 ms   |
| negative flag  |  5 ms    |   7 ms   |
| delegate       |  25 ms   |   14 ms  |
----------------------------------------

```

The first test was run on Unity 5.1.2, measured with `System.Diagnostics.Stopwatch` on 32-bit built project (not in designer!). The other one on Visual Studio 2015 (v140) compiled in 32-bit release mode with /Ox flag. Both tests were run on Intel i5-4670K CPU @ 3.4GHz, with 10,000,000 iterations for each implementation. code:

```
//positive flag
if(flag){
    doClick();
    flag = false;
}
//negative flag
if(!flag){ }
else {
    doClick();
    flag = false;
}
//delegate
action();

```

**conclusion:** While the Unity compiler does a good job when optimizing function calls, giving roughly same result for both positive flag and delegates (21 and 25 ms respectively) the branch misprediction or function call is still quite expensive (note: delegate should be assumed cache in this test).
Interestingly, Unity compiler is *not* smart enough optimize the branch when there are 99 millions of consecutive mispredictions, so manual negating of the test does yield some performance boost giving best result of 5 ms. The C++ version does not show any performance boost for negating condition, however the overall overhead of function call is significantly lower.
*most importantly:* the difference is pretty much *irrelevat* for any real-world scenario
> 22 votes

# Answer
### For completeness

(Not actually recommending that you do this as it's actually pretty straightforward to just write something like `if(!already_called)`, but it would be "correct" to do it.)

Unsurprisingly, the C++11 standard has idiomized the rather trivial problem of calling a function once, and made it super explicit:

```
#include <mutex>

void Update() {
if(mousebuttonpressed) {
    static std::once_flag f;
    std::call_once(f, ClickTheThing);
}

```

}

Admittedly, the standard solution is *somewhat* superior to the trivial one in presence of threads since it still guarantees that always exactly one call happens, never something different.

However, you aren't normally running a multithreaded event loop and pressing the buttons of several mice at the same time, so that thread safety is a bit superfluous for your case.

In practical terms, it means that in addition to the thread-safe initialization of a local boolean (which C++11 guarantees to be thread-safe anyway), the standard version must also do an atomic test\_set operation prior to calling or not calling the function.

Still, if you like being explicit, there's the solution.

**EDIT:**
Huh. Now that I've been sitting here, staring at that code for some minutes, I'm almost inclined to recommend it.
Actually it is not nearly as silly as it may seem at first, indeed it very clearly and unambiguously communicates your intent... arguably better structured and more readable than any other solution which involves an `if` or such.
> 3 votes

# Answer
Use function pointers or delegates.

The variable holding the function pointer need not be explicitly examined until a change needs to be made. And when you no longer need said logic to run, replace with a ref to an empty / no-op function. Compare with doing conditionals checks every frame for the entire life of your program - even if that flag was only needed in the first few frames after startup! - **Unclean and inefficient.** (Boreal's point about prediction is however acknowledged in this regard.)

Nested conditionals, which these often constitute, are even more costly than having to check one single conditional every frame, since branch prediction can no longer do its magic in that case. That means regular delays on the order of 10s of cycles - pipeline stalls *par excellence*. The nesting can occur above *or* below this boolean flag. I hardly need remind readers of how complex game loops can quickly become.

Function pointers exist for this reason - use them!
> 2 votes

# Answer
Some suggestions will vary depending on architecture.

Create clickThisThing() as a function pointer / variant / DLL / so / etc... and ensure that it is initialized to your required function when the object / component / module / etc... is instantiated.

In the handler whenever mouse button is pressed then call the clickThisThing() function pointer and then immediately replace the pointer with another NOP (no operation) function pointer.

No need for flags and extra logic for someone to screw up later, just call it and replace it every time and since it's a NOP the NOP does nothing and gets replaced with a NOP.

Or you could use the flag and logic to skip the call.

Or you could disconnect the Update() function after the call so the outside world forgets about it and never calls it again.

Or you have the clickThisThing() itself use one of these concepts to only respond with useful work once. This way you can use a baseline clickThisThingOnce() object / component / module and instantiate it anywhere you needed this behavior and none of your updaters need special logic all over the place.
> 2 votes

# Answer
In some script languages like javascript or lua can be easly done testing the function reference. In Lua (love2d) :

```
function ClickTheThing()
      .......
end
....

local ctt = ClickTheThing  --I make a local reference to function

.....

function update(dt)
..
    if ctt then
      ctt()
      ctt=nil
    end
..
end

```
> 1 votes

# Answer
In a Von Neumann Architecture computer, memory is where your program's instructions and data are stored. If you want to make code only run once, you could have code in the method overwrite the method with NOP's after the method is complete. This way if the method were to run again, nothing would happen.
> 0 votes

# Answer
In python if your planning on being a jerk to other people on the project:

```
code = compile('main code'+'del code', '<string>', 'exec')
exec code

```

this script demonestrates the code:

```
from time import time as t

code = compile('del code', '<string>', 'exec')

print 'see code object:'
print code

while True:
    try:
        user = compile(raw_input('play with it (variable name is code) (type done to be done:\t'), '<user_input>', 'exec')
        exec user
    except BaseException as e:
        print e
        break

exec code

print 'no more code object:'
try:
    print code
except BaseException as e:
    print e

while True:
    try:
        user = compile(raw_input('try to play with it again (type done to be done:\t'), '<user_input>', 'exec')
        exec user
    except BaseException as e:
        print e
        break

```
> 0 votes

# Answer
You can consider using static a variable.

```
void doOnce()
{
   static bool executed = false;

   if(executed == false)
   {
      ...Your code here
      executed = true;
   }
}

```

You can do this in `ClickTheThing()` function itself, or create another function and call `ClickTheThing()` in the if body.

It is similar to the idea of using a flag as suggested in other solutions, but the flag is protected from other code and cannot be altered elsewhere due to being local to the function.
> 0 votes

# Answer
Here's another contribution, it's a little more general/reusable, slightly more readable and maintainable, but likely less efficient than other solutions.

Let's encapsulate our once-executing logic in a class, Once:

```
class Once
{
    private Action body;
    public bool HasBeenCalled { get; private set; }
    public Once(Action body)
    {
        this.body = body;
    }
    public void Call()
    {
        if (!HasBeenCalled)
        {
            body();
        }
        HasBeenCalled = true;
    }
    public void Reset() { HasBeenCalled = false; }
}

```

Using it like the example provided looks as follows:

```
Once clickTheThingOnce = new Once(ClickTheThing);

void Update() {
    if(mousebuttonpressed) {
        clickTheThingOnce.Call(); // ClickTheThing is only called once
                                  // or until .Reset() is called
    }
}

```
> 0 votes

# Answer
I actually came across this dilemma with Xbox Controller Input. Although not EXACTLY the same it's pretty damn similar. You can change the code in my example to suit your needs.

Edit: Your situation would use this -\>

https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagrawmouse

And you can learn how to create a raw input class via -\>

https://docs.microsoft.com/en-us/windows/desktop/inputdev/raw-input

**But.. now onto the super awesome algorithm... not really, but hey.. it's pretty cool :)**

\*So... we can store the states of every button and which are Pressed, Released, and Held Down!!! We can also check Holding Time, but that does require a single if statement and can check any number of buttons, but there are some rules see below for this information.

Obviously if we want to check if something is pressed, released, etc.. you would do "If(This) { }", but this is showing how we can get the press state and then turn it off the next frame so your "ismousepressed" will actually be false the next time you check.

Full Code Here: https://github.com/JeremyDX/DX\_B/blob/master/DX\_B/XGameInput.cpp

How it works..

So I'm not sure the values you receive when you depict if a button is pressed or not, but basically when I load in XInput I get a 16bit value between 0 and 65535 this has 15 bits possible states for "Pressed".

The problem was every time I checked this It would simply give me the current state of the information. I needed a way to convert the current state into Pressed, Released, and Hold Values.

So what I did is the following.

First we create a "CURRENT" variable. Every time we check this data we set the "CURRENT" to a "PREVIOUS" variable and then store the new data to "Current" as seen here -\>

```
uint64_t LAST = CURRENT;
CURRENT = gamepad.wButtons;

```

With this information here's where it get's exciting!!

We can now figure out if a Button is being HELD DOWN!

```
BUTTONS_HOLD = LAST & CURRENT;

```

What this does is basically it compares the two values and any button presses that are shown in both will stay 1 and everything else set to 0.

I.e. (1 | 2 | 4) & (2 | 4 | 8) will yield (2 | 4).

Now that we have which buttons are "HELD" down. We can get the rest.

Pressed is simple.. we take our "CURRENT" state and remove any held down buttons.

```
BUTTONS_PRESSED = CURRENT ^ BUTTONS_HOLD;

```

Released is the same only we compare it to our LAST state instead.

```
BUTTONS_RELEASED = LAST ^ BUTTONS_HOLD;

```

So looking at the Pressed situation. If let's say Currently we had 2 | 4 | 8 pressed. We found that 2 | 4 where held. When we remove the Held Bits we are left with only 8. This is the newly pressed bit for this cycle.

The same can be applied for Released. In this scenario "LAST" was set to 1 | 2 | 4. So when we remove the 2 | 4 bits. We are left with 1. So the button 1 was released since the last frame.

This above scenario is probably the most ideal situation you can offer for bit comparison and it provides 3 levels of data with no if statements or for loops just 3 quick bit calculations.

I also wanted to document hold data so although my situation isn't perfect... what it does is we basically set the holdbits we want to check for.

So every time we set our Press/Release/Hold data we check if the hold data still equals the current hold bit check. If it doesn't we reset it's time to current time. In my case I'm setting it to frame indexes so I know how many frames it's been held down for.

The downside to this approach is I can't get individual hold times, but you can check multiple bits at once. I.e. if I set the hold bit to 1 | 16 if either 1 or 16 are not held this would fail. So it requires that ALL those buttons are held down to continue ticking.

Then if you look in the code you'll see all the neat function calls.

So your example would be reduced to simply checking if a button press occurred and a button press can only occur once with this algorithm. On the next check to press it will not exist since you can't press more then once you'd have to release before you can press again.
> 0 votes

# Answer
Not sure which language you are using, but if using c++: make ClickTheThing return bool

```
bool ClickTheThing()
{
    //Do something
    return true;
}

void Update()
{
    if(mousebuttonpressed)
    {
        static const bool unused = ClickTheThing();
    }
}

```

because its a static, it conly gets set once so once set, the call never happens again and we have no global variables to worry about either
> 0 votes

# Answer
Stupid cheap way out but you could use a for loop

```
for (int i = 0; i < 1; i++)
{
    //code here
}

```
> -3 votes

---
Tags: architecture, events
---


# Question
Title: Multiplayer tile based movement collisions cause client prediction to fail
I am developing a tile-based online multiplayer game, but I am stuck. Players can move across the grid in the four cardinal directions, as can enemies, but two players/enemies cannot occupy the same tile at the same time. Positions of all players/enemies are synced for all clients.

My current implementation of movement: Clients send a 'request to move' to the server whenever they are stationary on a tile.

I have implemented client prediction. When a button is pressed to move, the client shows their character immediately moving in that direction, as opposed to waiting for confirmation from the server, preventing lag between player input and visible results.

The issue arises when the player attempts to move to a position that will soon be occupied. For example, the player presses up when an enemy is very close to entering the tile above the player (though they can't currently know that the enemy will choose that tile next). Locally this is confirmed and the upwards animation begins, but by the time the request to move up arrives at the server, the tile is no longer free, and the player is not moved up on the server.

This creates a situation where the player's local position is out of sync with that of the server. My current solution to this is snapping the local player back to the server's position when this happens, but this looks awful. It seems to be happening a lot, making the game nearly unplayable.

Is there a way around this? Any help would be very much appreciated, thanks.

Some other notes: I send updates from the server 10 times a second, which consist of every object's position (and other stuff). When a movement event is processed, the object's position is updated immediately, even though an animation follows.

# Answer
> 2 votes
Your prediction method has "coarse granularity" so to say: when prediction fails, big amount of movement is cancelled, which leads to jarring visuals.

In comparison with games in other genres (FPS, RPG, plaformers, etc), where movement prediction is used, movement is usually continuous. In case of prediction fail, this leads to relatively small amount of movement being reverted, which may be smoothed further with quick client-side interpolation.

This is fundamental "no free lunch" problem. If prediction fails, it has to be corrected, otherwise you'll get desync. Thus, either make movement more "fine-grained" (i.e. by using smaller grid), or get rid of prediction (wait for server response).

Your game seems more similar to RTS. AFAIK, in that genre it's more common to use deterministic inputs ("lockstep"). Sometimes it may be notices as input lag in multiplayer games. (Technical details here.)

Because lockstep is not trivial to implement and might not fit your client-server model, I'd stick with server confirmation. Though, don't ask server to confirm anything, but rather just send a request — if server accepts request and starts movement, it'll send back movement update, thus confirming you request emergently.

# Answer
> 1 votes
Why not have your server respond to all move requests with the new location of the client's player?

Example:

Client A requests to move its player from (15, 15) to (15, 16). Both the current `position` and `destination` are included in the request.

The server recieves the request and determines where the player will be after attempting to move from `position` to `destination`, and sends the resulting `newPosition` back to the client. In this case, the server determines that the request cannot be authorized because there is currently a unit occupying space (15, 16), and thus `newPosition` is (15, 15) since the player was not able to move.

The client recieves the response and moves its player to `newPos`. In this case, the client moves the player back to (15, 15).

It might create a bit of a rubber-banding effect, but you might be able to mask it by accompanying it with a visible/audible collision effect if the client response includes a "denied" tag, or something like that.

---
Tags: networking, multiplayer, tiles, online
---


title: Clickable videos in unity

text:
# Question
Title: Clickable videos in unity
My sister is working on a visual novel. We wanted to use unity to build it. She wants to have videos with clickable buttons to skip to other scenes. The problem is we both are noobs! Do you guys have any tips on tutorials or anybody knows if this is possible? What would be the best method to tackle this.

I figured having each scene as an mp4 and having buttons trigger each mp4. but, how would that work with time-triggered Audio?

# Answer
The component you are looking for is the video player. It handles both video and audio playback.

If you want to play the video full-screen, then I would recommend to set the render mode to "Camera Near Plane". If you want to play the video in a window, then I recommend to use "Render Texture". This requires that you create a render texture asset to render to. That render texture can then be used as a texture for a quad or sprite in your scene or a RawImage on your UI canvas.

The documentation I linked to should tell you further details.

If you have multiple video clips which you want to play through the same video player, then you should deactivate "Play on Awake" on the video player and control the playback through a script. That script needs to:

1. set the correct video asset on the player (the `.clip` property)
2. call the `Play()` method of the player to start playback

The scripting documentation of the VideoPlayer class should give you more information on what else you can do with it.
> 0 votes

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


# Question
Title: Can I mention other games' titles, characters, maps, weapons etc. in my game?
Let's say I was about to make a quiz game where the questions are like this:

* When was Fallout 4 released?
* What is your first pickaxe in Minecraft?
* Who do you have to kill as the last boss in Skyrim?

And let's pretend I have 1000 of these questions, from 1000 games. What are the chances some of those 1000 could sue me, remove my game from the internet, pay them a fee etc.? Even if it becomes very popular.

Taking it one step further, could I buy their games, take in game screenshots personally, then use those as pictures in my own game?

Does it make a difference if it's a free-to-play or a game that has to be bought?

# Answer
First of all, I am not a lawyer, so I can not provide legal advise. When you are serious about this, do not rely on legal opinions of anonymous strangers on the Internet. Consult a real lawyer.

---

There is never zero chance to get sued. You can get sued for anything. Companies sometimes sue people even if they know they can not win. They just do it to shut down competitors or critics by tying them up with legal costs. It's called a SLAPP suit.

But in my experience, the chance to get sued for this is kinda low. You can not copyright basic trivia and you can not copyright information about products. So simply asking trivia questions about other games is unlikely to violate any copyrights.

Not even trivia questions themselves are necessarily protected by copyright. At least that's what an US court decided in 1987 in a lawsuit against the creators of Trivial Pursuit who got caught copying questions from a book. The court decided that since they didn't take the whole collection of questions and instead hand-pick questions from multiple sources, it's not copyright violation but simply research.

However, you still got to be careful about a couple things:

* Do not violate trademark law when you promote your game. For example, when you promote your game as "Fallout Quiz", then Bethesda might feel that this infringes on their trademark for "Fallout" which gives them the exclusive right to create games with Fallout in the name.
* Do not copy assets. For example, if you copy a popular sprite from a game asking the player to identify it, then having that sprite in your game is a copyright violation.
* Do not slide into defamation. When you make games look bad by misrepresenting them, you might invite a SLAPP suit.
> 7 votes

---
Tags: legal, copyright, trademark
---


# Question
Title: Monobehaviour script method does not appear as an option for UI button's On Click
I have the following script, and when I try to use a UI button to call the `CheckGuess` method, it does not appear as an option:

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

public class Guessthenumbergame: MonoBehaviour
{
    public InputField input;

    public Text infoText;

    private int guessNumber;

    private int userGuess;

    // Start is called before the first frame update
    void Start()
    {
        guessNumber = Random.Range(0, 100);

    }

    // Update is called once per frame
    public void CheckGuess()
    {
        userGuess = int.Parse(input.text);
        if (userGuess == guessNumber)
        {
            infoText.text = "You guessed the number right";
        }else if (userGuess > guessNumber)
        {
            infoText.text = "Your number is higher";
        }else if (userGuess < guessNumber)
        {
            infoText.text = "Your number is lower";
        }
        input.text = "";
    }
}

```

# Answer
> 1 votes
Your code as shown here does not compile.

Because you have both `using System;` and `using UnityEngine;`, the compiler doesn't know whether this line:

```
guessNumber = Random.Range(0, 100);

```

...wants to use the version of `Random` in the `System` namespace, or the one in the `UnityEngine` namespace.

So my guess is that the reason your function isn't showing up is because your code has not successfully compiled since you added it.

Make sure you're in the habit of checking the Console window in Unity and resolving any errors it tells you about. As long as there's a compiler error, the versions of your scripts you see in the editor will be stuck at the last version that successfully compiled.

When I disambiguate the reference by removing the `using System;` directive, or qualifying the reference as `guessNumber = UnityEngine.Random.Range(0, 100);`, the code compiles, and the `CheckGuess()` method appears as an option for the button's `On Click()`

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


# Question
Title: How to improve the charactercontroller for jumping?
I have an issue with my character controller, when I jump, it sometimes lands on surfaces it shouldn't be able to land on, like very steep slopes etc (even though my max slope is 45 deg). In this case, Controller.isGrounded() still is true. The controller doesn't fall off the steep slopes either, it just stays there and the controller can jump again.

I also notice that the controller sometimes can climb heights very awkardly (after jumping), like it is barely touching the elevated ground surface yet it can "push move" to climb it's way up

These problems both occur in the standard implementation given by unity https://docs.unity3d.com/ScriptReference/CharacterController.Move.html

See also: https://i.stack.imgur.com/YRJ0C.png (here it can jump on the steep slope and stay there, UCC is the example script from unity copy pasted)

How can I fix these things? Are there any existing solutions or guides for better character controllers?

# Answer
> 1 votes
So here is my thought on the issue, there may be an easier way but that doesn’t matter you have to start somewhere.

I’m assuming you are using a ray cast in order to check if the player is close to the ground, so what you can do is use RaycastHit.normal() to get a new vector that represents the normal of the object.

With this new vector you can calculate the slope of the plane, if it is steep enough you want to add a small force to the players horizontal.

That should be it, if you have anymore questions or you need clarification on anything I said (which you probably will seeing how I’m not wonderful at explaining things) please contact me.

---
Tags: unity, physics, collision-resolution
---


# Question
Title: Why the navmeshagent is not walking through the door?
The nav mesh agent have this components : Animator , Nav Mesh Agent , Box Collider , Agent Control(script) and a Rigidbody and both Use Gravity and Is Kinematic are set to true enable true.

When the character is getting close to the door the character stop and is not walking through. but if I disable the Nav Mesh Agent component I can drag the character through the door. but disabling the Nav Mesh Agent component is not a solution.

In the Navigation window I selected the door and set the door to be Navigation static and Walkable did it for all the door children then baked again but it didn't help much.

Screenshot of the agent near the open door and if I try to drag the agent in the scene view through the door he will not move through only if I disable the Nav Mesh Agent component first :

The waypoint the agent should get to is in the next room the blue teleporter.

This is the script that make the agent move to the waypoint :

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

public class AgentControl : MonoBehaviour
{
    public List<Transform> points;
    public bool waitTimeToMove = false;
    //notice WaitTime is a float now
    public float WaitTime = 10f;
    public bool randomWaitTime;
    float waitMinTime = 1f;
    float waitMaxTime = 10f;
    public bool loop = false;
    public Animator anim;

    private int destPoint = 0;
    private NavMeshAgent agent;
    private Transform originalPos;
    //two vars for handling timer
    private float timer = 0;
    private float originSpeed;

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();

        // Disabling auto-braking allows for continuous movement
        // between points (ie, the agent doesn't slow down as it
        // approaches a destination point).
        agent.autoBraking = false;

        originSpeed = agent.speed;

        if (randomWaitTime == true)
        {
            WaitTime = Random.Range(waitMinTime, waitMaxTime);
        }

        //transforms dont exist without A GameObject and a GameObject doesn't exist without a transform
        //create a new GameObject to hold our position
        GameObject originalPositionObject = new GameObject();
        originalPositionObject.name = "WP";
        originalPositionObject.tag = "Waypoint";
        originalPositionObject.transform.parent = GameObject.Find("Waypoints").transform;
        //set the new gameobjects position equal to where the transform is right now
        originalPositionObject.transform.position = transform.position;
        //add this to the points list instead
        points.Add(originalPositionObject.transform);

        anim = GetComponent<Animator>();
    }

    void GotoNextPoint()
    {
        // Returns if no points have been set up
        if (points.Count == 0)
            return;

        // Set the agent to go to the currently selected destination.
        agent.destination = points[destPoint].position;

        // Choose the next point in the array as the destination,
        // cycling to the start if necessary.
        destPoint = (destPoint + 1) % points.Count;
    }

    void Update()
    {
        // Choose the next destination point when the agent gets
        // close to the current one.
        if (!agent.pathPending && agent.remainingDistance < 1f)
        {
            //if wait to move is true
            if (waitTimeToMove)
            {
                //if timer is less than 10
                if (timer < WaitTime)
                {
                    //add Time.deltaTime each time we hit this point
                    timer += Time.deltaTime;
                }
                //no longer waiting because timer is greater than 10
                else
                {

                    waitTimeToMove = false;

                    anim.SetBool("Walk", true);
                }
            }
            //if we hit here waitToMove is false, so go ahead as usual
            else
            {
                if (loop == false && destPoint == points.Count - 1)
                {
                    anim.SetBool("Idle", true);
                    agent.speed = 0;
                }

                if (loop == true || destPoint != points.Count - 1)
                {
                    agent.speed = originSpeed;

                    GotoNextPoint();
                }
            }
        }
    }
}

```

# Answer
> -1 votes
Try adjusting the height and width of the Nav Mesh Agent.

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


title: How to use AddForce on a capsule?

text:
# Question
Title: How to use AddForce on a capsule?
I created a simple scene, with a box that serves as the ground, and a capsule that serves as the player. I added to the player a RigidBody, and a component that should move it using AddForce:

```
private void FixedUpdate() {
    rb = GetComponent<Rigidbody>();
    float horizontal = Input.GetAxis("Horizontal");
    rb.AddForce(new Vector3(horizontal * forceSize, 0, 0), ForceMode.Force);
}

```

However, instead of moving straight along the ground, my capsule rolls over its head:

I tried to mark the checkbox near Freeze Rotation: Z in my RigidBody component, but then the capsule stopped moving altogether.

What is the correct way to apply force to the capsule?

EDIT: Initially, the physic material on both the player's collider and the ground collider was None. Now, I changed it to a new material with dynamic friction and static friction 0, and it moves straight (even with gravity and without freezing the Z rotation). However, if I even slightly increase either type of friction in either one of the materials, the player falls on its face again. Why does friction have this effect on the player? And how can I move the player correctly when there is positive friction?

# Answer
I tried to set up a demo project to test around and found a simple approach based on rotation constraints as suggested by other users, and the `AddForce()` function as you needed it.

I applied a zero-friction material to both the capsule and the cube, and later found a nice value of `0.2` for one of the two only in Average combine mode (alternatively: `0.1` for both, but this is up to you).

The capsule's `RigidBody` component can be set as you wish, as long as you turn on Freeze Rotation Constraints for both the *X* and *Z* axes so that the capsule will always stand upwards. That's because your character-like collider isn't supposed to be rotating, except for on-spot turning: many movements are just cosmetic issues that you can deal with animations. It is only in charge of managing physics movements around your world.

Finally, I attached a script to the capsule object, which is a slightly edited version of your own code:

```
using UnityEngine;

public class CapsuleController : MonoBehaviour {
    public float forceSize;
    Rigidbody rb;

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

    void Update() {
        float horizontal = Input.GetAxis("Horizontal");
        rb.AddForce(new Vector3(horizontal * forceSize, 0f, 0f), ForceMode.Acceleration);
    }
}

```

This way, `AddForce()` applies a force in `ForceMode.Acceleration` mode (that is, same acceleration for everyone regardless of their mass) and the internal physics solver will step physics forward taking rotation constraints into account. The final result is a nice movement without the capsule tripping and tumbling down.
> 1 votes

# Answer
Either **freeze rotation** or use

```
GetComponent<Rigidbody>().MovePosition()

```
> 0 votes

---
Tags: unity, physics
---


# Question
Title: Need help converting LPDIRECT3DTEXTURE9 to openGl libgdx Pixmap
What i'm trying to achieve. I need to know the equivalent of `LPDIRECT3DTEXTURE9` to openGL, the problem is I only know `Pixmap` class of libgdx which `pixmap.drawPixel(x, y, color)` is only available, I cannot find how to convert `layer->lightMap->LockRect(0, &rectLock, 0, 0)`

Below is example code of c, `LPDIRECT3DTEXTURE9` lightMap is used which unknown in openGL to me.

```
D3DLOCKED_RECT rectLock;
D3DCOLOR* pixels;
LandLayer* layer;
int j;

for (int i = 0; i < m_layers.GetSize(); i++)
{
    layer = m_layers[i];
    layer->lightMap->LockRect(0, &rectLock, 0, 0);
    pixels = (D3DCOLOR*)rectLock.pBits;
    for (j = 0; j < MAP_SIZE * MAP_SIZE; j++)
        pixels[j] = D3DCOLOR_ARGB(layer->alphaMap[j], m_colorMap[j * 3], m_colorMap[j * 3 + 1], m_colorMap[j * 3 + 2]);
    layer->lightMap->UnlockRect(0);
}

```

What I have done in kotlin, using `Pixmap` from libgx https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/Pixmap.java

```
tmpColor.set( Color.toIntBits( r.toInt(),g.toInt(),b.toInt(),a.toInt()))
pixmap.drawPixel(x, y, tmpColor.toIntBits())

```

# Answer
> 2 votes
LPDIRECT3DTEXTURE9 is a texture object. OpenGL, by comparison to Direct3D, is weakly-typed, so there is no class or struct that is equivalent; instead texture objects are represented by unsigned integer "names" - the same GLuint data type that is used for other object types.

From the code you posted it looks as though you're trying to set texture data from a system memory array. The OpenGL calls to do this are glTexImage2D (for creating a new texture) or glTexSubImage2D (for updating an existing texture) - assuming a 2D texture, of course. There is no direct OpenGL equivalent to LockRect.

---
Tags: libgdx, directx9
---


# Question
Title: How to create a color grading LUT for Unity URP?
I'm watching a movie, and I would like to achieve the same colors in my game.

I think I have to use a Color Grading lookup table to achieve this in Unity with URP.

The best example I found example deals with Photoshop, but it didn't include any information or description, it was just a raw screen capture which I didn't really understand.

How can I create a LUT?

# Answer
LUTs can be used in Unity URP by

1. Creating a Volume in the Inspector ("Create" -\> "Volume" -\> "Global Volume")

2. Clicking "New" to create a new Volume Profile:

3. Clicking "Add Override" in the newly created Volume, then "Color Lookup".

4. Checking "Lookup Texture" and then assing a LUT in the slot next to it.

For the LUT, I have used one of the free samples that come with the free "Amplify Color" asset in the Unity Asset store.

The results are visible right away in both the scene view window and in the gameview window.

Also make sure that "Post Processing" is activated in the camera. I think by default it is not activated.
> 1 votes

---
Tags: unity, color, post-processing
---


# Question
Title: LibGDX Letter spacing is reduced if I use GlyphLayout to draw a bitmap font
I need to use `glyphlayout` so that I can centre the text, but I found if I do the text gets distorted due to the spacing being incorrect.

```
public SimpleButton(String text, float x, float y, float w, float h, BitmapFont font) {
    pos = new Vector2(x, y);
    this.w = w;
    this.h = h;
    this.text = text;
    this.font = font;
    glyphLayout.setText(font, text);
    hitbox = new Rectangle(x, y - h, w, h);
}

public void render(SpriteBatch batch) {
    font.draw(batch, text, pos.x, pos.y);
}

```

Like this it displays fine:

But using `glyphlayout` to draw it the spacing for some reason is different:

```
public void render(SpriteBatch batch) {
    font.draw(batch, glyphLayout, pos.x, pos.y);
}

```

Glyphlayout seems to be changing the spacing here, but I couldn't see any options for setting the spacing with it.

These are the settings for the Bitmap font in Hiero. No special fx, padding and spacing set to zero:

# Answer
I managed to solve the problem myself but it still seems like it may be a bug. It happens because `glyphLayout.setText(font, text);` is declared in the constructor method but it needs to be in the render method, or otherwise continually updated. I've no idea why this is, it would seem that declaring it once in the constructor method should work fine...but for some reason it doesn't.

```
public SimpleButton(String text, float x, float y, float w, float h, BitmapFont font) {
    pos = new Vector2(x, y);
    this.w = w;
    this.h = h;
    this.text = text;
    this.font = font;
    hitbox = new Rectangle(x, y - h, w, h);
}

public void render(SpriteBatch batch) {
    glyphLayout.setText(font, text);
    font.draw(batch, glyphLayout, pos.x, pos.y);
}

```

The text with `glyphlayout` displays with correct spacing using this code.
> 1 votes

---
Tags: java, libgdx, text, fonts
---


# Question
Title: How to convert point coordinate when taking a snapshot?
Can anyone explain me please how to convert point from Screen-coordinate system to Texture 2D? The screen size say for example 700x500 and Texture2D must be of size 1024x768. I am getting points from scene, convert them with camera.WorldToScreen and then multiply by ratio, which doesn't work correctly for some reason. Here is my code:

```
//PROCESSING POINTS
cam_pts[i] = detector.WorldToScreenPoint(pts[i]);
cam_pts[i].y = Screen.height - cam_pts[i].y;
cam_pts[i].x = cam_pts[i].x * (ImageWidth/(float)Screen.width);
cam_pts[i].y = cam_pts[i].y * (ImageHeight/(float)Screen.height);

```

```
//SAVING CAPTURE SCREEN
RenderTexture rt = new RenderTexture(ImageWidth, ImageHeight, 24);
detector.targetTexture = rt;
Texture2D screenShot = new Texture2D(ImageWidth, ImageHeight, TextureFormat.RGB24, false);
detector.Render();
RenderTexture.active = rt;
screenShot.ReadPixels(new Rect(0, 0, ImageWidth, ImageHeight), 0, 0);
detector.targetTexture = null;
RenderTexture.active = null;
Destroy(rt);
byte[] bytes = screenShot.EncodeToPNG();
string filename = string.Format("Screenshot_{0}.png", counter);
System.IO.File.WriteAllBytes(filename, bytes);

```

The red points must be at the corners of the pallet. I am new in Unity and C# and will be thankful if someone explains me how to do it right.

# Answer
> 1 votes
Thanx DMGregory for taking part. I found a decision to this problem. In the saving capture screen part must be added a few rows:

```
RenderTexture rt = new RenderTexture(ImageWidth, ImageHeight, 24);
        detector.targetTexture = rt;
        Texture2D screenShot = new Texture2D(ImageWidth, ImageHeight, TextureFormat.RGB24, false);

        float aspect = detector.aspect; //preserve old aspect ratio
        detector.aspect = (float)ImageWidth / (float)ImageHeight; //set new aspect ratio according to width and height of an image

        detector.Render();
        RenderTexture.active = rt;
        screenShot.ReadPixels(new Rect(0, 0, ImageWidth, ImageHeight), 0, 0);
        detector.targetTexture = null;
        RenderTexture.active = null;

        detector.aspect = aspect;// return back original aspect ratio

        Destroy(rt);
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = string.Format("Screenshot_{0}.png", counter);
        System.IO.File.WriteAllBytes(filename, bytes);

```

And then in the void Start()-function must be added:

```
Screen.SetResolution(ImageWidth, ImageHeight, false);
        detector = this.GetComponent<Camera>();// get camera object
        detector.aspect = (float)ImageWidth / (float)ImageHeight;// setting aspect ratio of the screen

```

This way ordinary coordinate conversion works/

---
Tags: unity, c#, textures, coordinates
---


title: Java LERP but with whole pixel values

text:
# Question
Title: Java LERP but with whole pixel values
I have a formula which returns a `Lerp` `Vector3` value in integers but the problem is it never reaches the desired target value. It's converting to pixel values first by multiplying by PPM which is `float` 32f.

```
private Vector3 lerp(final Vector3 source, final Vector3 target, float alpha) {
    Vector3 sourcePPM = new Vector3(source.x * PPM, source.y * PPM, 0);
    Vector3 targetPPM = new Vector3(target.x * PPM, target.y * PPM, 0);
    sourcePPM.x += Math.round(alpha * (targetPPM.x - sourcePPM.x));
    sourcePPM.y += Math.round(alpha * (targetPPM.y - sourcePPM.y));
    source.x = sourcePPM.x / PPM;
    source.y = sourcePPM.y / PPM;
    source.z = 0;
    return source;
}

```

I initialize my vector variable `source` to `new Vector3(0.0, 0.0, 0.0)`. Then, each frame I update it like this:

```
source = lerp(source, new Vector3(26.0, 29.0, 0.0), 0.06f);

```

But instead of eventually reaching the target, the value plateaus at a certain point:

```
Target destination: (26.0,29.0,0.0)
Actual final destination: (25.75,28.75,0.0)

```

Falling short of the target destination. If I don't round the values then it gets there fine but I need it to be in whole pixels.

The final line of intermediate values (too many to add all of them):

```
(25.0,27.90625,0.0)
(25.0625,27.96875,0.0)
(25.125,28.03125,0.0)
(25.1875,28.09375,0.0)
(25.25,28.15625,0.0)
(25.28125,28.21875,0.0)
(25.3125,28.28125,0.0)
(25.34375,28.3125,0.0)
(25.375,28.34375,0.0)
(25.40625,28.375,0.0)
(25.4375,28.40625,0.0)
(25.46875,28.4375,0.0)
(25.5,28.46875,0.0)
(25.53125,28.5,0.0)
(25.5625,28.53125,0.0)
(25.59375,28.5625,0.0)
(25.625,28.59375,0.0)
(25.65625,28.625,0.0)
(25.6875,28.65625,0.0)
(25.71875,28.6875,0.0)
(25.75,28.71875,0.0)
(25.75,28.75,0.0)

```

# Answer
The Greek philosopher Zeno proposed a paradox: an arrow can never strike its target. In order to do so, it would have to:

* First, cross half the distance to its target.
* Then, cross half the remaining distance (one quarter of the original distance)
* Then, cross half *that* remaining distance (one eighth of the original)
* Then, cross half of ***that*** remaining distance (one sixteenth of the original)
* Then...

Because we can continue taking halves forever, this means there's an infinite number of steps the arrow has to take to reach the target. How could we ever perform infinite actions in finite time?

The solution to Zeno's paradox is the (apparently) continuous nature of time and space. Because each of these steps takes less and less time, while still making tiny increments of progress, we can show with calculus that the sum of all these infinite steps really does take only a finite amount of time, and summing all those infinite infinitesimals really does bring us all the way to our target.

Why does this matter? Because when you use this pattern for `lerp`:

```
current (variable) = lerp(current (variable), target (fixed), alpha (fixed));

```

Instead of this one:

```
current (variable) = lerp(start (fixed), end (fixed), progress (variable));

```

You're saying "I want my object to move like Zeno's arrow" - what we call an "exponential ease-out" motion, or "exponential moving average" if the target can change mid-flight.

The amount your `current` variable changes each frame is proportional to *how far it still has to go*:

* In your first call, when `current` is a long way from `target`, that difference is large, and `alpha` times that distance is proportionately large, so your `current` variable changes a lot.
* But as `current` gets closer and closer to `target`, the difference gets less and less, so `alpha` times that distance is proportionately smaller, and your `current` variable starts moving more slowly.

Now, because space *isn't* very continuous in your game - it's rounded to discrete pixels - there comes a point where the difference between `current` and `target` is so small that after multiplying by `alpha`, it rounds to zero. The arrow never reaches its target, and Zeno is right! (For a different reason than he had in mind though).

So, some potential solutions:

1. Let your underlying vector in the feedback loop stay unrounded, but then save its rounded value to another variable you use for your simulation/display:

```
   unroundedPosition = unroundedLerp(unroundedPosition, target, alpha);
   roundedPosition = Round(unroundedPosition * PPM)/PPM;

   // Use `roundedPosition` for anything that reads this object's position.

```
2. Detect the case where you round to zero, and fudge it to avoid getting stuck:

```
    private Vector3 roundedLerp(final Vector3 source, final Vector3 target, float alpha) {
        Vector3 sourcePPM = new Vector3(source.x * PPM, source.y * PPM, 0);
        Vector3 targetPPM = new Vector3(target.x * PPM, target.y * PPM, 0);

        float deltaX = (targetPPM.x - sourcePPM.x);
        // If we can make a whole pixel of progress with alpha, proceed as normal.
        if(Math.abs(alpha * deltaX) > 0.5) {
            sourcePPM.x += Math.round(alpha * deltaX);
        // Otherwise, if we're more than half a pixel from our target, advance one pixel.
        } else if(Mathf.abs(deltaX) > 0.5) {
            sourcePPM.x += Math.signum(deltaX);
        }

        float deltaY = (targetPPM.y - sourcePPM.y);
        if(Math.abs(alpha * deltaY) > 0.5) {
            sourcePPM.y += Math.round(alpha * deltaY);
        } else if(Mathf.abs(deltaY) > 0.5) {
            sourcePPM.y += Math.signum(deltaY);
        }

        source.x = sourcePPM.x / PPM;
        source.y = sourcePPM.y / PPM;
        source.z = 0;
        return source;
    }

```
3. Use the non-exponential form of `lerp`, and add any easing you want yourself:

```
    // Store a progress variable that goes from zero to 1 over your desired movement.
    progress = Math.Min(progress + deltaTime/transitionDuration, 1);

    // This gives you a quadratic ease-out: fast at the start, slow at the finish.
    float easeOut = 1 - (1 - progress) * (1 - progress);

    currentPosition = roundedLerp(startPosition, endPosition, easeOut);

```
> 3 votes

# Answer
Here's what I would do and think about in your shoes:

* Print all the intermediate values. That might show you where the problem lies. If any value is not as expected, change your mental model (this may require research) such that your new model agrees with what you observed.
* My first guess about how to do this is to convert your given data to floats, calculate the lerp with floats, then convert the final result back to integers by rounding to nearest.
* Does `Math.round` round down, up, towards zero, to nearest integer? Make sure it does what you expect.

I can perhaps give a better answer if you print all the intermediate values and expand your question around the first value that surprises you. Note: You haven't showed us the `Vector3` constructor nor the type and precise value of `PPM` (is it `32.0`? Float or double?). Those might be helpful too.
> 0 votes

---
Tags: java, libgdx, lerp
---


title: How does cube mapping work?

text:
# Question
Title: How does cube mapping work?
Based on my reading of cube mapping tutorials so far, my understanding is that you need a direction vector, and from the direction vector we can determine the point of intersection with one of the six planes.

Is the direction vector the player's view direction? Besides that, I do not understand how having only one ray will give us the texture to fill the whole screen.

Furthermore, what if we are looking at one of the edge of the cube? Now we have to sample texture from two faces?

Can someone please explain what am I missing here?

# Answer
> So far, my understanding is that you need a direction vector, and from the direction vector we can determine the point of intersection with one of the six planes.

Basically, yes.

---

> Is the direction vector is the players view direction?

Any direction. In your shader code you can query the cubemap with any direction you want. It does not have to be where the player is looking.

For instance, aside from using cubemaps for skyboxes, one common use is reflections. For abstract, you compute the direction for the reflection and query there.

---

> I do not understand how having only one ray will give us the texture to fill the whole screen?

If you want to fill the screen with a cubemap, you would do a raycasting setup.

The basic setup is as follows:

1. Set a squad to fill the screen.
2. In your fragment shader, compute the direction for the ray and query there.

Alright, let me qualify that…

The fragment shader will run for every pixel (well, every fragment) of the screen, in parallel. Now, in a perspective projection, each pixel will be the projection of a line that reaches the camera. You want the direction of that line. That is what you query the cubemap with.

How do you get that direction? Imagine you are projecting the world into the near plane of the camera. If you know the size of the output, the position of the current pixel, and the distance to the nearplane, you can compute the position of the point in the near plane. Well, the direction from the camera to that point.

*The viewing frustrum - Intergraph Computer Systems.*

---

For anybody doing this in OpenGL, know, I kind of made it more complex that it is.

If you are going to fill the screen with a squad, and you need to find points in the near plane… Make the squad match the near plane, with the camera at the origin, and you solve this neatly in the vertex shader:

```
#version 330 core
layout (location = 0) in vec2 position;

uniform mat4 inverseProjection;
uniform mat4 inverseView;

out lowp vec3 cameraRayDirection;

void main()
{
    gl_Position = vec4(position.xy, 0.0, 1.0);
    cameraRayDirection = ((inverseView * inverseProjection) * gl_Position).xyz;
}

```

*In actuality, you only need two coordinates, don't you? I made position vec2 in this code, yes, it works.*

In the fragment shader, you get them interpolated, and ready to use.

---

> Furthermore, what if we are looking at one of the edge of the cube? Now we have to sample texture from two faces?

You don't have to worry about it. OpenGL understands cubemaps. You can bind your textures with `GL_TEXTURE_CUBE_MAP`, set the six faces, and your shader code does not have to worry about it. *Please refer to a tutorial on uploading textures with OpenGL.*

In your shader program, you define your texture sampler as samplerCube, for example:

```
uniform samplerCube SkyBox;

```

And then query using an unit vector:

```
return texture(SkyBox, direction);

```

---

Now, if you wanted to emulate this in CPU, not using any shader code… Then the cubemap probably isn't the best format.

You can convert the texture to a cylindrical form that you may query with the angles of the direction you want. See Converting to/from cubemaps.

Baring that, using the cubemap would require to find the intersection of the unit vector with the cube.
> 4 votes

# Answer
Adding to the accepted answer regarding how the texel lookup works:

> Furthermore, what if we are looking at one of the edge of the cube? Now we have to sample texture from two faces?

No, cubemaps sample only 1 of the 6 textures in 2D.

The textures can internally have a 1 pixel border that reproduces the pixels for the neighbouring texture on the cube, giving the impression that it's sampling from multiple faces but it is only sampling a single 2D texture.

The pseudo-code steps of what happens on the GPU are:

```
n = Normalise(xyz);
i = ScalarIndexOfLargestMagnitudeIn(n);
n = n / n[i]; // intersect with cube surface
uv = DeleteScalarAtIndex(n, i);
face_index = i*2 + IsNegative(n[i]);
pixel = Texture2DRead(cube_maps[face_index], uv * axis_flip_rule[face_index] + vec2(0.5, 0.5));

```

Where `ScalarIndexOfLargestMagnitudeIn` returns the index of the largest scalar in the vector (0=x, 1=y, 2=z)

`DeleteScalarAtIndex` returns a 2D vector from a 3D vector with scalar number i removed. (`i=0: return (y,z), i=1: return (x,z), i=2: return (x,y)`)

`IsNegative` returns 0 for positive value, 1 for negative value

There's also `axis_flip_rule` to flip the uv axis according to the face index that depend on which API you're using (ie: DirectX and OpenGL are different).

That can be implemented by flipping the 2D textures in memory in advance if you're doing it in software and left out of the texture lookup code.
> 1 votes

---
Tags: graphics, graphics-programming, cubemap, software-rendering
---


title: How to flip a rectangle

text:
# Question
Title: How to flip a rectangle
I'm curently working on a system that make the player character look towards the mouse pointer. My system is effective but i'm having an issue while displaying the rectangle.

In the Following code i test the mouse position by translating it in the world and then i test if the world pos of the mouse is greater than the position of the player or not. if the mouse is on left side of the boundary, the player will rotate to look at it. To make the rotation, i put the X coordinate on the other side of the position and i make the width negative. THis normaly should emulate the rotation. but my rectangle does not shows up.

```
Point MousePos = Vector2.Transform(Mouse.GetState().Position.ToVector2(), Matrix.Invert(Camera.GetViewMatrix())).ToPoint;
if (MousePos.X > Position.ToPoint().X)
{
    EntityDisplayRectangle.X = Position.ToPoint().X - (int)EntitySize.X * (int)TileSize.X * _displayResizeFactor / 2;

    EntityDisplayRectangle.Width = (int)EntitySize.X * (int)TileSize.X * _displayResizeFactor;
}else{
    EntityDisplayRectangle.X = Position.ToPoint().X + (int)EntitySize.X * (int)TileSize.X * _displayResizeFactor / 2;

    EntityDisplayRectangle.Width = -((int)EntitySize.X * (int)TileSize.X * _displayResizeFactor);
}
EntityDisplayRectangle.Y = (int)Position.Y - ((int)EntitySize.Y + 1);

```

here is two screenshots of what i curently have:

the red dot is a point drawn by this line

```
spriteBatch.DrawPoint(new Vector2(getEntityDisplayRectangle().X, getEntityDisplayRectangle().Y), Color.Red, 3);

```

So, is there an other way to do or is it even possible?

The player texture is from a tileSet and i use a source rectangle to pick the correct image from it

here is the code that draws the player:

```
spriteBatch.Draw(TileSet, EntityDisplayRectangle, TileSetOffsetRectangle, Color.White);

```

---

Up:

here is the rectangle drawn with a draw rectangle

Note: the red box is the collision box. it's showwn just for debug purpose

it seems that the rectangle struggle to exist when it's width is negative.

# Answer
Answer:

Very simple.

i've just created a public bool variable called facing.

in the ancient code i've made i replaced everything by facing=true or =false according to the position of the mouse. true for right and false for left.

then when i draw the sprite i test for this variable and depending on the direction i Apply a different effect.

when it's true the effect is empty ( new SpriteEffects()) but when it's false, i Apply the effect SpriteEffects.FlipHorizontally

this give the Following code (at the draw method of the entity class):

```
SpriteEffects effect;

if (facing)
{
    effect = new SpriteEffects();
}
else
{
    effect = SpriteEffects.FlipHorizontally;
}

spriteBatch.Draw(TileSet, destinationRectangle: EntityDisplayRectangle, sourceRectangle: TileSetOffsetRectangle, color: Color.White, rotation: 0, origin: new Vector2(0, 0), effects: effect, layerDepth: 0);

```

so with this method, no need to actually flip the rectangle. but only to flip at drawing.

i've found the answer in this stackex question

I Hope it helped people in the same situation.

P.S. the code to detect mouse pos is now really small:

```
Point MousePos = Vector2.Transform(Mouse.GetState().Position.ToVector2(), Matrix.Invert(Camera.GetViewMatrix())).ToPoint();
if (MousePos.X > Position.ToPoint().X)
{
    facing = true;
}
else
{
    facing = false;
}

```
> 0 votes

---
Tags: c#, xna, spritebatch, monogame-extended
---


# Question
Title: Mathf.Approximately: should I use it & for what cases?
For comparing floats they recommend using `Mathf.Approximately` At the same time, they don't use it, for example, for comparing types such as vectors. From Vector3.cs:

```
public bool Equals(Vector3 other)
{
    return x == other.x && y == other.y && z == other.z;
}

```

If I understand it correctly it wouldn't cause any problem when using `==` operator to compare floats that are formed the same way (or copied from the same source). For example:

```
float x = 10f / 10f;
float a = x; // or `a = 10f / 10f`;
float b = x;
bool equal = (a == b); // always `true`

```

but it can cause a problem if floats are formed differently even if their results are supposed to be the same. For example:

```
float a = 10f / 10f;
float b = 11f - 10f;
bool equal = (a == b); // result is unpredictable

```

Is my understanding correct?

# Answer
A better example to look at for vectors is the `==` operator:

```
// Returns true if the vectors are equal.
public static bool operator==(Vector3 lhs, Vector3 rhs)
{
    // Returns false in the presence of NaN values.
    float diff_x = lhs.x - rhs.x;
    float diff_y = lhs.y - rhs.y;
    float diff_z = lhs.z - rhs.z;
    float sqrmag = diff_x * diff_x + diff_y * diff_y + diff_z * diff_z;
    return sqrmag < kEpsilon * kEpsilon;
}

```

You can see that this applies an approximate-equality check, testing whether their difference has magnitude less than `kEpsilon`, or a hundred thousandth of a unit.

This way users get extra tolerance for rounding automatically, even if they do the most careless thing. If the user wants exact equality only, they need to ask for it, by using `Vector3.Equals()`. (This also ensures that if you use a vector as a key in a collection like a hash map/dictionary, you won't get spurious collisions from an overly-permissive comparison)

So the definition of `Equals` this way isn't the devs saying that `Mathf.Approximately()` is unnecessary. In fact it's just the opposite: they're saying that approximate equality checks or range checks should be your default, and you should reach for exact equality only when you're sure that's appropriate for your context, by typing extra to get `.Equals()` instead of `==`.
> 4 votes

# Answer
Floats have this thing called floating point errors. Since they are stored in binary, it is sometimes impossible to get the exactly correct results from mathematical operations on them.

So we have to allow for some margin of error and do our equality comparison that way. This `Math.Appr` functions usually does exactly that: instead of checking if they are exactly equal, it compares them on Epsilon, where if two paremeters are as close as the Epsilon, they are ruled equal.

The margin of error is usually called the Epsilon value (`float.epsilon` if I remember correctly) which represents the smallest float value greater than 0. But you may need bigger margins of error depending on the circumstances.

If you indeed need bigger margins of error, you can just do this yourself:

`isApprEqual = abs(x-y) <= marginOfError`
> 4 votes

---
Tags: unity, floating-point
---


# Question
Title: Find a path centered on the edge between traversable tiles
I'm trying to implement a pathfinding system in a simple tower defense game I'm working on. I've a 15x8 tilemap where each cell is of size 64x64.
*image 1* A is the start point, B is the end point, the green blob is the bad guy, the brown tiles are the route and the green tiles are the "walls".

So basically I want to auto find a grid-based path from point A to point B for the enemy, similar to this:
*image 2*

Down below are the scripts I've implemented in the game, should be a bit messy...

Main script

```
func _astar_search(graph, source, target):
    var q = Heap.new()
    var nodes = {}
    nodes[source] = Vertex.new(source, null, 0)
    q.insert(source, 0)

    while not q.empty():
        var current = q.extract_min()

        if current == target:
            break

        for next in graph.neighbors(nodes[current]):
            if nodes.has(next) == false:
                nodes[next] = Vertex.new(next)

            var new_cost = nodes[current].get_cost() + graph.weight(nodes[current], nodes[next])
            if new_cost < nodes[next].get_cost():
                nodes[next].set_cost(new_cost)
                nodes[next].set_parent(current)

                if q.contains(next) == false:
                    q.insert(next, nodes[next].get_cost() * _heuristic(target, next))

    return nodes

func _find_path(nodes, source, target):
    var path = []
    var current = target

    while current != source:
        path.append(nodes[current])
        current = nodes[current].get_parent()

    path.append(nodes[source])
    path.invert()
    #_dir.invert()
    return path

func _heuristic(a, b):
    return abs(a.x - b.x) + abs(a.y - b.y)

```

Graph class

```
func neighbors(vertex):
    var cell = vertex.get_cell()
    var result = PoolVector2Array([
        cell + Vector2.UP,
        cell + Vector2.LEFT,
        cell + Vector2.DOWN,
        cell + Vector2.RIGHT,
    ])

    #if fmod(cell.x + cell.y, 2) == 0:
    #   result.invert()

    result = _filter("_in_bounds", result)
    result = _filter("_walkable", result)
    return result

func _in_bounds(cell):
    return cell.x >= 0 and cell.x < size.x and cell.y >= 0 and cell.y < size.y

func _walkable(cell):
    return obstacles.has(cell) == false

```

It's not working properly. I need the path to be centralized in between the two "roads" just like the **image 2**, but what I've now is:

*image 3*

The blue line is the path generated by the algorithm and the red dots are the same path but centered at tile's position

Do you have any suggestions on how could I center the path?

# Answer
Your problem lies in generating the graph, before any actual pathfinding takes place. It looks like you want the intersections of tiles to be considered the nodes of your graph, and only want intersections where all four adjacent tiles are ground.

If you do it correctly, the pathfinder in your example will have only one valid path to choose from.
> 4 votes

# Answer
If I understand correctly, you want the algorithm to return a path that touches the center of each grid (the red dots, in your last image) rather than one that goes along the grid lines (the blue line, in your last image).

To accomplish this, you need only to add the half-size of your node to the node's world position. For example: Given a node whose grid position is at (0, 0) in grid that is centered at world position (10, 10), and your nodes are 3 world units wide, then the center of the given node would be at (11.5, 11.5).

Note that you may need to subtract the half-size from one or both axes instead of adding depending on the pivot position of your nodes. If your nodes pivot from the bottom-left, you would do it the same as in my example. However, if the pivot position were to be top-left, you would add to the x-axis and subtract from the y-axis instead.

However, a much easier solution, as noted by one of the other answers, is to simply offset your terrain tiles so that the grid lines touch the center of each tile instead. This way no math is necessary and the apparent result is the same.
> 3 votes

# Answer
So after much effort I finally get it working, although I'm not sure if I did it the best way. Tried to do what Agent Tatsu suggested but it didn't work. I did something based on what I understood from the BlueRaja's answer.

Basically I took every walkable tile of the map and "packed" each with its three adjacent tiles to form a "bigger tile". Each of these big tiles became a node in the graph, which I positioned at the center between the 4 small tiles.

That's it, took like 30 hours but easy right

Joking aside, thank you all for the help, stay safe
EDIT: I can't upvote right now but will once I've 15 reputation
> 2 votes

---
Tags: 2d, ai, path-finding, grid
---


# Question
Title: Unity: BuildFailedException Reference Library Missing Texture at index 1
I'm new to Unity and I have no idea what this error means, I'm following a tutorial on YouTube which had no error of the sort.

Any idea how can I fix this?

```
BuildFailedException: ARCore Image Library Generation: Reference library at 'Assets/ReferenceImageLibrary.asset' is missing a texture at index 1.
UnityEditor.XR.ARCore.ARCorePreprocessBuild.BuildImageTrackingAssets () (at Library/PackageCache/com.unity.xr.arcore@2.1.8/Editor/ARCoreBuildProcessor.cs:286)
UnityEditor.XR.ARCore.ARCorePreprocessBuild.OnPreprocessBuild (UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.xr.arcore@2.1.8/Editor/ARCoreBuildProcessor.cs:33)
UnityEditor.Build.BuildPipelineInterfaces+<>c__DisplayClass15_0.<OnBuildPreProcess>b__1 (UnityEditor.Build.IPreprocessBuildWithReport bpp) (at <af78ad00a40d4f61b82afc6cafb0a416>:0)
UnityEditor.Build.BuildPipelineInterfaces.InvokeCallbackInterfacesPair[T1,T2] (System.Collections.Generic.List`1[T] oneInterfaces, System.Action`1[T] invocationOne, System.Collections.Generic.List`1[T] twoInterfaces, System.Action`1[T] invocationTwo, System.Boolean exitOnFailure) (at <af78ad00a40d4f61b82afc6cafb0a416>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

```

The code is the following:

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

public class RecognitionScript : MonoBehaviour
{
    private ARTrackedImageManager _arTrackedImageManager;

    private void Awake()
    {
        _arTrackedImageManager = FindObjectOfType<ARTrackedImageManager>();

    }

    public void OnEnable()
    {

        _arTrackedImageManager.trackedImagesChanged += OnImageChanged;
    }

    public void OnDisable()
    {
        _arTrackedImageManager.trackedImagesChanged -= OnImageChanged;
    }

    public void OnImageChanged(ARTrackedImagesChangedEventArgs args)
    {
        foreach (var trackedImage in args.added)
        {
            UnityEngine.Debug.Log(trackedImage.name);
        }
    }
}

```

# Answer
The error message references the file `Assets/ReferenceImageLibrary.asset`. This is the part he's going over at around 3:30 into the video.

In the Project panel in the Unity Editor, find the file at `Assets/ReferenceImageLibrary`. Select this file, and you should see something in the Inspector. You most likely forgot to select a texture for one of the entries in the library (if that's the case, the preview image will say "None (Texture 2D)". Just click the "Select" button and select a texture from your project.
> 2 votes

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


title: Why my raycast sometimes not working?

text:
# Question
Title: Why my raycast sometimes not working?
As you see in picture, i cast rays to (vector3.right * direction) from center of boxCollider's bounds. It can detect the wall mostly, but sometimes it can't detect the wall and pass through it. the layer of wall is 'obstacle' and ray only detect that layerMask. why this happend?

```
            moveAmount.x = input.x * speed;
            moveAmount.z = input.z * speed;

            directionX = Mathf.Sign(moveAmount.x);
            rayLength = Mathf.Abs(moveAmount.x) + .015f;

            if (Physics.Raycast(rayOrigin, Vector3.right * directionX, out raycastHit, rayLength, collisionMask))
            {
                Debug.Log("Hit");
            }

```

# Answer
> 1 votes
In this case, adjust rayLength will be a solution. if rayLength is too short, it will raycast inside of wall at next frame.

---
Tags: unity, raycasting
---


# Question
Title: How to keep loading screen for minimum time?
Making my first game and stuck at keeping the loading screen visible for some time. It shows for an instance and disappears. By using loadasync the previous scene runs in the background? Do i have to pause everything and then move to the next scene? Thank you! The code is as follows:

```
public void LoadNextLevel()
{
    StartCoroutine(LoadAsyncronously());
}
IEnumerator LoadAsyncronously()
{
    int nextSceneIndex = SceneManager.GetActiveScene().buildIndex + 1;
    loadingScreen.SetActive(true);
    AsyncOperation operation = SceneManager.LoadSceneAsync(nextSceneIndex);
    float progress = Mathf.Clamp01(operation.progress / 0.9f);
    slide.value = progress;
    yield return new WaitForSeconds(2);
    SceneManager.LoadSceneAsync(nextSceneIndex);
}

```

# Answer
> 0 votes
In Unity, `SceneManager.LoadSceneAsync()` doesn't allow you to control the exact moment to load a scene, in case you wanted to do a "Load everything, but I tell you when to move to the next scene" thing. All it does is doing a non-blocking operation in the background, letting you know how long it's taking (via the progress value) but giving you no control on anything else.

Usually, best practices are all about to NOT willingly add time delay in a loading screen. Nobody wants to wait more time than needed, being the app a game, a companion app, anything. This is a common problem when creating splash screens as well: please, *do not* include a minimum waiting time, because all users want is to use the actual app/game, and not stare at the splash/loading screen more than needed.

Animations play nice when splash screens load information asynchronously (i.e. from a remote server), while in contrast loading screens do the same but in a different context: the user is already using the app, and is just waiting to play.

So, what if you want to exploit loading screens to display additional information, such as random game hints or even some useful game lore for the player to read, given that loading screens need to go away as soon as possible? I can think of two possible solutions, choose the one that works best for you.

# Idea 1: "Press \[button\] to continue"

* A script triggers the async load of the next game level AND shows up the loading screen
* The loading screen displays whatever you want in it, as well as a nice-looking loading bar
* As soon as the loading process is over, the next level is already there, BUT the game is paused: the loading screen is still visible, and pressing any button will hide the loading screen and resume the game

An example of such a solution is the loading screens in the first *F.E.A.R.* game instalment: choose a level, loading, press key, start play.

# Idea 2: smooth transition

* A script triggers the async load of the next game level AND shows up the loading screen
* The loading screen displays whatever you want in it, as well as a nice-looking loading bar
* As soon as the loading process is over, the next level is already there AND the game starts. But the loading screen gets hidden with a simple animation (say, a fade-out effect) giving you a pleasing feeling, opposed to an instant and brutal transition from loading screen to game

An example is the first *The Witcher* game instalment, where loading screens would fade away letting the actual game show up.

In case you were wondering "How can I carry over the loading screen object from a scene to the next?", here's the answer: `Object.DontDestroyOnLoad` lets you define an object that the engine will not destroy when a scene changes, letting you bring it with you to the next scene. Where it will be destroyed nonetheless.

---
Tags: unity, scene2d
---


# Question
Title: move along given path relative to the inital position
how can I move an object along a path "relative" to its inital position? I want it so if the object is initially positioned "around" the path instead of in the center, it will move along the path keeping that "displacement", as the below images

The blue line is the path and the red line is what the object, in this case the zombie, would follow if it had been initially positioned in the left and right sides of the "blue path", respectively:

Hope you understood. So far I've this

```
func move_zombie(delta):
    if target == null:
        return

    var target_pos = target.get_position()
    var pos = get_position()
    var dir = (target_pos - pos).normalized()
    var zombie_speed = 200.0
    position += delta * zombie_speed * dir

```

# Answer
> 2 votes
You'll track two separate position variables here: your current on-path position, and your current actual position, shifted from the path.

Store your offset from the start of the path when you first begin traversing:

```
waypoint_index = 0;
path_position = path.get_waypoint(waypoint_index);
offset = actual_position - path_position;

```

When you update your path position, something like this...

```
var next_waypoint = path.get_waypoint(waypoint_index);
var difference = next_waypoint - path
var step_size = speed * delta_time

if(dot(difference, difference) <= step_size * step_size) {
    // Snap to the waypoint instead of overshooting.
    // (You can also track how much "loose change" movement you have left
    //  and spend it advancing toward the next waypoint after this one)
    path_position = next_waypoint
    waypoint_index++
} else {
    path_position += difference.normalized * step_size
}

```

Then you also update your actual position by adding your offset back in:

```
actual_position = path_position + offset

```

---
Tags: 2d, movement
---


# Question
Title: Simulating Gas Density and Pressure in a 2D World
I'm building a small spaceship simulation app that looks a lot like a game for an upcoming talk I'm giving where I use this sample app to teach the F# programming language.

This small app is something like FTL meets Oxygen Not Included where you have a top-down 2D grid of tiles (similar to an old RPG) where each tile has its own mixture of gasses - right now oxygen and carbon dioxide, but potentially others.

I've got a few things I'm trying to simulate:

1. When new gasses are added to a tile by something like a vent or a life support system, that gas should expand to neighboring tiles if possible
2. When a pressure changes (e.g. opening a door to another area of the ship or a hull breach), air should flow from the high pressure tile to the low pressure tile next to it.

Given this, and given that some gasses naturally sift to the top of others, I'm trying to figure out a small set of simple rules to govern this behavior.

Previously I had all gasses equalizing with their neighbors and no concept of pressure, but that made it very difficult to treat scenarios like hull ruptures, so I'm looking for something a bit more realistic without getting complex or hyper-accurate.

For example, given tile A with 15g oxygen and 6g CO2 and neighboring tile B of 3g oxygen and 1g CO2, some air should clearly flow from A to B. However, what flows? Is it the lightest gasses? The heaviest gasses? A random or representative sampling of gasses in A? Are there any relevant physics principles I should be aware of?

Note: I posted here instead of in physics because I don't care extremely about nuanced accuracy, just something simple and believable

# Answer
Following on DMGregory's comment, and some late night / early morning ideas, I tried something a bit different today.

Previously I'd tried:

1. Every "turn" allow X percentage of a tile's gas to move, split evenly between neighboring tiles who had less of that gas. This worked, but resulted in slow movement.
2. Removing that percentage limit and instead allowing as much gas to move, but still split evenly between potential neighbors that could take it. This improved things a little, but was still very low in terms of hull ruptures.
3. Shifting to an equalization model where pressure was the only thing that mattered. If a tile had more pressure than its neighbors, it would shift its topmost gasses into its neighbor with the least pressure until pressure was equalized. It would then repeat this until pressure was equalized. This was fast, but it resulted in pockets of CO2 that never moved around and Oxygen that never made it into tiles
4. In addition to this pressurization model, light heavy gasses would attempt to sink by flowing into their neighboring tiles. This had about the same problems as the prior approach did, and additional complexity.

The working approach that I found is this:

1. Loop through each tile
2. Loop through each gas in the tile
3. While a tile has more of that gas than its neighbor with the least amount of that gas, flow that gas into that tile. This is done recursively so that gas flows into all neighbors, equalizing pressure of that gas.

This results in each gas spreading throughout the room and pressure invariably equaling out throughout the room. It also results in constant small currents of gasses flowing around, which is fine.

Additionally, when a tile is exposed to space, all of its gasses flow into it, and all of its neighbors start flowing gasses into that lower pressure area. This results in gasses flowing out of the tiles. It's not an extremely fast process for larger rooms, but it works better than my old process.

In terms of code, this looks like the following in F# (read from the bottommost function up):

```
  let private tryFindTargetForGasSpread gas pos world =
    let tile = world |> getTile pos
    let currentGas = getTileGas gas tile
    getContext(world, tile)
    |> getPresentNeighbors
    |> List.filter(fun n -> canGasFlowInto n && getTileGas gas n < currentGas)
    |> List.sortBy(fun n -> getTileGas gas n)
    |> List.tryHead

  let rec private equalizeTileGas pos gas world =
    let tile = world |> getTile pos
    let target = tryFindTargetForGasSpread gas pos world
    match target with
    | None -> world
    | Some neighbor ->
      world
      |> shiftGas tile neighbor gas
      |> equalizeTileGas tile.Pos gas // May be more gas to shift

  let simulateTileGas pos world = spreadableGasses |> List.fold(fun newWorld gas -> newWorld |> equalizeTileGas pos gas) world

```
> 0 votes

---
Tags: 2d, physics, simulations
---


# Question
Title: 2 Images, same object: tone difference and alignment
I would like to know a software which helps in post-production to calculate the general color/tone difference of 2 images. The images contain the same object, but arn't shot from the same position. One image might be sunny, the other cloudy, so one is more orange/yellow, the other more grey/blue, but the same object.

How would you align the tone of the image?

Background info: i shoot a couple of hundreds of images to produce textures for my models, the objects are outside, so weather conditions can change at any time, shooting must continue. I do photogrammetry, so I use the images to project them on the geometry and bake them in a UV Map. So in general I have a chunk of images made in sunny condition and another in cloudy. I would like to apply a tone to all cloudy images, having similar tone like in the sunny images.

It's not about HDR.

# Answer
This is where software such as GIMP or Photoshop come into play. There's going to be plenty of tutorials covering subjects such as image correction, replacing background objects, etc...

If I were doing this in Photoshop for example, it would be trivial to load both images into separate layers and then correct them to match.
> 0 votes

# Answer
In some photogrammetry softwares, you can select which photos should be used for texturing. So split your session into 2:

1) Take photos for texturing from a perfect angle (=parallel to the object)

2) Take photos just for 3D reconstruction

During 1), the lighting has to be the same, so work quickly. During 2), lighting doesn't matter much, you can take time for that.
> 0 votes

---
Tags: textures, image, color, post-processing
---