# Question
Title: How can I perform a deterministic physics simulation?
I'm creating a physics game involving rigid bodies in which players move pieces and parts to solve a puzzle/map. A hugely important aspect of the game is that when players start a simulation, it runs the same *everywhere*, regardless of their operating system, processor, etc...

There is room for a lot of complexity, and simulations may run for a long time, so it's important that the physics engine is completely deterministic with regards to its floating point operations, otherwise a solution may appear to "solve" on one player's machine and "fail" on another.

How can I acieve this determinism in my game? I am willing to use a variety of frameworks and languages, including Javascript, C++, Java, Python, and C#.

I have been tempted by Box2D (C++) as well as its equivalents in other languages, as it seems to meet my needs, but it lacks floating point determinism, particularly with trigonometric functions.

The best option I've seen thus far has been Box2D's Java equivalent (JBox2D). It appears to make an attempt at floating point determinism by using `StrictMath` rather than `Math` for many operations, but it's unclear whether this engine will guarantee everything I need as I haven't built the game yet.

Is it possible to use or modify an existing engine to suit my needs? Or will I need to build an engine on my own?

# Answer
---

## On handling floating point numbers in a deterministic way

Floating point is deterministic. Well, it should be. It is complicated.

There is plenty of literature on floating point numbers:

And how they are problematic:

For abstract. At least, on a single thread, the same operations, with the same data, happening in the same order, should be deterministic. Thus, we can start by worrying about inputs, and reordering.

---

One such input that causes problems is time.

First of all, you should always compute the same timestep. I am not saying to not measure time, I am saying that you will not pass time to the physics simulation, because variations in time are a source of noise in the simulation.

Why do you measure time if you are not passing it to the physics simulation? You want to measure the elapsed time to know when a simulation step should be called, and – assuming you are using sleep – how much time to sleep.

Thus:

* **Measure time: Yes**
* **Use time in simulation: No**

---

Now, instruction reordering.

The compiler could decide that `f * a + b` is the same as `b + f * a`, however that may have a different result. It could also compile to fmadd, or it could decide take multiple lines like that that happen together and write them with SIMD, or some other optimization I cannot think of right now. And remember that if we want the same operations to happen in the same order, we want to control what operations happen.

*And no, using double will not save you.*

You need to worry about the compiler and its configuration, in particular to synchronize floating point numbers across the network. You need to get the builds to agree to do the same thing.

Arguably, writing assembly would be ideal. That way you decide what operation to do. However, that could be a problem for supporting multiple platforms.

Thus:

---

## The case for fixed point numbers

Due to the way floats are represented in memory, large values are going to lose precision. It comes to reason that keeping your values small (clamp) mitigates the problem. Thus, no huge speeds and no large rooms. *Which also means you can use discrete physics because you have less risk of tunneling.*

On the other hand, small errors will accumulate. So, truncate. I mean, scale and cast to an integer type. That way you know nothing is building up. There will be operations you can do staying with the integer type. When you need to go back to floating point you cast and undo the scaling.

*Note I say scale. The idea is that 1 unit will actually be represented as a power of two (16384 for example). Whatever it is, make it a constant and use it. You are basically using it as fixed point number. In fact, if you can use proper fixed point numbers from some reliable library much better.*

I am saying truncate. About the rounding problem, it means you cannot trust the last bit of whatever value you got after the cast. So, before the cast scale to get one bit more than you need, and truncate it afterwards.

Thus:

* **Keep values small: Yes**
* **Careful rounding: Yes**
* **Fixed point numbers when possible: Yes**

---

Wait, why do you need floating point? Could you not work only with an integer type? Oh, right. Trigonometry and radication. You can compute tables for trigonometry and radication and have them baked in your source. Or you can implement the algorithms used to compute them with floating point number, except using fixed point numbers instead. Yes, you need to balance memory, performance and precision. Yet, you could stay out of floating point numbers, and stay deterministic.

*Did you know they did stuff like that for the original PlayStation? Please Meet My Dog, Patches.*

By the way, I am not saying to not use floating point for graphics. Just for the physics. I mean, sure, the positions will depend on the physics. However, as you know a collider does not have to match a model. We do not want to see the results of truncation of the models.

Thus: **USE FIXED POINT NUMBERS.**

---

To be clear, if you can use a compiler that lets you specify how floating points works, and that is enough for you, then you can do that. That is not always an option. Besides, we are doing this for determinism. Fixed point numbers does not mean there are no errors, after all they have limited precision.

I do not think that "fixed point number are hard" is a good reason to not use them. And if you want a good reason to use them, it is determinism, in particular determinism across platforms.

---

See also:

---

**Addendum**: I am suggesting to keep the size of the world small. With that said, Both OP ans Jibb Smart bring up the point that moving away from the origin floats have less precision. That will have an effect on physics, one that will be seen far earlier than the edge of the world. Fixed point numbers, well, have fixed precision, they will be equally good (or bad, if you prefer) everywhere. Which is good if we want determinism. I also want to mention that the way we usually do physics has the property of amplifying small variations. See The Butterfly Effect - Deterministic Physics in The Incredible Machine and Contraption Maker.

---

## Another way to do physics

I have been thinking, the reason why the small error in precision in floating point numbers amplify is because we are doing iterations on those numbers. Each simulation step we take the results of the last simulation step and do stuff on them. Accumulating errors on top of errors. That is your butterfly effect.

I do not think we will see a single build using a single thread on the same machine yield different output by the same input. Yet, on another machine it could, or a different build could.

There is an argument for testing there. If we decide exactly how things should work, and we can test on target hardware, we should not put out builds that has a different behavior.

---

However, there is also an argument for not working in away that accumulates so much errors. Perhaps this is an opportunity to do physics in a different way.

As you might know, there is continuous and discrete physics, both work on how much each object would advance on the timestep. However, continuous physics has the means to figure out the instant of collision instead of probing different possible instants to see if a collision happened.

Thus, I am proposing the following: use the techniques of continuous physics to figure out when the next collision of each object will happen, with a large timestep, much larger that the one of a single simulation step. Then you take the nearest collision instant and figure out where everything will be at that instant.

Yes, that is a lot of work of a single simulation step. That means that simulation will not start instantly...

... However, you can simulate the next few simulation steps without checking collision each time, because you already know when the next collision will happen (or that no collision happens in the large timestep). Furthermore, the errors accumulated in that simulation are irrelevant because once the simulation reaches the large timestep, we just place the positions we computed beforehand.

Now, we can use the time budget that we would have used to check for collisions each simulation step to compute the next collision after the one we found. That is we can simulate ahead by using the large timestep. Assuming a world limited in scope (this will not work for huge games), there should be a queue of future states for the simulation, and then each frame you just interpolate from the last state to the next one.

---

I would argue for interpolation. However, given that there are accelerations, we cannot simply interpolate everything the same way. Instead we need to interpolate taking into account the acceleration of each object. For that matter we could just update position the same way we do for the large timestep (which also means it is less error prone because we would not be using two different implementations for the same movement).

---

**Note**: If we are doing this floating point numbers, this approach does not solve the problem of objects behaving differently the further away from the origin they are. However, while it is true that precision is lost the further away you go from the origin, that is still deterministic. In fact, that is why did not even bring that up originally.

---

**Addendum**

From OP in comment:

> The idea is that players will be able to save their machines in some format (such as xml or json), so that each piece's position and rotation is recorded. That xml or json file will then be used to reproduce the machine on another player's computer.

So, no binary format, right? That means we also need to worry whatever or not the floating point numbers recovered match the original. See: Float Precision Revisited: Nine Digit Float Portability
> 55 votes

# Answer
I work for a company which makes a certain well known real-time strategy game, and I can tell you that floating point determinism is possible.

Using different compilers, or the same compiler with different settings, or even different versions of the same compiler, can all break determinism.

If you need crossplay between platforms or game versions then I think you'll need to go fixed point - the only possible crossplay which I'm aware of with floating point, is between PC and XBox1, but that's pretty crazy.

You'll need to either find a physics engine which is fully deterministic, or take an open source engine and make it deterministic, or roll your own engine. Off the top of my head, I have a feeling that Unity of all things added a deterministic physics engine, but I'm not sure if it's just deterministic on the same machine or deterministic across all machines.

If you are going to try to roll your own stuff, a few things that can help:

* IEE754 floats are deterministic if you're not doing anything too fruity (google "IEE754 determinism" for more info on what is or isn't covered)
* You need to make sure every client has their rounding mode and precision set identically (use controlfp to set it)
* rounding mode and precision can be changed by certain maths libraries, so if you're using any closed libs they you might want to check these after making calls (again using controlfp to check)
* some SIMD instructions are deterministic, a lot aren't, be careful
* as mentioned above, to ensure determinism you also need the same platform, the same exact version of the same compiler, compiling the same configuration, with the same compiler settings
* build some tooling in to detect state desyncs, and help diagnose them - e.g. CRC the game state every frame to detect when a desync occurs, then have a verbose logging mode you can enable where modifications to the game state are laboriously logged to a file, then take 2 files from simulations which desynced from eachother, and compare in a diff tool to see where it's gone wrong
* initialise all your variables in the game state, major source of desyncs
* the entire game simulation needs to happen in exactly the same order every time to avoid desyncs, it's incredibly easy to get this wrong, it's advisable to structure your game simulation in such a way that minimises this. I'm really not a software design pattern guy, but for this case it is probably a good idea - you might consider some kind of pattern where the game simulation is like a secure box, and the only way to mutate game state is to insert "messages" or "commands", with only const access provided to anything outside of the game state (e.g. rendering, networking, etc). So networking the simulation for a multiplayer game is a case of sending these commands over the network, or replaying the same simulation is a case of recording the stream of commands the first time around, and then replaying them each time the replay is viewed.
> 10 votes

# Answer
I'm not sure if this is the type of answer you're looking for, but an alternative *might* be to run the calculations on a central server. Have the clients send the configuration to your server, let it perform the simulation (or retrieve a cached one) and send back the results, which are then interpreted by the client and processed into graphics.

Of course, this shuts off any plans you might have to run the client in offline mode, and depending on how computationally intensive the simulations are you might need a very powerful server. Or multiple ones, but then at least you have the option to make sure they have the same hard- and software configuration. A real-time simulation might be hard but not impossible (think of live video streams - they work, but with a slight delay).
> 5 votes

# Answer
I'm going to give a counter-intuitive suggestion that, while not 100% reliable, should work fine most of the time and is very easy to implement.

**Reduce precision.**

Use a pre-determined constant time-step size, perform the physics over each time-step in standard double-precision float, but then quantise down the resolution of all variables to *single-precision* (or something even worse) after each step. Then most of the possible deviations that floating-point reordering could possibly introduce (compared to a reference run of the same program) will be clipped away because those deviations happen in digits that don't even exist in the reduced precision. Thus the deviation don't get the chance of a Lyapunov buildup (Butterfly Effect) that would eventually become notable.

Of course, the simulation will be slightly less accurate than it could be (compared to real physics), but that's not really notable as long as all of your program runs are inaccurate *in the same way*.

Now, technically speaking it is of course possible that a reordering will cause a deviation that reaches into a higher-significance digit, but if the deviations are really only float-caused and your values represent continuous physical quantities, this is exceedingly unlikely. Note that there are half a billion `double` values between any two `single` ones, so the vast majority of time-steps in most simulations can be expected to be exactly the same between simulation runs. The few cases where a deviation does make it through quantisation will hopefully be in simulations that don't run so long (at least not with chaotic dynamics).

---

I would also recommend you consider the complete opposite approach to what you're asking about: *embrace the uncertainty*! If the behaviour is slightly nondeterministic, then this is actually closer to actual physics experiments. So, why not *deliberately randomise* the starting parameters for each simulation run, and make it a requirement that the simulation succeeds *consistently* over multiple trials? That'll teach a lot more about physics, and about how to engineer the machines to be robust/linear enough, rather than super-fragile ones that are only realistic in a simulation.
> 3 votes

# Answer
Create your own class for storing numbers!

You can force a deterministic behavior if you know precisely how the computations will be performed. For example, if the only operations you deal with are multiplication, division, addition and subtraction, then it would be sufficient to represent all numbers as just a rational number. To do this, a simple Rational class would do just fine.

But if you want to deal with more complicated computations (possibly trigonometric functions for example), then you will have to write such functions yourself. If you wanted to be able to take the sine of a number, you would have to be able to write a function that approximates the sine of a number while only using the operations mentioned above. This is all doable, and in my opinion circumvents much of the hairy details in other answers. The tradeoff is that you instead will have to deal with some math.
> 0 votes

# Answer
There is some confusion of terminology here. A physical system can be completely deterministic, but impossible to model for a useful time period because its behaviour is extremely sensitive to the initial conditions, and an infinitesimally small change in the initial conditions will produce completely different behaviours.

Here's a video of a real device whose behaviour is *intentionally* unpredictable, except in a statistical sense:

https://www.youtube.com/watch?v=EvHiee7gs9Y

It is easy to construct simple mathematical systems (using only addition and multiplication) where the result after N steps depends on the N'th decimal place of the starting conditions. Writing software to model such a system consistently, on *any* computer hardware and software the user might have, is close to impossible - even if you have a budget big enough the *test* the application on every likely combination of hardware and software.

The best way to fix this is to attack the problem at its source: make the physics of your game as deterministic as it needs to be to get reproducible results.

The alternative is to try to make it deterministic by tweaking the computer software to model something which is *not* what the physics specified. The problem is that you have introduced several more layers of complexity into the system, compared with explicitly changing the physics.

As a specific example, suppose your game involves collisions of the rigid bodies. Even if you ignore friction, the *exact* modelling of collisions between arbitrary-shaped objects which may be spinning as they move is in practice impossible. But if you change the situation so that the only objects are non-rotating rectangular bricks, life gets very much simpler. If the objects in your game don't look like bricks, then hide that fact with some "non-physical" graphics - for example literally hide the instant of collision behind some smoke or flames, or a cartoon-text-bubble "Ouch" or whatever.

The player has to *discover* the game physics by playing the game. It doesn't matter if it is not "totally realistic" so long as it is self consistent, and similar enough to common-sense experience to be plausible.

If you make the physics itself behave in a stable manner, a computer model of it can also produce stable results, at least in the sense that rounding errors will be irrelevant.
> 0 votes

---
Tags: physics, physics-engine, floating-point
---


title: Unity get deleted scene back

text:
# Question
Title: Unity get deleted scene back
I did something clumsy and seem to have deleted a scene and all the game objects in my unity project.

I have the whole project under source control and so I think I should be able to get it back, but when I reverted to an older version of the project, I still couldn't see the scene.

Could I have done something to hide the scene so that I can't see it in the hierarchy? What file(s) should I be looking for in the earlier versions of the project?

# Answer
> 0 votes
The answer turned out to be simple. I hadn't deleted the scene, I just closed it, and was able to get it back by opening it from Assets/Scenes

# Answer
> 0 votes
On deleting Unity assets there is a warning that the action is not undo-able. Nevertheless the deleted Unity assets (i.e. project files) can be restored from the Windows' recycle bin even if they were deleted from within Unity. I'm not sure about other OSes but I assume it would be the same.

---
Tags: unity
---


title: How to decorate the floor with a grid?

text:
# Question
Title: How to decorate the floor with a grid?
I got this photo from mixamo.com — I want to draw grid lines similar to this on my floor.

I'm sure this is easy by using textures, but I'm trying to avoid using textures as much as possible. Is there a way to implement these floor patterns in OpenGL 3.3?

# Answer
One way to do a square pattern in glsl is with `mod`:

```
vec2 uv = coord;
float size = 1.0/8.0;   // size of the tile
float edge = size/32.0; // size of the edge
uv = (mod(uv, size) - mod(uv - edge, size) - edge) * 1.0/size;
color = vec4(0.9 - length(uv) * 0.5);
// 0.9 controls the brighness of the face of the tile
// 0.5 controls the darkness of the edge

```

See it at shadertoy.

Remember that `mod` gives us the reminder. Thus, it will go from `0.0` to whatever divisor we used. By offsetting the input by the width of the edge we get a value that is 0.0 on the tile, flat color, and has value on the edge. We scale the value so it goes to white. We need to pass it negative, so the face is white, not black, and the edge is black, not white... however, `1.0 - uv` does not gives us white. That is why I added the extra term `- edge` (This probably can be cleaned a little more). After that, we can tweak `1.0` to `0.9` to make the face gray, and we have some control over the color of the edged by adding a factor.

---

Update: I made an improved version:

```
vec2 uv = coord;
float size = 1.0/8.0;   // size of the tile
float edge = size/32.0; // size of the edge
float face_tone = 0.9; // 0.9 for the face of the tile
float edge_tone = 0.5; // 0.5 for the edge
uv = sign(vec2(edge) - mod(uv, size));
color = vec4(face_tone - sign(uv.x + uv.y + 2.0) * (face_tone - edge_tone));

```

See it at shadertoy.
> 3 votes

# Answer
It's pretty easy if you use shaders. You need to have the uv coordinates for the plane. Scale them up and mod them to have multiple, smaller tiles:

```
uv = mod(uv * tileCount, vec2(1));

```

You'll also need to define how large of a percentage the edges should take up from the tile. I'm going to reference it as `paddingWidth`. 0 is no padding, 0.5 is 50% padding. Now you can use `step` to get a value, that tells you whether the current pixel is inside the padding or not for each axis. It's going to be 0 if it is and 1 if it isn't:

```
float mixValueX = step(paddingWidth, uv.x);
float mixValueY = step(paddingWidth, uv.y);

```

Since you don't need to have one for each axis (the horizontal and vertical paddings are the same color), you can just take the minimum of these (since if either of them are 0, it's inside the padding):

```
float mixValue = min(mixValueX, mixValueY);

```

Now you can use mix to output a color:

```
vec4 color = mix(paddingColor, tileColor, mixValue);

```
> 0 votes

---
Tags: opengl, glsl, fragment-shader, grid
---


title: Soft Body rendering from OBJ model

text:
# Question
Title: Soft Body rendering from OBJ model
As part of my master thesis I have to do an softbody simulation.

I 'm using Bullet Physics engine.

I'm trying to render softbody, create from Meshes, with Shaders in OpenGL but the object doesnt seem to be rendered (it doesnt appear in the window).

I'm not sure if the problem is because of the way I created the sobtbody or the way I render it. Thank you in advance.

I'm using this function for creating a softBody from my OBJ Liver model :

```
        btScalar* verti = new btScalar[3 * (Liver.getMeshes()[0].vertices.size())];
        for (int i = 0; i < Liver.getMeshes()[0].vertices.size(); i++)
        {
            verti[3 * i] = Liver.getMeshes()[0].vertices[i].Position.x;
            verti[3 * i + 1] = Liver.getMeshes()[0].vertices[i].Position.y;
            verti[3 * i + 2] = Liver.getMeshes()[0].vertices[i].Position.z;
        }

        int* indi = new int[Liver.getMeshes()[0].indices.size()];
        for (int i = 0; i < Liver.getMeshes()[0].indices.size(); i++)
        {
            indi[i] = Liver.getMeshes()[0].indices[i];
        }

        btSoftBody* LiverSBody = btSoftBodyHelpers::CreateFromTriMesh(softBodyWorldInfo, verti,
            &indi[0],
            int(Liver.getMeshes()[0].indices.size()) / 3);

        LiverSBody->m_cfg.kVC = 0.5;
        btSoftBody::Material* pSpMat = LiverSBody->appendMaterial();
        //LiverSBody->m_materials[0]->m_kLST = 0.5;
        pSpMat->m_kLST = 1.0;
        LiverSBody->setPose(false, true);

        btTransform trans;
        trans.setIdentity();
        trans.setOrigin(btVector3(0,0,0));
        LiverSBody->transform(trans);

        LiverSBody->generateBendingConstraints(2, pSpMat);
        LiverSBody->m_cfg.piterations = 2;
        LiverSBody->m_cfg.kDF = 1.0;
        LiverSBody->m_cfg.kSRHR_CL = 1;
        LiverSBody->m_cfg.kSR_SPLT_CL = 0;

        LiverSBody->setTotalMass(10, true);
        LiverSBody->scale(btVector3(0.02, 0.02, 0.02));
        LiverSBody->getCollisionShape()->setMargin(0.1);

        float Friction = 0.9;
        float Restitution = 0.5;

        LiverSBody->setFriction(Friction);
        LiverSBody->setRestitution(Restitution);

        m_pSoftBodyWorld->addSoftBody(LiverSBody);

```

I'm using this class for loading and visualizing model https://learnopengl.com/code\_viewer\_gh.php?code=includes/learnopengl/model.h I need to extract from the softBody some data (Position, normal, texCoords, tangent and bitangent) to fill the vertex buffer objects but i don't know where to find most of it... I know that the position and the normals are in the softbody nodes but i can't find the other information needed (texCoords, ..).

```
//btSoftbody.h
struct Node : Feature
    {
        btVector3 m_x;       // Position
        btVector3 m_q;       // Previous step position
        btVector3 m_v;       // Velocity
        btVector3 m_f;       // Force accumulator
        btVector3 m_n;       // Normal
        btScalar m_im;       // 1/mass
        btScalar m_area;     // Area
        btDbvtNode* m_leaf;  // Leaf data
        int m_battach : 1;   // Attached
    };

```

# Answer
> 1 votes
You can't mix immediate mode (`glBegin`, `glEnd`, etc.) with the programmable pipeline (shaders) like this. You either need to stick to immediate mode (you really shouldn't, it's 2019) and use shaders that are compatible with it (using the built-in variables instead of attributes) or use a modern OpenGL version and pass the model information as vertex buffer objects (this would be the more preferred option in my opinion).

---
Tags: opengl, physics, 3d, textures, bullet-physics
---


title: Unlit Node Shadow Shader Graph

text:
# Question
Title: Unlit Node Shadow Shader Graph
How to make unlit node cast shadows? Is is possible with the current state of Shader Graph in LWRP?

In this great article Toon Shader OP grabs pass from VertexLit shader. Is something similar achievable with Shader Graph?

# Answer
I believe It shouldn't be a node because we use it once.it should be a something like toggle.

if you like to make this try to use `#pragma multi_compile` because in Standard shader `#pragma multi_compile_shadowcaster` used.

---

# ShadowCaster

by default unlit shader cast shadow , if you like to remove shadow caster in unlit shader just open your shader in shadergraph and copy the shader then create another shader and paste generated shader then just remove shadow caster pass

```
Name "ShadowCaster"
Tags{"LightMode" = "ShadowCaster"}

```

---

# Shadow Reciever

by default unlit shader don't recieve shadow we'll need to transfer texture coordinates from the vertex shader to the fragment shader.

```
// As a new include, below the existing ones.
#include "AutoLight.cginc"

…

// Add to the v2f struct.
SHADOW_COORDS(2)

…

// Add to the vertex shader.
TRANSFER_SHADOW(o)

```

but I couldn't use it in LightWeightRenderPipeline I think because it obsoleted.

so I tried to see difference of the generated shader in PBR and unlit to to understand what ShaderGraph PBR used to recieve the shadow. and I noticed it use custom lighting model and use shadowcoord.

```
    struct GraphVertexInput
    {
    //...
    float4 shadowCoord  : TEXCOORD2;
    };

    struct GraphVertexOutput
    {
    //...
    float4 shadowCoord  : TEXCOORD2;
    };

    half3 vertexLight = VertexLighting(vertexInput.positionWS, lwWNormal);
#ifdef _MAIN_LIGHT_SHADOWS
    o.shadowCoord = GetShadowCoord(vertexInput);
#endif

```

then you should use this shadowCoord in Lighting so you should make a custom lighting model.but this solution is very hard because I have to overwrite built-in hlsl files.

---

> In Unity 2019.2, we’re bringing even more features and functionality to Shader Graph.
>
> you can make your Custom Lighting in Shader Graph
>
> https://blogs.unity3d.com/2019/07/31/custom-lighting-in-shader-graph-expanding-your-graphs-in-2019/

you can use **Custom Function File Mode** to use your custom lighting function

```
void MainLight_half(float3 WorldPos, out half3 Direction, out half3 Color, out half DistanceAtten, out half ShadowAtten)
{
#if SHADERGRAPH_PREVIEW
   Direction = half3(0.5, 0.5, 0);
   Color = 1;
   DistanceAtten = 1;
   ShadowAtten = 1;
#else
#if SHADOWS_SCREEN
   half4 clipPos = TransformWorldToHClip(WorldPos);
   half4 shadowCoord = ComputeScreenPos(clipPos);
#else
   half4 shadowCoord = TransformWorldToShadowCoord(WorldPos);
#endif
   Light mainLight = GetMainLight(shadowCoord);
   Direction = mainLight.direction;
   Color = mainLight.color;
   DistanceAtten = mainLight.distanceAttenuation;
   ShadowAtten = mainLight.shadowAttenuation;

#endif
}

```
> 1 votes

---
Tags: unity, shaders, unity-shader-graph
---


# Question
Title: Is coroutine as good as a delay() function
I'm new to Unity and I was learning the usage of coroutines. Is calling a coroutine as good as a delay() function? Does Unity have a delay() function?

# Answer
ratchet freak's answer is an excellent explanation of the differences between using Thread.Delay() and coroutines in Unity. To address your second question, I suspect what you're looking for is `WaitForSeconds`.

From the documentation:

```
public class WaitForSecondsExample : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(Example());
    }

    IEnumerator Example()
    {
        print(Time.time);
        yield return new WaitForSeconds(5);
        print(Time.time);
    }
}

```

However, be aware that this example just starts the coroutine, it doesn't wait for it. For example, say you had some code in the `Start` function after the call to `StartCoroutine`. That code would get executed immediately, not after 5 seconds as you might expect. If you wanted to wait until after the the coroutine finished, you would have to either call that code from the coroutine, or set a value that gets checked somewhere else (like in `Update`), or wait for it inside another coroutine, etc.

For a simple timer, that can get messier than it needs to be. To circumvent that clutter, I like to use this free async/await library, which allows you to write code like the following

```
async void Start()
{
    print(Time.time);
    await new WaitForSeconds(5);
    print(Time.time);
}

```

Which does logically wait for the `WaitForSeconds` to finish before executing the code after it, without suspending the entire thread. In my opinion this is a much cleaner alternative to `Delay()`. Of course, async/await has its own gotchas and can be a little confusing if you've never dealt with it before. You can read more about using it with Unity here.
> 1 votes

# Answer
The problem with delay() as traditionally implemented (stopping the thread until it can continue again) means exactly that, it stops the thread and it cannot do anything else.

One underappreciated feature of unity (and in fact most game engines and gui frameworks) is that most of the main logic is executed on a *single thread*. This makes programming a lot easier as by default you don't have to deal with hairy multithreading.

However this means that if you don't allow that thread to continue working on other tasks (including stuff like taking input, updating the screen etc.) **the entire program just stops responding**.

---

But you still need some way to pause a set of actions action and resume it later.

This can be done explicitly by splitting the sequence of actions up in multiple sections and scheduling those to run at the correct times using timers or the `update` function that gets called every frame (which then dispatches to the correct section when it's ready for the next step) or implicitly by using the built-in coroutine system.

The coroutine system takes the yielded value and uses that to decide when to resume it. One possibility is a fixed delay or a conditional wait.

So the core system has a list of running coroutines along with their last yielded value. It then loops over those yielded values and tests whether to resume it. I like to believe that that one my previous post inspired this system.
> 0 votes

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


title: how find Child using Tag

text:
# Question
Title: how find Child using Tag
how find Child using Tag

so i have find this solution

```
enter code here foreach (Transform child in transform)
    {
        if (child != null && child.tag == "monster")
        {
            SpawnPoints.Add(child.transform);

            break;
        }

    }

```

it add same child 1000 time how add 1 time

# Answer
> 2 votes
Global functions:

Now, if you want to find an object with a tag that is also a child of a specific object you can use the following function:

```
Transform FindWithTag(Transform root, string tag)
{
    foreach (Transform t in root.GetComponentsInChildren<Transform>())
    {
        if (t.CompareTag(tag)) return t;
    }
    return null;
}

```

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


# Question
Title: How to make a gameObject follow non trivial trajectories?
as the title of the question says, I was wondering if there is common method to make gameObjects e.g. enemies or bullets follow curvilinear trajectories before reaching their target. For instance, assuming to be talking about a top-down 2D game, there are multiple ways to make an gameobject, say an enemy follow a straight line like this to go hit the player:

But how to make it so that before reaching the player it would do something like this?

Does somebody have an idea?

I know that the question may sound not too specific, therefore for sake of argument, how could I make so that a bullet shot from an enemy follows an arch "à la Wanted" before hitting the player instead of just flying straight?

# Answer
To add on to the discussion I think Bezier curves are good approach, and in terms of recalculating them you can pre-bake some curves and modify their points based on requirements, so the impact should not be heavy (less so in 2D)

Since you are working in 2D getting started is a bit easier, and ignore the z-axis (or y in unity, depending on your dominant hand :P )

Anyway. I just wanted to add these resources for you or anyone else who happens on this thread.

Have a look at this post. It is very in depth, but very useful I think.

There is also this Youtube series that I think might help:

Part 1 Bezier Curves in Unity: Linear Curve

Part 2 Bezier Curves in Unity: Quadratic Curve

Part 3 Bezier Curves in Unity: Cubic Curve

Good luck.
> 1 votes

# Answer
After some delay, here is my solution:

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

public class BezierShoot : MonoBehaviour
{
[SerializeField] GameObject target;
[SerializeField] Transform controlPoint0;
[SerializeField] Transform controlPoint1;
[SerializeField] Transform controlPoint2;
[SerializeField] Transform controlPoint3;
[SerializeField] GameObject pointerPrefab;//used during debugging, not necessary
[SerializeField] GameObject shotPrefab;
[SerializeField] float speed = 5f;
[SerializeField] float t = 0;//the parameter for the bezier curve
/**
     I want to try and make 2 points, one third and two thirds distance from player to object.
    1) I find the 1/4 and 3/4 distance on the connecting line
    2) I get the normalized distance from the new points from the target
    3) I get the perpendicular vector with respect to each point and the target and multiply by the distance parameter
    3.1) obtaining vector coordinates: I have direction tempDir
        normDir.x = tempDir.y
        normDir.y = -tempDir.x
     */

private void Update()
{
    if (Input.GetKeyDown(KeyCode.B))
    {
        CreateControlPoint1();
        CreateControlPoint2();
        StartCoroutine(BezierShooting());
    }
}

private void CreateControlPoint1()
{
    controlPoint0 = transform;
    controlPoint3 = target.transform;
    //the position of the control point will be taken at 1/4 the distance between the initial and the target point, which will act as first and last control points for the bezier curve
    controlPoint1.position = new Vector3(controlPoint0.position.x + (controlPoint3.position.x - controlPoint0.position.x)/4, controlPoint0.position.y + (controlPoint3.position.y - controlPoint0.position.y)/4, 0);
    //in order to determine lateral displacement i derive the vector perpendicular to the one connecting first and last control points
    Vector2 tempDir = new Vector2((controlPoint3.position.x - controlPoint1.position.x),(controlPoint3.position.y - controlPoint1.position.y));
    tempDir.Normalize();
    Vector2 normDir;
    normDir.x = tempDir.y;
    normDir.y = -tempDir.x;
    //i translate the control point by the desired amount sideways
    controlPoint1.Translate(-normDir.x * 2f, -normDir.y * 2f, 0);
}

private void CreateControlPoint2()
{
    controlPoint0 = transform;
    controlPoint3 = target.transform;

    controlPoint2.position = new Vector3(controlPoint0.position.x + (controlPoint3.position.x - controlPoint0.position.x)*3 / 4, controlPoint0.position.y + (controlPoint3.position.y - controlPoint0.position.y)*3 / 4, 0);
    Vector2 tempDir = new Vector2((controlPoint3.position.x - controlPoint2.position.x), (controlPoint3.position.y - controlPoint2.position.y));
    tempDir.Normalize();
    Vector2 normDir;
    normDir.x = tempDir.y;
    normDir.y = -tempDir.x;

    controlPoint2.Translate(-normDir.x * 2f, -normDir.y * 2f, 0);
}

private IEnumerator BezierShooting()
{
    var shotInstance = Instantiate(shotPrefab, transform.position, Quaternion.identity);//instantiate the bullet
    //the parameter for the bezier curve goes from 0 to 1, therefore it has been initialised to 0 and
    //the loop for the trajectory will go on until t=1 i.e. the bullet reached the target or hit something along the road
    while (t < 1 && shotInstance != null)
    {
        float invT = 1f - t;
        //the bezier curve equation. 4 points define a cubic bezier curve
        var currentPosition = invT * invT * invT * controlPoint0.position
                            + 3 * invT * invT * t * controlPoint1.position
                            + 3 * invT * t * t * controlPoint2.position
                            + t * t * t * controlPoint3.position;
        shotInstance.transform.position = currentPosition;
        t += Time.deltaTime / 1f;
        yield return null;
    }

    t = 0;
}

```

}

What it simply does is 1) creating 2 points that will be used as intermediate control points by temporarily creating two "axes", one in the direction from the first control point to the target, acting as my yHat let's say, and the other going perpendicularly to the previous. These will be used in the coroutine `BezierShooting()` to define the curve that the bullet will follow.

It is far from optimal, starting from the fact that I use two identical functions to create a single control point everytime (i started by doing it in the same function, literally just adding '2' to all that was referred to the second control point, but it always ended up spawining the control points in the same position) or from the fact that the bullet is moved by directly changing its transform position, whereas i would have preferred to work with the rigidbody, but in the end it works and the bullets travel very nicely ;) hope it can be helpful to somebody!
> 0 votes

---
Tags: 2d, ai, trajectory
---


title: Why separate data from logic?

text:
# Question
Title: Why separate data from logic?
I don't understand the purpose of separate `SystemClass` for functions. My composition looks like this:

```
class Color {
   void Blend(uint32_t entityID, float factor) {
      red[entityID] *= factor;
      green[entityID] *= factor;
      blue[entityID] *= factor;
   }

   static std::vector<float> red;
   static std::vector<float> green;
   static std::vector<float> blue;
}
std::vector<float> Color::red;
std::vector<float> Color::green;
std::vector<float> Color::blue;

```

I am keeping vectors of members to have possibility to iterate over specific member instead of loading whole struct.

My question is: what exactly is the reason for `SystemClass` with only logic?

```
class ColorComponent {
   static std::vector<float> red;
   static std::vector<float> green;
   static std::vector<float> blue;
}
std::vector<float> ColorComponent::red;
std::vector<float> ColorComponent::green;
std::vector<float> ColorComponent::blue;

class ColorSystem {
   void Blend(uint32_t entityID, float factor) {
      ColorComponent::red[entityID] *= factor;
      ColorComponent::green[entityID] *= factor;
      ColorComponent::blue[entityID] *= factor;
   }
}

```

How the second composition suppose to be better for performance?

I will be very grateful for explanation.

# Answer
> 2 votes
I'll take a stab at it. Some people are *much more* knowledgeable about c++ and how all that stuff work, so please feel free to comment and vote accordingly.

---

Both examples that you give are roughly equivalent in terms of efficiency. In both cases, the values for each element is contiguous. You're practicing 'struct-of-arrays' instead of 'arrays-of-structs' in both cases.

This practice is interesting to avoid trashing the cache when accessing only a subset of elements in a struct. That's because the data you need is pulled in the cache, with a little bit of data that is stored before it, and a little bit of data that is stored after it. So if you need that data that is immediately after it, then the CPU does not have to go fetch additional data, it is already in the cache.

In both cases here, you don't benefit from it as you access always the same data. (If this `Blend` function is accessed in a tight loop, the data may still be hot in the cache.)

This approach of separating the data from the logic is when the data needs to be accessed by multiple 'logic aspects' i.e. multiple un-related systems.

A `Transform` component is useful. For multiple systems. But in what system do you store it? Could be the one responsible for the display. Or the one responsible for the audio. What about the one responsible for the physics? The answer to this is to take the data out of the systems, let it be managed by something that does just that, and give a way to the systems to access the data they need, when they need it, and in a fast way.

Having the components designed as fine grain chunks of data, close together in memory, let the system loop over them fast, benefiting from the fact that the data is more often already in the cache when it is needed.

Another point of having the data *outside* the System, is that it can allow for easier testing. It's been the fashion lately: *dependency injection* . Roughly, if you supply the data to a class, you have better control over it, and it allows you to pass whatever you want, which means it lets you more freedom to pass trash data and see how the system reacts.

Keep in mind that there are multiple ways to approach this, and they will generally be done so to fix particular issues or improve specific aspects of a particular software. There is not really a one way that fits all the needs.

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


# Question
Title: What is the reason that people avoid PlayerPrefs to store character data and coins etc?
PlayerPrefs are easy to implement and i think it can be used to store important game data like selected character and coins and completed quests for small games, but i have read too much to make me ask this question that why not use it, and what is the other options for storing important game data in

# Answer
As implied by the name, PlayerPrefs is mostly intended for storing config options. But it can also be abused to store savegame data, if that data is rather small. If you target platforms without write-access to a filesystem (like WebGL) then it might in fact be your only option to persist data without relying on external online services.

However, if your game data gets larger, then you soon hit some limitations:

* Some of the platform-dependent methods it uses to store data are not designed to hold large amounts of data (like the Windows registry)
* There is no elegant way to store binary data or arrays. You either have to encode them as strings, or store a bunch of uniquely named Float or Int values (and in that case the keys will take up more space than the values, so it will be very inefficient).
* PlayerPref's loading and saving is all-or-nothing. You can not load a single savegame, you have to load them all.
* It is difficult for players to exchange savegames as files, especially between different platforms.

So if you plan to add savegames to your game and the game state which needs to be saved is more than just a hand full of numbers, then you might want to consider to create real savegame files on the filesystem in a format of your design which you read and write with the standard .NET classes for file access.

---

Also, if you have something which the player must not be allowed to modify (like ingame items bought through microtransactions or player progression in a multiplayer game), then you generally don't want to store those on the end-user device at all. In that case you won't get around setting up an online service which manages that data.
> 9 votes

# Answer
Another thing is that Player Prefs can be easily hacked, so if you don't want a gamer to hack into them and unlock an awesome character, you should avoid using it for that kind of memory.
> 0 votes

---
Tags: unity, databases, savegame
---


title: Why am I not getting stuck in the loop

text:
# Question
Title: Why am I not getting stuck in the loop
I'm new to Unity. I was learning coroutines and I wrote this.

```
private void Fire()
{
    if(Input.GetButtonDown("Fire1"))
    {
        StartCoroutine(FireContinuously());
    }
    if(Input.GetButtonUp("Fire1"))
    {
        StopAllCoroutines();
    }
}

IEnumerator FireContinuously()
{
    while(true)
    {
        GameObject laser = Instantiate(LaserPrefab, transform.position, Quaternion.identity) as GameObject;
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 10f);
        yield return new WaitForSeconds(firetime);
    }
}

```

When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?

# Answer
The reason is the keyword `yield` which has a specific meaning in C#.

On encountering the words `yield return` a function in C# returns, as one would expect.

> Using yield to define an iterator removes the need for an explicit extra class
>
> \[...\]
>
> When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

So there is no infinite loop. There is a function/iterator that can be called an infinite number of times.

The Unity function `StartCoroutine()` makes the Unity framework call the function/iterator once per frame.

The Unity function `StopAllCoroutines` makes the Unity framework stop calling the function/iterator.

And returning `WaitForSeconds(time)` from the iterator makes the Unity framework suspend calling the function/iterator for `time`.

---

A confused comment and an equally confused upvote on that comment encouraged me to elaborate further on what the keyword `yield` does and doesn't do.

If you write this:

```
IEnumerable<int> Count()
{
   int i = 0;
   yield return i++;
}

```

You can instead also write this:

```
IEnumerator<int> Count() {
    return new CountEnumerator ();
}
class CountEnumerator : IEnumerator<int> {
    int i = 0;
    bool IEnumerator<int>.MoveNext() { i++; return true; }
    int IEnumerator<int>.Current { get { return i; }
    void IEnumerator<int>.Reset() { throw new NotSupportedException(); }
}

```

It follows that the keyword `yield` is not related to multi-threading and does **absolutely not** call `System.Threading.Thread.Yield()`.
> 15 votes

# Answer
When the fire button is lifted, the second if statement is entered, and StopAllCoroutines is run. This means that the Coroutine that the while loop is running in is ended, thus there is no more infinite loop. The coroutine is like a container for the code to execute in.

I can recommend the Unity Manual and the Unity Scripting API to get a better grasp on what coroutines are and how powerful they can be.

This blog and searching youtube post was also helpful for me to better use coroutines.
> 8 votes

# Answer
Coroutines are a strange beast. Yield return causes the method to suspend execution until it is later stepped. Behind the scenes, it might look something like this:

```
class FireContinuouslyData {
    int state;
    bool shouldBreak;
}

object FireContinuously(FireContinuouslyData data) {
    switch (data.state) {
        case 0:
            goto State_0;
    }
    while (true) {
        GameObject laser = ...;
        laser.GetComponent...
        //the next three lines handle the yield return
        data.state = 0;
        return new WaitForSeconds(fireTime);
        State_0:
    }
}

```

And internal to Unity/C# (since yield return is a native c# feature), when you call StartCoroutine, it creates a `FireContinuouslyData` object, and pass it in to the method. Based on the return value, it determines when to call it again later, simply storing the FireContinuouslyData object to pass it in next time.

If you ever did a yield break, it could internally just set `data.shouldBreak = true` and then Unity would simply throw away the data and not schedule it again.

And if there were any data that needed to be saved between executions, it would also be stored in the data for later.

An example of how Unity/C# might implement the coroutine functionality:

```
//Internal to Unity/C#

class Coroutine {
    Action<object> method;
    object data;
}

Coroutine StartCoroutine(IEnumerator enumerator) {
    object data = CreateDataForEnumerator(method); //Very internal to C#
    Action<object> method = GetMethodForEnumerator(enumerator); //Also very internal to C#
    Coroutine coroutine = new Coroutine(method, data);
    RunCoroutine(coroutine);
    return coroutine;
}

//Called whenever this coroutine is scheduled to run
void RunCoroutine(Coroutine coroutine) {
    object yieldInstruction = coroutine.method(coroutine.data);
    if (!data.shouldBreak) {
        //Put this coroutine into a collection of coroutines to run later, by calling RunCoroutine on it again
        ScheduleForLater(yieldInstruction, coroutine);
    }
}

```
> 3 votes

# Answer
Another answer mentions that you are stopping co-routines when `"Fire1"` is up - this is completely correct, insofar as why the coroutine does not continue instantiating GameObjects after the first press of `"Fire1"`.

In your case however *this code will not become 'stuck'* in an infinite loop, which is what it looks like you're looking for an answer to - i.e. the `while(true) {}` loop, even if you did not stop it externally.

It won't get stuck but your coroutine won't end (without calling `StopCoroutine()` or `StopAllCoroutines()`) either. This is because Unity coroutines **yield** control to their caller. `yield`ing is different to `returning`:

* a `return` statement will cease execution of a function, even if there is more code following it
* a `yield` statement will pause the function, starting at the next line after `yield` when resumed.

Usually, coroutines will be resumed each frame but you're also returning a `WaitForSeconds` object.

The line `yield return new WaitForSeconds(fireTime)` roughly translates as "now suspend me, and don't come back until `fireTime` seconds have passed".

```
IEnumerator FireContinuously()
{
    // When started, this coroutine enters the below while loop...
    while(true)
    {
        // It does some things... (Infinite coroutine code goes here)

        // Then it yields control back to it's caller and pauses...
        yield return new WaitForSeconds(fireTime);
        // The next time it is called , it resumes here...
        // It finds the end of a loop, so will re-evaluate the loop condition...
        // Which passes, so control is returned to the top of the loop.
    }
}

```

Unless stopped, this is a coroutine which, once started, will perform the whole loop once every `fireTime` seconds.
> 1 votes

# Answer
A simple explanation: under the hood Unity is iterating over a collection (of YieldInstructions or nulls or whatever you `yield return`) using the `IEnumerator` that your function returns.

Since you use the `yield` keyword, your method is an iterator. It's not the Unity thing, it's a C# language feature. How does it work?

It is lazy and doesn't generate all the collection at once (and the collection may be infinite and impossible to be generated at once). Elements of the collection are generated as needed. Your function returns an iterator for Unity to work with. It calls its `MoveNext` method to generate a new element and `Current` property to access it.

So your loop isn't endless, it runs some code, returns an element and returns control back to Unity so it's not stuck and can do other work such as handling your input to stop the coroutine.
> 1 votes

# Answer
Think about how a `foreach` works:

```
foreach (var number in Enumerable.Range(1, 1000000))
{
  if (number > 10) break;
}

```

The control over the iteration is on the caller - if you stop the iteration (here with `break`), that's it.

The `yield` keyword is a simple way to make an enumerable in C#. The name hints at this - `yield return` yields control back to the caller (in this case, our `foreach`); it's the caller who decides when to continue to the next item. So you can make a method like this:

```
IEnumerable<int> ToInfinity()
{
  var i = 0;
  while (true) yield return i++;
}

```

This naively looks like it will run forever; but in reality, it depends entirely on the caller. You can do something like this:

```
var range = ToInfinity().Take(10).ToArray();

```

This can be a bit confusing if you're not used to this concept, but I hope it's also obvious that this is a very useful property. It was the simplest way that you could yield control to your caller, and when the caller decides to follow up, it can just do the next step (if Unity was made today, it would probably use `await` instead of `yield`; but `await` didn't exist back then).

All you need to implement your own coroutines (needless to say, the simplest stupidest coroutines) is this:

```
List<IEnumerable> continuations = new List<IEnumerable>();

void StartCoroutine(IEnumerable coroutine) => continuations.Add(coroutine);

void MainLoop()
{
  while (GameIsRunning)
  {
    foreach (var continuation in continuations.ToArray())
    {
      if (!continuation.MoveNext()) continuations.Remove(continuation);
    }

    foreach (var gameObject in updateableGameObjects)
    {
      gameObject.Update();
    }
  }
}

```

To add a very simple `WaitForSeconds` implementation, you just need something like this:

```
interface IDelayedCoroutine
{
  bool ShouldMove();
}

class Waiter: IDelayedCoroutine
{
  private readonly TimeSpan time;
  private readonly DateTime start;

  public Waiter(TimeSpan time)
  {
    this.start = DateTime.Now;
    this.time = time;
  }

  public bool ShouldMove() => start + time > DateTime.Now;
}

```

And the corresponding code in our main loop:

```
foreach (var continuation in continuations.ToArray())
{
  if (continuation.Current is IDelayedCoroutine dc)
  {
    if (!dc.ShouldMove()) continue;
  }

  if (!continuation.MoveNext()) continuations.Remove(continuation);
}

```

Ta-da - that's all a simple coroutine system needs. And by yielding control to the caller, the caller can decide on any number of things; they might have a sorted event table rather than iterating through all the coroutines on every frame; they might have priorities, or dependencies. It allows for very simple implementation of cooperative multi-tasking. And just look at how simple this is, thanks to `yield` :)
> 0 votes

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


# Question
Title: Unity my game starts in windowed mode, but the fullscreen box is checked
When I open my game the fullscreen box is checked, but the game is windowed. If I uncheck and check the box it will go into fullscreen. What is the fix?

```
public class Settings : MonoBehaviour
{

   public void SetFullscreen (bool isFullscreen)
{
    Screen.fullScreen = isFullscreen;
}
}

```

I save the current display resolution when the player hits the quit button

```
    public void Quit()
{
#if UNITY_EDITOR
    UnityEditor.EditorApplication.isPlaying = false;
#else
    Application.Quit();
#endif
}

```

# Answer
Remember, video games, and the computers that run them, are just machines. They do only what you tell them to, in the order you tell them to do it.

Right now, you only tell the machine "make the game's fullscreen state match this UI toggle" in the callback method *after* the player clicks it:

```
public void SetFullscreen (bool isFullscreen)
{
    Screen.fullScreen = isFullscreen;
}

```

If you want "to make the checkbox be unchecked if the player starts in windowed mode" then you have two steps:

1. Run some code at the start (say, on game start-up, or when the Settings screen is shown)

You can do this in a MonoBehaviour by making a method called `Start()` or `OnEnable()`
2. Inside that code, tell the game to change the toggle's checked state to match the current windowed state: `fullscreenToggle.isOn = Screen.fullScreen;`

Putting it together, it could look like this:

```
using UnityEngine.UI;

public class Settings : MonoBehaviour {

    // Populate this in the Inspector to point to your fullscreen toggle checkbox.
    public Toggle fullscreenToggle;

    // Run some code in the frame when this instance spawns.
    void Start() {
        // Match UI control state to current fullscreen/windowed state of the game.
        fullscreenToggle.isOn = Screen.fullScreen;

        // Do the rest of your Start() work...
    }

    // When the player clicks the toggle, update the game's fullscreen/windowed state.
    public void SetFullscreen (bool isFullscreen) {
        Screen.fullScreen = isFullscreen;
    }

    // Do the rest of your input handling...
}

```
> 1 votes

---
Tags: unity, c#, resolution, fullscreen
---


# Question
Title: Concerns about how to efficiently implement sprite atlas
I currently transform (translate, rotate, scale) a bunch of vertices in my own Java code, then populate an `mPositions` array and an `mTextureCoordinates` array, which draws a bunch of different textured sprites to the screen in one GL draw command. Works great.

However, I now wish to move the transformation process away from native Java code and over to the vertex shader, and so I will need to pass into the shader transformation matrices which encode the translation, rotation, and scaling operations for each sprite.

Given my current approach the naive and obvious choice is to introduce another array `mTransformations`, passed into the shader via a `GLES20.glVertexAttribPointer` command, which contains a matrix for each and every vertex.

But this way seems a little wasteful for two reasons:

1. I will have to add the same transformation matrix 6 times per sprite to the `mTransformations` array since each square sprite is made of 2 triangles (3+3 vertices)
2. Since I'm now going to use the shader to perform the transformations, the 6 canonical coordinates of each square sprite (two triangles) will be the same for every sprite. In effect I'd have to populate `mPositions` with the same coordinates over and over for each sprite.

Is there a more efficient way to do achieve what I want?

# Answer
For those also starting out trying to properly understand GLSL rather than just reuse online code, here's what I learned over the past few days. Note the below points refer to GLSL for GL ES 2.0.

Two key points were:

1. Get into the GPU mindset. GPU's have 100's or 1000's or cores all working in parallel, and a shader is basically designed to process lots of data via a Vertex Buffer Object (VBO) and process them in parallel.
2. `uniform`'s are limited in number. I think I read somewhere that the Intel chip sets have a 16kb limit, whereas AMD/Nvidia have a 64kb limit, and I generally get an error if I try to use more than 1024 `uniform`'s.

I managed to solve my original problem by passing in a VBO of `vertexId`'s via `attribute float a_vertexId`. I could then get the `spriteId` using `a_vertixId / 6` and the `vertexId` using `a_vertexId - spriteId * 6`. This enabled me to index into a `uniform` of canonical square vertices, which meant I didn't have to upload sprite vertices any more.

I was also able to address texture `uv` coordinates in this way too. I just sent up a texture ID per vertex via `attribute float a_texId`, then used the `spriteId`, `vertexId`, and `a_texId` to index into a `uniform` texture coordinates array. Even given the limits on the number of `uniform`'s allowed this is able to cope with around 1000 different textures per sprite atlas.

For the transformations, I just sent up the transfer parameters (per-vertex), i.e. `(tx, ty, angle, scalar)` and applied the following matrix inside the vertex shader:

$$\left( \begin{array}{cccc} \sigma\cos(\theta) & -\sigma\sin(\theta) & 0 & t\_x \\ \sigma\sin(\theta) & \sigma\cos(\theta) & 0 & t\_y \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{array} \right).$$

Ideally, it would be best to upload a per-sprite array of transformation matrices as a `uniform`, and use `spriteId` to index into that for the per-vertex processing. However, as mentioned above, given that we could have 1000's of sprites means that this just isn't possible. I have heard of Shader Storage Buffer Objects (SSBO's) in ES 3.0, but from what I've read, they're not always available in the vertex shader.

In general, I realised performance will differ between systems, and there will be a trade-off between data upload, and CPU vs GPU processing, so ultimately I'm going to create a few different sprite batch shaders and do some tests to see which ways work best.

Anyway, hope this helps someone.

**UPDATE**

In the end I used two shader programs, (i) a `GL_TRIANGLES` batcher for "dynamic" sprites that required **rotation**, scaling, translation, with transforms performed on the GPU as described above, and (ii) a `GL_POINTS` batcher (i.e. Point Sprites) for "static" sprites (such as background tiles) that required only scaling and translation (but **not** rotation); then again, it is possible to program the fragment shader to perform rotations on point sprites, but this is slow and comes with it's own limitations, e.g. it's the point sprite texture `uv` coordinates that are rotated and not the vertices so you have to be careful how you set up your sprite textures to avoid local boundary clipping.
> 0 votes

---
Tags: sprites, opengl-es2, texture-atlas
---


# Question
Title: Unity3d: Find a point on the line which has shortest distance from the third point
So, initially, I had points `A and C`. To get `point B`, I had to shoot a raycast down from `point A` and get the `hit.point`, which is `point B` now. `Point D` is somewhere between the raycast I shot from `A` and perpendicular to `C`. How do I find the `point D`.

# Answer
Ok, so your task is actually to project point onto line, defined by two points.

Code:

```
XY d = a + XY.Project (c - a, b - a);

```

`XY` is a 2-dimensional vector with these methods defined:

```
/// projection of vector v onto vector w
public static XY Project (XY v, XY w) => XY.Dot (v, w) / XY.Dot (w, w) * w;

/// dot product of vectors a and b
public static float Dot (XY a, XY b) => a.X * b.X + a.Y * b.Y;

```

Also you'll have to implement trivial `+-*/` operators.
> 1 votes

---
Tags: unity, c#, mathematics, raycasting
---


# Question
Title: Making a wrapping wire (like the Worms Ninja Rope) work correctly with moving geometry
I have implemented a 2D wire like the one described in this question which is made up of straight line segments between wrapping points. However, while the algorithms described in this answer work just fine for colliding with static geometry, it does not behave correctly when interacting with moving geometry. The method described in this answer does work correctly in some cases, but not when the rope does not move, since the collision detection method does not account for the movement of points.

How would you make the wire behave correctly when interacting with moving geometry?

# Answer
> 2 votes
After calculating the rope, save the points it bends at relative to the objects, that cause that bend and the rotational direction (whether the rope bent in the right or the left direction). You can use these relative positions to reposition the rope during gameplay, but there will be 3 different interactions you need to pay attention to:

1.) An object hit the rope, so it should bend around it: This can be solved very easily using the same techniques you used during setup.

2.) An object stopped colliding with the rope: This very easy to solve, but a bit tricky to detect. This is why you need to save the bending direction at the beginning. If the rope bent around an object to the left, but it now bends to the right, that means that it got deattached from the object and you should merge the two segments

3.) The rope got shorter: Since the rope has to adapt to the moving objects, more of it has to be used to bend around parts. To solve this, take the last segment and shorten it. If it's not long enough, remove that segment and shorten the second to last and so on.

---
Tags: 2d, collision-detection, physics, algorithm, rope-physics
---


# Question
Title: How to add multiple transforms to a collection?
I have an array of Transforms:

```
public Transform[] monsterOne;

```

I can put a child's transform in this array using this code:

```
monsterOne = child.GetComponents<Transform>();

```

But if I try to do this in a loop for each child, the next child just replaces the last one, instead of adding to the array:

```
foreach (Transform child in transform)
{
    monsterOne = child.GetComponents<Transform>();
}

```

How can I add all of these transforms into one collection?

# Answer
> 1 votes
Arrays in C# can't be appended-onto. What you might want instead is a List, which behaves a lot like an array, but you *can* add items to it:

```
// Declaration of member variable - you can initialize it at the same time.
public List<Transform> children = new List<Transform>();

...

// Populate the list's contents in a method like Start().
foreach(Transform child in this.transform)
{
    children.Add(child);
}

```

You can still access the `i`th item in the collection with `children[i]` or iterate over everything in the collection with `foreach`. The main difference is that if you want to know how many entries are in the collection, you need to use `.Count` with Lists, as opposed to `.Length` with Arrays.

Alternatively, you can pre-size the array to the size you need, then assign each entry one by one:

```
// Declaration of member variable - don't initialize it yet (we don't know the size yet).
public Transform[] children;

...

// Allocate an array of the right size and populate it inside a method like Start().
int childCount = transform.childCount;
children = new Transform[childCount];

for(int i = 0; i < childCount; i++)
{
    children[i] = transform.GetChild(i);
}

```

# Answer
> 0 votes
Every game object can have only one Transform compinent. You are trying to get multiple Transform components from one transform. Instead you should loop through parent's children. If monsterOne is your Transform of the parent.

Example:

```
for(int i = 0; i < monsterOne.childCount; i++) {
    monsterOne.GetChild(i); //This is the transform of each child in monsterOne
}

```

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


# Question
Title: How to access specific child indices (directly, not using tags or searches)?
I have a game object whose prefab is structured a very specific way. It is a conveyor belt. I intend to arrange them end-to-end and animate them all at once using a script. Right now I am trying to get the normalized heading vector between two children, TargetStart and TargetEnd (see images below):

You can see that both of these objects are children of the prefab's first child. Because all of these instances will be structured the same, I want to compute the *heading* for the conveyor belt by accessing the locations of these children by their indices relative to the parent (which sounds like it should be simple and should be more efficient than searching by name or tag). I am anticipating a structure like this (pseudo-code):

```
// heading = targetEnd's position - targetStart's position
vector3 heading = gameObject.GetChild[0][1].position - gameObject.GetChild[0][0].position;
vector3 direction = heading / heading.magnitude;

```

How can this be done? I would like to know this so I can access any child I need to for any object by the child's index.

# Answer
> 2 votes
Accessing by index is a little fragile, if the structure of your prefab were ever to change.

As your object is a prefab, you might consider adding fields to your `ConveyorBelt` script for the start and end position objects instead, like so:

```
public class ConveyorBelt : MonoBehaviour
{
    [SerializeField] private Transform targetStart;
    [SerializeField] private Transform targetEnd;
// . . .
}

```

You'd then access `targetStart.position` and similar, caching the values as you are already if it becomes a performance concern.

---

Unity will persist references to objects which are part of the same prefab, so every instance will reference its own start / end points. This allows a bit more flexibility for any future changes to your object structure.

# Answer
> 0 votes
Whelp, I feel silly now. I thought I kept stumbling over this before but the answer is in the documentation example. This is how I am doing it:

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

public class ConveyorBelt : MonoBehaviour
{
    public bool isMoving = true;
    public float speed = 0.1f;
    private float offset = 0f;
    private Vector3 targetStart;
    private Vector3 targetEnd;
    private Vector3 heading;
    private Vector3 direction;
    // Start is called before the first frame update
    void Start()
    {
        targetStart = gameObject.transform.GetChild(0).GetChild(0).position;
        targetEnd = gameObject.transform.GetChild(0).GetChild(1).position;
        heading = targetEnd - targetStart;
        direction = heading / heading.magnitude;
    }

    // Update is called once per frame
    void Update()
    {
        if (isMoving == true)
        {
            MoveBelt();
        }
    }

    public void MoveBelt()
    {
        offset += (Time.deltaTime * speed);
        if (Mathf.Abs(offset) > 999)
        {
            offset %= 1f; //thought this might save memory, maybe not
        }
        gameObject.GetComponent<Renderer>().material.SetTextureOffset("_MainTex", new Vector2(0, offset));
    }

    public void StopBelt()
    {
        isMoving = false;
    }

    public void OnTriggerStay(Collider other)
    {
        if (other.attachedRigidbody && isMoving == true)
        {
            other.transform.position = other.transform.position + direction * Time.deltaTime / (2 * Mathf.PI * 0.25f + 3f);
        }
    }
    public void SetSpeed(float newSpeed)
    {
        speed = newSpeed;
    }
}

```

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


# Question
Title: Can a Unity button detect a tap AND send that tap through to objects below it?
I'm trying to make a "highlight frame," like a flashing box around a button for use in the game's tutorial. When the frame is tapped, I'd like it to register the tap (so the frame can be dismissed) but ALSO allow the button underneath to register the same tap (so that button's action is triggered.)

Is this possible? For a button to "detect a raycast without blocking a raycast," or something similar?

I could just have the button's action dismiss any highlight frames that exist, but that would entail putting "dismiss frame if exists" statements all over the place in my code. It would be much neater just to have the frame be a button which dismisses itself, without blocking the interaction with whatever it's highlighting.

Is there a way to accomplish this?

# Answer
> 0 votes
As I mentioned in the comment, I think you can do better by not trying to intercept the player's click on the original button, but instead just react to the original button itself being clicked.

We can do this while maintaining the highlight's self-containment, by giving it a script like this:

```
using UnityEngine.UI;
using UnityEngine.Events;

public class ButtonHighlight : MonoBehaviour {

    // Point this at the button that you want to highlight & react to.
    public Button targetButton;

    // Optionally, you can use an event to fire the next beat in the tutorial sequence.
    public UnityEvent onHighlightDismissed;

    void OnEnable() {
        // Subscribe to the target button's click.
        targetButton.onClick.AddListener(OnTargetButtonClicked);
        // Trigger any in transition or animation here.
    }

    void OnTargetButtonClicked() {
        targetButton.onClick.RemoveListener(OnTargetButtonClicked);
        // Trigger any out transition or animation here.
        // This can be done in a coroutine to wait before turning off the highlight.
        gameObject.SetActive(false);

        // Trigger the next stage of the tutorial, if any.
        if(onHighlightDismissed != null)
            onHighlightDismissed.Invoke();
    }
}

```

Zero changes need to be made to the code of the buttons you're interacting with. We just eavesdrop on their existing click events, using an object that is not itself a raycast target, and clean up after ourselves once the player has clicked as desired.

We get several advantages from this approach:

* It more closely matches the intention of the feature:

+ "Hide the highlight when the player clicks the original button"

    instead of
    + "Hide the highlight when the player clicks this spoof button and then pretend the player clicked the original button"

This means we have fewer opportunities for the effect of the code to deviate from what we meant it to do.

With the latter style, we have to keep the spoof button carefully matched to the original - any change to one without the other risks breaking the link, so for example the player could click on the intended button and miss the highlight, leading to an invalid state where the player has clicked the button but the tutorial is still telling them to click it.
* We get all the normal hover / keyboard interactions of the underlying button (including tab ordering) "for free" - no extra fakery or edge cases to deal with. Your interface still works identically whether the highlight is present or not, reads the same to screen readers, etc., because we haven't interfered with the interaction logic at all.
* We're free to style the highlight however we want. It doesn't have to exactly match the shape and size of the source button, or be any specific type of object - it could be an arrow pointing at it from outside its bounds, or a particle system of sparkles showering around it, or a skinned mesh of a character grabbing the button... your visual styling is completely decoupled from the logic of "show this until the player clicks this button"

---
Tags: unity, gui, raycasting, ui-design
---


# Question
Title: Transparent sphere particles surrounded by squares when above/below water shader
I get this really strange effect in my builds, **and only in builds**, when particles intersect with/go under the water:

Supposed to look like:

I have no idea what to search for or what to look for, any clues?

EDIT:

Water shader causing issues (purchased asset, I've written the seller):

Particle used:

I've tried messing around with render queues and settings on the particle system, but no real luck.

EDIT: It seems if I disable the depth effects on the component in the editor, the issue dissapears. Here is code from the class "LPWDepthEffect"

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

namespace LPWAsset {
    [ExecuteInEditMode]
    public class LPWDepthEffect : MonoBehaviour {

        static Dictionary<Camera, Camera> depthCams = new Dictionary<Camera, Camera>();
        static Dictionary<Camera, float> camState = new Dictionary<Camera, float>();
        static RenderTexture depthTex = null;

        static Shader depthShader = null;
        bool receiveShadows;
        static bool recursiveGuard;

        static bool hideObjects = true;

        public void Init(bool receiveShadows) {
            this.receiveShadows = receiveShadows;
        }

        public void OnWillRenderObject() {
            var act = gameObject.activeInHierarchy && enabled;
            if (!act || !GetComponent<Renderer>()) return;

            var material = GetComponent<Renderer>().sharedMaterial;
            if (!material || !material.HasProperty("_EdgeBlend")) return;

            Camera cam = Camera.current;
            if (!cam) return;

            bool hasDepth = material.GetFloat("_EdgeBlend") > 0.5f ||
                (material.HasProperty("_LightAbs") && material.GetFloat("_LightAbs") > 0.5f);

            if (hasDepth) cam.depthTextureMode |= DepthTextureMode.Depth;

            if (!receiveShadows || !hasDepth) return; // only when both depth + shadows

            // Render only once per camera
            float lastRender;
            if (camState.TryGetValue(cam, out lastRender)) {
                if (Mathf.Approximately(Time.time, lastRender) && Application.isPlaying) return;
                camState[cam] = Time.time;
            } else {
                camState.Add(cam, Time.time);
            }

            // Safeguard from recursive
            if (recursiveGuard) return;
            recursiveGuard = true;

            // Rendertexture
            if (!depthTex) {
                depthTex = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 24, RenderTextureFormat.Depth);
                depthTex.name = "__DepthTex" + GetInstanceID();
                depthTex.hideFlags = HideFlags.DontSave;
            }

            // Camera
            Camera depthCam = null;
            depthCams.TryGetValue(cam, out depthCam);
            if (!depthCam) { // catch both not-in-dictionary and in-dictionary-but-deleted-GO
                GameObject go = new GameObject("Water Depth Camera id" + GetInstanceID() + " for " + cam.GetInstanceID(), typeof(Camera));
                depthCam = go.GetComponent<Camera>();
                depthCam.enabled = false;
                depthCam.transform.position = transform.position;
                depthCam.transform.rotation = transform.rotation;
                go.hideFlags = hideObjects ? HideFlags.HideAndDontSave : HideFlags.DontSave;
                depthCams[cam] = depthCam;
                depthCam.clearFlags = CameraClearFlags.Depth;
            }

            int oldPixelLightCount = QualitySettings.pixelLightCount;
            QualitySettings.pixelLightCount = 0;
            float oldShadowDistance = QualitySettings.shadowDistance;
            QualitySettings.shadowDistance = 0;

            if (depthCam != null) {
                depthCam.farClipPlane = cam.farClipPlane;
                depthCam.nearClipPlane = cam.nearClipPlane;
                depthCam.orthographic = cam.orthographic;
                depthCam.fieldOfView = cam.fieldOfView;
                depthCam.aspect = cam.aspect;
                depthCam.orthographicSize = cam.orthographicSize;
                depthCam.depth = cam.depth - 0.1f;

                //Render
                depthCam.worldToCameraMatrix = cam.worldToCameraMatrix;
                depthCam.projectionMatrix = cam.projectionMatrix;
                depthCam.cullingMask = ~(1 << 4) & cam.cullingMask; // without water
                depthCam.targetTexture = depthTex;
                depthCam.transform.position = cam.transform.position;
                depthCam.transform.rotation = cam.transform.rotation;
                if(depthShader == null) {
                    depthShader = Shader.Find("Hidden/LPWRenderDepth");
                }
                depthCam.renderingPath = RenderingPath.VertexLit;
                depthCam.RenderWithShader(depthShader, "RenderType");
                GetComponent<Renderer>().sharedMaterial.SetTexture("_DepthTexture", depthTex);
            }

            QualitySettings.pixelLightCount = oldPixelLightCount;
            QualitySettings.shadowDistance = oldShadowDistance;
            recursiveGuard = false;

        }

        // Cleanup all the objects we possibly have created
        void OnDisable() {
            if (depthTex) {
                Destroy_(depthTex);
                depthTex = null;
            }
            foreach (var kvp in depthCams) {
                Destroy_((kvp.Value).gameObject);
            }
            depthCams.Clear();
            camState.Clear();
        }

        public void Destroy_(Object o) {
            if (Application.isPlaying) Destroy(o);
            else DestroyImmediate(o);
        }

    }
}

```

And here is the DepthShader:

```
Shader "Hidden/LPWRenderDepth" {

    SubShader {
        Tags { "RenderType"="Opaque" }
        Pass {
            ZWrite On
            Lighting Off
            ColorMask 0

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 2.0

            #include "UnityCG.cginc"

            struct appdata {
              float3 pos : POSITION;
            };

            struct v2f {
              float4 pos : SV_POSITION;
            };

            v2f vert (appdata IN) {
              v2f o;
              o.pos = UnityObjectToClipPos(IN.pos);
              return o;
            }

            fixed4 frag (v2f IN) : SV_Target {
              return fixed4(0,0,0,0);
            }
            ENDCG
        }
    }

    SubShader {
        Tags { "RenderType"="Transparent" }

        Pass {
            ZWrite Off
            Lighting Off
            ColorMask 0

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 2.0

            #include "UnityCG.cginc"

            float4 vert () : SV_POSITION {
              return float4(0,0,0,0);
            }

            fixed4 frag () : SV_Target {
              return fixed4(0,0,0,0);
            }
            ENDCG
        }
    }

    SubShader {
        Tags { "RenderType"="TransparentCutout" }

        Pass {
            ZWrite Off
            Lighting Off
            ColorMask 0

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 2.0

            #include "UnityCG.cginc"

            float4 vert () : SV_POSITION {
              return float4(0,0,0,0);
            }

            fixed4 frag () : SV_Target {
              return fixed4(0,0,0,0);
            }
            ENDCG
        }
    }
}

```

# Answer
This was solved by moving the shaders to the "Assets/Resources" folder, since the scripts use `Shader.Find("...")`
> 1 votes

# Answer
Observing the problem, I believe the random quad projections in the water are actually the quads of the particles without their texture rendering correctly. i imagine that Shader.Find("...") was previously unable to find the texture to render onto each quad(if you don't know, a particle is an actual image, usually a blurry circle, mapped to a texture2D, mapped to a simple quad for performance speed), but would still render the quad and their respective color filters. I hope that sheds some light on the problem even though it was already solved.
> -1 votes

---
Tags: unity
---


# Question
Title: In Unreal Engine 4, how do I get the component's "game object" via C++?
I have an `ACharacter` instance with a weapons component that inherits from `UActorComponent`attached to it. I'm currently writing code that instantiates a weapon actor and attaches it to the `ACharacter` instance.

What I'm having trouble with is finding out how to get a reference to the `ACharacter` from the weapons code. In Unity, this would be a simple `this.gameObject` or `FindComponent<Character>` call, assuming the component belongs to the same transform.

Thank you!

# Answer
> 1 votes
To do this in Unreal and C++, you'll need to set a pointer to the class and then cast to it.

Casting is expensive in terms of overhead so if it's something you'll be doing often, it's best to get it sorted in Begin Play and call the variable in Tick or whenever you want to call it.

In the .h file:

```
class ACharacter;

```

In whatever section (public, private or protected) is best:

```
ACharacter* ComponentOwner = nullptr;

```

Over in your .cpp

```
#include "ACharacter.h"

```

Then in your Begin Play

```
ComponentOwner = Cast<ACharacter>(GetOwner());

```

It is good practise to protect your pointers to avoid crashes. While getting the program working, I'd check here at Begin Play as well:

```
if (!ComponentOwner)
{
  UE_LOG(LogTemp, Warning, TEXT("No ComponentOwner found!");
}

```

and then in Tick or whatever function is calling the character:

```
if (!ComponentOwner)
{ return; }

// Put your code here

```

# Answer
> 2 votes
Use `GetOwner()` in the component

---
Tags: c++, unreal-4, component-based, gameobject, unreal
---


# Question
Title: How to rotate a point around a pivot by changing the axis
I've been stuck on this forever now because I don't understand math in the slightest and when people talk about matrices they just give the table and don't explain how to actually go through each step.

My question is how do I rotate a point around a pivot by moving the axis instead of the point.

```
        Vector3 center = new Vector3(0.5f,0.5f,0.5f); //an arbitrary center
        Vector3 point = new Vector3(0.5f, 0.5f, 0); //an arbitrary point
        Vector3 endpoint; //how do I get this

        Vector3 current_east = Vector3.right;  //x
        Vector3 current_up = Vector3.up; //y
        Vector3 current_north = Vector3.forward; //z

        Vector3 moveto_east = Vector3.back;
        Vector3 moveto_up = Vector3.left;
        Vector3 moveto_north = Vector3.up;

```

So if I was to rotate the current vectors, to the moveto vectors what position would the point be in. (in this case it would be 0.5, 0, 0.5) buut how would I achieve this assuming the point and the axis will be arbitrarily defined. Picture for clarification.

# Answer
Ah, linear algebra. Few things that probably no one told you, but are pretty essential to understand matrices and rotations (i hope i don't mix the names, never learned maths in english).

1. Each point in space has a position, dependent on the basis you defined (you know, the perpendicular arrows starting at \[0, 0\])
2. Each column of the rotation matrix defines single arrow of your basis. For 'unrotated' world (rotation matrix is identity matrix), your X axis is in direction \[1, 0\] and Y in \[0, 1\].
3. If you want to rotate a point around the orgin of your basis, you effectively define new basis with rotated axes. If you want to rotate 90 degrees, your new X axis will be \[0, 1\] and Y will be \[-1, 0\]. Putting them into matrix (as columns), will give us matrix (which matches the formula from https://en.wikipedia.org/wiki/Rotation\_matrix ):

```
 [0 -1]
 [1  0]

```
4. To perform the rotation you have to multiply the rotation matrix by the vector (point's coordinates). To undo the rotation you have to multiply the rotation matrix *inverse* by the rotated point. Calculation of matrix inverse generally is difficult. There's a trick however. If basis is orthogonal (which simply means all axes are perpendicular to each other, and that's the case most of the time in 2D/3D graphics), then matrix inverse is its transposition (columns become rows). Inverse of above rotation matrix will become:

```
[ 0 1]
[-1 0]

```
5. To rotate a point A around an arbitrary point B using matrix M, you have to:

1. Define B as the origin of your basis (this will give us point A'; to do that simply subtract B from A)
    2. Rotate A' using M (multiply M by A')
    3. Restore the original origin (add B)

In matemathical terms it will be B+M\*(A-B)

If i understand correctly, you want to rotate a point A around B starting from rotation M1 (current\_\*) to rotation M2 (moveto\_\*). Matrices M1 and M2 are created from your east/up/north vectors (they become the columns of the matrices). So:

1. Define B as the origin (subtract B),
2. Undo the current rotation (multiply inverse of M1)
3. Perform moveto rotation (multiply M2)
4. Restore origin (add B)

Mathematically this will be: B+M2\*transpose(M1)\*(A-B)

(Hopefully i didn't mix anything, and my memory didn't fail me)
> 1 votes

---
Tags: unity, c#, matrix, rotate
---


# Question
Title: How to start building the racing levels in unity?
I had an idea of making more fun less redundantly designed level for a racing game, i have core mechanics and ui of the game sorted out but i m confused where to begin with the levels and how do i structure them. link of any sites that focusses on this would be greatly helpful.

# Answer
> 1 votes
You could try building some roads with some tools like:

https://github.com/MicroGSD/RoadArchitect or https://assetstore.unity.com/packages/3d/characters/easyroads3d-free-v3-987

Then you can use some more assets and props like:

https://assetstore.unity.com/packages/3d/props/exterior/road-props-low-poly-123340 https://assetstore.unity.com/packages/3d/environments/urban/city-voxel-pack-136141 https://assetstore.unity.com/packages/3d/props/exterior/traffic-and-vehicle-accessories-71194

All in all don't expect to think of a complete level/scene, go bit by bit and your imagination will follow :D

You can also find more tools for the terrain here: https://assetstore.unity.com/tools/terrain?category=tools%2Fterrain&orderBy=4

And ask for further help here: https://forum.unity.com/forums/world-building.146/

---
Tags: unity, game-design, level-design
---


# Question
Title: How can I ensure the player learns all skills in a single open level?
I am making a game that only has a single level. It is a survival game. If there were multiple levels, I can have the player learn new skills gradually. For example, level one requires jumping, level 2 requires climbing, level 3 requires both.

As a single open-world level which is intended to be replayed multiple times, I am having trouble finding any linearity in which I can teach the player how to play the game a little bit at a time. I am tossing them to the wolves.

Is there a common strategy to force the player to learn all the necessary skills to succeed? Currently I have 4 directions which the player can travel from the starting point. Each of which teaches them something. But my fear is that they will learn a single way and then have no reason to learn the other three skills, as each skill is equally beneficial.

How can I force the player to learn all four gameplay skills when only one is required to succeed at the game? Keep in mind, because of mechanics of this particular game and there only being one level, they must have the ability to learn all 4 skills from the beginning.

I hope this is not too foolish of a question, but I am stumped on how to make the players learn all four skills without front loading a tutorial.

*Reason for only one level is time and scope. Just can't make more. Gotta get this one right.*

# Answer
As @davidvanbrink said in a comment, **gating** is a common way of doing this: either put the starting position in an large enclosed area that requires all the skills to escape and contains basic tutorials on each, or have certain portions of the game be blocked by barriers that require one of the skills and make sure that every critical path contains one of each kind of gate.

Another approach is the **rock-paper-scissors** trick. Have challenges that require or are immune to one or more of the skills in question. *Prince of Persia: The Sands of Time* had enemies that required certain skills to defeat, forcing you to learn those skills.

Finally, you can try the **redundant solution** approach popularized by *Deus Ex*, where you show multiple paths to an objective, each more easily traversed with a different skill. That way they can complete the game with a single approach but can clearly see that they've "missed" a path that they can return to in a repeat play with a different strategy.
> 3 votes

# Answer
Achievements. After learning one skill from set, display progress information like "Skill learned: 1 / 4" (eg. "Lighting fire: 1/4 skills learned"). This way player will know there are 3 other skills to learn.
> 1 votes

---
Tags: level-design, tutorials, reinforcement-learning
---


# Question
Title: How to restart the timer after using deltaTIme
I am creating a simple game interface. When `fillAmount > 0`, the timer is stopped and reset. I want to restart the timer if the fill amount does not change for 3 seconds. All the code does now is counting 3 seconds and then displaying the time when it stops. How do I fix it?

```
private float startTime;
private float reStartTime;
public Barscript barscripts;

void Start() {
    startTime = Time.time
    DefaultImg = GetComponent<Image>();
}

void Update() {
    float t = Time.time - startTime;
    reStartTime = 3;
    float t1 = reStartTime - startTime;

    string hours = ((int) t / 6).ToString();
    string minutes = ((t % 6) * 10).ToString();

    Debug.Log(barscripts.fillAmount);

    if (batscripts.fillAmount > 0) {
        DefaultImg.sprite = Emoji3;
        startTime += Time.deltatime;
        timerText.text = " 0   :   00 "
        Debug.Log(t1);

        if (t1 < 0) {
            timerText.text = hours + "   :   " + minutes;
        }
    }
}

```

Here's a sample image of what I'm getting at the moment.

# Answer
> 3 votes
Assuming you want to create a time counter with deltaTime, it is easy like this:

```
float timeRunning =0.0f;
Update()
{
   timeRunning += Time.deltaTime;
   if(timeRunning >= 3.0f)
   {
   //Do things
   timeRunning = 0.0f; //Restart counting
   }
}

```

Inside the do things you could check the fillAmout's value with an older value (you should create a `lastFillAmount` variable)

# Answer
> 0 votes
I think this code should do what you want, its quite self-explanatory but if you have any question just don't hesitate to ask.

```
private float _lastFillAmountChangeTime;
private float _fillAmount;
private float _timer;

public float FillAmount
{
    get {  return _fillAmount;}
    set
    {
        // register the change if input value != current value
        if(value != _fillAmount)
        {
            _lastFillAmountChangeTime = UnityEngine.Time.time;
        }
        _fillAmount = value;
    }
}

private void Start()
{
    // give these fields initial values
    _lastFillAmountChangeTime = 0;
    _fillAmount = 0;
    _timer = 0;
}

private void Update ()
{
    // update timer
    _timer += UnityEngine.Time.deltaTime;

    // its more than 3 sec from the last change of FillAmount
    if (_lastFillAmountChangeTime + 3 < UnityEngine.Time.time)
    {
        // reset the timer
        _timer = 0;
    }
}

```

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