# Question
Title: Calculate angular velocity from rotation matrix difference
I am working on something for a game. I need to calculate the angular velocity, however in my situation I only have access to the previous rotation matrix and the current rotation matrix (and some other variables like dt or age of the object).

My angular velocity is hereby constant between t0 and t1.

The normal formula for the angular velocity `W(t) = dR(t)/dt * R(t)^-1` can't be used here, since I have discrete values. Is there a possibility to calculate the angular velocity between timestep t0 and t1 with the given R0 and R1 rotation matrix of an object?

I am not very advanced with matrix math, so please go easy on me.

# Answer
You can get the difference between the two transformations by multiplying the new one by the inverse of the old. (If these matrices are pure rotations, with no translation/scale/shear, then this inverse is just the transpose)

$$R\_\text{diffference} = R\_1 \times R\_0^{-1}$$

Now you can extract the quaternion representing the rotation from this difference matrix. The axis of rotation then points along the imaginary part of the quaternion, and the angle of travel is twice the arc cosine of the real component:

```
q = MatrixToQuaternion(R_difference)
axis = Normalize(q.xyz)
angle = 2 * Acos(q.w)

```

Or you can extract the angle and axis directly from the matrix as described here

Now to convert this to an angular velocity, you can simply multiply the axis unit vector by the angle travelled, divided by the time step over which the travel occurred.
> 1 votes

# Answer
Assuming the matrices you have are pure rotation matrices (i.e. they do not contain scale information) and describe a rotation around an axis which is the same as the one you want to calculate the angular velocity for, then you can extract their angle \\$θ\\$ directly.

A rotation of angle \\$θ\\$ around axis \\$z\\$ in 3D space for example is described by the augmented matrix $$R=\begin{pmatrix} \cos\theta & -\sin\theta & 0 & 0\\ \sin\theta & \cos\theta & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 1 \end{pmatrix}.$$ It is possible that you do not have the augmented matrix at hand in which case it will be a 3x3 matrix with the last row and last column trimmed off.

Hopefully the matrices you have are of a similar form (i.e. they describe a rotation around one of the basis vectors). Once you have extracted \\$θ\_0\\$ and \\$θ\_1\\$ you can find their difference \\$Δθ\\$ and from there you can use the angular velocity formula $$ ω = \frac{Δθ}{Δt} $$ If the matrices you have are not around one of the basis vectors then this becomes more complicated but the logic stands. Check this for rotation matrices around an arbitrary axis
> 0 votes

# Answer
The step rotation is \\$Q=R\_1R\_0^{-1}\\$ and the goal is to find its "logarithm" \\$X=α(\hat n\times)\\$ for the identity \\$Q=e^{X}\\$ where the unit vector \\$\hat n\\$ is the rotation axis, \\$(\hat n×)\\$ the skew-symmetric matrix realizing the cross product and \\$α\\$ the rotation angle.

If \\$Q\\$ is close to the identity, \\$X\\$ can be selected close to the zero matrix. Then it might be sufficient to approximate the matrix exponential by a Padé approximation and solve $$ (2I+X)(2I-X)^{-1}=Q\iff X=2(Q-I)(Q+I)^{-1}=2I-4(Q+I)^{-1} $$ This will give a skew-symmetric result within the boundaries of the floating point accuracy. Read off $$ X=α(\hat n\times)=\pmatrix{0&-z&y\\z&0&-x\\\-y&x&0},~~ α=\\|(x,y,z)\\|, \hat n=\frac{(x,y,z)}{α} $$
> 0 votes

---
Tags: physics, rotation, matrix
---


title: How can I make 3D lighting smooth?

text:
# Question
Title: How can I make 3D lighting smooth?
I'm trying to view 3D objects in a terminal. Everything was looking good until I implemented lighting. I'm using shadow rays to determine where the object should be lit. Although it's working I don't know how to make it smooth, I haven't tried anything since I don't actually know what to do.

Here's how a sphere is looking (light is coming from above):

As you can see it's either really dark (.) or light (@) so it's hard to determine the object.

# Answer
> 0 votes
> The sphere is blockey, I have a 3D array of characters and i use a distance function to fill up the array, so i cant use floats which make small circles really blockey, that's how i represent the sphere, you just gave me an idea maybe **i should stop representing the sphere as a 3D array and start representing it as a distance function** if the distance between the ray and sphere is less or equal than the radius of the sphere then the ray is intersecting the sphere

In your comment above, it looks like you've hit on the key insight you need for smooth lighting.

Given a ray, and a sphere's center point and radius, you can detect precisely where the ray hits the sphere, using algorithms like the ones in this past Q&A.

Now that you have a point on the sphere's surface, you can compute the surface normal at that point: a unit vector pointing perpendicular to the surface, directly out from the sphere. If your intersection routine doesn't already generate this, you can deduce it from the position of the reported intersection point:

```
 Vector3 normal = Vector3.Normalize(rayHitPosition - sphereCenter);

```

(Here, `Vector3.Normalize()` refers to the operation of dividing all components of a vector by that vector's length, to create a unit vector with length 1 in the same direction as the original)

You can compute the direction to the light source the same way:

```
 Vector3 toLight = Vector3.Normalize(lightPosition - rayHitPosition)

```

Given these two vectors, we can compute the diffuse illumination at this location. That's the scattered light you get bouncing off of a matte surface, like plaster. It's brightest when the light is hitting the surface dead-on (when the `toLight` and `normal` vectors point in the same direction), and fades as the surface turns away from the light, catching it just edge-on. We can model that with what's called a Lambertian term:

```
 float diffuse = Mathf.Max(Vector3.Dot(toLight, normal), 0);

```

Here `Vector3.Dot()` is the scalar product, multiplying the x component of one vector by the x component of the other, then y with y, z with z, and adding the three products together to make one number. Because we used unit vectors, that number is the cosine of the angle between the vectors - ie. it goes from 1 when they're pointing in the same direction, to 0 when they're perpendicular, to -1 when they're pointing in opposite directions.

I use a clamping function so that any values below zero - corresponding to the surface facing away from the light source - produce zero scattered light, instead of "negative light".

This will give you a smoothly varying value, from 1 on the part of your sphere closest to the light, and getting darker and darker until it hits zero at the terminator - the equator separating the lit portion of the sphere from the shadowed half.

You can scale this diffuse component by the brightness (or colour) of your light source, relative to the exposure of your image, then map the resulting value into your character range for display.

We can use simple vector tools like this to compute additional lighting terms to get different surface appearances - like adding the specular reflections you'd see on shiny surfaces, or metallic reflections you'd see from metal, but those might not be very noticeable in your text-based representation.

---
Tags: lighting, text-based
---


title: Select specific tile in Tilemap

text:
# Question
Title: Select specific tile in Tilemap
I am following this video tutorial on how to implement drag-to-select behavior like in an RTS. The only difference is, I'm using a tilemap.

The selection area is a square which I can drag to make it as big as I want, like in any top down RTS.

CodeMonkey in his video uses `Physics2D.OverlapAreaAll` to get a list of all colliders in the selected area. I want to use this to specifically see which "vegetation" tiles I've selected. However, no matter which vegetation tile I select, or how many, I always get one result - the vegetation tilemap itself.

You can clearly see from this picture that every grass tile and every tree tile have a collider around them, which is why this works, but how can I get exactly those that I selected?

Other than vegetation from the tilemap, I also want this to work with GameObjects that have Box2DColliders on them, and that works out of the box. I also made those MonoBehaviors inherit an interface called `ISelectable`, so I can only add to the selected list entities that have that inherit that interface. I tried to do the same with vegetation like so `public class Vegetation : Tile, ISelectable` but it doesn't work.

What am I missing? Can this even work on a specific tile basis?

# Answer
> 1 votes
We can use the Tilemap's Grid to convert the world-space bounds of our selection rectangle into grid coordinates within the map:

```
LayoutGrid grid = tilemap.layoutGrid;
Vector3Int bottomLeftCell = grid.WorldToCell(bottomLeft);
Vector3Int topRightCell = grid.WorldToCell(topRight);

Vector3Int min = Vector3Int.Min(bottomLeftCell, topRightCell);
Vector3Int max = Vector3Int.Max(bottomLeftCell, topRightCell);
Vector3Int size = max - min + Vector3Int.one;

BoundsInt bounds = new BoundsInt(min, size);

```

Then we can ask the Tilemap to give us an array of all tiles in those bounds:

```
TileBase[] tiles = tilemap.GetTilesBlock(bounds);

```

Now you can walk through this tile array to find the vegetation tiles you care about (say, gathering up all the ones that implement `ISelectable`). They don't strictly need colliders for this purpose, since you can detect them by position and tile type, in case that simplifies any of your physics scene.

You'll still use your physics queries to detect objects that aren't part of the tile map, and use this method to inspect the tiles.

---
Tags: unity, 2d, physics, tilemap, raycasting
---


# Question
Title: How can I hide the camera gizmo in Unity?
How can I hide the camera gizmo in Unity?

As said here I tried to use the gismos menu in the top of my Scene view. But it does not work. Why?

Also, I tried saving my scene and project after the gizmo changes. Did not help. I have the **Unity 2020.1.17f1**.

# Answer
You'll note there are two columns in the Gizmos menu:

* one for the **gizmos** (like the white wireframe box that shows your camera frustum),
* and one for the **icons** (like the picture of a camera or light that shows the location of those objects, even when not selected)

**Click the camera icon** *next to* the checkbox in the Gizmos menu to hide the camera icon in your scene.
> 3 votes

---
Tags: unity, camera
---


# Question
Title: How to read ARGB pixel data from SDL2 surface and store them in an array?
I've been trying for hours now to figure out why this piece of code is giving me seg fault, but can't figure out why.

```
 void pixel::Texture::LoadTexture(const char* filepath)
 {
    SDL_Surface* image = IMG_Load(filepath);
    SDL_Surface* formattedImage = SDL_ConvertSurfaceFormat(image, SDL_PIXELFORMAT_ARGB8888, 0);

    textureBuffer = new Uint32[formattedImage->pitch * formattedImage->h];

    width = formattedImage->w;
    height = formattedImage->h;
    pitch = formattedImage->pitch;

    SDL_LockSurface(formattedImage);

    Uint32* pixels = (Uint32*)formattedImage->pixels;

    int bpp = formattedImage->format->BytesPerPixel;

    for(int y = 0; y < height; y++)
        for(int x = 0; x < width; x++)
            textureBuffer[(formattedImage->pitch * y) + (x * bpp)] = pixels[(formattedImage->pitch * y) + (x * bpp)];

    SDL_UnlockSurface(formattedImage);

    SDL_FreeSurface(image);
    SDL_FreeSurface(formattedImage);
 }

```

Essentially, what I'm doing is I have an array of unsigned 32 bit integers called the texture buffer. All I do is load an image into a surface then convert it's pixel format to ARGB then start reading each pixel and storing it inside my texture buffer array but for some reason the pixels array gets an out of bounds error at some point in runtime and I can't figure out exactly why.

# Answer
> 1 votes
This code gives the *byte* offset to the pixel at coordinates `x`, `y`:

```
(formattedImage->pitch * y) + (x * bpp)

```

But you're providing it as the index into an array to which you've assigned the type `Uint32*`:

```
Uint32* pixels = (Uint32*)formattedImage->pixels;

```

This is like measuring a distance in kilometers, then using it to give someone driving directions in miles. A trusting person (or CPU) following your directions will end up overshooting the destination by a long way!

A `Uint32` is 4 bytes, so each time you step your byte offset forward by 1 pixel by incrementing `x` by 1, your index into the pixel data leaps forward 4 * 4 = 16 bytes:

```
pixels[(formattedImage->pitch * y) + (x * bpp)];

```

So you burn through your data 4x faster than you meant to, and by the time your code thinks it's read just a quarter of the data, it's already at the end of the collection. You continue reading 3x the total data size past there until you trigger the fault.

It looks to me like your code is better set up for iterating with an index measured as a pixel count, rather than as a byte offset, which we can do with a couple small tweaks:

```
textureBuffer = new Uint32[width * height];

for(int y = 0; y < height; y++)
    for(int x = 0; x < width; x++)
        textureBuffer[width * y + x] = pixels[width * y + x];

```

Note that we no longer multiply by `pitch` or `bpp` here.

There's probably a more modern C++ way to iterate over this collection as a range, or just do a memcopy, but I'm afraid I'm not fluent enough in the language to advise on the particulars there.

---
Tags: c++, sdl2
---


# Question
Title: How can I prevent the following animation frames from affecting the state of the previous animation frames in Unity?
How can I prevent the following animation frames from affecting the state of the previous animation frames in Unity?

E.g. I create a frame at **0:20** by moving a character leg. And that is it - that is what I would like my character to look like at the **0:20** and I would like to change nothing more about the current positioning of my character parts and never.

But, here I proceed to the **0:40** and move another part of my character - foot this time. And now instead of starting to move after the **0:20** the foot starts to move from the **0:00**.

That drives me crazy, because now I have to go through all of the frames before the **0:40** and modify the foot position. Of course in the presented case there is only one frame to update - that is the **0:20**. But when I work with complex and long animations I easily stumble across having to update 10 or even more of the previous frames each time I decide to move a part which I did not move in the previous frames.

I noticed the **Add keyframe** button in the **Animation** window. I would expect it to preserve all the character parts in frame and solve my issue. But it does not prevent the case explained above from happening.

Another thing I was thinking about is to develop animations backwards - starting from the last frame and proceed to the first frame. But that feels like a lame user experience from a Unity user point of view.

Any help here would be appreciated.

# Answer
> 1 votes
The reason this happens is that you didn't tell Unity where you wanted the animation to start, because you had no keyframes on the foot position property until the one you created at 0:40. So Unity assumes you want the movement to start at the start of the animation.

Keyframes are handled independently for each property, so having a keyframe on a different object property does not count as a keyframe for the foot.

You can add a property for the foot position by clicking the Add Property button, then create a keyframe on that property at the time you want the motion to start. Or you can use this trick to create the keyframe you need automatically:

1. Place the play head at the time when you want the motion to start (ie. 0:20 in this example)
2. Hold CTRL to enable snapping, and move your object one snapping tick over, then back to where it was, without letting go in between. (The snapping helps you get back exactly to where you were, without error)

This automatically adds a property for this object's position to the animation, and creates a keyframe at the current play head position. So now you have a keyframe for the start of your motion.
3. Now move the play head to the time you want the motion to finish (ie. 0:40), and move the object as you were trying to do before.

Because you've already created a keyframe for the start of the motion, the motion starts from that keyframe, rather than from the start of the animation at 0:00.

# Answer
> 1 votes
This is caused by the Animation window's automatic easing curves. At the bottom of the animation window there are two tabs, "Dopesheet" and "Curves". In the "Curves" tab you can view or edit the smoothing/easing curves. Switch from bezier to linear if you don't want this type of side effect to occur when you edit a keyframe.

1. Right-click a point on the curve
2. Select Left Tangent \> Linear
3. Repeat for Right Tangent

---
Tags: unity, animation
---


# Question
Title: LibGDX make player rotate towards mouse pointer (Player facing mouse)
I am tryna makin' a 2D game with a 3D player (kinda of Factorium). I got stuck on the rotating of the player. I'd like it look always torwards to the mouse. e.g. If I move mouse on the top-left of the window, player will rotate towards the same direction.

I read on some other question about the method below, but it doesn't work properly:

```
private void rotatePlayerToMouse(OrthographicCamera camera) {

    Vector3 mousePos = camera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
    Vector3 playerPos = this.getPosition();//this.instance.transform.getTranslation(Vector3)

    float degree = (float)Math.atan2(mousePos.y - playerPos.y, mousePos.x - playerPos.x);
    System.out.println(degree);
    this.instance.transform.rotate(new Vector3(0f, 0f, 1f), degree);
}

```

This method allows player to rotate. Player rotates both direction, but it doesn't stop rotating...

What is wrong?

# Answer
> 1 votes
Two obvious problems here:

* You've labelled a variable `degree` that's actually measured in radians, not in degrees.
* You're telling the object how much to rotate *by*, not giving it a target angle it should rotate *to*.

These can both be solved by reading the documentation for the methods you're using. It tends to show when you don't.

```
float radians = (float)Math.atan2(mousePos.y - playerPos.y, mousePos.x - playerPos.x);

this.instance.transform.setFromEulerAnglesRad(0, 0, radians).setTranslation(playerPos);

```

---
Tags: java, libgdx
---


# Question
Title: How to play sound in WebGL build in Unity?
I have a project that works fine when I build for windows, but doesn't work when I switch platform to WebGL. The `[SerializeField] AudioClip` variables in the inspector are all 'missing', even after I check 'override for WebGL' convert to AAC. And when I try to link any audio file to an AudioClip within a WebGL build in the inspector, it doesn't seem to work.

How do I get sound to play within WebGL?

To recreate the problem:

* Switch platform to WebGL.
* Create a new Script in any recent unity version, then add a \[SerializeField\] AudioClip x.
* Put that script on a new gameobject and try to link an audio asset to it (default import settings, however don't forget to check 'override for WebGL' to AAC, otherwise you will get compiler errors when you switch platform).

# Answer
> 1 votes
I finally found the solution! I do not have to override for WebGL to AAC at all, I just needed the default sound asset settings, and then install Windows Media Foundations. You can find it here: https://support.microsoft.com/en-us/topic/media-feature-pack-list-for-windows-n-editions-c1c6fffa-d052-8338-7a79-a4bb980a700a

Once I installed it and rebooted, my project works fine.

---
Tags: unity, webgl, audio, sound
---


# Question
Title: How to convert screen space to world space?
I have a shader that should do raymarching.

But I have problems converting the fragment's position to a worldspace coordinate.

This is my vertex shader:

```
VertexShaderOutput VS(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Position = float4(input.Position.xy*2,0.0, 1.0);
    float4 worldPos = output.Position;
    output.WorldPos = mul(worldPos, InverseViewProjection);
    output.UV = input.UV;
    return output;
}

```

`input.Position` in this case is a quad from `-0.5` to `0.5`, hence why I multiply it by 2.

In my pixel shader, I want to get the ray start position from `output.WorldPos`.

However, the shader outputs `WorldPos` as this:

```
x = -118.943700000, y = -25.704420000, z = 23.763410000

```

This is wrong, because the camera is at around

```
x = -3846 y = -810 z = 734

```

What am I doing wrong? I expected a world position, but it seems to be a screen space position?

Here is how I create my matrices (DirectX SimpleMath):

```
View = Matrix::CreateLookAt(WorldPosition, target, up);
Projection = Matrix::CreatePerspectiveFieldOfView(fov, w / (float)h, n, f);
ViewProjection = View * Projection;
ViewProjection.Invert(InverseViewProjection);
Projection.Invert(InverseProjection);
View.Invert(InverseView);

```

The game renders perfectly fine, So I am certain The View/Projection Matrices are not wrong.

# Answer
Okay after a lot of fiddling. I needed to divide `xyz` with `w`: Here is my Vertex Shader for a fullscreen quad;

```
VertexShaderOutput VS(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Position = float4(input.Position.xy,0.0, 1.0);
    float4 worldPos = output.Position;
    worldPos = mul(worldPos, InverseViewProjection);
    worldPos.xyz /= worldPos.w;
    output.WorldPos = worldPos;
    output.UV = input.UV;
    return output;
}

```
> 1 votes

---
Tags: camera, hlsl, fragment-shader
---


# Question
Title: Why does my stencil buffer allow pixels through?
I'm rendering a scene using OpenGL. The scene consists of a grassy environment and a small lake (visible as two surfaces). To achieve water surface transparency, I'm using a stencil buffer to render water surfaces separately from other geometry. For context, here's a screenshot of the scene *without* water surfaces:

Here's the same scene, but with water surfaces stenciled out (the black portions of the screen):

Here's the fragment shader I'm using (where `fSource` is fullscreen UV coordinates). As you can see, it simply samples from a previously-used frame buffer and outputs the pixel directly to the screen. With stenciling enabled, only pixels not covered by a water surface are rendered.

```
#version 440 core

in vec2 fSource;

out vec4 outColor;

uniform sampler2D image;

void main()
{
    outColor = texture(image, fSource);
}

```

Here's the problem. When I change this fragment shader to output a solid color, those underwater pixels are suddenly visible (the stencil buffer and stencil settings have not changed). What I'd expect here is non-submerged pixels to be purple, but the water surface pixels (previously black) to remain black (since they should still be rejected through stenciling). Instead, *everything* is purple, including the water surface.

```
#version 440 core

out vec4 outColor;

void main()
{
    outColor = vec4(1, 0, 1, 1);
}

```

As an additional test, I tried rendering only pixels *under* the water surfaces with a solid color. These pixels *should* be rejected via stenciling (appearing black, just like before), but for some reason, they're visible.

```
#version 440 core

in vec2 fSource;

out vec4 outColor;

uniform sampler2D image;
uniform sampler2D positions;

void main()
{
    vec3 position = texture(positions, fSource).xyz;

    // The water surfaces happen to sit at Y value 7.85.
    if (p.y < 7.85)
    {
        outColor = vec4(1, 1, 0, 1);
    }
    else
    {
        outColor = texture(image, fSource);
    }
}

```

I confirmed the problem by instead sampling with shifted UV coordinates (rather than outputting solid yellow). Again, pixels are showing up on the water surfaces, seemingly ignoring the stencil buffer.

```
#version 440 core

in vec2 fSource;

out vec4 outColor;

uniform sampler2D image;
uniform sampler2D positions;

void main()
{
    vec3 position = texture(positions, fSource).xyz;

    // The water surfaces happen to sit at Y value 7.85.
    if (p.y < 7.85)
    {
        outColor = texture(image, fSource + vec2(0.1, 0));
    }
    else
    {
        outColor = texture(image, fSource);
    }
}

```

My understanding of stenciling is that it prevents the fragment shader from running *at all* on certain portions of the screen (i.e. fragments pass or fail based on stencil settings). If that were true, then no matter what the fragment shader outputs, that pixel should remain black (in this context). Clearly, the fragment shader is still being run for pixels that *should* be rejected due to stenciling, which means I must be misunderstanding how the stencil buffer works.

**Why is the fragment shader still running on pixels that should be rejected through stenciling?**

**Update 1:** here are my stencil settings. No other objects (apart from water surfaces) write to the stencil buffer.

```
// Render water surfaces. 0x10 represents water.
glEnable(GL_STENCIL_TEST);
glStencilMask(0xFF);
glStencilFunc(GL_ALWAYS, 0x10, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);

BindWaterFrameBuffer();
BindWaterShader();
DrawWaterSurfaces();

// Render the scene. Due to the stencil settings, only non-surface pixels should be rendered.
glStencilMask(0x00);
glStencilFunc(GL_EQUAL, 0x00, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

BindDefaultFrameBuffer();
BindSceneShader();
DrawFullscreenQuad();

```

**Update 2:** here's another screenshot showing the submerged solid color test, but with a lower Y threshold (three meters below the water). What *appears* to be happening, then, is that pixels sampled using the GLSL `texture` function correctly honor the stencil buffer, while direct color outputs don't. However, even that can't quite be true since, as shown above, sampling pixels outside the stenciled portion of the screen still results in those pixels showing up.

```
#version 440 core

in vec2 fSource;

out vec4 outColor;

uniform sampler2D image;
uniform sampler2D positions;

void main()
{
    vec3 position = texture(positions, fSource).xyz;

    // The water surfaces happen to sit at Y value 7.85, but here, I'm using a threshold three meters below that.
    if (p.y < 4.85)
    {
        outColor = vec4(1, 1, 0, 1);
    }
    else
    {
        outColor = texture(image, fSource);
    }
}

```

---

# Answer
> 1 votes
I solved the problem. Through other work, I discovered that my stencil buffer wasn't clearing properly due to not calling `glStencilMask(0xFF)` before `glClear()` (a stencil mask of `0x00` was still active from the end of the previous frame). The reason this was difficult to track down as a problem source is that `glStencilMask`'s interaction with `glClear` isn't currently documented (see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glStencilMask.xhtml), at least not explicitly.

As for *why* this fixed the issue presented in this post, I'm still not sure, since even if the stencil buffer wasn't cleared, those water surface pixels should have still been rejected via stenciling. I considered deleting the question, but decided to keep it up in case someone else runs into a similar problem.

---
Tags: opengl, shaders, glsl, fragment-shader, stencil
---


# Question
Title: LibGDX Bounding system with tiledMap, 3D model player and ortho cam
Begins explaining my achieve: as I said in my last question, I am tryna makin' a 2D game with 3D player as Factorium. For hours I am tryna to make a kinda of bounding system:

1)Camera will follow player untill the left border of the screen will reach the left edge of the map

2)If left edge has been reached, only player keep walking towards left

3)Once player come back, camera will follow player again only when it will have reached the right distance

These steps for each side

First image: left edge of the map still not reached, so camera keep following player constraints it at its center.

Second image: camera reached it, but layer kept waling, then begins come back

Thirds image: distance between player and left edge is at lest as half camera viewport, so camera begins follow player again.

Of course, I tried something...

```
/**
 * Using tile map proeprties
 * @param translateCords how much player has to be moved
 * @return if the player can me moved<br> e.g. if the camera will not be over the map's edge
 * after have been moved
 */
private boolean canPlayerMove(Vector3 translateCords) {
    Vector3 playerPos = this.entityPlayer.getPosition();
    Vector3 futurePos = playerPos.add(translateCords.x, translateCords.y, 0);

    TiledMapTileLayer.Cell cell = ((TiledMapTileLayer)this.tiledMap.getLayers().get(0)).getCell((int)futurePos.x, (int)futurePos.y);
    return cell.getTile().getProperties().containsKey("blocked");
 }

```

This for move camera

```
     /**
 * @param translateCords how much camera has to be moved
 * @param camPos current camera position
 * @return if the camera can me moved<br> e.g. if the camera will not be over the map's edge
 * after have been moved
 */
private boolean canCameraMove(Vector2 translateCords, Vector3 camPos){
    if( (translateCords.x < 0 && camPos.x - this.viewportWCam >= 0) ||
        (translateCords.x > 0 && camPos.x + this.viewportWCam <= this.widthWorld) ||
        (translateCords.y < 0 && camPos.y - this.viewportHCam >= 0) ||
        (translateCords.y > 0 && camPos.y + this.viewportHCam <= this.heightWorld)) {
        return true;
    }
    return false;
}

```

I tried a lots of other stuff...

# Answer
> 0 votes
To make the camera be centered on the player, but also not pan beyond the bounds of the map you simply need to clamp the camera position in such a way that is never is more than half the visible distance from an edge.

So for example

```
Vector2 playerPos = /* you set this somehow */
float mapWidth = /* this should be the width of your map in world space */
float mapHeight = /* this should be the height of your map in world space */

float cameraX = Math.min(Math.max(playerPos.x, camera.viewportWidth / 2.0f), mapWidth - camera.viewportWidth / 2.0f);
float cameraY = Math.min(Math.max(playerPos.y, camera.viewportHeight / 2.0f), mapHeight - camera.viewportHeight / 2.0f);
camera.position.set(cameraX, cameraY, 0);
camera.update();

```

Side note; the above fails if the camera viewport is larger than the entire map.

---
Tags: java, libgdx
---


title: Behavior tree: why?

text:
# Question
Title: Behavior tree: why?
I am new to UE4 and game programming altogether. Following multiple tutorials and documentations I see mentions of behavior trees. In tutorials they do not use them in favor of blueprints because they do not want to complicate it.

I can find many resources about behavior trees with "HOW" but I can not find any "WHY". So my question is, why does it exist and why should I learn it, or if I even should? What are advantages of it comparing to blueprints or even writing my own code?

# Answer
> 1 votes
Personally from going from a finite state machine to a behavior tree i find there are multiple advantages:

1. Iteration time: With a behavior tree you have modules that are kind of like Lego-blocks, so you can put together a couple of behaviors and you can have an AI up and running rather quickly. Say you want it to chase the player. You create a sequence called "Chase Player", you make it rotate towards the player, you set the speed and then finally you tell it to move, and then it will repeat those steps untill either its out of range or any other condition you set for "Chase Player"
2. Modularity: As said above, you have several nodes which are the building blocks of the AI. Those are different parts that come together to create a functioning AI. And its only your imagination that will limit what the AI can do. And you can define the parameters yourself, say in "Chase player" the speed node needs to be 10, but in "Flee" the speed node needs to be 20. It's all decoupled from eachother as you create individual nodes, which makes it flexible.
3. Tree-like structure The behavior tree is a tree as the name suggests, which means each composite node, or a root node / a sub root node, (ie Chase player) have branches that have their own nodes, or leaves if you want to call it that. Meaning each composite node controls their own branches and nodes attached. Again, this allows for modular and decoupled design. Meaning you can have 1 composite node have 10 branches for one behavior, while another composite node may have 2 or 5, it's all up to you to decide how complex a behavior should be.

So yea, i would suggest learning Behavior Trees for those simple reasons, it might have a steep learning curve as there are a lot of concepts to wrap your head around in the start, but once you get familiar with it, prototyping AI becomes really easy. And also it has been around since the Halo days, and it's still widely used in games, so if you need reference, hit up some games and study their behavior. Happy dev'ing.

# Answer
> 1 votes
Taken from a reddit thread: "Most of the non-blackboard AI functions are really buggy anyways, and I was only able to get error tolerant AI using the behavior tree."

* this indicates that if using Behavior trees, it is harder to make bad errors in your AI

Taken from a reddit thread: "In my (admittedly very limited) experience, it's biggest benefit is that it's a tool designed around creating AI specifically. It makes you structure your logic in a way that is visually easier to troubleshoot in simulation as your AI gets more complicated.. but logically I don't think it does anything magical that couldn't be done without it."

* this also indicates the same and also that the more complex your AI, the more Behavior trees shine.

https://www.reddit.com/r/unrealengine/comments/6t1ca0/advantages\_of\_using\_behavior\_tree\_so\_far\_its\_more/

---
Tags: ai, unreal-4, behavior-tree
---


# Question
Title: How to avoid banding with raymarched fog?
I have a raymarching shader for fog. It works well but It creates artifacts in the form of banding:

I understand the problem: The step size is too large and the sample points above the ground are not hitting the floor until the distance is bigger again.

However, How can this be reduced/ avoided?

My Shader looks like this:

```
float4 PS(PixelShaderInput input) : SV_TARGET {
    float3 rayStart = input.WorldPos.xyz;
    float3 viewDirection = normalize(input.WorldPos.xyz-CamPositionWS.xyz);
    float depth = linearize_depth(DepthTexture.Sample(DepthSampler, input.UV).x, NearPlane, FarPlane);
    float4 result = float4(FogColor, 0);
    float stepSize = 300;
    float stepAmount = ((NoiseTexture.Sample(Sampler, input.UV * 64).x)) * 64;
    [unroll(96)]
    while (stepAmount < depth) {
        float3 samplePos = rayStart + (viewDirection*stepAmount);
        stepAmount += stepSize;
        float fogDist = distance(samplePos, FogCenter);
        if (fogDist > FogRadius)
            continue;
        result.a += density(fogDist,FogRadius)*FogDensity;
        if (result.a >= 1) {
            result.a = 1;
            break;
        }
    }
    result = saturate(result);
    return result;
}

```

# Answer
Instead of increasing your sample depth by `stepSize` every time, why not divide `depth` by `floor(depth/stepSize)` and incrementing by that? That will give you *n* evenly-spaced sample points between camera and the surface.

Then the step length will vary slightly to give the same number of samples on proximate points.

It would still give you a transition as the number of sample points increases (say your stepSize is `1` by default and depth transitions from `4.999` to `5.0`, you'd go from 4 sample points at `1.25`, `2.5`, `3.75`, `4.999` to 5 points on integers 1-5, but assuming your fog is homogenous, that shouldn't be too jarring.

Let's say we want a sample every 1 unit by default, then look at some different depths: 4, 4.5, 5, 5.5, 6

* 4.0: 1, 2, 3, 4 \[4 samples, 1 unit step\]
* 4.5: 1.125, 2.25, 3.375, 4.5 \[4 samples, 1.125 unit step\]
* 5.0: 1, 2, 3, 4, 5 \[5 samples, 1 unit step\]
* 5.5: 1.1, 2.2, 3.3, 4.4, 5.5 \[5 samples, 1.1 unit step\]
* 6.0: 1, 2, 3, 4, 5, 6 \[6 samples, 1 unit step\]
> 1 votes

---
Tags: hlsl, fragment-shader, raymarching
---


# Question
Title: Starcraft 2 Editor: I want to make two players share their income
I have a scenario where there are 4 teams vs. a raging Zerg horde constantly attacking them. The idea was allow that player 1 & player 2 in the same team share their income, so that one player could focus on getting the income (SCV income as they deliver the goods) and the other defending.

I haven't gotten the trigger right yet. Anyone have some tips for me?

# Answer
You'll want to look in triggers for an action called, "Set Alliance Aspect". Then look to have them share "Resource Spending". You might have to run it twice so it works in both directions, I'm not sure. I haven't gotten a chance to play around with this feature, I only recently discovered it myself.

Anyway, good luck. Hope this helps.
> 1 votes

---
Tags: map-editor, starcraft-2
---


title: Seam on UV Sphere

text:
# Question
Title: Seam on UV Sphere
I created a uv sphere model in Blender, and I'm loading it as an obj into my OpenGL game. I'm attempting to model a 2d image as a texture for this sphere to make the moon, but I've run into this issue.

The moon texture WITH my attempted fix is here:

I have looked hard for a solution, and I've found others with similar problems. However, I can't figure out how to implement their solutions. I don't understand what they're trying to say enough to fix it. They mention something about the wrapping of the texture coordinates from 1.0 to 0.0 where the triangles meet.

What is being rendered appears to be the entire correct moon model for 95% of the sphere and then the entire image file rendering between this 0.95 and 1.0.

Any help with understanding this or solving it would be greatly appreciated. I'm loading the obj with the code seen here.

# Answer
It looks like in your code you are trying to fix the seam by resetting the texture coordinates to match up where they join:

```
addedTextures.put(currentVertexPointer * 2 + 0, tex.x == 0 ? 1 : tex.x);

```

This *creates* the problem. One strip of longitude triangles contains texture coordinates that should go from 0 up to slightly above 0, and you've changed them to be from 1 *down* to slightly above 0. This creates the "entire image file rendering between this 0.95 and 1.0" effect you are seeing.

Remove this code.

You should get a seamless sphere if the texture coordinates on the model vary from 0 to 1 exactly, and the texture parameters have `GL_TEXTURE_WRAP_S` set to `GL_REPEAT` (not strictly necessary for this particular model, but useful in general for wrapping textures).
> 0 votes

---
Tags: opengl, geometry, sphere
---


# Question
Title: How to calculate the Forward, Up, Right vectors using the rotation angles?
As the title says, I have the pitch and the yaw of an object, How do i use them to calculate the forward, up, right vectors (like the ones in unity), I've searched everywhere and only could find the forward vector.

# Answer
> 1 votes
Assuming your axes are set up like Unity's...

```
forward.x =  cos(pitch) * sin(yaw);
forward.y = -sin(pitch);
forward.z =  cos(pitch) * cos(yaw);

```

Since pitching acts around the right axis, you can neglect pitch for that case. Then it's basically the same as the forward axis, shifted by 90 degrees of yaw (turning sine into cosine and cosine into negative sine)

```
right.x =  cos(yaw);
right.y =  0;
right.z = -sin(yaw);

```

And the up vector is just the cross product of the two.

```
up = cross(forward, right);

```

Or equivalently:

```
up.x = sin(pitch) * sin(yaw);
up.y = cos(pitch);
up.z = sin(pitch) * cos(yaw);

```

---
Tags: 3d, vector
---


title: Transforming Vector3 points to Vector2

text:
# Question
Title: Transforming Vector3 points to Vector2
I'm trying to convert a list of Vector3 on Vector2 because I need to put them in a graph like this:

The graph is easy to do having the Vector2 list, but I have a non-trivial problem obtaining the Vector3 Points:
As you can see, I get them using a **Plane** which can be in any orientation and rotation.
What formula can I use to convert them so I get X,Y points no matter the rotation of the plane.

*PD: I use this code to do the job but it doesn't work on different positions and rotations of the plane...*

```
projectedPosition.X = Vector3.Dot(ballPosition - planeOrigin, planeX);
projectedPosition.Y = Vector3.Dot(ballPosition - planeOrigin, planeY);

```

*PlaneY = Vector3.up & PlaneX = plane.transform.forward*

# Answer
> 1 votes
> PlaneY = Vector3.up & PlaneX = plane.transform.forward

One of these things is not like the other. You're using a global axis vector for one, and the plane's axis vector for the other. Try this instead:

```
PlaneY = -plane.transform.right;
PlaneX =  plane.transform.forward;

```

Or:

```
var localPosition = plane.transform.InverseTransformPoint(ballPosition);

projectedPosition.X =  localPosition.Z;
projectedPosition.Y = -localPosition.X;

```

---
Tags: unity, c#, vector, linear-algebra
---


# Question
Title: How can I convert a rigidbody velocity value to some normal reading speed value?
```
void Update()
    {
        var vel = rigidbody.velocity;
        movementSpeedUiText.text = vel.ToString();

```

The result is :

what I understand from this ? what is the speed ? I don't want to know only if the player is moving or not but what is the speed. what I see is some vector3.

This is the complete script :

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

public class PlayerSpeedDistanceController : MonoBehaviour
{
    public GameObject target;
    public GameObject speedArea;
    public float speed;
    public Animator animator;
    public Text movementSpeedUiText;
    public Text distanceFormTargetUiText;
    public Text playerDirectionUiText;

    private float distance;
    private Rigidbody rigidbody;
    private Vector3 lastPosition;
    private bool isMoving;

    // Start is called before the first frame update
    void Start()
    {
        lastPosition = transform.position;
        isMoving = false;

        rigidbody = GetComponent<Rigidbody>();

        movementSpeedUiText.text = animator.GetFloat("Forward").ToString();
        distanceFormTargetUiText.text = Vector3.Distance(transform.position, target.transform.position).ToString();
        playerDirectionUiText.text = transform.forward.ToString();
    }

    // Update is called once per frame
    void Update()
    {
        if (isMoving == false)
        {
            movementSpeedUiText.text = "0";
        }
        else
        {
            movementSpeedUiText.text = animator.GetFloat("Forward").ToString();
        }
        distanceFormTargetUiText.text = Vector3.Distance(transform.position, target.transform.position).ToString();
        playerDirectionUiText.text = transform.forward.ToString();

        if (transform.position != lastPosition)
            isMoving = true;
        else
            isMoving = false;

        lastPosition = transform.position;
    }
}

```

because the player have animator and also some more animators on the childs the movement speed is affected by this animators. even if the player is not moving he is still looks like moving when calculating the speed.

"Forward" is parameter of the HumanoidWalk speed so when I press the W key and the player is moving it's showing the value of the "Forward" parameter.

and because when the player is not moving I don't press on W or any other key it's showing in the movementSpeedUiText text some E long number. That's why I added the part that detect if the player is moving or not and if not I assign "0" to the text.

The problem now is when I press on the W key and move the player the text is stuttering flickering.

# Answer
Sounds like you want something like...

```
velocity.magnitude.ToString("F1");

```

This takes the vector velocity, converts it to a scalar speed, and expresses it as a text string in "Fixed-point" notation ("F") with one digit after the decimal ("1").

See Standard Numeric Format Strings for more ways you can control how the value is represented in text.
> 1 votes

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


# Question
Title: Experiencing strange behavior in Unity when rotating a 2D GameObject according to the slope it is standing on
I am trying to rotate a square GameObject, so it appears to be standing perpendicular to the slope underneath it. However, when above a slope, the square constantly "spins"; it seems like the rotation is set and then immediately set back to 0, causing it to jitter.

I am currently using a RayCast based character controller instead of rigidbody. To change the rotation, I added the follow line of code following the vertical RayCast:

```
if (_raycastHit)
    {
       transform.rotation = Quaternion.FromToRotation(transform.up, _raycastHit.normal) * transform.rotation;

    ...
    }

```

It calculates and rotates the square correctly, but I am not sure why it resets back to 0 every other frame. To avoid taking up too much space, the character controller I am using is hosted on GitHub here. Specifically, this is in the `moveVertically()` method.

# Answer
It looks like you might want something as simple as:

```
transform.rotation = Quaternion.LookRotation(Vector3.forward, _raycastHit.normal);

```

Or, if you rotate your character to flip them, you can use `transform.forward` instead of `Vector3.forward`.
> 0 votes

---
Tags: unity, 2d, rotation, raycasting
---


# Question
Title: Need help with optimizing loops scanning for enemies in tile based horizontal scroller
I'm looking for an optimization for my loops searching for enemies in a tile based horizonal scroller. My enemy array is in a struct and I am looping through the array with 3 loops. First loop finds the enemy on the left side of the screen within the array, the second loop finds the enemy on the right side of the screen. The third loop then displays all enemies that fall within the two parameters.

This routine certainly seems to do the job, but it seems too bulky being 3 loops. Any suggestions for better optimizations to cull down the code length or improvements in speed?

```
void apple()
{
    unsigned char baddyStart = 0;
    unsigned char baddyEnd = 0;
    unsigned char enemyLow = 0;
    unsigned char enemyHigh = 0;

    unsigned char windowStart = player.tile_X_position - 1;
    unsigned char windowEnd = player.tile_X_position + NEAR_PLAYER;

    unsigned char arrayScan = 0;

    if (windowEnd > MAX_PLAYER_POS)
    {
        windowEnd = MAX_PLAYER_POS;
    }

    //need to find enemy closest to player in window
    for (temp1 = 0; temp1 < enemies_per_level; temp1++)
    {
        baddyStart = enemy_locations[temp1].tile_X_position;

        if (baddyStart == windowStart)
        {
            //found the lowest location in window
            enemyLow = temp1;
            break;
        }
    }

    //find the enemy furthest to player in window
    for (temp2 = temp1; temp2 < enemies_per_level; temp2++)
    {
        baddyEnd = enemy_locations[temp2].tile_X_position;

        if (baddyEnd == windowEnd)
        {
            //found the highest location in window
            enemyHigh = temp2;
            break;
        }
    }

    //show the ranges
    printf ("enemyLow = %d\n", enemyLow);
    printf ("enemyHigh = %d\n", enemyHigh);
    printf ("baddyStart = %d\n", baddyStart);
    printf ("baddyEnd = %d\n", baddyEnd);

    arrayScan = enemyLow;

    while (arrayScan <= enemyHigh)
    {
        baddyStart = enemy_locations[arrayScan].tile_X_position;

        if(baddyStart >= baddyEnd)
        {
            //printf("GREATER THAN\n");
            return;
        }

        if (baddyStart == 0)
        {
            //printf("NOT EXISTING\n");
            //baddy deleted
        }//to bypass deleted baddies

        printf("arrayScan=%d   \n", arrayScan);
        printf("%d    ", enemy_locations[arrayScan].tile_X_position);
        printf("%d    ", enemy_locations[arrayScan].x_displacement);
        printf("%d    ", enemy_locations[arrayScan].y_position);
        printf("%d    ", enemy_locations[arrayScan].sprite_number);
        printf("%d    ", enemy_locations[arrayScan].movement);
        printf("%d    ", enemy_locations[arrayScan].energy);
        printf("%d    ", enemy_locations[arrayScan].param1);
        printf("%d    ", enemy_locations[arrayScan].param2);
        printf("\n");

        arrayScan ++;
    }
}

```

EDIT.

I can bring the function a little closer to optimization by combining the find the minimum and maximum to 1 loop instead of 2 loops.

void apple()
{
    unsigned char baddyStart = 0;
    unsigned char baddyEnd = 0;
    unsigned char enemyLow = 0;
    unsigned char enemyHigh = 0;

    unsigned char windowStart = player.tile_X_position - 1;
    unsigned char windowEnd = player.tile_X_position + NEAR_PLAYER;

    unsigned char arrayScan = 0;

    if (windowEnd > MAX_PLAYER_POS)
    {
        windowEnd = MAX_PLAYER_POS;
    }

    //need to find enemy closest and furthest to player in window
    for (temp1 = 0; temp1 < enemies_per_level; temp1++)
    {
        baddyStart = enemy_locations[temp1].tile_X_position;
        baddyEnd = enemy_locations[temp1].tile_X_position;

        if (baddyStart == windowStart)
        {
            //found the lowest location in window
            enemyLow = temp1;
        }
        if (baddyEnd == windowEnd)
        {
            //found the highest location in window
            enemyHigh = temp1;
            break;
        }
    }

    //show the ranges
    printf ("enemyLow = %d\n", enemyLow);
    printf ("enemyHigh = %d\n", enemyHigh);
    printf ("baddyStart = %d\n", baddyStart);
    printf ("baddyEnd = %d\n", baddyEnd);

    arrayScan = enemyLow;

    while (arrayScan <= enemyHigh)
    {
        baddyStart = enemy_locations[arrayScan].tile_X_position;

        if(baddyStart >= baddyEnd)
        {
            //printf("GREATER THAN\n");
            return;
        }//seems working

        if (baddyStart == 0)
        {
            //printf("NOT EXISTING\n");
            //baddy deleted
        }//to bypass deleted baddies

        printf("arrayScan=%d   \n", arrayScan);
        printf("%d    ", enemy_locations[arrayScan].tile_X_position);
        printf("%d    ", enemy_locations[arrayScan].x_displacement);
        printf("%d    ", enemy_locations[arrayScan].y_position);
        printf("%d    ", enemy_locations[arrayScan].sprite_number);
        printf("%d    ", enemy_locations[arrayScan].movement);
        printf("%d    ", enemy_locations[arrayScan].energy);
        printf("%d    ", enemy_locations[arrayScan].param1);
        printf("%d    ", enemy_locations[arrayScan].param2);
        printf("\n");

        arrayScan ++;
    }
}
```
</code></pre>

# Answer
I did eventually come across a way to optimize by using a completely different algorithm that had slipped my mind. I was searching for enemies by using a linear search. Things improved considerably by using a binary search.

```
static unsigned char search(unsigned char value)
{
    if(value < enemy_locations[0].tile_X_position)
    {
        return enemy_locations[0].tile_X_position;
    }
    if(value > enemy_locations[enemies_per_level-1].tile_X_position)
    {
        return enemy_locations[enemies_per_level-1].tile_X_position;
    }
    lo = 0;
    hi = enemies_per_level - 1;
    while (lo <= hi)
    {
        mid = (hi + lo) / 2;
        if (value < enemy_locations[mid].tile_X_position)
        {
            hi = mid - 1;
        }
        else if (value > enemy_locations[mid].tile_X_position)
        {
            lo = mid + 1;
        }
        else
        {
            return enemy_locations[mid].tile_X_position;
        }
    }
    output = enemy_locations[lo].tile_X_position - value;
    if (output < value - enemy_locations[hi].tile_X_position)
    {
        return enemy_locations[lo].tile_X_position;
    }
    else
    {
        return enemy_locations[hi].tile_X_position;
    }
}

```
> 1 votes

---
Tags: c
---


title: Convert a UV shader to Triplanar

text:
# Question
Title: Convert a UV shader to Triplanar
I am doing procedural environment generation using Houdini and Unity. There are two main shader features I want:

1. Vertex-Color Height Blending - I currently have a shader for this which I purchased. It supports Diffuse/Normal/Metallic/Smoothness/Height/Ambient Occlusion and has the following "pragma" (I don't exactly know what this means but maybe it's useful info):

```
 // Physically based Standard lighting model, and enable shadows on all light types
 #pragma surface surf Standard fullforwardshadows

 #pragma target 4.0

```
2. Triplanar shader - Since the environment is procedurally generated, I don't want to do manual UV mapping. I have just been using automatic UVs so far and it doesn't look that great with the Vertex-Color shader. I do have a Triplanar shader that I downloaded but it doesn't support the Vertex-Color stuff.

I would love to find a way to shader combine these two functionalities. How can I support all those types of textures?

# Answer
Somewhere in your shader you'll have a series of texture samples that look something like this...

```
fixed4 diffuse = tex2D(_DiffuseTexture, i.uv);
fixed4 normal = tex2D(_NormalTexture, i.uv);
fixed4 metalness = tex2D(_MetalTexture, i.uv);
// ...

```

You can replace those with a function that does triplanar mapping. Something like...

```
fixed4 sampleTriplanar(sampler2D texture, float3 position, float3 weights) {
    return weights.x * tex2D(texture, position.yz)
         + weights.y * tex2D(texture, position.zx)
         + weights.z * tex2D(texture, position.xy);
}

```

So...

```
fixed4 diffuse = sampleTriplanar(_DiffuseTexture, triplanarPos, triplanarWeight);
fixed4 normal  = sampleTriplanar(_NormalTexture, triplanarPos, triplanarWeight);
// ...

```

Here `triplanarPos` is your worldspace position, scaled to your desired tiling frequency.

`triplanarWeight` is a set of weight coefficients for each projection plane, based on the normal vector. You could calculate it something like...

```
// Give more value to the axes the normal is facing.
float3 triplanarWeight = normal * normal;

// Squaring this can help tighten the blending zone,
// making the result look less feathery.
triplanarWeight *= triplanarWeight;

// Dividing by the total ensures the three weights sum to 1.0.
triplanarWeight /= dot(triplanarWeight, 1.0f);

```

Note that this triples the amount of texture taps in your shader, so it will have a substantial performance impact. You may want to consider whether you need all those separate textures, or if you can pack some of them together to save samples at runtime.

There's also a neat trick CD Projekt RED uses, using conditional branching to save some texture taps in areas where one or two of the projections dominate. They found the branching overhead was worth the savings in texture bandwidth in their case, so that may be worth investigating if you find you need that optimization.
> 1 votes

---
Tags: unity, shaders, textures, vertex-shader, triplanar-texturing
---


# Question
Title: Gizmos not being drawn until GameObject selected
I have implemented Scene loading in my game and have three scenes: `Persistent`, `Main Menu` and `Game`

By default, the player is loaded into the `Persistent` scene, which immediately loads the `Main Menu`, and when the player clicks on Play, `Main Menu` is unloaded and `Game` is loaded.

Now, the two active scenes are `Persistent` and `Game`.

However, I have a script with `OnDrawGizmos` on a GameObject in the `Game` scene. It seems that by default gizmos only begin to be drawn when I click on that GameObject, sort of activating it, and everything works fine. This used to just work before because `Game` was my only scene and Unity automatically selected that first GameObject. Now, with multiple scenes, no GameObject is selected by default and my gizmos won't draw until I manually click on it.

How can I solve this?

# Answer
> 0 votes
I think you're looking for this

> Selection.activeGameObject = {Whatever object you want selected}

---
Tags: unity, debugging, scene
---


# Question
Title: How do I implement an input wrapper like Unity's in SDL2?
This is my first time actually trying to wrap the the SDL event handling functions in a class of my own. I'm trying to achieve a design similar to unity's where you have this static Input class and you can call it's functions whenever to check for various input events.

**Here is the class:**

```
class InputManager
{
private:
    InputManager() = default;
    InputManager(const InputManager& c) = delete;

private:
    static SDL_Event event;
    static bool isKeyPressed;
    static bool isKeyReleased;
    static bool isMousePressed;
    static bool isMouseReleased;

    static int keyIndex;
    static int buttonIndex;

public:
    static InputManager* GetInstance();
    void Update();

public:
    bool KeyDown(int iKeyIndex);
    bool KeyStillDown(int iKeyIndex);
    bool KeyUp(int iKeyIndex);
    bool KeyStillUp(int iKeyIndex);
    bool MouseDown(int iButton);
    bool MouseStillDown(int iButton);
    bool MouseUp(int iButton);
    bool MouseStillUp(int iButton);
};

```

**and it's implementations:**

```
SDL_Event InputManager::event;
bool InputManager::isMousePressed = false;
bool InputManager::isMouseReleased = false;
bool InputManager::isKeyPressed = false;
bool InputManager::isKeyReleased = false;

InputManager* InputManager::GetInstance()
{
    static InputManager* instace = new InputManager();
    return instace;
}

void InputManager::Update()
{
    SDL_PollEvent(&event);
}

bool InputManager::KeyDown(int iKeyIndex)
{
    if(event.type == SDL_KEYDOWN && event.key.keysym.sym == iKeyIndex && isKeyPressed == false)
    {
        isKeyPressed = true;
        return true;
    }
    else if(event.type == SDL_KEYUP)
    {
        isKeyPressed = false;
        return false;
    }
    else
        return false;
}

bool InputManager::KeyStillDown(int iKeyIndex)
{
    if(event.type == SDL_KEYDOWN &&
       event.key.keysym.sym == iKeyIndex)
        return true;
    else
        return false;
}

bool InputManager::KeyUp(int iKeyIndex)
{
    if(event.type == SDL_KEYUP && event.key.keysym.sym == iKeyIndex && isKeyReleased == false)
    {
        isKeyReleased = true;
        return true;
    }
    else
    {
        isKeyReleased = false;
        return false;
    }
}

bool InputManager::KeyStillUp(int iKeyIndex)
{
    if(event.type == SDL_KEYUP &&
       event.key.keysym.sym == iKeyIndex && event.key.repeat == 0)
        return true;
    else
        return false;
}

bool InputManager::MouseDown(int iButton)
{
    if(event.type == SDL_MOUSEBUTTONDOWN && event.button.button == iButton && isMousePressed == false)
    {
        isMousePressed = true;
        return true;
    }
    else if(event.type == SDL_MOUSEBUTTONUP)
    {
        isMousePressed = false;
        return false;
    }
    else
        return false;
}

bool InputManager::MouseStillDown(int iButton)
{
    if(event.type == SDL_MOUSEBUTTONDOWN && event.button.button == iButton)
        return true;
    else
        return false;
}

bool InputManager::MouseUp(int iButton)
{
    if(event.type == SDL_MOUSEBUTTONUP && event.button.button == iButton && isMouseReleased == false)
    {
        isMousePressed = true;
        return true;
    }
    else
    {
        isMousePressed = false;
        return false;
    }
}

bool InputManager::MouseStillUp(int iButton)
{
    if(event.type == SDL_MOUSEBUTTONUP && event.button.button == iButton)
        return true;
    else
        return false;
}

```

Now I know this class has it's flaws and it certainly does, for instance the `KeyUp(int iKeyIndex)` and `MouseUp(int iButton)` functions seem to always be true unless I move the mouse or do any type of event. I'm aware of issue and why it's happening but I can't seem to find a solution for it. I would like to know how to fix these issues.

# Answer
> 1 votes
First, let's look at the doc for SDL\_PollEvent, specifically the example code provided:

```
while (1) {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        /* handle your event here */
    }
    /* do some other stuff here -- draw your app, etc. */
}

```

and the remarks:

> If event is not NULL, the next event is removed from the queue and stored in the SDL\_Event structure pointed to by event. The 1 returned refers to this event, immediately stored in the SDL Event structure -- not an event to follow.

---

There are a couple of issues with this class, as you mention, directly related to how the SDL\_PollEvent is used:

* it can handle only *one* event per frame, there *could* be more than one event per frame;
* it will "handle" *all* the events, including the SDL\_WindowEvent, SDL\_QuitEvent, etc. You don't want to handle those events in your InputManager.

I have not worked with Unity's input manager, but the way it looks, it is keeping some kind of *state*. It looks a bit like what you've tried to do: you need to update a *state* with the *events* as a specific phase, so that your game code can consult the input state as it needs, without modifying the state. You need to do this for each key.

The following pseudoc++.

```
class InputManager
{
private:
  enum class KeyState
  {
    JustUp
    Up
    JustDown
    Down
    DownRepeat
  };

  using keyIndex = int;
  map<keyIndex, KeyState> m_keyStates;
  map<keyIndex, KeyState> m_mouseStates;

  // singleton ctor stuff

public:

  // singleton getter stuff

  // This should be called at the beginning of each frame to tell your manager
  // that a new frame is starting. Use this to move the keys that were "just*"
  // to a "*" state.
  void prepareFrame()
  {
    for( auto& [keyIndex, state] : m_keyStates )
    {
      if ( state == JustUp )
        state = Up;
      else if ( state == JustDown )
        state = Down
    }
  }

  // This is called by your main loop to update the state of your input manager.
  // Each (keyboard) `key` or (mouse) `button` event will be sent to this
  // function.
  void handleInputEvent( const SDL_Event* event )
  {
    assert( event->type == key || event->type == button );

    if ( event->type == key )
    {
      KeyState newState;

      if ( event->key.type == SDL_KEYDOWN )
        newState == KeyState::JustDown;
      else if( event->key.type == SDL_KEYUP )
        newState == KeyState::JustUp;

      // This event is sent by the OS, it is based on user's preferences; Useful
      // when text is typed, less useful in the context of a game.
      if ( event->key.repeat != 0 )
        newState == KeyState::DownRepeat;

      m_keyStates[event.key.keysym.sym] = newState;

    }
    else if ( event->type == button )
    {
      // Do the same here for handling the (mouse) `button`.
    }
  }

  // Assuming your "KeyUp" mean "Has the key just been released?"
  bool KeyUp(int iKeyIndex) const
  {
    if ( m_keyStates.count( iKeyIndex ) > 0 )
    {
      if ( m_keyStates[iKeyIndex] == JustUp )
        return true;
    }
    return false;
  }

  // Assuming your "KeyStillUp" mean "Is the up now?"
  bool KeyStillUp(int iKeyIndex) const
  {
    if ( m_keyStates.count( iKeyIndex ) > 0 )
    {
      if ( m_keyStates[iKeyIndex] == JustUp || m_keyStates[iKeyIndex] == Up )
        return true;
      else
        return false;
    }
    // It's not in the map, so we assume it has not been interacted with yet, we
    // consider it's up by default
    return true;
  }

  // This should be used if you want to offer the same "key repeat" experience
  // as the user has with their OS.
  bool KeyDownOS(int iKeyIndex) const
  {
    if ( m_keyStates.count( iKeyIndex ) > 0 )
    {
      if ( m_keyStates[iKeyIndex] == JustDown
        || m_keyStates[iKeyIndex] == DownRepeat )
        return true;
    }

    // It's not in the map, so we assume it has not been interacted with yet, we
    // consider it's up by default
    return false;
  }

  // Use the same patterns as above to implement the KeyDown, KeyStillDown,
  // Button* functions...

}

```

Now you need to have something like this in your main loop to update this state.

```
while (1) {

  InputManager::GetInstance()->prepareFrame();

  SDL_Event event;
  while ( SDL_PollEvent( &event ) ) {

    switch( event.type )
    {
      case key:
      case button:
        InputManager::GetInstance()->handleInputEvent( &event );
        break;

      // case OTHERS....
    }
  }

  // the rest of your game loop....
}

```

This should help you get you started.

Final notes:

* I've not worked with SDL before, so this is a rough and needs to be tuned with sweat and tears. I found that handling inputs is some of the most annoying code to write.
* I'm not sure how SDL handles key-modifiers (Shift, Ctrl, Alt), nor how you would like to handle them. E.g. one key could be received as `K` (upper-case k), or `Shift+k` (Shift as modifier, with lower-case k).

---
Tags: c++, input, sdl2
---


# Question
Title: Unity Animation makes object spawn at x0 y0 z0
I was making an animation for a coin in my game in Unity, and when I was testing the full game, I saw that the coin is spawning at `x0` `y0` `z0` and is doing the animation there. Then I realized that it was the animation, that increases and decreases `y position` and `y rotation`, starting at 0.

So, I need to make the animation, that increases and decreases `position y` and `rotation y`, without affecting the actual position, because it will be different the position of the coins each time.

In a while I will upload a screenshot for describing better the problem.

Any clue?

# Answer
> 2 votes
Put the animated GameObject inside another GameObject. So for example, you have a prefab named "Coin" with a child inside it named "Coin Mesh" or something like that. Then you can animate the mesh's *local position* within its parent, without it disrupting the coin's world position.

It's also generally a good idea to delete keyframes for properties you aren't using. So for example, when you added the transform position to the animation, it probably created initial keyframes for the X, Y, and Z axes. If you are only animating the coin along the Y-axis, you can delete the keyframes for the X and Z axes so that the animation won't override the GameObject's position along those axes.

---
Tags: unity, animation, coordinates
---


# Question
Title: Get Prefab Asset From Gameobject in Edit Mode
I want to get a **prefab asset** (that resides in **Project Window**) and assign it to a field like the one you get when you manually drag the prefab asset from **Project Window** to GameObject field:

But when I try to do the same thing in code (and in Edit Mode) with this function:

```
GameObject prefab_instance = PrefabUtility.GetNearestPrefabInstanceRoot(gameobj) as GameObject;

```

I get a **prefab instance** but not a **prefab asset**:

How do I get a reference to **prefab asset** from the gameobject that was created from it?

# Answer
If I understand what you want to do, then I think you want to use PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot in combination with AssetDatabase.LoadAssetAtPath.

Like so:

```
string path = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(gameobj);
GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path);
Debug.Log(go.name, go);

```
> 2 votes

# Answer
If you want to find prefab variant of an instance you should use

```
PrefabUtility.GetCorrespondingObjectFromSource(YourPrefabInstance)

```

If you want to find orginal prefab of an instance you should use

```
PrefabUtility.GetCorrespondingObjectFromOriginalSource(YourPrefabInstance)

```

It will work only in Editor mode.
> 0 votes

---
Tags: unity
---


# Question
Title: How to make UI image bounce back and forth inside another UI image?
I've been trying to create a battle system for my game, and I've been trying to get a UI image to bounce back and forth inside another image, but for some reason, the UI image goes out of the other UI and bounces back, like so:

Here's the script I add to the moving arrow image, in order to make it bounce:

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

public class JumpSystem : MonoBehaviour
{
    private Vector2 startPosition;
    public int speed;

    // Start is called before the first frame update
    void Start()
    {
        startPosition = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = new Vector2(startPosition.x + Mathf.Sin(Time.time * speed), transform.position.y);
    }
}

```

Is there any way I can prevent this incident from occurring? Please help me understand this and thank you in advance.

# Answer
By using a `RectTransform` instead of a `GameObject` or `Tranform` type, I was able to access the anchorMin and anchorMax inside of the UI. Then, I simply created a private *positionPercentage* float and used `Mathf.PingPong()`, in order to get the back-and-forth movement I desired.

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

public class JumpSystem : MonoBehaviour
{
    public float speed = 0.75f;
    private float positionPercentage; // float changed to allow back and forth movement
    public RectTransform imageTransform; // new type chosen

    void Update()
    {
        positionPercentage = Mathf.PingPong(speed * Time.time, 1); // determines the rate of UI movement

        // implement the positionPercentage movement
        imageTransform.anchorMin = new Vector2(positionPercentage, 0.5f);
        imageTransform.anchorMax = new Vector2(positionPercentage, 0.5f);
    }
}

```
> 0 votes

# Answer
Try to put it in the Lateupdate(). or try to use mathf.lerp.
> 0 votes

# Answer
Disclaimer: There's probably an off-the-self way to get this result from Unity with a built in `lerp` of some kind. That's a fine idea & it would probably be my first choice. This answer is meant to explain how to get the result manually.

Let's take the expression below apart, understand what it does & doesn't do, and then fix it:

`startPosition.x + Mathf.Sin(Time.time * speed)`

Starting from the inside & thinking about the math in general, `Mathf.Sin(n)` will return a value between -1 & 1 (inclusive).

By using `Time.time` instead of `n` you get something that will oscillate between -1 & 1 over time.

Multiplying `Time.time` by `speed` will scale the **rate** of oscillation. A `speed` of 2 will double the rate whereas a `speed` of 0.75 will make it one fourth slower.

Adding `startPosition.x` will **displace** the result. For instance, if `startPosition.x` has a value of 10.0, then the net result is an oscillation between 9.0 and 11.0.

Thus, the original expression alters the rate and midpoint of the oscillation.

Since you want to oscillate in a **region of a particular size**, you need to introduce math to scale the **range** the oscillation. Let's say you want to keep the animation within the bounds of 20 & 25. That requires a range of 5. But recall that `sin` goes from -1 to 1, so a scaling factor of 2.5 would change it to -2.5 to 2.5, which is a total range of 5 (part of our goal):

```
xMin = 20;
xMax = 25;
range = xMax - xMin;
scale = range/2.0;
x = scale * Mathf.Sin(Time.time * speed);

```

The last step is to move it to the desired location. One way to think about that is to recall that `sin` oscillates about a midpoint. If the target region is 20 to 25, then the target midpoint would be 22.5 and if we check the math, 22.5 ± 2.5 gives a result of 20 to 25. Note that the midpoint is actually the same as the starting bound plus half the range, which is the same thing as the scale. So the final expression would be something like this:

```
xMin = 20;
xMax = 25;
range = xMax - xMin;
scale = range/2.0;
xMid = mMin + scale;
x = xMid + scale * Mathf.Sin(Time.time * speed);

```

The code above *could* be simplified, however it has the benefit of being very explicit: you know what each part does making it easier to understand, modify & maintain. Adjust as necessary to fit your needs.
> 0 votes

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


# Question
Title: Make movement speed relative to player character rotation in Unity?
I'm doing a strict topdown 2D game where the character looks at wherever the mouse is pointing (same perspective as GTA 2 or Darkwood) . I want to make movement speed for strafing and backing up slower than walking forward. I'm having a hard time figuring out how to do this using Angle() and understanding vector math.

Any help would be appreciated

# Answer
The dot product between the movement vector and character’s looking vector will give you a scale between -1 and 1. This could help you scale your movement based on the angle that the movement differs from the looking direction.

You could also just get the absolute value of angle between these vectors and have different cases like if \> 80 degrees, slow by 50% (strafing) if \> 160% slow by 75% (backwards)
> 0 votes

---
Tags: unity, movement, vector
---


# Question
Title: Best practices for labeling game versions?
Does anyone know if there's a best practice for labeling game versions.

I'm not sure if there's a standard name for it other than versioning but what I mean is basically:

* 1.0
* 1.1
* 1.2
* 1.3.1 beta

# Answer
There is no standard, but you should do it in a way that makes sense to you and contains all the information you may need to track that build. I worked for a company that essentially broke it down like this:

**\[Major build number\].\[Minor build number\].\[Revision\].\[Package\]**

i.e. Version: 1.0.15.2

* **Major build number**: This indicates a major milestone in the game, increment this when going from beta to release, from release to major updates.
* **Minor build number**: Used for feature updates, large bug fixes etc.
* **Revision**: Minor alterations on existing features, small bug fixes, etc.
* **Package**: Your code stays the same, external library changes or asset file update.

Combined changes roll over to the most significant change. For example, if you're incrementing the minor build number, the revision and package both reset to 0.

Even though the categories are defined, there's still ambiguity for what kind of features actually cross over between a revision and a minor build number. It's up to you. If you make lists of the features that will need to be implemented before each increment, you'll also have a plan to follow, but in the end it's your decision as to what fits into each category.
> 31 votes

# Answer
Stack Overflow has a great discussion on this called How To Do Version Numbers, which references the Versioning Style Guide.

Summary:

* MAJOR version when you make incompatible API changes
* MINOR version when you add functionality in a backwards-compatible manner
* PATCH version when you make backwards-compatible bug fixes
* Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format
> 11 votes

# Answer
As far as I know, there is *no* standard for that. Practice will vary depending on companies, teams and projects: **there is no such thing as a best practice.** The most important thing is not the actual convention, but the fact that everyone sticks to it.

That said, the scheme you mentioned is quite common for released games. 1.0 will typically be the gold master, and patches will start from there: 1.1, 1.2... It'as also used in pre-release customer versions such as private or open betas.

For games in development I've rarely seen this system used. It is much more common to refer to a build by its atomic change ID (e.g. Perforce changelist number). This is particularly useful for a middle-scale project where everything (code & assets) is stored on the same repository, and continuous integration is in place. In this case, **having both an atomic change number *and* a version number is redundant and error prone.** Some builds will be promoted to a milestone after QA: alpha, beta, release candidate, and labelled as such.

For big projects, the simple concept of a "game version" doesn't apply anymore. You'll have several platforms, SKUs, languages, single-player mode, multi-player mode, etc. Managing versions becomes then a full-time job (sometimes called a *data manager* -- this is Ubisoft terminology, probably called differently elsewhere), the labeling scheme is then much more complex and highly dependant on the actual game being made.
> 7 votes

# Answer
Game Versions Really depend on how you want to use it like 1.0.2021 or maybe 1.1.4.3. It can mean different things depending on the company/small team/person that created the game.
> -1 votes

---
Tags: version-control
---


# Question
Title: Select box-shape grid between two positions on tilemap
I want to be able to click and hold on a certain point and mark it as `startPosition`. Then, while the mouse is held down and moved, mark that second position as `endPosition`.

When the mouse is finally released, I want to get all the positions between those two points.

Here is my code so far:

```
for (float x = startPosition.x; x <= endPosition.x; x++)
        {
            for (float y = startPosition.y; y <= endPosition.y; y++)
            {
                Vector3Int newPosition = Utilities.GridPosFromWorldPos(new Vector2(x, y));
                if (!selectedPositions.Contains(newPosition)) { selectedPositions.Add(newPosition); }
            }
        }

```

This works only when dragging up and/or to the right. As soon as I try to go to left or bottom, the `endPosition` coordinates become smaller than the `startPosition` coordinates, which breaks the for loop.

How can I solve this?

# Answer
> 1 votes
Solved like this:

```
        Vector3 lowerLeftTile = new Vector3(Mathf.Min(startPosition.x, endPosition.x), Mathf.Min(startPosition.y, endPosition.y));
        Vector3 upperRightTile = new Vector3(Mathf.Max(startPosition.x, endPosition.x), Mathf.Max(startPosition.y, endPosition.y));

        for (float x = lowerLeftTile.x; x <= upperRightTile.x; x++)
        {
            for (float y = lowerLeftTile.y; y <= upperRightTile.y; y++)
            {
                Vector3Int newPosition = Utilities.GridPosFromWorldPos(new Vector2(x, y));
                if (!selectedPositions.Contains(newPosition)) { selectedPositions.Add(newPosition); }
            }
        }

```

---
Tags: unity, 2d, mathematics, tilemap, grid
---


# Question
Title: How do I avoid StackOverflow due to circular dependencies in a FSM?
I have a FSM defined as the following which essentially iterates though the actions in the current state and transitions to another state depending on the result of calling the Act function on the current action.

```
public interface IAction
{
    public abstract IState Act();
}

public interface IState
{
    public IAction[] Actions { get; }
}

public class StateController
{
    public IState CurrentState;

    public void Update()
    {
        foreach (var action in CurrentState.Actions)
        {
            var state = action.Act();
            TransitionToState(state);
        }
    }

    private void TransitionToState(IState nextState)
    {
        if (nextState == null || nextState == CurrentState)
        {
            return;
        }

        CurrentState = nextState;
    }
}

```

If I have start implementing my states and setting their actions then things get ugly pretty quickly as I set one of the return states of the LookAction to a new instance of SleepState which itself sets a return state to a new instance of WakeState.

```
public class WakeState : IState
{
    public IAction[] Actions { get; }

    public WakeState()
    {
        Actions = new IAction[]
        {
            new LookAction()
            {
                TargetNotVisibleState = new SleepState() // StackOverflow as this calls SleepState instantiates WakeState in its constructor
            },
            new WaitForTimeElapsedAction(2f)
            {
                TimeElapsedState = new AttackState()
            }
        };
    }
}

public class SleepState : IState
{
    public IAction[] Actions { get; }

    public SleepState()
    {
        Actions = new IAction[]
        {
            new LookAction(true)
            {
                TargetVisibleState = new WakeState()
            },
            new WaitForTimeElapsedAction(2f)
            {
                TimeElapsedState = new ScanState()
            }
        };
    }
}

public class LookAction : IAction
{
    public IState TargetVisibleState;
    public IState TargetNotVisibleState;
    public IState TargetOutOfRangeState;

    public IState Act()
    {
        if (TargetOutOfRange())
        {
            return TargetOutOfRangeState;
        }

        return CanSee() ? TargetVisibleState : TargetNotVisibleState;
    }

    ...

```

How would it be best to avoid this without losing the ability to set any State for the return state in an Action?

# Answer
> 1 votes
You might want to create all your states first, only once they're created you hook them all together. So it means that your state constructors do no create new states, you let your state machine do the creation and the connection.

Another pattern that you could use is to construct all the states upfront, then do a "finalize initialization" pass at it, where you supply all the states that exist and let the states finish up their own initialization (pseudocode):

```
var states = dict(name, IState);

states["WakeState"] = new WakeState();
states["SleepState"] = new SleepState();
states["AttackState"] = new AttackState();

foreach ( var state in states ):
  state->finalizeInit(states);

```

With finalizeInit:

```
class SleepState : IState
{
    public void finalizeInit(dict(name, IState) AllStates)
    {

      Actions = new IAction[]
        {
            new LookAction()
            {
                TargetNotVisibleState = AllStates["SleepState"]
            },
            new WaitForTimeElapsedAction(2f)
            {
                TimeElapsedState = AllStates["AttackState"]
            }
        };
    }
}

```

Yet another option is to let the states tell the state machine which state to go to next by its identifier, not by setting explicit a new state. (pseudoc#)

```
public class StateController
{
    public IState CurrentState;
    private dict(StateName, IState) AllStates;

    public StateController()
    {
      AllStates["WakeState"] = new WakeState();
      AllStates["SleepState"] = new SleepState();
      AllStates["AttackState"] = new AttackState();
      CurrentState = AllStates["SleepState"];
    }

    public void Update()
    {
        foreach (var action in CurrentState.Actions)
        {
            var stateName = action.Act();
            if ( TransitionToState(state) )
              break;
        }
    }

    private void TransitionToState(string nextState)
    {
        if (nextState == "" || nextState == CurrentState.name || AllStates[nextState] == null)
        {
            return false;
        }

        CurrentState = AllStates[nextState];
    }
}

```

Of course, you'll neet to adapt your states and actions to use strings instead of states:

```
public class WakeState : IState
{
    public IAction[] Actions { get; }

    public WakeState()
    {
        Actions = new IAction[]
        {
            new LookAction()
            {
                TargetNotVisibleState = "SleepState" // StackOverflow as this calls SleepState instantiates WakeState in its constructor
            },
            new WaitForTimeElapsedAction(2f)
            {
                TimeElapsedState = "AttackState"
            }
        };
    }
}

public class LookAction : IAction
{
    public string TargetVisibleState    = "";
    public string TargetNotVisibleState = "";
    public string TargetOutOfRangeState = "";

    public string Act()
    {
        if (TargetOutOfRange())
        {
            return TargetOutOfRangeState;
        }

        return CanSee() ? TargetVisibleState : TargetNotVisibleState;
    }
}

```

With these two last options, you'll need to know all the states that exist beforehand because you'll need to create them all from your state machine, but they still give you the option to let the States decide "where to go next".

---

It seems odd to me that you allow multiple changes of state during the same frame.

You may want to prevent this by allowing only one change of state during the frame:

```
    public void Update()
    {
        foreach (var action in CurrentState.Actions)
        {
            var state = action.Act();
            if ( TransitionToState(state) )
              break;
        }
    }

    private bool TransitionToState(IState nextState)
    {
        if (nextState == null || nextState == CurrentState)
        {
            return false;
        }

        CurrentState = nextState;
        return true;
    }

```

Alternatively, you could add a timer during which the state cannot change to another state.

---
Tags: c#, fsm
---


# Question
Title: Batches Count increase when applying GPU instancing
I have camera across a very weird issue where my batches count significantly increase if I enable GPU instancing: Before applying GPU instancing"

After Applying Gpu Instanching:

I have a pylon object where i am sharing the material with standar specular shader.

# Answer
There are a few different ways we can combine objects for rendering.

**GPU instancing** gathers together a buffer of vertices with a buffer of instance transforms, allowing you to draw many differently positioned/rotated/scaled copies *of the same object* in a single draw call, as long as they all use the same material. This also saves some VRAM/bandwidth, since you're sending the vertices just once, rather than again and again for each instance.

**Static or dynamic batching** does something similar, but accomplishes it by baking the transformations for the instances into one big vertex buffer, containing multiple copies of the object(s) in different positions/rotations/scales. Unity can do this either at build time (static batching), or at runtime (dynamic batching). This costs more memory and bandwidth than instancing, but it can combine multiple *different source meshes* into a single call, as long as they're small and all use the same material.

In this case, it sounds like your scene has a lot of *different* meshes using the same material. So when using the static/dynamic batching, Unity is able to combine them into mixed batches, containing multiple different source meshes. That lets it send fewer draw calls in total.

When using instancing, Unity can't combine different source meshes into the same batch, so it has to keep them separate, resulting in more batches in this particular scene.

Some things that could tip the scale:

* If your game is CPU-bound, the CPU-side work required for dynamic batching could be a bottleneck.
* If your game is tight on video memory, the copying of vertex data required for static and dynamic batching could be a limitation.
* If you have only a few copies of lots of different objects, instancing them might not give a big savings.

Because of all these different trade-offs here, the engine can't always pick the best option efficiently on the fly. That's why it's so important to profile, as you've been doing. In your case, it looks like not using instancing is slightly better for this scene, so you can use that information to tune the performance of your game.
> 1 votes

---
Tags: unity, shaders, optimization
---


# Question
Title: How to avoid entities flying far away when tabbing out and then tabbing back in?
I'm developing a game which uses a standard Entity-Component-System.

Every frame, the `PhysicsSystem` runs, which, among other things, updates the position of entities based on their velocity. Something like this:

```
execute(delta: number, elapsed: number) {
  for (let entity of this.scene.query(CT.Transform, CT.Physics)) {
    let transform = entity.get(CT.Transform);
    let physics = entity.get(CT.Physics);

    let movementIncrement = physics.direction.multiply(delta * physics.friction * physics.speed);

    physics.velocity = physics.velocity.multiply(1 - delta * physics.friction).add(movementIncrement);
    transform.pos = transform.pos.add(physics.velocity.multiply(delta));
  }
}

```

This works fine, except there's an issue. When the user switches to another tab, waits some time (let's say 5 seconds), and then tabs back in, sometimes the entities instantly fly away so far that they fly off the map and out of bounds.

I'm not sure why this would happen, as it never happens during normal gameplay. Something to do with the tab becoming inactive for a time, and then active, seems to cause this issue.

I suppose a possible solution is to "pause" the game if the tab loses focus, but I rather the game keep running in the background unless the user manually pauses by hitting escape.

Does anyone know why this is happening? The rest of the game continues functioning normally, it's just the entity positions fly away for some reason.

# Answer
The browser suspends your page to save CPU power during that time.

When tabbing back in the physics engine sees 1 frame with a 5 seconds duration so it moves the objects for that entire 5 seconds before processing friction and what not.

The first thing is your velocity * friction calculation should be a power function, not a linear factor of time.

For example, with `delta = 2.0` and a `friction = 0.25` your formula multiplies by 0.5 `(1 - 2.0 * 0.25)` but if we were to calculate two 1 second frames the result would be 0.5625 `(1 - 1.0 * 0.25) * (1 - 1.0 * 0.25)`

It should be calculated as `velocity * pow(1-friction, delta)`.

The other issue is that `1 - delta * physics.friction` possibly gives you a negative factor when (delta * friction) is larger than 1.
> 1 votes

# Answer
Assuming the browser suspends the execution of the code of the page, when the browser gets back go your game *you should only run the equivalent of one normal frame*.

Running a 5 second frame does not make sense when your game is made to run frames 60 times per second. Imagine all the collisions that will be missed.

Instead of using a delta-time based like you have now, pre-define your delta time to be 1/60, and limit your framerate to that.

This way, everything you run your physics, whether the browser has suspended your game or not, you'll never experience odd behaviour like this.

Another option is to clamp your frame time to a maximum when it gets to your window; before you run the frame, make sure it is at most e.g. 1/30, and use it as your delta time before passing it to your game functions.
> 1 votes

---
Tags: physics, mathematics, javascript, entity-system
---


# Question
Title: How can I check if the player is moving or not?
The problem is that the player have Animator so even if he is not moving he is still moving a little :

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

public class DetectCollision : MonoBehaviour
{
    public Transform player;
    public Transform target;
    public bool turnOnOffPlayerAnimator = false;

    float timeElapsed = 0;
    float lerpDuration = 3;
    float startValue = 1;
    float endValue = 0;
    float valueToLerp = 0;

    private Animator playerAnimator;
    private bool entered = false;
    private bool prevFacing = false;
    private Rigidbody rigidbody;

    // Start is called before the first frame update
    void Start()
    {
        rigidbody = player.GetComponent<Rigidbody>();

        playerAnimator = player.GetComponent<Animator>();

        if (turnOnOffPlayerAnimator)
            playerAnimator.enabled = false;
    }

    // Update is called once per frame
    void Update()
    {
        var currFacing = IsFacing(target);
        if (currFacing != prevFacing)
        {
            // here you switched from facing to not facing or vise verca.
            timeElapsed = 0;
        }
        prevFacing = currFacing;

        var distance = Vector3.Distance(player.position, target.position);

        if (IsFacing(target))
        {
            if (entered && distance > 30)
            {
                if (timeElapsed < lerpDuration)
                {
                    valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
                    playerAnimator.SetFloat("Forward", valueToLerp);
                    timeElapsed += Time.deltaTime;
                }
                playerAnimator.SetFloat("Forward", valueToLerp);

                if(rigidbody.velocity == Vector3.zero)
                {
                    Debug.Log(valueToLerp);
                }
            }
        }
        else
        {
            if (valueToLerp < 0.9f)
            {
                if (timeElapsed < lerpDuration)
                {
                    valueToLerp = Mathf.Lerp(endValue, startValue, timeElapsed / lerpDuration);
                    playerAnimator.SetFloat("Forward", valueToLerp);
                    timeElapsed += Time.deltaTime;
                }
                playerAnimator.SetFloat("Forward", valueToLerp);
            }
        }

        if(turnOnOffPlayerAnimator)
        {
            playerAnimator.enabled = false;
        }
        else
        {
            playerAnimator.enabled = true;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        entered = true;

        Debug.Log("Entered !");
    }

    private void OnTriggerExit(Collider other)
    {
        entered = false;

        Debug.Log("Exited !");
    }

    private bool IsFacing(Transform target)
    {
        Vector3 forward = player.TransformDirection(Vector3.forward);
        Vector3 toTarget = target.position - player.position;
        return Vector3.Dot(forward, toTarget) > 0;
    }
}

```

I tried to use the Rigidbody on the player :

```
if(rigidbody.velocity == Vector3.zero)
                    {
                        Debug.Log(valueToLerp);
                    }

```

Using a break point I see that the velocity of the rigidbody the left side is 0.0,0.0,0.0 also the Vector3.zero have the same values but it's never get inside to the Debug.Log

In another script I get the player info also the movement speed :

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

public class PlayerSpeedDistanceController : MonoBehaviour
{
    public GameObject target;
    public GameObject speedArea;
    public float speed;
    public Animator animator;
    public Text movementSpeedUiText;
    public Text distanceFormTargetUiText;
    public Text playerDirectionUiText;
    public Text playerOnSpeedAreaUiText;

    private float distance;
    private Rigidbody rigidbody;

    // Start is called before the first frame update
    void Start()
    {
        rigidbody = GetComponent<Rigidbody>();

        movementSpeedUiText.text = animator.GetFloat("Forward").ToString();
        distanceFormTargetUiText.text = Vector3.Distance(rigidbody.position, target.transform.position).ToString();
        playerDirectionUiText.text = transform.forward.ToString();

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        var movement = rigidbody.velocity;

        movementSpeedUiText.text = movement.magnitude.ToString("0.###");

        distanceFormTargetUiText.text = Vector3.Distance(rigidbody.position, target.transform.position).ToString();
        playerDirectionUiText.text = IsFacing(target.transform).ToString();

    }

    private bool IsFacing(Transform target)
    {
        Vector3 forward = transform.TransformDirection(Vector3.forward);
        Vector3 toTarget = target.position - transform.position;
        return Vector3.Dot(forward, toTarget) > 0;
    }
}

```

And I see on the movementSpeedUiText UI text that when the player is standing the movement speed is moving between : 0.001 to 0.002 mostly stay on 0.002

I want to find when the player is standing. when it's 0.001 or 0.002 I see the player standing. but in the first script it's never get inside to the DEbug.Log

```
Debug.Log(valueToLerp);

```

This small movements 0.001 or 0.002 I guess they are because the player animator make the player idle his body moving a bit.

still I'm not sure how to detect then that the player is standing not moving because he is not moving I mean the player is not changing position.

# Answer
Have you considered something like this?

```
public float stationaryTolerance = 0.005f;

public bool IsStationary { get {
    return rigidbody.velocity.sqrMagnitude < stationaryTolerance * stationaryTolerance;
}}

```

Or...?

```
Vector3 _lastPosition;
bool _isStationary;

void FixedUpdate() {
    float travelSquared = (rigidbody.position - _lastPosition).sqrMagnitude;
    _isStationary = travelSquared < stationaryTolerance * stationaryTolerance;

   _lastPosition = rigidbody.position;
}

```

Either way, you can adjust your `stationaryTolerance` value higher or lower until it properly distinguishes "still enough" from "visibly moving"
> 2 votes

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