# Question
Title: My character can jump even when its not grounded
Here is the code

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

public class PlayerMovementscript : MonoBehaviour
{
    //vars
    public CharacterController controller;

    public float speed = 12f;

    Vector3 velocity;

    public float gravity = -9.81f;

    public Transform groundCheck;
    public float groundDistanace = 0.4f;
    public LayerMask groundMask;
    public float jumpHeight = 3f;
    bool isGrounded;
    //-----------------------------------

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistanace, groundMask);

        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }
}

```

character controller and etc

# Answer
> 1 votes
I suspect that Physics.CheckSphere actually finds the capsule collider on the game object itself, which prevents it from ever returning false.

To prevent that either:

* Put the player and the ground on different layers and then pass a LayerMask to CheckSphere which excludes the player but includes the ground or
* Use `Physics.OverlapSphere` to get an array with all the colliders, and then check each collider to confirm that it is a collider you consider "ground".

# Answer
> 0 votes
### Ok I found a half answer but still inconsistent

I lowered my groundcheck, but now when hitting the ground my "character" slows down when a bit above the ground and the space key only works when it wants too.

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


# Question
Title: When to use a vertex array and when to use a VBO?
I'm trying to learn about **vertex arrays** and **vertex buffer objects**, but I don't understand the differences in terms of:

* case-of-use (static geometry like terrains, geometry that changes every frame like a particle system, etc.)
* performance
* portability (old graphics card, consoles, devices like Android or iPhone, etc.)

some clarifications?

# Answer
> 14 votes
Here is a decent writeup about VBOs.

**Performance**

Here is a good overview of the calling semantics.

Here here is another good overview of performance issues; in it we see that VBOs are more performant than arrays.

The reason we prefer VBOs is that the data is loaded onto the card, and so you don't have to transfer it every frame. Depending on the type of VBO created, you can give the graphics driver hints on the usage (write-many, read-many vs. write-many, never-read, etc).

**Usage**

VBOs are really good for static geometry like terrain that you don't expect to change, or for instanced geometry.

Vertex arrays are good for data that changes frequently but that also is read by the host machine--so, for directly rendering data that is being manipulated (laser rangefinder data buffers, for example, are where I've used them) frequently. If you can get away with never reading the data on the host device (so, just pushing it out onto the card), VBOs in write-only mode are a good option.

**Portability**

*Client Side Vertex Arrays* These are available in OpenGL prior to 3.0, deprecated in 3.0, and gone in 3.1+. OpenGL ES supports them (OpenGL ES 2 does not).

*VBOs* These are available after OpenGL 1.5. These are the only way to store geometry data in OpenGL ES 2 (and so, WebGL).

# Answer
> 11 votes
(I'm adding this here due to the the fact that ChrisE's answer is highly ambiguous, which is unfortunately due to the ambiguity of the original question. However I'm going to assume the OP's question should have been titled "when to use **VAOs** and when to use **VBOs**".)

**V**ertex **B**uffer **O**bjects (which really aren't dissimilar from other types of **B**uffer **O**bjects, for example **U**niform **B**uffer **O**bjects) provide a means for uploading vertex data to the graphics hardware.

**V**ertex **A**rray **O**bjects are used in addition to **VBO**s in order to improve client-side (CPU-side) performance, by reducing the number of calls needed to rebind individual vertex buffers and re-set vertex attributes every time you want to change to render in a certain way. Instead of doing all that work every frame, you do it once (at initialisation), and then simply rebind the appropriate **VAO** for each (set of) draw call(s) that use the associated vertex attributes.

In spite of this, using **VAOs** does not release you from the additional responsibility of having to do `glBindBuffer` \+ `glBufferData` for any data that *changes* each frame, for instance, game entity positions / rotations / transform matrices. It is only when you have entirely static data that you need only do `glBindVertexArray(&vao) -> glDraw*(...) -> glBindVertexArray(0)` to render.

# Answer
> -2 votes
In short words VBO is an array of raw data, when VAO is an array of ATTRIBUTES - an instruction for shader program how to use the data.

VBO allows to keep data on GPU side, which saves transfer time, you just need to know VBO's id.

But VBO by itself is not enough. You have to instruct GPU how to use it. You have to define "Vertex Attribute Pointers" (command glVertexAttribPointer) for each attribute (input data variable) of your shader. Before VAO you had to define attributes for each glDrawArrays call (it's a lot), in every frame (like 30+ times per second). VAO allows to attach an entire array of attributes by just VAO's id. So, when VBO is relatively independent, the VAO is VBO+shader-specific.

---
Tags: opengl
---


title: Simple real-time 3D wind simulation

text:
# Question
Title: Simple real-time 3D wind simulation
I am a 4th-year student in the apply math department. It's my final year, so I am working on my bachelor's thesis. The topic is "Real-time weather effects simulation for grassland". The huge work was done by my tutor, so the grassland simulation itself had been already implemented. Now we decided to limit the work to adding 3d wind modal and snowfall for result presentation. The snow particle system has been implemented recently, however, I've coped with problems while seeking information on how to implement real-time 3d wind field simulation.

There are plenty of quite complex articles on how to simplify real turbulence simulation, but it's too excessive for my work. On the other hand, there are quite simple 2D approaches using Perlin Noise, but I can't find something like that for the 3-dimensional scene.

Summing up, Could someone share some typical solution for my issue, or just post a good link?

Thank's a lot in advance and sorry for my poor English.

UPD Screenshot of the scene for whatever it may be worth

# Answer
> 1 votes
I think curl noise is the right idea.

The concept of curl noise is fairly straightforward. It involves taking the derivative vector of a smooth coherent 2D noise, and rotating it 90 degrees. The result is a vector field which never converges or diverges at point, but instead flows neatly in cycles. Curl noise can be extended to 3D if you consider it relative to a 2D plane, by introducing an extra dimension to the noise, and performing the derivative rotation around the vertical axis. From there, you can evaluate a wind vector at any point, but the wind won't change direction over time. To address this, add a fourth coordinate to vary the noise through time.

If your world is flat, then assuming Y is vertical, you can just rotate the dx/dz derivative values and keep dy as it is. Your rotated derivative might become `<dz, dy, -dx>` or `<-dz, dy, dx>` depending on which direction you rotate. I'm not quite sure if this preserves the divergence-free property, but I think it will be good enough. If your world is spherical rather than flat, you'll need to do the rotation around the unit vector pointing away from the world's center, but it's the same basic idea.

When you add in the time coordinate, you will need 4D noise instead of 3D. You could use the 4D noise as it is, incrementing the W dimension ad infinitum. However, you may eventually run into precision problems as the value becomes arbitrarily large. To solve this, you can use a noise that loops in the W coordinate, and subtract the repeat period each time it is detected to be ahead of it.

You can manufacture noise that loops in one coordinate, by using 5D noise like `noise(x, y, z, const1*sin(const2*t), const1*cos(const2*t))`. This works, but it is probably needlessly complex. Ordinary Perlin noise that uses a permutation hash does loop in every coordinate. But, unmodified Perlin noise is characteristically ineffective at producing features that are pointed in directions other than 45 and 90 degrees. As such and as usual, I don't recommend using it. Not in its raw form at least.

I would use one of two methods for noise: Domain-rotated Perlin, or a well-implemented Simplex-type noise. Domain-rotating Perlin in a certain way allows you to hide the worst and most grid-aligned parts of the N+1 dimensional noise, from N dimensional slices. It also still allows the last coordinate to be periodic. Simplex-type noise is designed to have less visible grid bias on its own. In this 4D case, I believe it is also faster, especially when you also compute the derivatives. Then, if you apply the same domain rotation, you can make `w` periodic if the noise uses a periodic hash internally, as well as achieve the best possible appearance.

One final part. When the wind is far up in the atmosphere, any vertical component should produce convincing wind. However, as you get too close to the ground, it might be problematic to have wind vectors that point into the ground. If you can generate surface normals of your terrain, though, you can slightly alter the directions of the wind depending on how close you get to the ground. To find the direction the wind should blow if it were right on the ground, you could take `<ground wind vector>=[<wind vector>-(<wind vector> dot <surface normal>)*<surface normal>]/(<surface normal> dot <surface normal>)`. The division part isn't necessary if your surface normal is already length 1, but it's more efficient to do the division than to make `<surface normal>` length 1 beforehand. To smoothly change to this vector, get a slide `t=max(0, 1-((y-terrainHeight(x,z))/bufferDistance))^2` and compute `<result wind vector>=(1-t)*<wind_vector>+t*<ground wind vector>` To calculate the surface normal in the first place, you need the derivative of the terrain. To get the derivative, you can either compute it analytically by using derivative-supporting noise, or check neighboring terrain height values. Once you have the derivative, you can turn it into a surface normal using a similar process to this. In the case of a flat world, the tangent plane is just the flat XY or XZ plane.

* Here is a link to domain-rotated Perlin. For best results, use noise4\_ImproveXYZ\_ImproveXY if X/Y are your horizontal directions, or use noise4\_ImproveXYZ\_ImproveXZ if X/Z are. Use `w` as your time variable. It repeats at w=4096 (i.e. `noise4_ImproveXYZ_...(x, y, z, w) = noise4_ImproveXYZ_...(x, y, z, w+4096*k)` where `k` is an integer). All evaluators for the 4D noise repeat in the `w` coordinate at `w=4096`.
* Here is a link to a modified 4D implemetation of my OpenSimplex2 algorithm. I have added derivatives to it, as well as the same domain rotations. All evaluators except for "unoriented" repeat in the `w` coordinate after `w=sqrt(20)*2048`, or approx. `w=9158.934435839139`.

EDIT: These are both in Java, but you can port them if needed.

A bit late on this. Hope it still helps!

---
Tags: 3d, simulations
---


# Question
Title: Generate vertices of a sphere by using spherical coordinates
I'm trying to generate points for a sphere by subdividing the space of spherical coordinate in **res** sector and **res** slices.

At first I did my own implementation, but it wasn't working. After a while I looked online and I copied Songho implementation and others as well.

But I still have the same issue:

The points are not evenly spaced in the sphere, creating a strip.

This is the code I'm using to generate the sphere:

```
   float sectorStep = 2 * PI / res;
    float stackStep = PI / res;
    float sectorAngle, stackAngle;
    for(int i = 0; i <= res; ++i){
        stackAngle = PI / 2 - i * stackStep;
        float xy = r * sinf(stackAngle);
        float z = r * cosf(stackAngle);
        for(int j = 0; j <= res; ++j){
            sectorAngle = j * sectorStep;
            float x = xy * sinf(sectorAngle);
            float y = xy * cosf(sectorAngle);
            vertices.push_back(glm::vec3(x,y,z));
        }
    }
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &verticesVBO);
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, verticesVBO);
    glBufferData(GL_ARRAY_BUFFER, vertices.size(), vertices.data(), GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(0);
    glBindVertexArray(0);

```

And here it's how I draw it:

```
    glm::mat4 projection = glm::perspective(glm::radians(camera.getFOV()), (float) SCR_WIDTH / (float) SCR_HEIGHT, 0.1f, 100.0f);
    glm::mat4 view = camera.getViewMatrix();

    glm::mat4 model = glm::mat4(1.0f);
    shader.use();
    shader.setUniform("projection_view", projection*view);
    shader.setUniform("model", model);
    glBindVertexArray(sphere.VAO);
    glDrawArrays(GL_POINTS, 0, sphere.vertices.size());

```

I wanted to draw the vertices first and then move to drawing the triangles.

Sorry if this is a stupid question.

# Answer
> 0 votes
To sum it up: the formula I was using was wrong, as @DMGregory suggested.

But I was also passing vertices.size() as the dimension of the vertices vector, while the correct line would have been:

```
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), vertices.data(), GL_STATIC_DRAW);

```

# Answer
> 0 votes
This line says your `stackAngle` is measured from `0` at `z = +r` to `PI` at `z = -r`:

```
float z = r * cosf(stackAngle);

```

But this line says your `stackAngle` goes from `PI/2` (where `z` is `0`) to `-PI/2` (where `z` is `0` again):

```
stackAngle = PI / 2 - i * stackStep;

```

In between, `stackAngle` will pass over over `0` (where `z = +r`), but it will never visit `+-PI` (where `z = -r`).

So you're doubling over the top hemisphere and missing the bottom entirely.

It looks like you want:

```
// stackAngle is "radians south of the north pole,"
// running from 0 to PI. Keep xy = sin, z = cos.
stackAngle = i * stackStep;
float xy = r * sinf(stackAngle);
float z = r * cosf(stackAngle);

```

or:

```
// stackAngle is "radians north of the equator,"
// running from PI/2 to -PI/2. Swap sin & cos between xy & z.
stackAngle = PI / 2 - i * stackStep;
float xy = r * cosf(stackAngle);
float z = r * sinf(stackAngle);

```

---
Tags: opengl, graphics, geometry, graphics-programming, sphere
---


# Question
Title: How do I get my fish to face the right way?
I'm making this 2d collecting game in Unity where you collect fish. However I can't get them to face the direction they are going. I've asked on some Discords and got no answer. Thanks in advance.

Here's is the video of the fish.

And here's the code:

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

public class NewBehaviourScript : MonoBehaviour
{
    public float minY;
    public float maxY;
    public float minX;
    public float maxX;
    public float speed;
    public float maxZ;
    Vector2 targetPosition;

    // Start is called before the first frame update
    void Start()
    {
        targetPosition = GetRandomPosition();
    }

    // Update is called once per frame
    void Update()
    {
        if ((Vector2)transform.position != targetPosition)
        {
            transform.right = (Vector2)targetPosition;
            transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);

        } else {
            targetPosition = GetRandomPosition();
        }
    }

    Vector2 GetRandomPosition()
    {
      float randomX = Random.Range(minX, maxX);
      float randomY = Random.Range(minY, maxY);
      return new Vector2(randomX, randomY);
    }
}

```

# Answer
> 1 votes
It looks like you're trying to point your local right vector toward the target, but you're assigning a *position* instead of a *direction*.

```
transform.right = (Vector2)targetPosition;

```

First, get the *direction* from your current position to your target.

```
var targetDirection = targetPosition - transform.position;

```

Then you can either assign this directly as you were trying to do before...

```
transform.right = (Vector2)targetDirection;

```

Or you can construct the specific rotation you want, something like this:

```
var upToTarget = Quaternion.LookRotation(Vector3.forward, targetDirection);
var rightToUp = Quaternion.Euler(0, 0, 90);
var rightToTarget = upToTarget * rightToUp;

```

You can now assign this rotation to your transform:

```
transform.rotation = rightToTarget;

```

As mentioned in the comments, you can also flip the sprite when facing to the left, so the fish doesn't end up upside-down, with something like:

```
spriteRenderer.flipX = targetDirection.x < 0f;

```

---
Tags: unity, c#, 2d, vector, oop
---


# Question
Title: How to implement drawing only to the specific area of the window?
I'm trying to implement "canvas" where I will display loaded texture and select specific parts of it so I can put them on tilemap, I'm also trying to add zooming and panning only in "canvas" part of the window. I've tried using view and viewport but setting viewport size is what I'm struggling with the most. What I've tried:

First I set the view to be size of the window and its center is offset by (-250, -20) - this the point where properties window ends (x = 250) along with main menu bar (y = 20):

```
m_view.reset(sf::FloatRect(-250.0f, -20.0f, get_window().getSize().x, get_window().getSize().y));

```

Then if window has been resized I process the Resized event:

```
if (event.type == sf::Event::Resized)
{
    m_view.reset(sf::FloatRect(-250.0f, -20.0f, event.size.width, event.size.height));
    get_window().setView(m_view);
}

```

But if I want to implement panning (moving the view) and zooming I need to set viewport so it will only render in "canvas" area. I can try to set viewport's FloatRect manually but what if window will get resized? How do I deal with this problem?

Godot TileSet/TileMap Editor as reference

# Answer
> 1 votes
The Cherno on YouTube did something similar for his Scene Viewport in his Game Engine series.

It's written in C++/OpenGL/ImGui, but it's easily translated. From a high level, you need to create a viewport panel/window that you draw to as a "Scene Viewport".

---
Tags: c++, sfml, imgui
---


# Question
Title: How can I limit the rotation angle of the object?
At the top

```
float speed = 1.0f;
float rotationAngle = 45;

```

In Update :

```
private void Update()
    {
            if (Mathf.Approximately(transform.localPosition.y, 7))
            {
                float rotationY = rotationAngle * Mathf.Sin(Time.time * speedRot);
                transform.Rotate(new Vector3(0f, rotationY, 0));
            }
    }

```

but it's just rotating nonstop at the same direction.

I need it to rotate for example in the limited range of 45 to both sides like a ping pong from side to side. and optional to make it to rotate in limited angle/s for all axis but now for the Y how to limit it like a ping pong to rotate 45 degrees to the right then back to the left and so on nonstop but in limited angle/s.

# Answer
> 1 votes
`Transform.Rotate()` does not rotate set the Transform to a specific rotation. It rotates the Transform by a given amount. In other words, you're telling Unity "increase the Y-axis rotation by `rotationY` degrees" instead of "set the Y-axis rotation to `rotationY` degrees".

It sounds like what you want is just to set the rotation:

```
float rotationY = rotationAngle * Mathf.Sin(Time.time * speedRot);
transform.eulerAngles = new Vector3(0f, rotationY, 0);

```

If you want the GameObject to rotate around its initial orientation:

```
Quaternion startRotation;
void Start() {
    startRotation = transform.rotation;
}

void Update() {
    if (Mathf.Approximately(transform.localPosition.y, 7)) {
        float rotationY = rotationAngle * Mathf.Sin(Time.time * speedRot);
        Quaternion delta = Quaternion.Euler(new Vector3(0f, rotationY, 0));
        transform.rotation = startRotation * delta;
    }
}

```

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


# Question
Title: Normalize a rotation around the Z-axis (issue with GLM)
I'm trying to undo some transformations coming from an external tool\*. I'm getting different results depending on subtle differences in the input and wondering how to convert to a rotation about the Z-axis only.

The transformations are expressed as a `matrix = translation * rotation * -translation`. I want to decompose the resulting matrix into a single translation and rotation around Z -- I know this is possible given the source material (2D plane).

My problem is coming from GLM `decompose`. Given a matrix that looks like this:

```
[         -0.5 |     0.866025 |            0 |            0 ]
[    -0.866025 |         -0.5 |            0 |            0 ]
[            0 |            0 |            1 |            0 ]
[            0 |            0 |            0 |            1 ]

```

If I call `decompose`, then take the eulerAngles of the Rotation I end up with either:

* ( 0, -0, 2.09439 ) from quat( 0.5, 0, 0.866025, 0 )
* ( 3.14159, 1.0472, 3.14159 ) from quat( 0.5, 0, 0, 0.866025 )

The difference depends on how the matrix was generated, whether the rotation was 120degrees or -240degrees. The display must be clipping the floating point, introducing a subtle change.

I'm assuming both these rotations are actually the same.

**How do I force/convert the result to be a rotation about the Z axis only.**

---

*\*The external tool is Inkscape which uses the CSS/SVG function `rotate(r, cx, cy)` instead of a rotation and transform. That function results in the matrix: translate(cx,cy,0) * rotate(r, (0,0,1)) * translate(-cx,cy,0)*

# Answer
> 1 votes
If there is no shearing in play, then `Atan2(matrix[0].y, matrix[0].x)` gives you the angle of rotation about the z axis in radians.

This is because the first column gives you the direction that the local x-axis points after rotation. If it's (1, 0) then there's no rotation (or a multiple of 2 pi). If it's (0, 1) there's been a 90 degree rotation, etc. `Atan2` is insensitive to the length of the vector, so we don't need to worry about scaling here.

---
Tags: 2d, mathematics, transformation
---


title: Pathfinding over a moving platform

text:
# Question
Title: Pathfinding over a moving platform
I have beens struggling with the following. In the game I am developing with Unity 5 in C#, I need to implement basic pathfinding over moving platforms (not *with* moving platforms). It means, I am not concerned that NPC are able to take moving platforms, I am specifically concerned that the whole pathfinding process should happen on big moving floors.

Being that the case, NavMeshes are not an option. Would anyone happen to know of any approach, or have any good tips for that? Thanks in advance for your time.

# Answer
> 2 votes
The devs who made Sea of Thieves built their skeleton ships to let enemy skeletons walk around on it while it was moving. I don't know too much of the details but I heard that they baked the nav mesh down on the sea floor and have the ai agents use that while being on a ship. here's a link to the video: https://youtu.be/mZOZyCenz1E

A Minecraft mod called Valkyrien Skies used something similar. Basically the mod lets you build physics based airships that you can run around on while it flies. What they did was take a static copy of your build (sb) and hide it far away from the player while a physics enabled (pe) copy is left with the player. Any entity that interacts with the pe is actually interacting with the sb. Enemy AIs can still attack players and move around when they get aboard. Or at least that's how I understood it when I asked the mod devs. A lot has changed over the years so I'm not sure of how the mod works now. Here's their link anyways: https://www.curseforge.com/minecraft/mc-mods/valkyrien-skies

# Answer
> 1 votes
You could create your own waypoint-based graph, update it every frame and perform a Breadth First Search on that, or you could maybe try looking at one of the A\* projects (there are free ones) on the Asset Store.

To make the waypoint graph, Make the waypoints a child of the platform they represent, so that they move with the platform. You could set a waypoint tag on your waypoints and search for all waypoints in your player script. The waypoint should have a MonoBehaviour which contains the other waypoints it is connected to. Thus you have the nodes and edges of a graph. You can perform a simple Breadth First Search or use your implementation of Dijkstra's or A\* for traversing the graph.

Then you could check the height difference between this and the next waypoint in your traversal and if it is higher than a certain amount, you won't go there (that is a platform is above the character), a bit like how navmeshes are baked. If you need more help implementing this, feel free to ask.

---
Tags: path-finding, moving-platforms
---


# Question
Title: How to make non-standard sized zones for a procedurally generated 2d map?
I am making a procedurally generated map with different zones (plains, forest, village, etc) and am currently just designing each one as a square zone. However, I think it'd be neat if the zones were more randomly distributed so that they could be irregular sizes. I'm not sure how to do that in a good way. (Any given tile needs to know what zone it belongs to quickly and deterministically based on its x, y, and random seed for the world)

Are there existing algorithms for this?

# Answer
> 2 votes
I am going to assume extra emphasis on the performance. There are plenty of thorough answers on this topic already, but if you are interested in something brutally simple and fast (as in real-time Python), I can offer you a method of "squeezed squares".

General idea is as follows:

* Each block belongs to some bigger chunk. This is purely virtual construct, the chunk does not need to be a storage unit. Chunk's coordinates can be easily inferred from block's coordinates. The point here is that clusters of blocks may share common seed.
* Chunk's coordinates are feed to deterministic RNG to generate two properties: `size_bias` and `biome_id`.
* To determine blocks's `biome_id`, scan surrounding NxN chunks to select closest one after adjusting for `size_bias`.
* That is it. Tweak the parameters (`size_bias`, `chunk_size`, `N`) for best results.

Few examples with different settings. (Blue arrows point to selected chunk.)

| 1 | 2 | 3 | 4 |
| --- | --- | --- | --- |
|  |  |  |  |

Python pseudocode.

```
def get_chunk(location):
    half = chunk_size / 2
    location = Vector(location.x % chunk_size + half, location.y % chunk_size + half)
    seed = global_seed + location.x + location.y
    rng = make_rng(seed)
    biome_id = rng.range(num_biome_types)
    size_bias = rng.uniform(1.0, max_size_bias)
    return ChunkInfo(location, biome_id, size_bias)

def get_nearby_chunks(block):
    for x in range(block.location.x - N, block.location.x + N + 1):
        for y in range(block.location.y - N, block.location.y + N + 1):
            yield get_chunk(Vector(x, y))

def get_block_biome_id(block):
    chunks = list(get_nearby_chunks(block))
    biased_distance = lambda chunk: (block.location - chunk.location).size - chunk.size_bias
    chunks.sort(key=biased_distance)
    return chunks[0].biome_id

```

Cons:

* Not ideal for 3D: surface might look crater-y.
* Sometimes visibly aligns to chunk grid — decrease chunk size, increase sample radius and bias variance.

---
Tags: procedural-generation, maps
---


title: How to get the source code for a game?

text:
# Question
Title: How to get the source code for a game?
I read here a spectacular story of someone (scrappily) fixing some things in a game's source code, making it load 4 times faster!

How did the developer get the source code in the first place? Is there a common pattern to getting game source code?

Link to the GitHub repository talked about in the article: https://github.com/tostercx/GTAO\_Booster\_PoC

# Answer
> 5 votes
Getting access to a game's sourcecode can be anything between trivial to impossible. Factors which decide that are:

* What technology was used to create the game? Decompiling executables to readable sourcecode can be easy (like in Java) to hard (like C++). Some technologies even *require* to include the sourcecode with the game, because they interpret the sourcecode at runtime (like browser-based javascript, for example).
* Did the developers take measures to make sourcecode access easier or harder? They might run their code trough an obfuscator before creating the game build to make it harder to read. With compiled languages, they might run the exe through some additional obfuscation steps to make decompiling harder. Or they might even offer parts of their sourcecode in a public repository for players to view, perhaps even with documentation.
* Are there server-sided components? When parts of the game run on a server, then the code for those components is inaccessible to players, unless it gets leaked by an insider or hacker.

But if you want to know more about how a player going by the synonym *t0st* troubleshot the loading time problem in GTA 5 and fixed it, they wrote an essay about that. tl;dr:

1. They used a profiler to find the parts of the code which took the most time to execute.
2. They disassembled the game executable by dumping the memory at runtime and running it through a C++ decompiler.
3. They dug through the barely readable C++ sourcecode and found out that the slow parts parse strings containing JSON data.
4. They found out that the JSON data in question contained the data about items, and that they were parsed in a very inefficient manner.
5. They created a more efficient implementation and injected it as a DLL, which is a popular method for modding parts of games which weren't intended to be accessible to modders.

---
Tags: software-engineering, debugging
---


# Question
Title: How mesh transformation works under the hood
We can look at the most popular engines like Unity and Unreal engine (maybe Godot and other).

As far as I understand (at least I would do this), we store the original mesh, and then for every change (shift, rotation or scaling) we turn the change into a matrix, and apply it to all vertices of the copy of the original mesh, with which we will work later.

But it seems to me that this will not be very fast, so I doubt if this is really so.

I tried to see how the transform is implemented in the source code of the Unreal engine, but ... there is so much code that after spending a few hours searching, I gave up.

I will be glad to see a link to an implementation in an unreal engine (or any popular engine in general), but extra points - if you explain the code.

PS: if you know several implementations of transformation, then I would be glad if you tell me about the known ones and, if possible, describe their pros and cons.

# Answer
> 3 votes
You correctly describe how transformations work, you're just making a wrong assumption that the process *seems slow*. *Graphics* processing units are tailor-made to do this specific thing, i.e. linear algebra calculations.

My thinking is that you have a wrong view of what a GPU is and compare it to a CPU. If a CPU has 4-8 cores, a GPU has 1000s of them and each small core can undertake a single calculation. In a fraction of a second, all of the 1000s of GPU cores can calculate 1000s of multiplications between mesh position vectors and transformation matrices since these operations can be vectorized.

Regarding where in the source code this happens in the engines above, you will probably not find it in the form you are expecting since it happens on the GPU side (i.e. you will not see matrix multiplication code). GPU APIs usually provide ways to load the mesh data and the transformation data in their memory and the calculations are dictated via GPU-specific programs called *shaders*.

# Answer
> 3 votes
There's an additional detail I want to clarify here:

> As far as I understand (at least I would do this), we store the original mesh, and then for **every change** (shift, rotation or scaling) we turn the change into a matrix, and apply it to all vertices of the copy of the original mesh, **with which we will work later**.

This seems to imply that when I translate a mesh, the engine stops everything, moves every single vertex in the mesh, stores their new positions, then continues executing the next line of code. If I then rotate the mesh, it loads those stored positions after the previous translation, rotates every single vertex, then stores the translated+rotated results...

That's not how it works.

Instead, with each instance of a rendered mesh we store a "transformation" data structure, usually consisting of a translation vector, a rotation quaternion, an axis-aligned scale triplet, and a reference to a parent transformation (for hierarchical nesting of objects). We might also store a local-to-world or world-to-local matrix, or generate those on demand when needed.

When I rotate an object, the engine just updates the quaternion stored in its transformation data. When I translate it, the engine updates the translation vector. When I scale it, the engine updates the scale triplet. And that's it. Only those 3-4 numbers need to be recalculated immediately. We can then set a dirty flag to let us know the transformation has changed, and regenerate the matrix the next time it's needed.

When it comes time to render the objects, we run through our scene graph and update the transformation matrices of any objects that have changed (or whose parents have changed). Then we send that matrix and the raw, unchanged vertex data to the GPU to render.

Note that nowhere in this process so far have we actually moved a single vertex. Our mesh data often stays effectively read-only in memory. I can have thousands of differently-transformed instances of an object all referring to a single copy of the mesh data for that object, with every vertex exactly where I put it in the 3D modelling tool when authoring it.

The transformations get applied on demand in the GPU. The vertex shader gets passed each vertex in its original as-modelled position (what we call "object space"), and a matrix to use to transform that vertex into world space, or directly into the camera's projection space. So no matter how many transformations I've applied to the vertex, the shader only needs to do a couple of matrix multiplications to find its final displayed position (and possibly transform its normal, tangent, etc). All those sequences of translations and rotations get folded down into a single matrix, so computing the result of 1000 transformations is no more expensive than 1 for each vertex.

That transformed vertex position gets sent down the pipeline to be rasterized into pixel positions to draw, then it's effectively forgotten at the end of the draw call. We don't store the transformed vertices anywhere, we just re-transform them again cheaply next frame.

Now, I've glossed over here a few special cases where we will compute new vertex positions CPU-side, like when we're dynamically batching multiple meshes together into one common coordinate space to draw in a single call. But those are exceptions to the rule.

---
Tags: unity, transformation, 3d-meshes, unreal, mesh
---


title: Runner 3D Movement

text:
# Question
Title: Runner 3D Movement
I am making a 3D basic runner game, where my character constantly "runs" in a constant pace. At first I used MovePosition() to implement the movement behavior, but I encountered a weird behavior while colliding with other rigidbodys, especially dynamic rigidbodys. So I tried using AddForce() instead -

```
Vector3 desiredVelocity = new Vector3((transform.forward.normalized.x * playerSpeed), 0f, 0f);
rb.AddForce(desiredVelocity - rb.velocity, ForceMode.VelocityChange);

```

The collisions behave fine now, but I'm having issues with the gravity - With this implementation, the rigidbody gets "pushed" forward and the bigger the force added to it, the lower gravity gets, and it becomes kind of a trade-off, where increasing gravity makes the player "slower" and increasing the force added makes the gravity effect lower. Pretty intuitive physics issue.

I'm not sure if there's a simple solution for this physics issue or should I approach it differently. What would be the proper, standard implementation for this kind of movement?

Thank you in advance, Omer

# Answer
> 1 votes
Because you're forcing your velocity to match your input value each frame, you're stopping gravity from accumulating into a large downward velocity. Each physics step, the object has to start falling from what's effectively the peak of its arc, never getting to the fast portion of the downward arc.

If your running push is meant to be only horizontal, and your gravity is vertical, you can solve this by just zeroing out your velocity change on the y axis:

```
Vector3 desiredVelocity = new Vector3(playerSpeed, 0f, 0f);
Vector3 velocityChange = desiredVelocity - rb.velocity;

velocityChange.y = 0f;

rb.AddForce(velocityChange, ForceMode.VelocityChange);

```

---
Tags: unity
---


# Question
Title: Make my Random.range not repeat same position
So I want to make my `array Gameobject transform` to `transform array points` position but it will be randomized position when start only without repeating a position

so make some script like this:

```

    public GameObject[] collectibleAyatGO;
    public Transform[] transformPoint;
    public List<int> TakeList = new List<int>();
    private int randomNumber;

public void RandomTransformPosition()
    {
        TakeList = new List<int>(new int[transformPoint.Length]);

        for (int i = 0; i < transformPoint.Length; i++)
        {
            randomNumber = Random.Range(0, transformPoint.Length);
            while (TakeList.Contains(randomNumber))
            {
                randomNumber = Random.Range(0, transformPoint.Length);
            }

            TakeList[i] = randomNumber;
            collectibleAyatGO[i].transform.position = transformPoint[TakeList[i] - 1].position;
        }
    }

```

it seem not working or make my unity notresponding maybe due to while loop, Am I doing right here ?

# Answer
It looks like you just want a Fisher-Yates Shuffle.

```
// Make an array containing the whole numbers 0, 1, 2...
var randomIndex = new int[transformPoint.Length];
for (int i = 0; i < randomIndex.Length; i++) {
    randomIndex[i] = i;
}

// Shuffle that array into a random permutation.
for (int i = 0; i < randomIndex.Length; i++) {
    int swapIndex = Random.Range(i, randomIndex.Length);
    int swap = randomIndex[swapIndex];
    randomIndex[swapIndex] = randomIndex[i];
    randomIndex[i] = swap;
}

// Assign positions to your objects, using your permuted indices.
for (int i = 0; i < randomIndex.Length; i++) {
    collectableAyatGO[i].transform.position = transformPoint[randomIndex[i]].position;
}

```

By construction, no index is repeated twice, and we complete this with a linear scan through the array, with no guess-and-check while loop nested inside.

You can even combine this into one loop and skip the temporary index array, using "The inside out algorithm" presented at the link above:

```
for (int i = 0; i < transformPoint.Length; i++) {
    int j = Random.Range(0, i+1);
    collectableAyatGO[i].transform.position = collectableAyatGO[j].transform.position;
    collectableAyatGo[j] = transformPoint[i].position;
}

```

Though it's less obvious at a glance how this code works, compared to the step-by-step version.
> 3 votes

---
Tags: unity
---


title: can I legally make a "RTX game"

text:
# Question
Title: can I legally make a "RTX game"
I'm making a game called "karlson RTX", a remake of the game "karlson" by danidev, but it has "RTX" in the name and the game starts with a the way it's meant to be played splash screen, containing the nvidia icon, and soon to be containing it's slogan

will this game (which will be released free, and open source) run into any legal issues? and if so how can I fix them?

I suppose it's free advertising for the brand but you can never be too sure, It also isn't in any way offending the brand if anything promoting it

# Answer
> 3 votes
NVidia briefly describes trademark usage here and here. It sounds like you need to be a partner to use their trademarks, although I think those documents may be primarily directed at hardware manufacturers.

> Partners should not incorporate NVIDIA Brand Features into their own productname, service names, trademarks, logos, or company names.

Perhaps more relevant are their general legal notices:

> NVIDIA's trademarks may be used publicly with permission only from NVIDIA

---
Tags: legal, copyright
---


# Question
Title: Centering Image inside ImGui window causes bug
I've tried drawing RenderTexture directly to the ImGui window and I've stumbled upon a bug. Everything is drawn correctly until I center ImGui Image inside the ImGui window.

Centered Image:

Not centered Image:

As you can see when Image is centered in the ImGui window some lines aren't showing up (they are drawn and I'm not talking about first vertical line, last horizontal etc.) but when Image is slightly off-centered RenderTexture is drawn properly. Is it a bug or am I doing something wrong?

Example source code:

```
#include "imgui.h"
#include "imgui-SFML.h"

#include <SFML/Graphics.hpp>

const sf::Time TIME_PER_FRAME = sf::seconds(1.0f / 60.0f);
bool isTextureLoaded = false;

void render_grid(sf::RenderTexture &renderTexture)
{
    sf::Vertex line[2];
    for (int i = 0; i <= renderTexture.getSize().y; i += 32)
    {
        line[0] = sf::Vector2f(0, i);
        line[1] = sf::Vector2f(renderTexture.getSize().x, i);
        renderTexture.draw(line, 2, sf::Lines);
    }

    for (int i = 0; i <= renderTexture.getSize().x; i += 32)
    {
        line[0] = sf::Vector2f(i, 0);
        line[1] = sf::Vector2f(i, renderTexture.getSize().y);
        renderTexture.draw(line, 2, sf::Lines);
    }
}

void process_imgui(sf::RenderWindow &window, sf::RenderTexture &renderTexture, sf::Sprite &sprite)
{
    //ImGui::SetNextWindowPos(ImVec2{ 251, 20 });
    ImGui::SetNextWindowSize(ImVec2{ static_cast<float>(window.getSize().x - 251.0f), static_cast<float>(window.getSize().y - 20.0f) });
    ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2{ 0, 0 });
    ImGui::Begin("Tileset", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysHorizontalScrollbar);

    renderTexture.clear();
    renderTexture.draw(sprite);
    render_grid(renderTexture);

    //float x = (ImGui::GetWindowSize().x - static_cast<float>(renderTexture.getSize().x)) * 0.5f; //doesn't draw grid correctly
    float x = (ImGui::GetWindowSize().x - static_cast<float>(renderTexture.getSize().x)) * 0.499f; //draws grid correctly
    ImVec2 imagePosition(x, 20.0f);
    ImGui::SetCursorPos(imagePosition);
    ImGui::Image(renderTexture, ImVec2(static_cast<float>(renderTexture.getSize().x), static_cast<float>(renderTexture.getSize().y)));

    static bool saveToFile = true;
    if (saveToFile)
    {
        sf::Image image(renderTexture.getTexture().copyToImage());
        image.saveToFile("correct.png");
        saveToFile = false;
    }

    ImGui::End();
    ImGui::PopStyleVar();
}

int main(void)
{
    sf::RenderTexture renderTexture;
    sf::Texture texture;
    sf::Sprite sprite;

    sf::RenderWindow window(sf::VideoMode(1600, 900), "Test");
    window.setFramerateLimit(60);
    window.resetGLStates();

    texture.loadFromFile("test1.png");
    renderTexture.create(texture.getSize().x, texture.getSize().y);
    sprite.setTexture(texture);

    renderTexture.draw(sprite);
    render_grid(renderTexture);

    ImGui::SFML::Init(window);

    sf::Clock clock;
    sf::Time timeSinceLastUpdate = sf::Time::Zero;

    while (window.isOpen())
    {
        sf::Time elapsedTime = clock.restart();
        timeSinceLastUpdate += elapsedTime;

        while (timeSinceLastUpdate > TIME_PER_FRAME)
        {
            timeSinceLastUpdate -= TIME_PER_FRAME;

            sf::Event event;
            while (window.pollEvent(event))
            {
                ImGui::SFML::ProcessEvent(event);

                if (event.type == sf::Event::Closed)
                    window.close();
            }
        }

        ImGui::SFML::Update(window, elapsedTime);
        process_imgui(window, renderTexture, sprite);

        window.clear();
        ImGui::SFML::Render(window);
        window.display();
    }

    ImGui::SFML::Shutdown();
    return 0;
}

```

Example texture:

# Answer
As noted in my comment, it could be a rasterization/sub-pixel issue.

The line thickness is small enough that during the rasterization process the lines end up between the pixels and are being discarded.

Try increasing the line thickness to see if that fixes the problem.
> 1 votes

# Answer
It was a "rounding error". When you encounter similar bug then make sure your ImGui window/Image inside window are on rounded position. In my case "float x" variable was 39.5f and when I ceiled it everything was rendered correctly. Also you can check if your image size translates to the integer factor (e.g. it's drawn at 1x, 2x, 3x etc. of its real size). This fix is directly from the author of imgui-sfml.
> 1 votes

---
Tags: c++, sfml, imgui
---


title: Map circular thumbstick to square

text:
# Question
Title: Map circular thumbstick to square
I want to make a plane controller using SDL2. I want to use one joystick for pitch/roll. Y-axis sets the pitch-flaps, and X-axis sets the roll-flaps.

But there is one problem: Say I want to fully pitch and roll at the same time: I will hold the joystick at a 45 degree angle. But in SDL2, the joyAxis then get reported as 0.707... which is roughly half of the square root of 2. I understand why this happens: the physical joystick is restricted within a circle, so to move it up, you need to sacrifice a little bit of left/right. So the magnitude of the input vector is at most 1, instead of sqrt(2). How do I correct for this in code? I can't think of a good mapping.

I would like something like this:

```
float rawInput[2] = {0.707, 0.707};
float actualInput[2] = squaredCircle(rawInput); // {1,1}

rawInput = {1, 0};
actualInput = squaredCircle(rawInput); // {1,0}

```

What is a good `squaredCircle` function?

# Answer
> 1 votes
If the angle is 45° + 90°k, we want to multiply by sqrt(2). When the angle is just 90°k, we want to multiply by 1.

Thus, linearly interpolate between 1 and sqrt(2) based on `abs( atan(x/y) - 45° )/45`, then scale the input by that value.

This works because atan(x/y) gives a value in the domain \[0°, 90°\>. We then subtract 45° to get a range of \[-45°, 45°\>, which we then mirror with abs() to \[45°, 0, 45°\>. We then normalize it to \[0,1\>.

Because division by 0 is undefined, we will manually check that y is not 0. Since this implies a 90° angle, it also solves our incomplete domain. We now have a domain of \[0,1\].

```
#include <math.h>
#include <stdio.h>

#ifndef M_PI
#define M_PI 3.141592654
#endif

#define SQRT2 1.414213562

#define NEAR_ZERO 0.000001

typedef struct vec2f_t {float x,y;} vec2f;
#define vec2f(x,y)  (vec2f){x,y}
#define printv2(v2) printf(#v2"=vec2(%f, %f)\n",v2.x,v2.y)

vec2f squaredCircle(vec2f in)
{
    if (fabs(in.x) < NEAR_ZERO){
        return in; // multiple of 90 degs so don't scale
    }

    float t = fabs( atan(in.x/in.y) - M_PI/4 ) * (4/M_PI); // a/(b/c) = a*(c/b)
    // t = 1 when multiple of 90 deg
    // t = 0 when multiple of 90 deg + 45 deg

    // scale = (sqrt(2.0) - 1.0)*(1.0-t) + 1.0;
    // (a-1)*(1-b) + 1 = a + a*-b + -1*1 + -1*-b +1
    //                 = a - ab +b -1 +1
    //                 = a*(1 - b) + b

    float s = SQRT2*(1.0-t) + t;

    return (vec2f){s*in.x, s*in.y};
}

int main(){
    vec2f in = vec2f(1.0, 0.0);
    in = squaredCircle(in);
    printv2(in);

    in = squaredCircle(vec2f(0.707, 0.707));
    printv2(in);

    in = squaredCircle(vec2f(0.5, 0.5));
    printv2(in);

    in = squaredCircle(vec2f(0.0, 1.0));
    printv2(in);
}

```

---
Tags: mathematics
---


# Question
Title: Enemy Follows the Player Even His Death Animation Triggered
I have a 2D game project and I am coding but still on learning level. If I put simply, its based on player's escape and enemy follows to hurt him. Important case is, I am using A\* PathFinding for this because there are obstacles for enemies and they need to pass them.(A stars pathfinding here: https://arongranberg.com/astar/ )

Problem is: Enemy following Player, wherever he goes on the flat rectangular scene, but when I kill enemy while following, his death animation triggered and he dies in 3 seconds but he still keeps following me while he is dying process going on and even when he is lying down on the ground. Simply flies to me.

What I need is to make him stop at that very location when his "isDead" parameter gets triggered. Because of A\* using, I couldn't find a way to do it and override A\* somehow.

Enemy has two scripts, one of them is the A\* Path Finding script and the other is my Melee\_Enemy which I use for animations, taking damage..etc kinda stuff. Melee\_Enemy script is down below.This is the code I use for attack when close to player, and isDead function:

> ```
> public float stopDistance;
> private float attackTime;
> private bool isCloseForAttack;
> public float attackSpeed;
>
> public void Update()
> {
>     animator = gameObject.GetComponent<Animator>();
>
>     if (player != null && !isDead)
>     {
>         if (Vector2.Distance(transform.position, player.position) > stopDistance)
>         {
>             animator.SetTrigger("isNotRunning");
>         }
>         else
>         {
>             animator.SetTrigger("isRunning");
>             if (Time.time >= attackTime)
>             {
>                 StartCoroutine(Attack());
>                 attackTime = Time.time + timeBetweenAttacks;
>             }
>         }
>     }
>
>     IEnumerator Attack()
>     {
>         player.GetComponent<Player>().TakeDamage(damage);
>
>         Vector2 originalPosition = transform.position;
>         Vector2 targetPosition = player.position;
>
>         float percent = 0;
>         while (percent <= 1)
>
>
>             percent += Time.deltaTime * attackSpeed;
>         float formula = (-Mathf.Pow(percent, 2) + percent) * 4;
>         transform.position = Vector2.Lerp(originalPosition, targetPosition, formula);
>         animator.SetTrigger("attackMove");
>
>         yield return null;
>
>     }
> } }
>
> ```

@DMGregory

This is how I tried to disable the script:

On my Enemy, there are two scripts, one is the script I use for energy, taking damage.etc named "Melee\_Enemy" which that is the script I shared in my post. Other script is the AI Pathfinder Script of the separate component I use. I want to disable second script by coding it in the first script. What I tried is:

On top I created

> public Component aiScript;

After Update() I used this:

> if(isDead) { Destroy(gameObject.GetComponent(aiScript)); }

But with this the code, unity has an error: aiScript cannot convert from 'UnityEngine.Component' to 'System.Type'

# Answer
> 0 votes
So how I solve the problem is, with help of @DMGregory I defined on top of the Melee\_Enemy script:

> public Component aiScript

I dragged and dropped my A\* Pathfinding script to the inspector, the area I defined as aiScript component. After that I add another code after Update() function:

> ```
>     if(isDead)
>     {
>         Destroy(aiScript);
>     }
>
> ```

So by doing this, when Enemy's Death animation trigered with (isDead), following component simply disables itself. And this is how my problem came to a solution.

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


# Question
Title: Place tiles along a specific axis / direction
I want to be able to place tiles only in the direction I've started "drawing" them.

For an example, if I click and hold on tile at position `(0,0)`, and start dragging to the right, I only want to select or draw on coordinates `(1,0)`, `(2,0)`, `(3,0)` and so on. However, for the next tile, if I point my mouse at the tile `(4,1)`, I only want `(4,0)` to be selected, aka, ignore the `Y` changes because I'm currently placing on the `X` axis.

What would be a good and clean way to do this?

I've tried doing this but not only does it not work well, my code is very bloated because I'm not good at this logic that requires more math than usual. Here's what I tried (needless to say it's very messy and didn't work properly):

```
private bool isSelecting;
private Vector3Int selectionDirection = Vector3Int.zero;
public List<Vector3Int> selectedPositions = new List<Vector3Int>();
private SelectDirect selectDirect;

    if (Mouse.current.leftButton.wasPressedThisFrame)
    {
        if (UIManager.IsMouseOverUI()) { return; }

        Vector3Int gridPosition = Map.GetGridPosFromMousePos();

        if (Map.IsInsideMap(gridPosition))
        {
            if (!selectedPositions.Contains(gridPosition)) { selectedPositions.Add(gridPosition); }
            isSelecting = true;
        }
    }

    if (Mouse.current.leftButton.wasReleasedThisFrame)
    {
        isSelecting = false;
        selectedPositions.Clear();
        selectionDirection = Vector3Int.zero;
        selectDirect = SelectDirect.None;
    }

    if (isSelecting)
    {
        if (selectionDirection == Vector3Int.zero && selectedPositions.Count == 2)
        {
            selectionDirection = selectedPositions[1] - selectedPositions[0];

            if (Mathf.Abs(selectionDirection.x) + Mathf.Abs(selectionDirection.y) > 1)
            {
                isSelecting = false;
                selectedPositions.Clear();
                selectionDirection = Vector3Int.zero;
                selectDirect = SelectDirect.None;
                return;
            }

            if (selectionDirection.x == 1) { selectDirect = SelectDirect.Right; }
            else { selectDirect = SelectDirect.Up; }

            Debug.Log(selectDirect);
        }

        Vector3Int gridPosition = Map.GetGridPosFromMousePos();

        if (Map.IsInsideMap(gridPosition))
        {
            switch (selectDirect)
            {
                case SelectDirect.None:
                    if (!selectedPositions.Contains(gridPosition)) { selectedPositions.Add(gridPosition); }
                    break;
                case SelectDirect.Right:
                    if (gridPosition.x - selectedPositions[selectedPositions.Count - 1].x == Mathf.Abs(selectionDirection.x) && !selectedPositions.Contains(gridPosition))
                    {
                        selectedPositions.Add(gridPosition);
                    }
                    break;
                case SelectDirect.Up:
                    if (gridPosition.y - selectedPositions[selectedPositions.Count - 1].y == Mathf.Abs(selectionDirection.y) && !selectedPositions.Contains(gridPosition))
                    {
                        selectedPositions.Add(gridPosition);
                    }
                    break;
            }
        }
    }

```

# Answer
> 1 votes
Some semi pseudo code

* Change `SelectDirect.Up` to `SelectDirect.Vertical` and `SelectDirect.Right` to `SelectDirect.Horizontal`
* ```
if (Mathf.Abs(selectionDirection.x) == 1) {
    selectDirect = SelectDirect.Horizontal;
    fixedY = selectedPositions[0].y;
}

```
* On the case switch `Horizontal` you can compare `SelectedPiece.position` vs `Vector2(SelectedPiece.x, fixedY)`. This should work for left movement without extra code.
* `Vertical` is going to work the same, just comparing against a stored x value;

You are storing either the initial x or y value of your first selected tile. After drawing a horizontal line, if the selected tile has not the same y value as the original one, the line is not straight and gets discarded. You can fine tune this later if you want with a small toleranz of maybe 1 tile (to add the intended tile) by setting the fixed value instead of the current selected.

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


# Question
Title: Prevent feet from moving for a Unity character from a Mixamo animation
So my question isn't about root motion, but rather just keeping the feet in place on the ground for a Mixamo animation... I tried to just delete the feet and toes in avatar configure, but nope... I am wondering if there is some sort of simple way to have an animation affect all but the feet?

# Answer
> 2 votes
One way to do this would be with animation layers. Create a new layer in the animator window and give it an avatar mask that only uses the upper body. That way, when you play an animation that layer the feet will not move

---
Tags: unity, animation
---


# Question
Title: Making a 2D gun spin from recoil when it shoots
I am trying to clone the game "Flip the Gun" as an exercise.

Here is the behaviour I have so far.

And here is the code I am using:

```
if (Input.GetKeyDown(KeyCode.Space))
{
    rigidbody2D.AddForceAtPosition(
                transform.position-recoilPoint.transform.position * recoilForce,
                recoilPoint.position,
                ForceMode2D.Impulse
    );
}

```

As you can see in the video, the gun is moving too fast and rotating too fast. It seems out of control. I am not sure if the way of adding force to the gun is correct or not.

Thank DMGregory for editing the question for me. I am new to this family so that helped a lot. :)

# Answer
The default `rigidbody.AddForce` applies the force facing the center of mass of your rigidbody, so it will never directly cause any rotation. But there is also the method `rigidbody.AddForceAtPosition(Vector3 force, Vector3 position, ForceMode mode)`. This method can be used to apply forces to an object which are off-center and thus will result in a mix of rotation and velocity, depending on how far off-center it is.

A good way to use this would be to create a childObject to your gun which represents the point where you want the force to act and then use the position and direction of that object as input for AddForceAtPosition. Here is an (untested!) example script. This script uses a 3d Rigidbody. For a game with 2d physics, replace `Rigidbody` with `Rigidbody2D`:

```
[RequireComponent(typeof(Rigidbody))]
class GunRecoil : MonoBehaviour {

    [SerializeField] private Transform recoilPoint;
    [SerializeField] private float recoilForce = 10.0f;
    private Rigidbody myRigidbody;

    private Start() {
        myRigidbody = GetComponent<Rigidbody>();
        if (recoilPoint == null) {
            Debug.LogWarning("You forgot to assign the Recoil Point in the inspector!");
        }
    }

    private void FixedUpdate() {
        if(Input.GetButtonDown(KeyCode.space)) {
            myRigidbody.AddForceAtPosition(
                recoilPoint.forward * recoilForce,
                recoilPoint.position,
                ForceMode.Impulse
            );
        }
    }
}

```
> 1 votes

---
Tags: unity, c#, 2d, physics, torque
---


title: Unity Hanging On Application Reload

text:
# Question
Title: Unity Hanging On Application Reload
I have recently added Vivox general voice chat to the game I am working on. Ever since adding it, I have run into issues with the application reload time after editing a script. If I edit a script and switch back to Unity, it hangs on the application reload window for a very long time, most times never recovering until I force close Unity or until Unity just crashes. Has anyone run into a similar issue with this or any other package?

# Answer
Make sure that you are ending your sessions with Vivox and logging out when the editor quits. You can use the `void OnApplicaitonQuit()` function in Unity and add code there to end the session and log the user out. If you don't close the sessions and logout it will build up in the garbage collector and cause Unity to freeze up.
> 2 votes

---
Tags: unity
---


# Question
Title: A* Pathfiding movement is not stopping and constant
I'm trying to make my player move towards mouse click using A\* Pathfinding but I'm having some odd issues that I can't solve.

One of the issues is that player is moving a little bit even though it arrives at the position of the other transform

The second one is that the force is that is applied to the player is not constant, I would like it to keep always the same movement speed. I've tried to change to use transform.Translate to move the player with constant movement speed but it makes the movement to be like walk a little then stop, walk a little then stop...

This is the code that I'm using

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

public class Player : MonoBehaviour
{

    [SerializeField] private float speed = 100;
    [SerializeField] private Text lifeText;
    [SerializeField] private int life;
    [SerializeField] private GameObject target;
    [SerializeField] private float nextWaypointDistance = 3f;

    //AI configurations
    private Path path;
    private Rigidbody2D rigidbody;
    private Seeker seeker;
    private int currentWaypoint = 0;
    private bool reachedEndOfPath = false;

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

        InvokeRepeating("UpdatePath", 0f, .2f);
    }

    // Update is called once per frame
    void Update()
    {
        lifeText.text = "Vida: " + life.ToString();

        if (Input.GetMouseButtonDown(1)) //right click
        {
            Vector2 mousePos = Input.mousePosition;
            Vector2 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
            target.transform.position = worldPos;
        }
    }

    private void UpdatePath()
    {
        if (seeker.IsDone())
            seeker.StartPath(rigidbody.position, target.transform.position, OnPathComplete);
    }

    void FixedUpdate()
    {
        if (path == null) return;

        if (currentWaypoint >= path.vectorPath.Count)
        {
            reachedEndOfPath = true;
            return;
        }
        else
        {
            reachedEndOfPath = false;
        }

        Vector3 direction = (path.vectorPath[currentWaypoint] - (Vector3)rigidbody.position).normalized;

        Vector3 force = direction * speed * Time.deltaTime;

        rigidbody.AddForce(force);

        float distance = Vector2.Distance(rigidbody.position, path.vectorPath[currentWaypoint]);

        if (distance < nextWaypointDistance)
        {
            currentWaypoint++;
        }
    }

    private void OnPathComplete(Path p)
    {
        if (!p.error)
        {
            path = p;
            currentWaypoint = 0;
        }
    }

}

```

What I want to is to make the movement smoother and with constant movement speed.

Can you guys help me?

# Answer
> 1 votes
You're currently using a force to accelerate in the direction of your next waypoint. This can lead you to overshoot the point, because you arrive with some velocity that you then need to brake.

Instead, you can compute a point some suitable distance further along your path, without overshooting:

```
var nextPoint = Vector3.MoveTowards(rigidbody.position,
                                    path.vectorPath[currentWaypoint],
                                    movementSpeed * Time.deltaTime
                 );

```

Then either compute a velocity/force to take you to that point, or simply ask your rigidbody to slide its way there:

```
rigidbody.MovePosition(nextPoint);

```

---
Tags: unity, c#, path-finding
---


# Question
Title: Significant frame drop upgrading from Unity 2019 to Unity 2020
I used to use Unity 2019.4.22f1, but now that 2020.3.0f1 has been marked as LTS, I've decided to switch to it.

For no apparent reason, it seems like my game is getting consistently lower framerate, precisely, almost like it's cut in half. I used to get 800-1000 FPS in my game but now its around 400-500. I've tested with multiple things that are even more demanding, and where I used to get 500 fps, I now get 200 fps.

It's clear that this is likely a configuration thing, but I don't know which settings to change, if any of them have been.

There is this SX article here which didn't get answered and seems to have the same problem: Link

And this article which seems to talk about a similar problem, though it is marked as fixed: Link

# Answer
> 1 votes
Answered by the nice people in the comments. Summary:

> The discussion under the second link you posted came to the conclusion that it's the Unity Editor which now takes a few milliseconds longer to render. That means two things: 1. it doesn't scale with the complexity of your game scene and 2. it won't affect what actually matters: the performance of exported games.

---
Tags: unity, performance
---


# Question
Title: Which array does dstArrayElement refer to in the VkWriteDescriptorSet structure?
Here is the link of VkWriteDescriptorSet structure from vulkan specification:

https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkWriteDescriptorSet.html

Text pertaining **dstArrayElement**

> dstArrayElement is the starting element in that **ARRAY**. If the descriptor binding identified by dstSet and dstBinding has a descriptor type of VK\_DESCRIPTOR\_TYPE\_INLINE\_UNIFORM\_BLOCK\_EXT then dstArrayElement specifies the starting byte offset within the binding.

I want know which array this statement is refering to?

# Answer
I'll start with a bit context about `VkDescriptorSetLayoutBinding` and answer your question afterwards.

---

`VkDescriptorSetLayoutBinding` allows to describe not only *one* resource, but an array of resources.

Let's assume that you did not want to use only one texture in a GLSL shader:

```
layout(set = 0, binding = 0) uniform sampler2D texture;

```

but an array of textures:

```
layout(set = 0, binding = 0) uniform sampler2D textures[];

```

you'd create a `VkDescriptorSetLayoutBinding` with multiple texture descriptors, e.g. like follows:

```
VkDescriptorSetLayoutBinding dsLayout = {};
dsLayout.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
dsLayout.descriptorCount = 100u;

```

---

With `VkWriteDescriptorSet` you *write* the actual resource information to the GPU, s.t. your shaders know where they can "find" the resource on the GPU... or maybe more accurate: how they can access a certain resource.

If you wanted to write all `100` texture descriptors at once, you'd set the following data:

```
VkWriteDescriptorSet write = {};
write.dstArrayElement = 0u;
write.descriptorCount = 100u;

```

But if only the 70th texture has changed, you'd like to update only that one with:

```
VkWriteDescriptorSet write = {};
write.dstArrayElement = 69u;
write.descriptorCount = 1u;

```

---

So, **to answer your question**: `dstArrayElement` refers to the array of descriptors defined in `VkDescriptorSetLayoutBinding`. There will be many cases where `VkDescriptorSetLayoutBinding` only describes one descriptor (one could also say: an array of length 1), but if you use one `VkDescriptorSetLayoutBinding` to describe an array of resources, you might not always want to update all of them, but only one (or a few) by specifying an offset into the array of descriptors via `dstArrayElement`.

Btw.: `VkDescriptorSetLayoutBinding` and `VkWriteDescriptorSet` are linked to the same resource via its `binding` and `dstBinding` members, respectively.
> 3 votes

---
Tags: vulkan
---


# Question
Title: Implementing priority structure into a behavior tree, to react to player actions
My goal is to have a behavior tree that can run alone (autonomously) but also react to input from the player.

I'm making an AI for a hack and slash game where the AI will fight you, chase you, etc. and play defensive based on certain stats (health etc), but I want to add an additional layer; events from player. Say the player attacks, I want a random chance maybe 5-10% to trigger a dodge or step-back from the AI.

Currently I have its own selector running, but that is not sufficient, as it just has same priority or triggers on the same level as the other selectors / sequences in the tree. So how do I go about implementing a priority into the tree?

I want to have dodge, which should be labelled as maybe priority 1 if the event triggers, else it should just go about its usual business.

# Answer
You did not specify engine, but any decent BT implementation should support some form of task abortion by a decorator, or at least re-running selection on demand.

Make dedicated event handling node right under the root selector, highest priority. Attach a decorator that checks if there is any pending event(s). Allow it to abort lower priority tasks. Put all relevant event handlers under that node.

You probably want to add another decorator, that locks current event handler (ignores other events) for duration of the animation (e.g. dodge), but be aware of event priority (death \> dodge) and relevance/expiration (e.g. chaining next dodge while current one runs).

### How to implement required functionality from scratch.

Nodes should have an `Abort` method, and it must be deterministic: that is, once called, underlying processes (e.g. coroutines and threaded tasks) must be cancelled immediately. If that's not possible, then make `Abort` to be a task itself, although this is undesirable.

Decorators should recalculate their states once relevant underlying state changes. One way to do it is with Blackboard and Services. Blackboard is just a collection of variables relevant to the BT; blackboard must notify decorators when any variable changes. Service is blackboard update function that is ran periodically, it copies and/or recalculates relevant state from outside (the agent and the world) into blackboard.

(Note that I am using UE4 terminology here, not sure if standard; btw UE4 BTs are great, you may as well just copy UE's model).

Once relay/gate-type decorator recalculates it's state to new outcome that enables it's node, the decorator should ask BT to re-select current node, starting selection from decorator owner's parent, but only if currently running node is lower priority or child (otherwise BT would just select that higher-priority node again). Note that node need to be aborted only if BT selects another node, otherwise it should continue uninterrupted.
> 0 votes

---
Tags: ai, behavior-tree
---


# Question
Title: Raycast is not restricting by other layer collider
I have converted my project to URP and suddenly I found the situation where my Raycast code even is working beneath the collider (other layer colliders):

```
if (DisplayMessage.Click && Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 1000f, layermask))

```

I corss check the signature of raycast it is fine and the collider it self. Is there any changes in URP? Here is the way i am setting the layer:

```
int layermask => LayerMask.GetMask("Interact");

```

Scenario: In my scene, I have a plane (Default Layer) and a cube(Interact layer). The cube is beneath the Plane. But my camera Detecting the cube on mouse pointer and bypassing the Floor. The raycast should acctually not work if there any object of the desired layer.

# Answer
> 1 votes
This is unrelated to URP. That's part of the rendering system, while raycasts are handled by the physics system, and it's the same physics system no matter what renderer you use.

When you give a layer mask to a raycast, you are asking it to consider colliders only on the layers enabled in the mask. Any other layers are ignored - the raycast behaves as though those colliders were deleted from your scene.

So if you want to cast a ray, then check if it hit the layer of your choice (and not an intervening collider on a different layer), you can do it like so:

```
if (DisplayMessage.Click
    && Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 1000f)
    && hit.collider.gameObject.layer == interactionLayer) {
    // Do a thing.
}

```

Here we include *all* layers in our raycast, so obstacles on other layers can block it. Then, once we've hit something, we check whether it's the layer we wanted to hit. If not (ie. we hit an obstacle on a different layer), then we fail out of the `if`. Only if we hit our desired layer with no obstacles in between do we enter the body of the `if`.

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


# Question
Title: Why does the triangle rendered by OpenGL ES 2.0 , with SDL 2.0 context, vanishes after a single render, if events are not polled?
I was experimenting with OpenGL ES 2.0 and being new to OpenGL, I was trying to render a simple triangle. But I was shocked to see that, if I **do not** call `SDL_PollEvent(...)` after `glDrawArrays(...)` in the game loop, I see the triangle render on the screen for a split second and then it vanishes altogether ! But, if I call `SDL_PollEvent` then **everything is fine** ! Can anyone explain to me the reason for this abnormal behavior???

However, this is the interesting part of my code:

This code works perfectly, if I **uncomment** the **commented** block of code:

```
uint32_t vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(pos);
glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void*)0);

bool run = true;
SDL_Event e;
while (run)
{
    glDrawArrays(GL_TRIANGLES, 0, 3);
  SDL_GL_SwapWindow(window);

/*while(SDL_PollEvent(&e))
{
      switch(e.type)
      {
           case SDL_QUIT:
                run = false;
                break;
      }
} */

```

}

Vertex Shader:

```
precision mediump float;
attribute vec3 pos;
void main()
{
    gl_Position = vec4(pos.xyz, 1.0);
}

```

Fragment Shader:

```
precision mediump float;
void main()
{
      gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);
}

```

Every help will be greatly appreciated, Thankyou everyone in advance !

# Answer
> 2 votes
This behaviour is normal. Due to internal structure of the SDL, you are required to call `SDL_PollEvent` or `SDL_PumpEvents` (it is called internally by `SDL_PollEvent`) in your main loop so that SDL event subsystem works as expected. Without this call, your loop is stuck infinitely somethere within SDL waiting for the events to be processed.

See details on the SDL\_PollEvent wiki page.

Considering your comment the SDL\_PumpEvents wiki page mentiones that event pumping should be done on the same thread that initialized the video subsystem. So your intent is, unfortunatelly, not compatible with internal architecture of the SDL either. But event pumping is really extra lightweight stuff, not sure if it's worth it anyway.

---
Tags: game-loop, opengl-es2, sdl2
---


# Question
Title: Is it possible to prevent the collider 2D outline from hiding in Unity?
Is it possible to prevent the collider 2D outline from hiding in Unity?

I am creating some animations in Unity. To create animations I select different parts of a hero and move them frame by frame. Now I am working on the run animation and would like to see the bottom collider during parts movement for the animation creation.

In my case the collider outline is red:

I don't want the red bottom line (which is the collider outline) to disappear while I am creating animations. Should I research the Unity extensions and maybe write my own which would prevent the collider from hiding or is it possible to achieve what I want out of the box somehow?

# Answer
> 2 votes
You can add a script that draws a gizmo along this line. Here's an example:

```
public class ColliderVisualizer : MonoBehaviour {

    public EdgeCollider2D edge;
    public Color32 color = new Color32(255, 0, 0, 255);

    public void OnDrawGizmos() {

        if (edge == null) return;

        Gizmos.color = color;

        var points = edge.points;

        Vector3 previous = transform.TransformPoint(points[0] + edge.offset);

        for(int i = 1; i < points.Length; i++) {
            Vector3 next = transform.TransformPoint(points[i] + edge.offset);
            Gizmos.DrawLine(previous, next);
            previous = next;
        }

    }
}

```

Place this on your object, and assign the edge collider to the `edge` field in the Inspector. Then it will continue drawing the edges in the edge collider whether or not the object is selected.

You can modify this script to work with other types of collider if you need - I was just guessing that yours is an edge collider based on the example image.

---
Tags: unity, animation, collider, outline
---


# Question
Title: Should I change velocity or apply force to implement a jump in Unity?
I have started making a basic platformer game just for fun. Its going to be the style of the original Super Mario Bros game, but with 3d assets.

My problem is that I'm using a rigidbody and using code I have always used to make my player object jump. It seems really slow. I am using a capsule object, the standard size (which is 2 units height). I have played about with the mass, ive tried 1 and 40. And other than having to increase the 'jumpForce' value accordingly, it seems to have not changed the jump speed at all.

So I'm hoping there is a way to tweak the flight of the jump whilst still using the Rigidbody component, and if so how please?

If not, I think I'm able to write my own code to make the gravity etc, but this seems stupid since Unity is a well established game framework I expect other people have also needed to change it and I'm sure there is a way I just don't know about.

Hope someone can help me.

Many thanks!

PS (Here is the basic code I have to make the character jump): PPS: It's not super-slow , like being in space. (I've had that problem in LibGDX where my objects scales were all wrong. But this time I have just the standard sized Capsule (1x2 units) and the platform is about 4 units above the ground. He jumps ok, but I'd like to make him jump really-fast like mario can

```
 public class PlayerController : MonoBehaviour {
     Rigidbody rb;
     Vector3 faceRight = new Vector3(0, 90, 0);
     Vector3 faceLeft = new Vector3(0, -90, 0);
     float halfHeight;

     float speed = Constants.speed;
     float jumpForce = Constants.jumpForce;

     private bool IsGrounded()
     {
         return Physics.Raycast(transform.position, Vector3.down, halfHeight + 0.1f);
     }

     void Start () {
         halfHeight = GetComponent<Collider>().bounds.extents.y;
         rb = GetComponent<Rigidbody>();
         rb.transform.Rotate(0, 90, 0); // make the capsule face right at start.
     }

     void Update () {
         HandleKeys();
     }

     void HandleKeys()
     {
         if (Input.GetKey(KeyCode.A))
         {
             if (rb.transform.eulerAngles != faceLeft)
                 rb.transform.eulerAngles = faceLeft;

             rb.transform.Translate(Vector3.forward * speed * Time.deltaTime);
         }
         if (Input.GetKey(KeyCode.D))
         {
             if (rb.transform.eulerAngles != faceRight)
                 rb.transform.eulerAngles = faceRight;

             rb.transform.Translate(Vector3.forward * speed * Time.deltaTime);
         }
         if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
         {
             rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
         }
     }
 }

```

# Answer
> 0 votes
The answer turned out to be simple again. And thanks to DMGregorys comments above I found the answer quickly.

Just go to ' Edit\> Project Settings\> Physics' and play with the gravity and the jumpForce you create and you can achieve different jumping and falling speeds without changing velocity directly yourself in code, and hence disrupting the physics calculations (such as gravity, velocity, collisions etc)

# Answer
> 1 votes
I doubt you still need help on this now, but the problem is that you're changing the value of `JumpForce` in the script. This value gets overridden by the value attached to the object you are applying force to. Try changing the value in the inspector instead.

---
Tags: unity, physics, rigidbody
---


# Question
Title: How can I change the root namespace for scripts in Unity?
How can I change the root namespace for scripts in Unity?

I went to `Edit` \- `Project Settings...` \- `Editor` \- `Root namespace` and put there the `gameplay` value.

I checked that the `Assembly-CSharp.csproj` has the `<RootNamespace>gameplay</RootNamespace>`

Now I go to VS Code editor, create a class and the class still uses a wrong namespace. What may I be missing here?

# Answer
> 5 votes
In Jetbrains Rider there is one option on folder properties named "Namespace provider" when we use a right-click mouse on the folder. Just uncheck that check box and the namespaces work as expected. You can use this for the Project and Scripts folders.

I'm not sure if VS Code has this option.

**Two good videos for namespaces in Unity:**

---
Tags: unity, c#, visual-studio-code
---


# Question
Title: Why the Vector3.Dot value is -12 when running the game?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System;

public class InteractableItem : MonoBehaviour
{
    public string currentMode;

    private Transform player;
    private InteractableMode currentInteractableMode;
    private string currentDesription;
    private float originDistance;

    private void Awake()
    {
        player = GameObject.Find("Player").transform;

        originDistance = transform.GetComponent<InteractableItem>().distance;
    }

    public enum InteractableMode
    {
        Description,
        Action,
        ActionWithoutThrow
    };

    public enum ViewMode
    {
        FrontView,
        AllView
    };

    public ViewMode viewMode = ViewMode.AllView;

    public InteractableMode interactableMode = InteractableMode.Description;
    public float distance;

    [TextArea(1, 10)]
    public string description = "";

    public bool IsAnyAction()
    {
        return interactableMode == InteractableMode.ActionWithoutThrow || interactableMode == InteractableMode.Action;
    }

    public bool IsActionWithoutThrow()
    {
        return interactableMode == InteractableMode.ActionWithoutThrow;
    }

    private void Start()
    {
        currentMode = GetComponent<InteractableItem>().interactableMode.ToString();
        currentInteractableMode = GetComponent<InteractableItem>().interactableMode;
        currentDesription = GetComponent<InteractableItem>().description;

    }

    private void Update()
    {
        var heading = transform.position - player.transform.position;
        var dot = Vector3.Dot(heading, -transform.forward);

        if(viewMode == ViewMode.FrontView
            && dot < 1)
        {
            transform.GetComponent<InteractableItem>().distance = 0;
        }

        if (viewMode == ViewMode.FrontView
            && dot > 1)
        {
            transform.GetComponent<InteractableItem>().distance = originDistance;
        }
    }
}

```

The script is attached to some objects and one of them the ViewMode is set to FrontView and then when running the game first time the dot value is -12 and then it's getting inside and going the line :

```
if(viewMode == ViewMode.FrontView
    && dot < 1)
{
    transform.GetComponent<InteractableItem>().distance = 0;
}

```

but it should not set the distance to 0. only if I'm getting close enough to the item then it should see the item from the front and then only if I'm moving the player behind the item the dot should be minus and set the distance to 0 but for some reason the dot is minus 12 when running the game so it's setting the distance to 0 right away.

# Answer
> 0 votes
Your code returns a negative value if the player is behind the item. This is easy to verify with a simple test script:

```
public class DotTest : MonoBehaviour {

    public Transform target;
    public float dot;

    private void Start() {
        Assert.IsNotNull(target);
    }

    private void Update() {
        var heading = transform.position - target.transform.position;
        dot = Vector3.Dot(heading, -transform.forward);
    }
}

```

Just move the object with this script around and watch the value of the `dot` field in the Inspector.

`Vector3.Dot()` returns a positive value if two vectors are facing the same direction, and a negative value if they're facing opposite directions. You're comparing the direction *from the player to the item* to the item's backward vector.

If you don't want the code to return a negative value in this situation, you need to change the code (just get rid of the minus sign before `transform.forward`). If you think this same code is working correctly in other places and not here, you are mistaken.

# Answer
> 0 votes
The dot product returns -12 because you're facing away from the object initially.

You should use

```
var heading = player.transform.position - transform.position;
var dot = Vector3.Dot(heading.normalized, transform.forward);

```

to figure out if you're facing the object. And heading must be normalized for the dot product.

If dot is greater than 0 then you're facing the object (might want a higher threshold, such as Mathf.Cos(45 * Mathf.Deg2Rad) for looking at it up to 45 degrees)

And use `heading.magnitude` to find the distance.

Also, by flipping around `transform.position - player.transform.position` you avoid the negative operator on the Vector3.

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


# Question
Title: Box2d: High screen resolution / frequency causes high friction?
I'm using Cocos Creator with (built-in) box2d for physics.

Recently our game behaves weirdly on our new device Galaxy S20 Ultra 5G - which has screen size = 1440 x 3200 - frequency = 120Hz.

After stop pushing, all our physical bodies almost stop immediately like they has very high friction. No other device react that way.

Anyone experienced this issue can give me an advice?

# Answer
> 1 votes
The problem is with high freequency 120Hz

Solution is to set fixed deltaTime for update physics world instead of using graphic update time

```
cc.director.getPhysicsManager().enabledAccumulator = true;

```

Docs can be found here: https://docs.cocos.com/creator/api/en/classes/PhysicsManager.html#enabledaccumulator

---
Tags: android, box2d, cocos2d, resolution, screen
---


# Question
Title: How to fix diagonal velocity being greater than axis-aligned?
I have a 2D top-down RPG type game, with movement in 8 directions (N/E/S/W/NE/NW/SE/SW) involving both x and y velocity.

I'm finding when I'm moving in the diagonal directions, I'm building both x and y velocity and it's making my character move faster than they do in a straight line along only x or only y. Is there a fix for this, so no matter which of the 8 directions I travel along, it's the same speed?

My code works like this. I initialize my variables and speed:

```
vel_x, vel_y=0
spd=1

```

Then each frame in my game loop, I apply drag to reduce the velocity:

```
vel_x*=0.2
vel_y*=0.2

```

Then my button presses add/subtract the `spd` value from their corresponding velocity direction x/y when pressed.

Lastly, I add the `vel_x` to my sprite's x position and same with `vel_y` for my sprite's y position.

How would I address this? Would I look at button press actions for when both keys are held, or limits for when `vel_x` *and* `vel_y` are 'high' enough in tandem?

I've done the latter and it helps, but I can't make it accurate.

Images: With velocity removed and just +-1 speed increases/decreases. Left is the proposed adjustment to the vertical movement. Right is no adjustment. Is left moving at same speed all the time and right isn't?

# Answer
> 3 votes
> Is there a fix for this so no matter what of the 8 I travel its the same speed?

Yes... You want to apply a total force and split it between x and y

To do this for any angle, you apply `± totalForce * sin(angle)` in one direction, and `± totalForce * cos(angle)` in the other.

Your case is simpler as the angle is fixed at 45 degrees when moving diagonally, and conveniently both `sin(45)` and `cos(45)` are the same ... `0.70710678118` (which happens to be `1/sqrt(2)`)

So multiply your X and Y forces by `0.70710678118` when moving diagonally, and the total will be the same as when moving in a cardinal direction.

Even better... If you use the formulas above instead of the fixed value, it works for *any* direction including N/E/S/W.

You can get the angle from the player's current rotation around the Y axis.

> How would I address this...?

If I've understood correctly and you're concerned about how forces add up over time...

Usually, you apply some form of damping so that movement decreases over time if there's no input.

You can do this a number of ways, but the simplest is probably to calculate the current speed (eg by checking how far the sprite had travelled in the timespan since the last frame) then multiply that speed by some number just below `1` (say `0.95`) and use that as your speed for the next frame.

That way, when you're applying a force, the sprite accelerates and when you let go, it slows down and eventually comes to a stop.

If you can't find a value that feels "just right", there's a lot of research on different ways to damp... Wikipedia's article on Damping might be a good starting point to get some search terms.

Edit:

> Is this equivalent to me irl walking straight 1m/s then turning diag and walking 1ms?

Yes

Think in terms of a 2D grid. We'll draw a triangle with the base being how far we travel in X and the side being how far we travel in y.

The hypotenuse is the resulting motion.

Moving Straight up?

* x stays at zero
* y increments by 1

No need to do any fancy calculations as that's obviously 1 unit.

Now let's move diagonally NE...

* x increases by `0.70710678118`
* y increases by `0.70710678118`

How long is the hypotenuse? Well, from Pythagoras, it should be

```
sqrt(x ^ 2 + y ^ 2)
or
sqrt(0.70710678118 ^ 2 + 0.70710678118 ^ 2)

```

(Remember I said `0.70710678118` is equivalent to `1/sqrt(2)`? This is one reason that's helpful to know ...).

```
1 / sqrt(2) ^ 2 simplifies to 1/2 or 0.5

```

So we get

```
sqrt(0.5 + 0.5)
or
sqrt(1)

```

Which is -of course- `1`

So yes, it's moving at the same speed of 1 unit/s.

# Answer
> 3 votes
You use trigonometry. Here we can just use the Pythagorean theorem:

```
a² + b² = c²

```

If the player is moving at a 45° angle, `a` and `b` are the same, so we can simplify to

```
2a² = c²
a² = c²/2
a = sqrt(c²/2)

```

Let's say that your desired movement speed is 10.

```
2a² = 10²
a² = 100 / 2
a = sqrt(50)
a = 7.071

```

So if you want the player to move diagonally at a total speed of 10 units/second, move them 7.071 units along X and 7.071 units along Y.

# Answer
> -1 votes
Think intuitively first.

orthogonal speed is a 2D Vector with an X and Y component.

if that Vector was (1,1). Then that makes the multiplier for x and y both 1. That means that diagonally, you're still going to be traversing the grid at 1 /ms in both directions.

Anytime we accelerate / decelerate we modify the speed vector.

the speed vector gets multiplied by the amount of time that has elapsed since the last frame in this case.

You then simply add / subtract the position vector.

---
Tags: 2d, mathematics, movement, linear-algebra, lua
---


# Question
Title: How to give a certain scene different preference settings then other scenes unity
In my unity game that I am creating there are 4 scenes. 3 of those scenes rely on a backdrop because they are the main menu, death screen and the escape screen(for when you escape the place). Therefore they need a high resolution image. However, the other scene (the main game scene) is incredibly laggy when the quality setting for the texture quality isn't "eighth res". How can I make it so that the texture quality for only my game scene is eighth res and the rest is normal res? This might help: my build order value is the main menu is 0, my game is 1, my death scene is 2 and my escape scene is 3. thanks in advance

# Answer
> 1 votes
ok, so I approached this all wrong. I thought that this texture setting would be a build related thing however I realized that I could just change the setting via scripting. So I put an event system in each of my scenes and gave it this incredibly simple script: menu and others that aren't game scene (c#):

```
    void Start()
    {

            QualitySettings.masterTextureLimit = 8;

    }

```
and what I did for the main game scene (c#):
```
  public static int low = 0;
    public static int medium = 0;
    public static int high = 1;
    // Start is called before the first frame update
    void Start()
    {
        if(low == 1)
        {
            QualitySettings.masterTextureLimit = 8;
        }
        if(medium == 1)
        {
            QualitySettings.masterTextureLimit = 2;
        }
        if(high == 1)
        {
            QualitySettings.masterTextureLimit = 1;
        }

    }
```

# Answer
> 1 votes
When you import a texture into your game, you can set the texture resolution and quality settings different for each one.

Open up the directory with your textures in your Asset explorer, click on each texture, look at the Inspector window and then set the "Max Size", and "Compression" to the lowest setting which still looks good enough for the particular use-case of that texture.

More about texture import settings in the manual.

---
Tags: textures, rendering, scene, lag, settings
---


# Question
Title: Rotating player around planet causes drift in gun aiming at mouse
I have a bug with the rotation of a gun object that follows the mouse position. It has issues when the parent object player rotates. Example:

The player has a gravity script to keep them aligned with the 'planet' as you walk around it. The gun is a child of the player, and it's supposed to always rotate to point at where the mouse is (sorry you can't see it in the gif). The gun normally flips itself at 90 and -90 (top and bottom), and flips the player to face the same side the mouse is on.

The problem is that the player rotates to stay aligned with the planet, but the 90 and -90 angles that the gun uses to decide whether to flip itself and the player of course don't rotate.

Here's my code for the gun:

```
  Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
  difference.Normalize();
  float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;

  float startRotation = rotationZ + offset;

  float shotRotation = startRotation + Random.Range(-scatter, scatter);

  transform.rotation = Quaternion.Euler(0f, 0f, startRotation);

  //Flip the gun at top and bottom
  if (rotationZ < -90 || rotationZ > 90)
  {
      if (player.transform.eulerAngles.y == 0)
      {
          transform.localRotation = Quaternion.Euler(180, 0, -rotationZ + offset);
      }
      else if (player.transform.eulerAngles.y == 180)
      {
          transform.localRotation = Quaternion.Euler(180, 180, -rotationZ + offset);
      }
  }

  //Use gun rotation to set player direction
  //left
  if (rotationZ >= -90f || rotationZ <= 90f)
  {
      animator.SetFloat("Vertical", 0);
      animator.SetFloat("Horizontal", -1);
  }
  //right
  if (rotationZ <= -90f || rotationZ >= 90f)
  {
      animator.SetFloat("Vertical", 0);
      animator.SetFloat("Horizontal", 1);
  }

```

# Answer
I think you can simplify this pretty massively. No trigonometry or angle calculations required.

```
// Point my gun's right vector in the direction of "difference" in world space,
// adjusting as needed for the parent's orientation.
transform.right = difference;

// This cross product gives us the direction to the right of the character,
// even if you've flipped them around to face left.
Vector3 playerRight = Vector3.Cross(player.transform.up, Vector3.forward);

// Detect whether this points the gun to the left side of the player character.
bool facingLeft = Vector3.Dot(difference, playerRight) < 0f;

// If so, flip the gun sprite vertically, so it doesn't look upside-down.
// (This replaces the 180 degree pitch you were using earlier).
gunSprite.flipY = facingLeft;

// Set animator variables accordingly.
animator.SetFloat("Vertical", 0);
animator.SetFloat("Horizontal", facingLeft ? -1 : 1);

```
> 0 votes

---
Tags: unity, 2d, rotation, angles, aiming
---


# Question
Title: Hide/move the Particle Effect panel on the Scene view window
The problem for example is if I want to drag the particle system object to the bottom-right corner of my view, then it goes behind the Particle Effect panel.

Is there any way to do hide or move this panel in editor mode and/or in runtime mode?

# Answer
I found a solution, I just created new empty GameObject dragged the object with the particle system to be child of it and now I can drag it around just dragging the empty GameObject.
> 1 votes

---
Tags: unity
---


# Question
Title: What is the difference between the two circles in the rotation tool in Unity?
What is the difference between the two circles in the rotation tool in Unity?

In 2D rotation tool there are two circles which allow to rotate an object. And I can not conceive a difference between them. Could someone explain me what is the purpose of having both of them? It seems they both do the same.

# Answer
> 0 votes
After the comments provided under the question I was able to grasp the idea of the circles. There are four circles. Three of them are used to rotate around x, y and z axis and the fourth is used to rotate relatively to the camera which is used during the scene management in editor.

---
Tags: unity, rotation, editors, rotate
---


# Question
Title: LeanTween : How to check if gameObject is destroyed?
I am trying to animate a `gameObject` using `LeanTween` which has got destroyed already.

The `MissingReferenceException` occurs in `LeanTween.setOnUpdate();`

The null check doesn't work either: `(gameObject != null)`

I have used `LeanTween.cancel(gameObject,false);` but it still throws an exception.

# Answer
> 0 votes
Null check does not work for `gameobjects` so using is null or is object is a better idea. Never check monobehaviors with `!= null`

---
Tags: unity
---