# Question
Title: Storing voxels for a voxel Engine in C++
I am trying to write a little voxel engine because it's fun, but struggle to find the best way to store the actual voxels. I'm aware I will need chunks of some sort so I don't need to have the entire world in memory, and I'm am aware I need render them with reasonable performance.

I read about octrees and from what I understand it starts with 1 cube, and in that cube can be 8 more cubes, and in all those 8 cubes can be another 8 cubes etc. But I don't think this fits my voxel engine because my voxel cubes/items will all be the exact same size.

So another option is to just create an array of 16\*16\*16 size and have that be one chunk, and you fill it with items. And parts where there aren't any items will have 0 as value (0 = air). But I'm afraid this is going to waste a lot of memory and won't be very fast.

Then another option is a vector for each chunk, and fill it with cubes. And the cube holds its position in the chunk. This saves memory (no air blocks), but makes looking for a cube at a specific location a lot slower.

So I can't really find a good solution, and I'm hoping someone can help me with that. So what would you use and why?

But another problem is rendering. Just reading each chunk and sending it to the GPU using OpenGL is easy, but very slow. Generating one mesh per chunk would be better, but that means every time I break one block, I have to rebuild the entire chunk which could take a bit of time causing a minor but noticeable hiccup, which I obviously don't want either. So that would be harder. So how would I render the cubes? Just create all the cubes in one vertex buffer per chunk and render that and maybe try to put that in another thread, or is there another way?

Thanks!

# Answer
Storing the blocks as the positions and the values is actually very inefficient. Even without any overhead caused by the struct or object you use, you need to store 4 distinct values per block. It would only make sense to use it over the "storing blocks in fixed arrays" method (the one you described earlier) is when only a quarter of the blocks are solid, and this way you don't even take any other optimization methods into account.

Octrees are actually great for voxel based games, since they specialize at storing data with larger features (e.g. patches of the same block). To illustrate this, I used a quadtree (basically octrees in 2d):

This is my starting set containing 32x32 tiles, which would equal 1024 values:

Storing this as 1024 separate values doesn't seem that inefficient, but once you reach map sizes similar to games, such as Terraria, loading screens would take multiple seconds. And if you increase it to the third dimension, it starts to use up all space in the system.

Quadtrees (or octrees in 3d) can help the situation. To create one, you can either go from tiles and group them together, or go from one huge cell and you divide it until you reach the tiles. I will use the first approach, because it's easier to visualize.

So, in the first iteration you group everything into 2x2 cells, and if a cell only contains tiles of the same type, you drop the tiles and just store the type. After one iteration, our map will look like this:

The red lines mark what we store. Each square is just 1 value. This brought the size down from 1024 values to 439, that's a 57% decrease.

But you know the mantra. Let's go one step further and group these into cells:

This reduced the amount of stored values to 367. That's only 36% of the original size.

You obviously need to do this division until every 4 adjacent cell (8 adjacent block in 3d) inside a chunk is stored inside one cell, essentially converting a chunk to one large cell.

This also has some other benefits, mainly when doing collision, but you might want to create a separate octree for that, which only cares about whether a single block is solid or not. That way, instead of checking against collision for every block inside a chunk, you can just do it against the cells.
> 23 votes

# Answer
Octrees exist to solve exactly the problem you describe, allowing dense storage of sparse data without large search times.

The fact that your voxels are the same size just means that your octree has a fixed depth. eg. for a 16x16x16 chunk, you need at most 5 levels of tree:

* chunk root (16x16x16)
    + first tier octant (8x8x8)
        - second tier octant (4x4x4)
            * third tier octant (2x2x2)
                + single voxel (1x1x1)

This means you have at most 5 steps to go to find out whether there's a voxel at a particular position in the chunk:

* chunk root: is the whole chunk the same value (eg. all air)? If so, we're done. If not...
    + first tier: is the octant that contains this position all the same value? If not...
        - second tier...
            * third tier...
                + now we're addressing a single voxel, and can return its value.

Much shorter than scanning even 1% of the way through an array of up to 4096 voxels!

Notice that this lets us compress the data wherever there's a full octant of the same value - whether that value is all air or all rock or anything else. It's only where octants contain mixed values that we need to subdivide further, down to the limit of single-voxel leaf nodes.

---

For addressing the children of a chunk, typically we'll proceed in Morton order, something like this:

1. X- Y- Z-
2. X- Y- Z+
3. X- Y+ Z-
4. X- Y+ Z+
5. X+ Y- Z-
6. X+ Y- Z+
7. X+ Y+ Z-
8. X+ Y+ Z+

So, our Octree node navigation might look something like this:

```
GetOctreeValue(OctreeNode node, int depth, int3 nodeOrigin, int3 queryPoint) {
    if(node.IsAllOneValue)
        return node.Value;

    int childIndex =  0;
    childIndex += (queryPoint.x > nodeOrigin.x) ? 4 : 0;
    childIndex += (queryPoint.y > nodeOrigin.y) ? 2 : 0;
    childIndex += (queryPoint.z > nodeOrigin.z) ? 1 : 0;

    OctreeNode child = node.GetChild(childIndex);

    return GetOctreeValue(
                child,
                depth + 1,
                nodeOrigin + childOffset[depth, childIndex],
                queryPoint
    );
}

```
> 7 votes

---
Tags: c++, voxels
---


# Question
Title: Lat, Lon and elevation Conversation into unity coordinates
I have came across a very vague project problem and its feasibility report or communication procedures I have to define. And here is the current scenario:

1. I have two applications
2. One is built on **Unity3d** (which is under my control)
3. The second is also an application (which i don't know, and not under my control-) but it is related to a **map service app**.

Now the actual thing I want to do is that: If a user click in the map application than, the touch should be recognize in the unity application too.

Suppose I have able to communicate with both applications and the map application providing me the latitude, longitude and elevation information on-click. Now the question is **how do I convert its lat, lon and elev into my project work-space/unity coordinates?**. I found 3D coordinates on a sphere to Latitude and Longitude, and its about sphere. I don't have sphere I have an environment where different models are placed precisely according to map (there is no dummy models, all are accurate) and the map projection is based on **snake-grid**.

# Answer
Since the map projection is dependent on complex parameters not exposed to us, a formula-based exact solution seems unlikely.

Instead, I'd recommend the game developer's favourite tool: piecewise approximation! This is how we handle textures, 3D models, time and physics, and it works for maps too.

To simplify the problem, we'll assume `y = elevation` (you can add a scaling or offset factor here as needed), and focus on how (lat, long) map to (x, z) in your scene.

Our strategy will be to cover our map in a web of known points. Then for any arbitrary input within the span of that web, we can interpolate the position of nearby known points.

Start by manually picking feature points that you can clearly identify in both your mapping application and your Unity scene built from that map. Make sure you have good coverage in your main areas of interest, and have at least some points all the way out to the outer bounds of your Unity scene / outside the expected area of play.

For each point, note both:

* the latitude & longitude coordinates that your mapping app reports for that point
* the x & z position of the corresponding point in your Unity scene

Use Delaunay triangulation to turn this point cloud in the 2D lat-long plane into a triangle mesh.

Now it's effectively an inverse texture mapping problem: we have a set of vertices (x, z) with texture coordinates (lat, long), forming a triangle mesh over your Unity scene. Given a texture coordinate (lat, long), we want to know where it sits on one of your mesh's triangles.

We can use a Binary Space Partition to divide the lat-long plane into polygons along the triangle edges, each touching three of your feature points. You can then walk the tree to find which polygon a particular input (lat, long) pair falls into, in logarithmic time, and get the three feature points for that region.

Next you can find the barycentric coordinates of this (lat, long) pair compared against its feature point triangle's (lat, long) positions. Use these barycentric coordinates as interpolation weights to blend the feature points' (x, z) positions, then substitute the y you got from your elevation, and the result is a 3D position in your Unity scene.

The position you get out will exactly match your map at the feature points, and use an affine approximation in between. You can add more closely spaced feature points if you find it's inaccurate in any problem regions.
> 1 votes

---
Tags: unity, c#, 3d, coordinates, snake-grid
---


# Question
Title: Problem resolving angles in Unity (trying to apply a field force between particles)
So im trying to build a visual physics simulator that I intend to use at work to help some of my students understand how various forces interact within multi particle systems. I also want them to see how computational physics is done, and so want to code some physics into unity as opposed to use the pre-installed physics systems.

So I have a bunch of Spheres on my 2D plane which are acting as my particles - they have charge and mass. Im calculating the Coulomb Force that each particle acts upon one another, which gives a Vector2, where x is the magnitude of the force, and y is the angle the force acts. This all works perfectly I think:

```
force = (coulombConstant * particleCalculating.getCharge() * particleApplying.getCharge()) / (distance.magnitude * distance.magnitude);
angle = Mathf.Atan(distance.x / distance.y);

```

(except for some powers which I will sort out later, this works fine)

Then, the idea is to sum all these forces together as such:

```
foreach (Vector2 particle in forces)
{
    netXForce += particle.x * Mathf.Sin(particle.y);
    netYForce += particle.x * Mathf.Cos(particle.y);
}

```

Then I apply this to get an acceleration, and generate a velocity and move the particle.

Which should all work... the problem is the unity angle system (or my use of the unity angle system, whichever you prefer :)). I cant get it to differentiate from 0.5 rad to the bottom left and 0.5 rad to the top right (for example). This means two particles repelling one another actually add to each others acceleration a they are trying to go in opposite directions.

Any help here would be great - even if its just a description of why the unity angle system is great :)

# Answer
This isn't a problem with Unity, this is a problem with using the wrong math function for the job.

As you'll remember from high school math class, the tangent of an angle repeats with a period of \\$\pi\\$:

That means that in one half of the unit circle, it gives the same value as in the other half of the unit circle.

This is because the sign on the x and the sign on the y combine when you do the division:

\\$\frac {-y} {-x} = \frac y x \\$ & \\$\frac {-y} {x} = \frac y {-x} \\$

So, the right tool for this job is the 2-argument arctangent, available in most programming environments as "atan2", and Unity is no exception.

```
angle = Mathf.Atan2(distance.y, distance.x);

```

(Note here I've flipped x & y relative to your example, since in mathematical convention 0 degrees corresponds to the positive x axis and proceeds counter-clockwise as we increase the angle. This means exchanging your use of `Sin` & `Cos`)

Of course, you could skip all the trig and just work in plain Cartesian vectors rather than polar coordinates:

```
Vector2 GetCoulombForce(float chargeA, float chargeB, Vector2 positionA, Vector2 positionB) {
    var offset = positionB - positionA;
    float strength = coulombConstant * chargeA * chargeB / offset.sqrMagnitude;
    return offset.normalized * strength;
}

```

This gives the force exerted by A onto B. Negate it for the force exerted by B onto A.
> 1 votes

---
Tags: unity
---


title: View Space From gl_FragCoord

text:
# Question
Title: View Space From gl_FragCoord
Trying to get the example code for CalcEyeFromWindow() (first one on the page) to work in WebGL, but having no luck.

Paired down the code to the following with some explicit values just in case something is amiss with parameter passing. Visualizing the output on a sphere of unit radius, centered in the view and 3 units from the camera. Using step() in the output to provide sharp color transitions on the sphere.

The current output is black. If I set the step to 0 for X and Y, the transitions for X and Y are centered on the sphere, so it would seem that the problem is at least in part due to the calculation of clipPos.w.

Vertex shader:

```
precision highp float;

attribute vec3 a_position;

uniform mat4 u_modelMatrix;
uniform mat4 u_viewMatrix;
uniform mat4 u_projectionMatrix;

void main()
{
    gl_Position = u_projectionMatrix * u_viewMatrix * u_modelMatrix * vec4(a_position, 1.0);
}
```

Fragment shader:

```
precision highp float;

uniform mat4 u_inverseProjectionMatrix;
uniform mat4 u_projectionMatrix;

vec3 CalcEyeFromWindow(void)
{
    vec3 ndcPos;
    // Hard code window-space position at gl_FragCoord
    // Hard code viewport dimensions
    ndcPos.xy = (2.0 * gl_FragCoord.xy) / vec2(1000, 500) - 1.;
    // Hard code clipping depths
    ndcPos.z = (2.0 * gl_FragCoord.z - 1. - 4.) / (4. - 1.);

    vec4 clipPos;
    clipPos.w = u_projectionMatrix[3][2] /
       (ndcPos.z - (u_projectionMatrix[2][2] / u_projectionMatrix[2][3]));
    clipPos.xyz = ndcPos * clipPos.w;

    return (u_inverseProjectionMatrix * clipPos).xyz;
}

void main() {
    // Step to clarify position
    gl_FragColor = vec4(step(vec3(.5, .5, 2.2), CalcEyeFromWindow() *
         vec3(1,1,-1)), 1.);
}
```

# Answer
The problem was that I had used the clip plane depths where I should have used the near and far values as passed to glDepthRange, which I now know are 0 and 1 by default. So, since I use these default values, the calculation of ndcPos.z should be:

```
ndcPos.z = (2.0 * gl_FragCoord.z - 0.0 - 1.0) / (1.0 - 0.0);

```

which can be simplified to:

```
ndcPos.z = 2.0 * gl_FragCoord.z - 1.0;

```
> 1 votes

---
Tags: webgl, spaces
---


# Question
Title: How can I get the specific tile in a collision with a Tilemap?
I am developing a simple platformer, I have three types of tiles right now:

* **Floor:** does nothing on collision.
* **Bad:** makes the player lose the game.
* **Good:** makes the player beat the game.

I am trying to detect the collision with this code I found:

```
extends RigidBody2D

func _process(delta):
    var tile = get_parent().get_node("TileMap").get_cellv(get_parent().get_node("TileMap").world_to_map(position))
    print(tile)

```

The `tile` variable is supposed to contain the identifier of the type of tile the player is touching, but it doesn't, it always returns -1 (No exception or error, just -1).

I believe returning -1 means it isn't touching any tile, but it is.

This is using Godot 3.0 stable.

What am I missing?

Thank you for your patience.

# Answer
> 0 votes
I've found a way to make it work, I am not sure if this is the best possible solution but it works:

```
extends RigidBody2D

func _integrate_forces(state):
    var tilemap= get_parent().get_node("TileMap");
    for i in range(get_colliding_bodies().size()):
        var tile_pos = tilemap.world_to_map(state.get_contact_local_position(i))
        var tile = tilemap.get_cellv(tile_pos)

```

This function is inside my player script. `var tile` will contain the type id of each colliding tile.

# Answer
> 0 votes
I don't know if this helps, but in my case i was raycasting and found a neat set of key value pairs to my aid:

```
var result = space_state.intersect_ray(origin, get_global_mouse_position(), [self, owner]);

```

If the colliding object is a tilemap, there is a entry called 'metadata' which contains the coordinates (in terms of tilemap coordinates) of that tile which collided with the ray.

---
Tags: collision-detection, tiles, tilemap, godot
---


# Question
Title: How to compute the moves amount in a match-3 game?
I have a match-3 mobile game, similar to these popular games in the store. Mechanics are different, but the gameplay stays the same:

* NxN board
* X moves
* Y objectives to complete to win
* tons of different levels. When you complete a level, you unlock a new one

When you run out of moves, you have to buy moves or try again, so you have to think on each move.

And the problem is in the moves, I'm trying to calculate the amount of moves required for each level. I want it to be be slightly lower than the average, so it takes 3-4 attempts for an average player to complete.

I discovered that "being stuck" 2 or 3 times on a level makes it a lot more fun, than completing levels each time with a single attempt.

# My current solution

I have couple hundred players and with them - some statistics. With each level attempt (lost or won) I save it on my server to use it for calculations:

```
ID | Level Number | Used Moves | Lost/Won

```

Then, each week, I compute a sum of attempts on each level, and I do this for all players. Then, I compute a mean average on each level:

```
avg_lvl_attempts = sum_level_attempts / player_count

```

So **if 3 people took level 10**, all of them with **4 attempts**, it would be:

```
avg = (4 + 4 + 4) / 3 = 4

```

Which means that it takes the players 4 attempts, on average, to complete level 10. Then, based on that, I increase the amount of moves on level 10 by a small amount, so it's a little bit easier for them (because I want to achieve 3 on average). And I do that for each level.

The problem with that solution is that it can produce strange results, for instance if someone had 130 attempts (it happens sometimes).

# The question

Is there any algorithm, or mathematical trick to do these kind of things more accurately, like excluding edge cases etc?

# Answer
I wrote a comment but I think it needs some pictures to be explained, so I'm writing an answer.

Let's say you have an array of attemps, entry `i` is the number of attempts of players `i` for a certain level: `level_1_attempts = [3, 4, 10, 180, 13, 4, 5, ...]`

You can compute an histogram of these attempts. That is, you count how many players attempted `1` times, how many attempted `2` times, and so on.

Then, you can visualize such histogram using some software (python with the matplotlib module, for example). What you see will help you deciding how to modify the number of moves of your level. Let's consider an example of what you could observe:

In this case, you can clearly see that there are two populations of players. One is attempting 'normally' a few times (less than 10) and then succeeds. The other population is extermely bad at playing and needs 180 attempts. Since the latter population is very small, you want to exclude those from your statistics (pink lines). It might be useful to use log-log scale or semilog, in your case, especially if you observe some very high values.

Of course, it could be much more complicated than that, for example if you have a somewhat flat distribution that does not have a clear mean. One needs to observe the data and take a decision. The histogram is a great way to do that.
> 1 votes

---
Tags: mathematics, level-design
---


# Question
Title: Set / Get UserPointer - What Do They Do?
I see a lot of talk about glfwGetWindowUserPointer() and glfwSetWindowUserPointer() but I can't for the life of me understand what these functions actually do.

From http://discourse.glfw.org/t/what-is-a-possible-use-of-glfwgetwindowuserpointer/1294:

> "If you are trying to use glfw in a program that follows object-oriented design, for example, you can use this pointer to store the address of the instance that is handling a particular window, and forward the callbacks (which have to be static functions, because of the way the API works) to the appropriate member functions."

The author of that comment then posts the following example:

```
/* Constructor for the MyWindowHandler class */

MyWindowHandler (GLFWwindow * window)
{
....
    glfwSetWindowUserPointer(window, reinterpret_cast<void *>(this));
}

/* Key event callback wrapper function */

static void key_callback (GLFWwindow * window, int key, int scancode, int
                                                        action, int mods)
{
    MyWindowHandler * handler =
    reinterpret_cast<MyWindowHandler *>(glfwGetWindowUserPointer(window));

    if (handler)
        handler->keyEvent(key, scancode, action, mods);
}

```

What confuses me is that (at least as far as I can tell) I was able to achieve the exact same outcome in my program without using glfwSetWindowUserPointer() or glfwGetWindowUserPointer() at all.

```
/* Class constructor (just provided for reference) */

GLFW::GLFW(int right, int top)
    : m_Window(0)
{
    if (!glfwInit())
    {
        std::cout << "GLFW initialisation failed!\n";
        __debugbreak();
    }

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    m_Window = glfwCreateWindow(right, top, "OpenGL Window", NULL, NULL);

    if (!m_Window)
    {
        glfwTerminate();
        std::cout << "Could not create window!\n";
        __debugbreak();
    }

    glfwMakeContextCurrent(m_Window);
    glfwSwapInterval(2);

    if (glewInit() != GLEW_OK)
    {
        std::cout << "GLEW initialisation failed!\n";
        __debugbreak();
    }

    std::cout << glGetString(GL_VERSION) << std::endl;
}

/* My callback member function */

void GLFW::MouseMovement(int x, int y)
{
    std::cout << "Mouse moved\n";
    // do other stuff...
}

/* Main.cpp */

static void MouseMovementCallback(GLFWwindow* window, double x, double y)
{
    GLFW* glfw = nullptr;
    glfw->MouseMovement(x , y);
}

int main()
{
    GLFW glfw(1200, 600);
    glfwSetCursorPosCallback(glfw.GetWindowID(), MouseMovementCallback);

    // ......
    // ......
}

```

In the above code my 'MouseMovement' callback function was called... so I'm rather stumped as to what the purpose of the glfwGetWindowUserPointer() and glfwSetWindowUserPointer() functions actually is.

I'm sure there is something rather obvious that I am missing here, hopefully someone can enlighten me.

Thanks in advance.

# Answer
> 1 votes
```
static void MouseMovementCallback(GLFWwindow* window, double x, double y)
{
    GLFW* glfw = nullptr;
    glfw->MouseMovement(x , y);
}

```

This is undefined behavior. And it only happens to work because MouseMovement doesn't access any of it's fields.

Skipping using the userpointer only works when there is just 1 `GLFW` sitting in a global somewhere. (Which is fine in most games.)

However if you ever want to open a second window you need a way to differentiate them and get access to the object that manages it. The easiest way is setting the userpointer. Or you need to have fully separate callbacks for each window.

Most callback APIs have a way to pass a user-defined pointer through to the callback. One of the main reasons is because globals are discouraged and the only way to get back to your data without the userpointer is to use a global.

---
Tags: opengl, c++, visual-studio, glfw, window-management
---


title: Missing texture after add new actors

text:
# Question
Title: Missing texture after add new actors
I want to add two types of characters multiple times but when I add a new actor to stage texture in "old" actors stops render.

I can add multiple `KnightActor` (without `RatActor`) or multiple `RatActor` (without `KnightActor`). When I try to add multiple `KnightActor` and `RatActor` on one stage only textures from newest actors are rendered (one `RatActor` and one `KnightActor`)

GameScreen.kt

```
override fun render(delta: Float) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)

    actorManager.addNewActors(stage)

    viewPort.camera.update()

    stage.act(delta)
    stage.draw()

    world.step(delta, 8, 3)
    debugger.render(world, viewPort.camera.combined)
}

```

ActorManager.kt

```
fun markToAdd(actor: BaseActor<*>) {
    toAdd.add(actor)
}

fun addNewActors(stage: Stage) {
    toAdd.forEach { actor: BaseActor<*> ->
        stage.addActor(actor)
        actor.addToWorld(worldService.getWorld())
        Gdx.app.log("afterAdd", (++charactersOnStage).toString())
    }
    toAdd.clear()
}

```

KnightActor.kt

```
override fun draw(batch: Batch, parentAlpha: Float) {
    super.draw(batch, parentAlpha)

    if (isMoving) {
        frameStateTime += Gdx.graphics.deltaTime
    }

    // DRAW TEXTURE
    val frame = animationManager.getFrameAndChangeSpeed(AnimationType.KNIGHT_WALK_RIGHT, frameStateTime, getSpeed())
    val frameX: Float = position.x - (size.width / 2)
    val frameY: Float = position.y - (size.height / 2)

    batch.draw(frame, frameX, frameY, size.width, size.height)

    // END DRAW
}

```

RatActor.kt

```
override fun draw(batch: Batch, parentAlpha: Float) {
    super.draw(batch, parentAlpha)

    if (isMoving) {
        frameStateTime += Gdx.graphics.deltaTime
    }

    // DRAW TEXTURE
    val frame = animationManager.getFrameAndChangeSpeed(AnimationType.RAT_WALK_LEFT, frameStateTime, getSpeed())
    val frameX: Float = position.x - (size.width / 2)
    val frameY: Float = position.y - (size.height / 2)

    batch.draw(frame, frameX, frameY, size.width, size.height)

    // END DRAW
}

```

AnimationManager.kt

```
fun getAnimation(animationType: AnimationType): Animation<TextureRegion> {
    return AssetsManager.loadSprite(animationType.spriteFile, animationType.alias).getAnimationForSprite(animationType.alias, animationType.width, animationType.height)
}
fun getFrameAndChangeSpeed(animationType: AnimationType, stateTime: Float, speed: Float, looping: Boolean = true): TextureRegion {
    val animation = getAnimation(animationType)
    animation.frameDuration = 1 / speed
    return animation.getKeyFrame(stateTime, looping)
}

```

# Answer
In `BaseActor` class I was clearing screen with `Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)`. After removing it, everything works as it should.
> 1 votes

---
Tags: libgdx, textures, kotlin
---


# Question
Title: Draw a texture2D at specific coordinates on another Texture2D
I have a ShipTexture and a Sail Texture. I need to draw the sail texture at a specific location on the shipTexture (call it the sailMountPoint) regardless of the location vector associated with the ship. I.e. the sail should be mounted to the ship and move with it.

I have tried various methods calculating the offset from the vector2 location coordinates of the shipTexture, but am not really coming close. I have also put a color indicator (in the rgba data) in the texture where the sail mount is on the ship texture. During some pre-processing, I then calculated the offset from this position.

Something like the following:

```
    public class SailMountTextureCoordinates
{
    public static Dictionary<string, Dictionary<int, Tuple<int, int>>> SailMountCords = new Dictionary<string, Dictionary<int, Tuple<int, int>>>();
}

```

## Preprocessing:

```
public Tuple<int, int> GetSailMountCords(Texture2D texture, int rows, int cols, string key)
        {
            Color[,] Colors = TextureUtility.TextureTo2DArray(texture);

            for (int r = 0; r < rows; r++)
            {
                for (int c = 0; c < cols; c++)
                {
                    // target frame on the texture
                    int width = texture.Width / cols;
                    int height = texture.Height / rows;
                    int X = width * c;
                    int Y = height * r;

                    for (int a = X; a < X + width; a++)
                    {
                        for (int b = Y; b < Y + height; b++)
                        {
                            //If we find a the red sail mount color
                                if (Colors[a, b].R == 255 && Colors[a, b].G == 45 && Colors[a, b].B == 0 && Colors[a, b].A == 255)
                            {
                                if (!SailMountTextureCoordinates.SailMountCords.ContainsKey(key))
                                    SailMountTextureCoordinates.SailMountCords.Add(key, new Dictionary<int, Tuple<int, int>>());
                                SailMountTextureCoordinates.SailMountCords[key][r] = new Tuple<int, int>(a-X, b-Y);
                            }
                        }
                    }
                }
            }
            return null;
        }

```

## Mounting the sail:

```
        // set the sail location here (equal to ship location plus the offset on the texture to hit the mount)
        float offsetX = (0.5f * (float)(_texture.Width / nColumns));
        float offsetY = (0.5f * (float)(_texture.Height / nRows));
        shipSail.location.X = location.X - offsetX + SailMountTextureCoordinates.SailMountCords[bbKey][currRowFrame].Item1;
        shipSail.location.Y = location.Y - offsetY + SailMountTextureCoordinates.SailMountCords[bbKey][currRowFrame].Item2;

```

It is worth noting that I am using a large sprite sheet for both textures, then setting the source rectangle for the correct ship and sail frame.

Are there any easier ways to do this in monogame/XNA? So far I've had no luck with this route.

# Answer
> 0 votes
Here is how I draw something (object B) at a specific position of something else (object A).

First, you need to have a method (or something) to get the X and Y position of object A:

```
public float getPosX()
{
    return pos.X;
}

```

Then you simply set the position of your object B in `Update` method as below:

```
objectB.setPos(objectA.getposX() + offsetX, objectA.getposY() + offsetY);

```

I would recommend you draw your object A in a specific scale to your screen's width and height (for example, `objectA.width = screenWidth / 10`). After doing this, if your object A is moving, your object B will always follow object A's position.

Edit: The image below is the result of my code:

---
Tags: c#, xna, textures, monogame, texture-atlas
---


# Question
Title: Convert 3D direction vectors to yaw/pitch/roll angles
I have the code below that takes a set of yaw, pitch, and roll rotation angles (in degrees), and populates forward, right, and up basis vectors to express this rotated orientation as a Cartesian coordinate basis.

Now I'd like to do the opposite operation: given a forward, right, and up vector, how do I determine the yaw, pitch, and roll angles of this orientation?

Here is the code I'm using to convert from angles to vectors (run this code online):

```
// Example program
#include <iostream>
#include <string>
#include <math.h>

#define PITCH 0 // up/down
#define YAW   1 // left/right
#define ROLL  2 // fall over

void AngleVectors(const float *angles, float *forward, float *right, float *up)
{
    float sr, sp, sy, cr, cp;

    float cy;
    float angle;

    angle = float(angles[YAW] * (M_PI * 2 / 360));
    sy = sin(angle);
    cy = cos(angle);

    angle = float(angles[PITCH] * (M_PI * 2 / 360));
    sp = sin(angle);
    cp = cos(angle);

    angle = float(angles[ROLL] * (M_PI * 2 / 360));
    sr = sin(angle);
    cr = cos(angle);

    if (forward)
    {
        forward[0] = cp * cy;
        forward[1] = cp * sy;
        forward[2] = -sp;
    }
    if (right)
    {
        right[0] = (-1 * sr * sp * cy + -1 * cr * -sy);
        right[1] = (-1 * sr * sp * sy + -1 * cr * cy);
        right[2] = -1 * sr * cp;
    }
    if (up)
    {
        up[0] = (cr * sp * cy + -sr * -sy);
        up[1] = (cr * sp * sy + -sr * cy);
        up[2] = cr * cp;
    }
}

int main()
{
  float forward, right, up;
  float angles[3];
  angles[PITCH] = 0;
  angles[YAW] = 270;
  angles[ROLL] = 0;
  AngleVectors(angles,&forward,&right,&up);
  char buffer[256];
  sprintf(buffer,"%f %f %f",forward,right,up);

  std::cout << buffer;
}

```

# Answer
> 1 votes
This is related to the problem of converting from Cartesian Coordinates to Spherical Coordinates. Note that the reverse operation is not unique: there are many possible angle triplets that produce the same rotation transformation, so any function we choose will necessarily have to standardize on one option. This means an angle triplet might not necessarily round-trip convert to vectors and back as you expect, even though the result will be equivalent in effect when rotating vectors.

The details will vary a little based on the conventions you choose (eg. in what order are the angles in an angle triplet applied?) In your case it looks like your conventions are:

* In a neutral rotation (0 degrees on all axes)...

+ forward = (1, 0 0)
    + right = (0, -1, 0)
    + up = (0, 0, 1)

    (ie. this is a right-handed coordinate system, with x+ forward, y+ left, z+ up)
* From this neutral rotation...

+ increasing YAW rotates the forward vector to the *left*
    + increasing PITCH rotates the forward vector *downward*
    + increasing ROLL rotates the up vector to the *right*
* Rotations are applied in the order (from most local to most global)

+ Roll
    + Pitch
    + Yaw

So, given two unit vectors (length = 1), we can compute the angles like so:

```
void AnglesFromVectors(float *angles, const float *forward, const float *up)
{
    // Yaw is the bearing of the forward vector's shadow in the xy plane.
    float yaw = atan2(forward[1], forward[0]);

    // Pitch is the altitude of the forward vector off the xy plane, toward the down direction.
    float pitch = -asin(forward[2]);

    // Find the vector in the xy plane 90 degrees to the right of our bearing.
    float planeRightX = sin(yaw);
    float planeRightY = -cos(yaw);

    // Roll is the rightward lean of our up vector, computed here using a dot product.
    float roll = asin(up[0]*planeRightX + up[1]*planeRightY);
    // If we're twisted upside-down, return a roll in the range +-(pi/2, pi)
    if(up[2] < 0)
        roll = sign(roll) * M_PI - roll;

    // Convert radians to degrees.
    angles[YAW]   =   yaw * 180 / M_PI;
    angles[PITCH] = pitch * 180 / M_PI;
    angles[ROLL]  =  roll * 180 / M_PI;
}

```

---
Tags: c++, 3d, geometry, euler-angles
---


# Question
Title: How to detect 2D line on line collision?
I'm a flash actionscript game developer who is a bit backward with mathematics, though I find physics both interesting and cool.

For reference this is a similar game to the one I'm making: Untangled flash game

I have made this untangled game almost to full completion of logic. But, when two lines intersect, I need those intersected or 'tangled' lines to show a different color; red.

It would be really kind of you people if you could suggest an algorithm for detecting **line segment** collisions. I'm basically a person who likes to think 'visually' than 'arithmetically' :)

Edit: I'd like to add a few diagrams to make convey the idea more clearly

P.S I'm trying to make a function as

```
private function isIntersecting(A:Point, B:Point, C:Point, D:Point):Boolean

```

Thanks in advance.

# Answer
> 21 votes
I use the following method which is pretty much just an implementation of this algorithm. It's in C# but translating it to ActionScript should be trivial.

```
bool IsIntersecting(Point a, Point b, Point c, Point d)
{
    float denominator = ((b.X - a.X) * (d.Y - c.Y)) - ((b.Y - a.Y) * (d.X - c.X));
    float numerator1 = ((a.Y - c.Y) * (d.X - c.X)) - ((a.X - c.X) * (d.Y - c.Y));
    float numerator2 = ((a.Y - c.Y) * (b.X - a.X)) - ((a.X - c.X) * (b.Y - a.Y));

    // Detect coincident lines (has a problem, read below)
    if (denominator == 0) return numerator1 == 0 && numerator2 == 0;

    float r = numerator1 / denominator;
    float s = numerator2 / denominator;

    return (r >= 0 && r <= 1) && (s >= 0 && s <= 1);
}

```

There's a subtle problem with the algorithm though, which is the case in which two lines are coincident but don't overlap. The algorithm still returns an intersectioin in that case. If you care about that case, I believe this answer on stackoverflow has a more complex version that addresses it.

**Edit**

> I did not get a result from this algorithm, sorry !

That's strange, I've tested it and it's working for me except for that single case I described above. Using the exact same version I posted above I got these results when I took it for a test drive:

# Answer
> 5 votes
Without Divisions! So no problem with precision nor by division by zero.

Line segment 1 is A to B Line segment 2 is C to D

A line is a never ending line, the line segment is a defined part of that line.

Check if the two bounding boxes intersect : if no intersection -\> No Cross! (calculation done, return false)

Check if line seg 1 straddles line seg 2 and if line seg 2 straddles line seg 1 (ie. line Segment 1 is on both sides of Line defined by the line Segment 2).

This can be made by translating all points by -A (ie. you move the 2 lines so A is in origo (0,0))

Then you check if point C and D is on different sides of the line defined by 0,0 to B

```
//Cross Product (hope I got it right here)
float fC= (B.x*C.y) - (B.y*C.x); //<0 == to the left, >0 == to the right
float fD= (B.x*D.y) - (B.y*D.x);

if( (fc<0) && (fd<0)) //both to the left  -> No Cross!
if( (fc>0) && (fd>0)) //both to the right -> No Cross!

```

If you haven't already got a "No Cross" then continue using not A,B versus C,D but C,D versus A,B (same calcs, just swap A and C, B and D), if there are no "No Cross!" then you have an intersection!

I searched for the exact calculations for the cross product and found This blog post that explains the method too.

# Answer
> 1 votes
I just want to say, I needed it for my Gamemaker Studio game and it works well:

```
///scr_line_collision(x1,y1,x2,y2,x3,y3,x4,y4)

var denominator= ((argument2 - argument0) * (argument7 - argument5)) - ((argument3 - argument1) * (argument6 - argument4));
var numerator1 = ((argument1 - argument5) * (argument6 - argument4)) - ((argument0 - argument4) * (argument7 - argument5));
var numerator2 = ((argument1 - argument5) * (argument2 - argument0)) - ((argument0 - argument4) * (argument3 - argument1));

// Detect coincident lines
if (denominator == 0) {return (numerator1 == 0 && numerator2 == 0)}

var r = numerator1 / denominator;
var s = numerator2 / denominator;

return ((r >= 0 && r <= 1) && (s >= 0 && s <= 1));

```

# Answer
> 1 votes
The accepted answer gave a wrong answer in this case:

```
x1 = 0;
y1 = 0;
x2 = 10;
y2 = 10;

x3 = 10.1;
y3 = 10.1;
x4 = 15;
y4 = 15;

```

These lines obviously don't intersect, but according to the function in the "correct answer" the lines do intersect.

This is what I use:

```
function do_lines_intersect(px1,py1,px2,py2,px3,py3,px4,py4) {
  var ua = 0.0;
  var ub = 0.0;
  var ud = (py4 - py3) * (px2 - px1) - (px4 - px3) * (py2 - py1);

  if (ud != 0) {
    ua = ((px4 - px3) * (py1 - py3) - (py4 - py3) * (px1 - px3)) / ud;
    ub = ((px2 - px1) * (py1 - py3) - (py2 - py1) * (px1 - px3)) / ud;
        if (ua < 0.0 || ua > 1.0 || ub < 0.0 || ub > 1.0) ua = 0.0;
  }

  return ua;
}

```

returns 0 = the lines do not intersect

returns \> 0 = the lines intersect

**Update to answer the question:**

I did not create this code myself. It is over 5 years old and I don't know what the original source is. But..

I think the return value is the relative position of the first line where they cross (to explain it badly). To calculate the point of intersection you could probably use lerp like this:

```
l = do_lines_intersect(...)
if (l > 0) {
    intersect_pos_x = l * (px2-px1);
    intersect_pos_y = l * (py2-py1);
} else {
    // lines do not cross
}

```

(I DID NOT TEST THIS)

---
Tags: mathematics, actionscript-3, linear-algebra
---


# Question
Title: How to cut polygon shape sprite in Multiple Sprite Editor Unity
Here is a sprite I have taken from internet and trying to slice it out in many smaller pieces.

But the problem is I have polygon shape sprite, how to cut it out, selected in picture ?

Rest are just fine.

# Answer
Why do you need to do this? Just move the top right part in a programm like photoshop or gimp and then let Unity slice it automatically. If you later need collision detection on that ground, you can create an edge collider.

I don't think there is way to slice something into a non-rectangle form. Otherwise please correct me.
> 0 votes

---
Tags: unity, sprites, spritesheet
---


# Question
Title: How to add material to a blueprint created?
My project has a cube and a capsule.

**Below you can see an inserted cube of the modes tab. Beside a capsule inserted from a blueprint created by me:**

**I can drag the material I created and use it in the cube, but not in the capsule:**

**Note that the cube has a tab to insert the material:**

**But the capsule I created does not have that same tab:**

I would like to know what components I would have to add to the capsule so that the capsule could have a material.

# Answer
Materials can only be applied to some subclasses of UPrimitiveComponent, like UStaticMeshComponent. If you select the StaticMeshComponent of your Capsule actor in its components list (in the Details tab), you can drag the material into its slot on there.

**See below:**

**Result:**

You might not be able to drag and drop the material into the viewport on the actor in some circumstances.
> 2 votes

---
Tags: unreal-4, materials
---


# Question
Title: How to handle a scrollable map and player coordinates
I have a large map that a player will navigate over. Currently, it is just a single background image, but I would like to make it tiled map. How do I properly keep track of player coordinates?

Currently what I have working is:

1) I have a 800px wide by 500px high playing area 2) The player is normally positioned in the center of the screen at approximately (400px x 250px) 3) When the arrow keys are pressed instead of the player moving the map moves. I am currently using background-position at the moment to set which area of a background is displayed.

What I am currently trying to wrap my head around:

4) When the map reaches the boundaries it will no longer scroll, but my player is stuck in the center. 5) How to get the player back to the center again when they start to travel away from the corners.

The main problem I am having is knowing what coordinates I should be keeping track of. For example, should I be keeping track on only one of the following, or all three of the following:

* Player position in map
* Map position on screen
* Player position on screen

What is a standard way to handle player movement like this?

# Answer
> 1 votes
The way this is typically handled is to introduce a notion of a "camera" to your game.

The camera is another entity that exists at some position in the game world, like your player character. It represents the current point of view, from which you can determine what should be visible and where to draw it on the screen.

With this approach, all your entity positions are stored/tracked/manipulated in your world's coordinate system, relative to a fixed point in your game world, so they're completely decoupled from the pixel grid of your screen. As a side benefit, this makes it much easier to adapt your game to different screen resolutions, or handle changes in your graphics assets later, since all your gameplay code is in world coordinates and can remain unchanged.

Each frame, you update the camera's position after the player has moved. For example, to follow the player when they're in the middle of the map, but stop at the world bounds, you can write something like this:

```
// Update the worldspace bounds of our camera view, in case the window changed size.
camera.worldHalfWidth = displayArea.pixelWidth / camera.pixelsPerWorldUnit;
camera.worldHalfHeight = displayArea.pixelHeight / camera.pixelsPerWorldUnit;

camera.x = Math.max(camera.worldHalfWidth, Math.min(player.x, world.width - camera.worldHalfWidth));
camera.y = Math.max(camera.worldHalfHeight, Math.min(player.x, world.height - camera.worldHalfHeight));

```

When it comes time to draw the background and entities in your game world, you can use the camera to decide where they belong:

```
worldToScreenPoint = function(worldPoint) {
    var worldOffset = new Point(worldPoint.x - camera.x, worldPoint.y - camera.y);
    var pixelOffset = new Point(worldOffset.x * camera.pixelsPerWorldUnit, worldOffset.y * camera.pixelsPerWorldUnit);
    return new Point(displayArea.center.x + pixelOffset.x, displayArea.center.y + pixelOffset.y);
}

```

(My apologies if my Javascript is a little crude - I mostly use C# these days. Hopefully it's enough to convey the important steps!)

If you're drawing on a canvas, you can equivalently use the 2D context's transformation methods to apply the world-to-pixel coordinate conversion, and use the camera as a way to update that transformation.

---
Tags: javascript, tilemap
---


# Question
Title: RogueLike - Map and Entities - how to store it?
Started to write my own RL, and already fell into analysis (paralysis?) when implementing map class.

My **TILE** class looks like:

```
class CMapTile
{

public:

    enum eMapTileType
    {
        E_UNKNOWN = 0,
        E_FREE,
        E_WALL,
        E_ALL
    };

    CMapTile();
    virtual ~CMapTile();
    uint8_t GetType();
    uint8_t IsBlocking();
    uint8_t GetSymbol();

protected:
    uint8_t m_uiType;
    uint8_t m_uiBlocking;
    uint8_t m_uiSymbol;

};

```

Then i wrote a class for the map itself

```
#include "CMapTile.hpp"

class CMap
{
public:

    CMap();
    void Init(const uint8_t& ruiWidth, const uint8_t&  ruiHeight);
    void Generate();
    void Print();
    CMapTile GetTile(const uint8_t& ruiX, const uint8_t& ruiY) const;

private:

    uint8_t m_uiWidth;
    uint8_t m_uiHeight;

    std::vector<CMapTile> m_vTiles;
};

```

And here is me thinking. With the design above, Map has no idea about entities. Entities have no idea about map.

So when i want to move Player **RIGHT** given above i will have to make two checks (totally separated). A check for map if tile is blocking and a check in a vector of entities if there is any entity on that position (X+1).

```
// Obtain tile to the right
CMapTile *pTile = m_Map->GetTile(pPlayer->GetPosX()+1, pPlayer->GetPosY());

// Obtain entity to the right
CEntity *pEntityToRight = m_EntitiesManager.GetEntity(pPlayer->GetPosX()+1, pPlayer->GetPosY());

// Check if blocking
if(pTile != NULL && pTile->IsBlocking() == false)
{

    // Check if any entity there and blocking
    if(pEntityToRight != NULL && pEntityToRight->IsBlocking == false)
    {
        // Update Player Pos to Tile position
        pPlayer->SetPosition(pTile->GetPosX(), pTile->GetPosY());

        // Update Map Entity Id for this Tile
        _Tile->SetEntityId(pPlayer->GetID());
    }
}

```

Maybe instead i should have an integer in the CMapTile storing an id of an entity, like below:

```
class CMapTile
{

public:

    enum eMapTileType
    {
        E_UNKNOWN = 0,
        E_FREE,
        E_WALL,
        E_ALL
    };

    CMapTile();
    virtual ~CMapTile();
    uint8_t GetType();
    uint8_t IsBlocking();
    uint8_t GetSymbol();
    int     GetEntityID();
protected:
    uint8_t m_uiType;
    uint8_t m_uiBlocking;
    uint8_t m_uiSymbol;
    int     m_iEntityID; // <<<<<<<-----

};

```

Thanks to which i can make a simple call to CMap like this to check if i can move player Right:

```
  // Obtain tile to the right
CMapTile *pTile = m_Map->GetTile(pPlayer->GetPosX()+1, pPlayer->GetPosY());

// Check if blocking
if(pTile->IsBlocking() == false)
{
    // Update Player Pos to Tile position
    pPlayer->SetPosition(pTile->GetPosX(), pTile->GetPosY());

    // Update Map Entity Id for this Tile
    _Tile->SetEntityId(pPlayer->GetID());
}

```

With the above CMapTile::IsBlocking would have to know about Entity class, to figure out if entity is a blocking type or not.

**Questions** This sounds simple but that initial design has an effect on later development. Examples:

*What happens later when for an example NPC would have to attack player?*

*How from the NPC class the logic knows where is the player located or if he (NPC) can move right ? - having no idea about the map.*

*Should i pass the MAP pointer to the AI logic ?*

*Which is the proper way to go to separate the logic and make all of the above simple in future stages of development ?*

# Answer
> 3 votes
I don't see a problem with the representation of your tilemap in memory. I think I can simplify it by make a tilemap a simple `vector<uint8_t>` but as we don't know what features you need let's not touch that topic now, as there isn't really a specific way of doing this.

About tile walkability: different entities may interact with tiles in different ways. Example: a ghost may pass through walls. Consider having a single uint8\_t to represent a tile\_type, and let logic for different entities to decide if they can walk or no walk a tile. For example, birds can pass over a tree tile, the player's character can't. This way you can have ghosts and birds. Do not ask the tile if it is blocking, ask the entity if it can walk a tile.

If you don't like logic in entities, ask the engine if a given entity can walk a tile. If you are using Entity/Component/System approach, ask the relevant system if a given entity can walk a tile.

Should i pass the MAP pointer to the AI logic? I would have a globals::MAP, but this depends on which design patterns you want to follow. You can, it isn't either correct or incorrect. Tip: I found myself requiring map at different functions in graphical RPGs, that's why I prefer globals. If you are working alone no need to overprotect your map, you know where you may modify it or not.

About storing entities IDs in tilemap: again, it isn't incorrect, and for text-based probably not overkill performance wise, as long as you are aware that this makes your tilemap also an scene grid. An scene grid is a form of scene partitioning, either for physics or for rendering. In this case, you are using the grid to easy check if near squares contain an entity.

One question you must ask yourself: Do you need more than a single entity in an square at a given time? Most graphical RPGs don't allow it and for the rare "cutscenes" where there may be special cases they just code them as scripted animations (suspending game "physics" temporarily), so you may very well be fine by having your tilemap being your scene grid with a single field for an entity ID. Problems start if the answer is "yes, I need more than a single entity".

Possible solutions are:

* Replace the entity ID field for a vector (required memory will skyrocket, but depending on your bigger map worst case you may not care).
* Don't store entities IDs in the tilemap, just store them in a separate vector/list and when you want two entities to interact search for suitable entities by iterating through the whole list. This forces you to think in advance in your worst possible case, the problem is that you may change your mind later, so this doesn't scale. Take this as a premature optimization for the specific scenario of allowing a very small number of entities alive at the same time.

If you already know that you only need 100 entities at the time, and that your maps will be big, 1000x1000. You can estimate like this:

* a list with 100 entities ids, with 32 bit per element, is only 400 Bytes. I calling it an entity list, but you probably want to use a `vector<>`. For a linked list there is extra data.
* a 1000x1000 tilemap, with a 32 bit field for entities ids is 4 MB only for the entities references, doesn't matter if their are set to 0 or reference an actual alive entity, I didn't add the other fields the tile structure contains. Yes, bigger than the list approach, but still a joke for today's hardware.

You must also think in list traversal time vs scene grid near square checking. Of-course the grid beats the list, but at what memory cost. All depends on the number of entities you expect and the size of maps you may want to have.

Some notes: I said "very small number of entities" but for today machines it may be thousand of them (the simpler their interactions are the more you may have). The list strategy plays well with an entity spawn strategy where you load a bunch of entities when entering a certain room/going near a certain zone, and unload them when they no more pursuit you. But if you want an honest open world simulation, and load/unload entities are a no go for you, entity lists aren't your friend (except that your big open world map only requires 100 entities in total, then any strategy would do).

If you can't decide on an strategy, just test them with a fabricated worst possible case (a really big map with thousands entities). Maybe you don't know yet how many you will need for the worst map your final game will have, but you may have an idea, just use bigger numbers than in your worst possible imagined case.

The only value you obtain from this answer is to help you think in some problems now. Problems you will hit eventually anyway while advancing the project.

Need help deciding? Go for the scene grid and single entity per square. Because it's simpler to code. Also, force yourself to think in things like max possible entities at a given time smells to premature optimization. The bigger possible map is not only limited by their size in memory, but also by the time you need to expend in creating them, so I don't expect them to be very big (of-course, there is the case of procedural generation, that makes big maps cheaper to create).

Tip: you are already using getters, and that's OK. By having a proper wrapping interface, if you switch strategies at some point, while your getters prototype doesn't require to change, the rest of the code doesn't require any change either, you will only have to rewrite the getters inner code.

In brief:

* Ask the map the type of tile of a given coordinate.
* Ask the entity/system if a given entity can walk that type of tile.
* Use scene grid because is simpler to code, until you hit the horizon where it won't work for you anymore (and probably you won't hit it)
* Be smart with wrapper functions prototypes in case you decide to switch strategies in the future.

Possible optimization: for most possible scenarios, you only need a tile to be a uint8\_t value, and nothing more. The value determines everything, including the symbol used to render it (if that is what the symbol member is for in your code). But I can think of a case where this is not valid, if you want to have secret passages, then you may disguise a passable tile with the symbol of a wall, but note that that can be solved too by having another tile value for the passable wall tile.

tile 23, renders as ¤ and not passable by player.

tile 24, renders as ¤ but passable by player.

```
¤¤¤¤¤¤¤¤¤¤
¤¤¤T¤¤¤¤¤¤
¤¤¤¤¤¤¤¤¤¤
¤¤¤¤¤¤¤    ££
¤¤   ¤¤  £££
          £E
   P    E  £

```

Above, the two ¤ are tile 24, while all the others are tile 23, the player can move to T by walking over those two tiles. The presence of T gives the hint that there is a secret passage.

---
Tags: c++, text-based, roguelikes
---


# Question
Title: How to get the Javascript equivalent of GameMaker's `hspeed` and `vspeed` given only `direction` and `speed`?
I'm using a NodeJS server to control NPC movement in a multiplayer game, and when they get too close to the edge of the room I need to reverse either the horizontal or vertical components of their velocities (how to decide which, is a bridge I'll cross when I get there).

The problem is I already have their `direction` and `speed`, and am able to convert it to `hspeed` and `vspeed`, but not back again.

I need the inverse of this function:

```
function velocityToSpeeds(direction, speed) {
  return {
    x: -speed*Math.sin(Math.toRad(direction - 90)),
    y: -speed*Math.cos(Math.toRad(direction - 90))
  };
}

```

# Answer
### You want to convert cartesian coordinates to polar.

Use `Math.atan2(vy, vx)` to get direction (it's in radians).
For velocity magnitude, use `Math.sqrt(vx*vx+vy*vy)`.

`vx` and `vy` are your horizontal and vertical components of speed.

### Also

Your existing code can be simplified.

```
function velocityToSpeeds(direction, speed) {
  return {
    x: speed*Math.cos(Math.toRad(direction)),
    y: speed*Math.sin(Math.toRad(direction))
  };
}

```
> 1 votes

# Answer
I got it to work with these formulas:

```
function velocityToSpeeds(direction, speed) {
  return {
    hspeed: Number(-Number(speed)*Math.sin(Math.toRad(Number(direction) - 90))) + 0,
    vspeed: Number(-Number(speed)*Math.cos(Math.toRad(Number(direction) - 90))) + 0
  };
}

function speedsToVelocity(hspeed, vspeed) {
  return {
    direction: Math.round(Number(Math.toDeg(Math.atan2(Number(vspeed), Number(hspeed))))) + 0,
    speed: Math.round(Number(Math.sqrt(Number(hspeed) * Number(hspeed) + Number(vspeed) * Number(vspeed)))) + 0
  }
}

```

Here are a couple more as a bonus:

```
function negativeHspeed(direction) {
  return ((180 - direction) + 360) % 360;
}

function negativeVspeed(direction) {
    return 360 - direction;
}

```
> 0 votes

---
Tags: javascript, game-maker, trigonometry
---


# Question
Title: Problem Implementing SAT Collision in 3D, OBB vs OBB
I am trying to implement SAT collision detection between 2 OBBs, however, I am getting a lot of false positives, can anyone help me figure out what I am doing wrong, thank you in advance.

This is my C++ code for reference, I am using GLM math library for all calculations:

```
uint MyRigidBody::SAT(MyRigidBody* const a_pOther)
{
    //distance between two points
    float offset = glm::distance(this->GetCenterGlobal(), a_pOther->GetCenterGlobal());

    //corners of the first rigid body
    std::vector<vector3> OBBPoints;

    //back bottom left
    vector3 backBottomLeft1 = m_v3MinG;
    OBBPoints.emplace_back(backBottomLeft1);
    //front up right
    vector3 frontUpRight1 = m_v3MaxG;
    OBBPoints.emplace_back(frontUpRight1);
    //back bottom right point
    vector3 backBottomRight1 = vector3(m_v3MaxG.x, m_v3MinG.y, m_v3MinG.z);
    OBBPoints.emplace_back(backBottomRight1);
    //back up right point
    vector3 backUpRight1 = vector3(m_v3MaxG.x, m_v3MaxG.y, m_v3MinG.z);
    OBBPoints.emplace_back(backUpRight1);
    //back up left point
    vector3 backUpLeft1 = vector3(m_v3MinG.x, m_v3MaxG.y, m_v3MinG.z);
    OBBPoints.emplace_back(backUpLeft1);
    //front bottom left
    vector3 frontBottomLeft1 = vector3(m_v3MinG.x, m_v3MinG.y, m_v3MaxG.z);
    OBBPoints.emplace_back(frontBottomLeft1);
    //front bottom right point
    vector3 frontBottomRight1 = vector3(m_v3MaxG.x, m_v3MinG.y, m_v3MaxG.z);
    OBBPoints.emplace_back(frontBottomRight1);
    //front up left point
    vector3 frontUpLeft1 = vector3(m_v3MinG.x, m_v3MaxG.y, m_v3MaxG.z);
    OBBPoints.emplace_back(frontUpLeft1);

    //corners of the second rigid body
    vector3 v3MinLOther = a_pOther->GetMinGlobal();
    vector3 v3MaxLOther = a_pOther->GetMaxGlobal();

    //corners of the first rigid body
    std::vector<vector3> OtherOBBPoints;

    vector3 backBottomLeft2 = v3MinLOther;
    OtherOBBPoints.emplace_back(backBottomLeft2);
    //front up right
    vector3 frontUpRight2 = v3MaxLOther;
    OtherOBBPoints.emplace_back(frontUpRight2);
    //back bottom right point
    vector3 backBottomRight2 = vector3(v3MaxLOther.x, v3MinLOther.y, v3MinLOther.z);
    OtherOBBPoints.emplace_back(backBottomRight2);
    //back up right point
    vector3 backUpRight2 = vector3(v3MaxLOther.x, v3MaxLOther.y, v3MinLOther.z);
    OtherOBBPoints.emplace_back(backUpRight2);
    //back up left point
    vector3 backUpLeft2 = vector3(v3MinLOther.x, v3MaxLOther.y, v3MinLOther.z);
    OtherOBBPoints.emplace_back(backUpLeft2);
    //front bottom left
    vector3 frontBottomLeft2 = vector3(v3MinLOther.x, v3MinLOther.y, v3MaxLOther.z);
    OtherOBBPoints.emplace_back(frontBottomLeft2);
    //front bottom right point
    vector3 frontBottomRight2 = vector3(v3MaxLOther.x, v3MinLOther.y, v3MaxLOther.z);
    OtherOBBPoints.emplace_back(frontBottomRight2);
    //front up left point
    vector3 frontUpLeft2 = vector3(v3MinLOther.x, v3MaxLOther.y, v3MaxLOther.z);
    OtherOBBPoints.emplace_back(frontUpLeft2);

    vector3 v3OtherCenter = a_pOther->GetCenterLocal();

    std::vector<vector3> normalList;

    //normal of x axis of this body
    vector3 A0 = vector3(GetModelMatrix()*vector4(AXIS_X,1.0f));
    normalList.emplace_back(A0);
    //normal of z axis of this body
    vector3 A1 = vector3(GetModelMatrix()*vector4(AXIS_Y, 1.0f));
    normalList.emplace_back(A1);
    //normal of the y axis of this body
    vector3 A2 = vector3(GetModelMatrix()*vector4(AXIS_Z, 1.0f))
    normalList.emplace_back(A2);

    //normal of x axis of other body
    vector3 B0 = vector3(a_pOther->GetModelMatrix()*vector4(AXIS_X, 1.0f));
    normalList.emplace_back(B0);
    //normal of y axis of other body
    vector3 B1 = vector3(a_pOther->GetModelMatrix()*vector4(AXIS_Y, 1.0f));
    normalList.emplace_back(B1);
    //normal of the z axis of other body
    vector3 B2 = vector3(a_pOther->GetModelMatrix()*vector4(AXIS_Z, 1.0f));
    normalList.emplace_back(B2);

    //9 cross product axes
    vector3 A0CrossB0 = glm::cross(A0, B0);
    normalList.emplace_back(A0CrossB0);

    vector3 A0CrossB1 = glm::cross(A0, B1);
    normalList.emplace_back(A0CrossB1);

    vector3 A0CrossB2 = glm::cross(A0, B2);
    normalList.emplace_back(A0CrossB2);

    vector3 A1CrossB0 = glm::cross(A1, B0);
    normalList.emplace_back(A1CrossB0);

    vector3 A1CrossB1 = glm::cross(A1, B1);
    normalList.emplace_back(A1CrossB1);

    vector3 A1CrossB2 = glm::cross(A1, B2);
    normalList.emplace_back(A1CrossB2);

    vector3 A2CrossB0 = glm::cross(A2, B0);
    normalList.emplace_back(A2CrossB0);

    vector3 A2CrossB1 = glm::cross(A2, B1);
    normalList.emplace_back(A2CrossB1);

    vector3 A2CrossB2 = glm::cross(A2, B2);
    normalList.emplace_back(A2CrossB2);

    int result = 0;

    for (uint i = 1; i < normalList.size()+1; i++)
    {
        if (!IsOverlapping(normalList[i-1], OBBPoints, OtherOBBPoints,offset))
        {
            result = i;
            break;
        }
    }

    //there is no axis test that separates this two objects
    return result;
}

bool MyRigidBody::IsOverlapping(vector3 axis, std::vector<vector3> thisPoints, std::vector<vector3> otherPoints,float offset)
{

    bool overlap = false;

    //vector to hold the dot products of the this rigid body's points to the given axis
    std::vector<float> dots1;

    //adding the dot products to a vector
    for (int i = 0; i < thisPoints.size(); i++)
    {
        dots1.emplace_back(glm::dot(axis, thisPoints[i]));
    }

    //vector to hold the dot products of the other rigid body's points to the given axis
    std::vector<float> dots2;

    //adding the dot products of to a vector
    for (int i = 0; i < otherPoints.size(); i++)
    {
        dots2.emplace_back(glm::dot(axis, otherPoints[i]));
    }

    //holding the min and max from the first set of dot products
    float min1 = *std::min_element(dots1.begin(), dots1.end());
    float max1 = *std::max_element(dots1.begin(), dots1.end());

    //holding the min and max from the first set of dot products
    float min2 = *std::min_element(dots2.begin(), dots2.end());
    float max2 = *std::max_element(dots2.begin(), dots2.end());

    if (min2<max1&&min1<max2)
    {
        overlap = true;
    }

    return overlap;

}

```

Here is an example of one false positive I get, with body B rotated -55.0 radians about the Z axis. For each axis, I list the axis vector and the min & max projection value of each object along that axis:

axis 0: (2.90000033, 1.40000010, 0.000000000)

```
    max1    3.31810808
    max2    4.44125700
    min1    2.17760968
    min2    1.60608065

```

axis 1: (1.90000033, 2.40000010, 0.000000000)

```
    max1    3.76422477
    max2    3.86839604
    min1    2.19537735
    min2    0.942635834

```

axis 2: (1.90000033, 1.40000010, 1.000000000)

```
    max1    3.45290613
    max2    4.08557701
    min1    1.92733908
    min2    1.17654514

```

axis 3: (2.823576453, -0.819152057, 0.000000000)

```
    max1    1.77099395
    max2    4.12324381
    min1    0.837887466
    min2    1.45174122

```

axis 4: (3.06915212, 0.573576450, 0.000000000)

```
    max1    2.76739883
    max2    4.38953018
    min1    1.97729456
    min2    1.85467112

```

axis 5: (2.250000000, 0.000000000, 1.000000000)

```
    max1    2.20817542
    max2    3.91630626
    min1    1.44707108
    min2    1.69250262

```

axis 6: (0.000000000, 0.000000000, -6.32854843)

```
    max1    0.374500990
    max2    0.249922007
    min1    -0.374500990
    min2    -0.249922007

```

axis 7: (0.000000000, 0.000000000, -2.63344145)

```
    max1    0.374500990
    max2    0.249922007
    min1    -0.374500990
    min2    -0.249922007

```

axis 8: (1.40000010, -2.90000033, -3.15000010)

```
    max1    0.0287668779
    max2    1.71970975
    min1    -1.70785379
    min2    -0.592771530

```

axis 9: (0.000000000, 0.000000000, -8.33297253)

```
    max1    0.374500990
    max2    0.249921992
    min1    -0.374500990
    min2    -0.249921992

```

axis 10: (0.000000000, 0.000000000, -6.27616978)

```
    max1    0.374500990
    max2    0.249922007
    min1    -0.374500990
    min2    -0.249922007

```

axis 11: (2.40000010, -1.90000033, -5.40000010)

```
    max1    0.741111636
    max2    1.95341909
    min1    -0.620677114
    min2    0.0398745090

```

axis 12: (0.819152057, 2.82357645, -5.50939655)

```
    max1    1.97528100
    max2    1.45832372
    min1    0.520946801
    min2    -0.149432912

```

axis 13: (-0.573576450, 3.06915212, -3.20701790)

```
    max1    2.13298345
    max2    1.00086546
    min1    0.411477685
    min2    -1.00041628

```

axis 14: (1.40000010, 0.349999666, 3.15000010)

```
    max1    1.47155154
    max2    2.03141236
    min1    0.468779355
    min2    0.537880898

```

# Answer
> 0 votes
Thanks for sharing your axis values. It revealed that you have more parallel axes than we'd expect from two rotated boxes, suggesting that you're computing the projection axes incorrectly.

It looks like the problem is here:

```
//normal of x axis of this body
vector3 A0 = vector3(GetModelMatrix()*vector4(AXIS_X,1.0f));
normalList.emplace_back(A0);
//normal of z axis of this body
vector3 A1 = vector3(GetModelMatrix()*vector4(AXIS_Y, 1.0f));
normalList.emplace_back(A1);
//normal of the y axis of this body
vector3 A2 = vector3(GetModelMatrix()*vector4(AXIS_Z, 1.0f))
normalList.emplace_back(A2);

//normal of x axis of other body
vector3 B0 = vector3(a_pOther->GetModelMatrix()*vector4(AXIS_X, 1.0f));
normalList.emplace_back(B0);
//normal of y axis of other body
vector3 B1 = vector3(a_pOther->GetModelMatrix()*vector4(AXIS_Y, 1.0f));
normalList.emplace_back(B1);
//normal of the z axis of other body
vector3 B2 = vector3(a_pOther->GetModelMatrix()*vector4(AXIS_Z, 1.0f));
normalList.emplace_back(B2);

```

By appending a 1.0 to the end of the vector, you're telling GLM "this vector represents a position - please include the object's translation when you transform it"

But these normal vectors *do not* represent positions. They represent *directions*. So the fourth component should be zero.

(In fact, since you just want the axes of the matrix, you can read them straight out of the matrix's columns without doing a matrix multiplication at all)

It also looks like you're computing your vertex positions incorrectly. If one of the bodies is rotated, then the worldspace coordinates of its vertices are not simply interleaves of its min & max points. That will give you the vertices of its axis aligned bounding box, but since you're doing an OBB test you want the vertices of the box itself, transformed by its model matrix.

We can see the difference by drawing a simple example in 2D. Here the worldspace coordinates of the vertices we want to work with are (2, 1), (1, 4), (7, 6), (8, 3)

But if we take the worldspace min & max of all of these points to make two corners, and then form our remaining corners by interleaving values from that min & max, we get the box (1, 1) (1, 6), (8, 6), (8, 1), which as you can see sits considerably outside the real bounds of our object.

# Answer
> 0 votes
It looks like you are computing the axes correctly, so I doubt that is your problem.

First, a couple of asides you may not be aware of:

It is possible for you to get degenerate cases in SAT, in the case of computing the cross product of two parallel axes.

In such a degenerate case, you do not attempt to compute the min/max, and just pass over the axis. This can be done easily using glm by simply checking it against itself:

```
vector3 A0CrossB0 = glm::cross(A0, B0);
if (A0CrossB0 == A0CrossB0)
{
    normalList.emplace_back(A0CrossB0);
}

```

The reason this works, is that if the two input axes are parallel, the values in the output will be "NaN"(It works in glm, but don't assume it will work in other math libraries). You can check this in a debugger. Equality checks between two NaN values will always be evaluated as false.

I also noted the following:

```
if ( min2 < max1 && min1 < max2 )
{
    overlap = true;
}

```

You have not addressed the possibility of "containment", where a much smaller projection can be contained within a larger one. See the image below for a number line representation of this case:

So I would change this to:

```
if ( min2 < max1 && min1 < max2 )
{
    overlap = true;
}
if (min2 > min1 && max2 < max1 )
{
    overlap = true;
}
if (min1 > min2 && max1 < max2 )
{
    overlap = true;
}

```

But on to your question proper:

As DMGregory correctly stated in his answer, your use of the matrix is incorrect.

First I would suggest turning your model transform into a mat3:

```
glm::mat3 transformA = glm::mat3(A.GetModelMatrix());

```

This will strip out the scale and position components of the transform, making it a rotation only transform, from which you can get your principle axes for your OBB:

```
glm::vec3 localX = transformA[0];
glm::vec3 localY = transformA[1];
glm::vec3 localZ = transformA[2];

```

Then, you can compute the points using the OBB dimensions (halfwidth, halfheight, halflength), like so:

```
pointsA[0] = position + (localX * halfwidth) + (localY * halfheight) + (localZ * halflength);
pointsA[1] = position + (localX * halfwidth) - (localY * halfheight) + (localZ * halflength);
pointsA[2] = position + (localX * halfwidth) + (localY * halfheight) - (localZ * halflength);

```

and so on.

This will give you the world space coordinates for the vertices of your OBB. Repeat this for the other OBB, using it's own transform, position and dimensions, and you will get its worldspace coordinates and axes.

Computing the min/max projections in the same space along with the other changes I suggested, should prevent any false positives. (this is taken from my own working code btw).

---
Tags: c++, collision-detection, glm, separating-axis-theorem
---


# Question
Title: What engine is used in an introductory game-development course?
I am preparing a course in game-development. It is a choice-coures for 3rd-year students of computer science, who have working knowledge of several programming languages (C, C++, Java), algorithms, data structures etc. For the class and home exercises, I am considering two systems.

Initially, I thought of using Unreal Engine - since it is widely used in the industry, so using it will give the students an edge when looking for a job.

However, I then thought that such a complex engine might distract students from the design aspects of a game, and put them too much into the intricacies of graphics and animation. So I thought of using PyGame, which is much simpler.

My question is: what game-development engines are commonly used in similar courses (introductury GD courses for undergraduate CS students)?

# Answer
The top 3 are probably Unity3D (C#), Unreal Engine 4 (Blueprint/C++), and Pygame.

The good parts of Unity and Unreal are that they give you immediate access to a full-featured 3D renderer, and they have tools to support exploring almost any interest area in game dev. This comes with the drawback of having to learn a somewhat complex API to get started, *especially* for UE4. The engine developers have done all they can to provide free tutorials and documentation to speed up the process.

Learning an API and integrating well with an existing codebase are important skills because the students will likely need to do the same at any game dev company immediately after being hired.

That said, Unity differs from UE4 in that the framework/API given to the user is basically a clean slate, with no user control or game mechanics already implemented. Any user interaction or game mechanics need to either come from a plugin or be coded from scratch in simple C#.

With UE4, the Pawn and Character classes along with some utility components present an easy way to bypass initial boilerplate code and jump immediately to user interaction and game mechanics for a generic game type like an FPS. UE4’s Blueprints system makes it more accessible to the general public in some ways, but these students will want and need to code.

The choice here probably should be between Unity and UE4. Unity is likely the best option here for an introductory course, and UE4 is a more realistic scenario for experience integrating with an existing API.
> 0 votes

---
Tags: architecture, education
---


# Question
Title: Is it always necessary to synchronize rendering in a game loop?
When writing a game loop from scratch in java for an android game applications, it is very common in many tutorials I have read that the keyword synchronized is used to synchronize update and rendering methods of the SurfaceHolder of the SurfaceView that manages the game objects.

I understand the basics of synchronization and the importance of synchronizing i.e. a method which should be called n times, and is called inside multiple threads. But what I want to know is if the synchronization block, that synchronizes around a SurfaceHolder, and contains the SurfaceHolder's draw (rendering) and update methods, needs the synchronization if the plan is to ONLY call the update and draw methods inside one single thread (the game loop).

To conclude, the main concerns I have are:

1) Can the draw method inside the SurfaceView class be called by some inherrited, or just hidden method that I'm not aware of, so that I always have to synchronize the method?

2) Is there any reason to NOT use the synchronization if it's not needed; i.e., is the functionality computationally heavy?

Please let me know if anything in my question is unclear :)

# Answer
This post assumes the game uses a “core gameplay loop” and concurrent threads for gameplay and rendering.

Usually game engines render one frame behind the core gameplay loop, using the most up to date state (position, rotation, color, etc) of all the game objects from the previous cycle. Besides disregarding synchronous operation entirely and risking many race conditions by trying to render *during* a game loop, this is the lowest-latency way to do rendering.

The synchronization needed here is to make sure that:

1. The next cycle state is ready before the render thread starts on it, so the same cycle state does not get rendered twice.
2. The render thread finishes frame *n* before frame *n+2* is started by the gameplay loop, which frees up CPU power for the rest of the render task and stops the gameplay loop from getting more than a single cycle ahead from the render.
> 0 votes

---
Tags: java, android, game-loop, synchronization, thread
---


# Question
Title: 2D Top Down: Can't follow the path accurately
In my game, there are many agents. Agents request a path, then after attaining a path to "goal" they follow the path. However player and many other things in the world can impact their position by pushing them or pulling them.

When agents get pushed and they happen to advance forward closer to "goal", I want them to smartly follow the previously given path.

I have pictures below to enhance your understanding of my situation.

I COULD recalculate path every a few seconds or when agent gets out of path BUT I have DOZENS of these little agents. I don't want to do path finding for DOZENS of agents again, again, again, and again whenever they walk out of the path.

# Answer
The way you generally do this is to run the path-finding algorithm again every so often.

For lots of units, you can speed things up using hierarchical pathfinding and/or swarm pathfinding and/or using predefined paths between waypoints and merely pathing to the nearest waypoint.
> 1 votes

# Answer
There are many possibilities to do it:

1) Repath

2) Use path segments directions - and check if at goal like follows:

If (dot(playerToGoalDirection,SegmentDirection) \< 0) Go to the next path point update path segment.

You can add some tracing to sieve out waypoints that you dont want to move to after being hit.

For example trace to the next point if success trace to the next-next point if success remove the next point and path to next-next point

*Remark: PlayerToGoalDirection is the direction to the current waypoint*

You can see the second in action here:

https://drive.google.com/file/d/1x4MPTSwyEtNeSRd1YHjr4nzOG41cp5Sc/view?usp=drivesdk
> 1 votes

# Answer
As already mentioned, there can be multiple solutions to this. Depends on project setup and your preferences, so just one more idea to add:

Maybe you can just recalculate path only after collision. So let's say logic could be following:

1. calculate path just once for each object and let them move
2. whenever any of those objects will collide (maybe only with respective layer/tag), stop navigation
3. let that object to stop (check for velocity) and once stopped recalculate only then the path again

That would minimize amount of agent recalculation unlike calculating it each frame. Letting object to stop can also emulate visually some "confusion" effect caused by hit, which can eventually be enhanced if you wait some time before you initiate agent movement after hit again

Again it depends on your project setup, but can give some hint on how to take this
> 1 votes

# Answer
EDIT2: A series of heuristics is likely in order using the below. If within distance that node scores some points. Then if it's angular difference to the next node is close to 0, it scores (a lot) more points. Then if none of that works out, recalculate. If it *does* work out, simply move to the highest scoring node.

---

First, you should probably maintain a rough angle between the agent and it's goal, that way you can approximate the direction it's supposed to be going.

Second, you might have an impacted agent perform a distance calc on the next nodes in the path. If it's within distance then just go to the nearest node (+1) of that path and follow it. If it's outside of distance then recalculate. The nearest node (+1) (maybe recalculate just to this node) will look fairly natural I think.

This should save you most of your A\* calculations and give a natural looking move.
> 0 votes

---
Tags: path-finding, path-tracing
---


# Question
Title: How to create smoke that spreads outward in all directions?
I saw many tutorials about smoke grenade but they just use volumetric smoke. I want to make something like the smoke grenade in PUBG, where the smoke spreads in all directions; how to do that?

The Unreal Engine 4 smoke grenade throws out smoke in a particular direction, like this:

But I want something more like PUBG's that spreads smoke evenly in all directions:

# Answer
> 1 votes
Assuming you want to create a smoke particle system which mimics the behavior of a smoke grenade the docs provide a pretty good effect that just hast to be tweaked to your needs:

UE4 - Niagara - Smoke Particle System

---

Key Settings in the particle system:

* Spawn radius from small to big over time - e.g. using a curve (to achive the pop effect)
* Sprite size from small to big over lifetime of the particle (make it seem like they fade out)
* Small random force upwards during the lifetime

# Answer
> 0 votes
I'm no expert but to PUBG smoke looks either like very simple particle effect, or even worse, a bunch of "billboard" textures.

When you add a texture to the game in UE4, you can use an option "billboard", that means that it will always rotate to face the players camera.

If you are interested in why the smoke goes in all the directions equally, that might be related to lack of wind or just settings of the particle generator. There are a lot of good tutorials on that, just search "UE4 particles".

---
Tags: unreal-4, particles, effects
---


# Question
Title: Unity Vertex Color Shader with Transparency
I'm trying to achieve a simple effect: I have a cube mesh and I want some of the vertices to change color. In this case, I want it to form some sort of a gradient where the unchanged vertices are set to the default color (with alpha = 1) and the changed vertices to slowly fade (default color with alpha decreasing towards 0).

I'm able to modify these vertices' color with this piece of code:

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

public class Test : MonoBehaviour
{
    Mesh mesh;
    Vector3[] vertices;
    Color[] colors;
    List<int> verticesToChange;

    void Start()
    {
        mesh = GetComponent<MeshFilter>().mesh;
        vertices = mesh.vertices;
        colors = new Color[vertices.Length];
        verticesToChange = new List<int>();

        for(int i = 0; i < vertices.Length; i++) {
            colors[i] = Color.white; //Set the default vertex color
            if(Mathf.Approximately(vertices[i].y, 0.5f)) //Change only the vertices on the plane y=0.5
                verticesToChange.Add(i);
        }

    }

    void Update()
    {
        foreach(int i in verticesToChange) {
            colors[i].a = Mathf.Max(colors[i].a - Time.deltaTime * 0.5f, 0f);
        }

        mesh.colors = colors;
        //Not needed here, but I will be changing the vertices' position too later
        mesh.RecalculateBounds();
        mesh.RecalculateNormals();
        mesh.RecalculateTangents();
    }
}

```

My problem is selecting a shader that actually uses this color and this color only. I've tried Unlit/Color, Unlit/Transparent and Particles/Standard Unlit with multiple combinations of Rendering Mode, Color Mode and Albedo color.

Is there a built-in shader that does this and I'm not getting the right combination of its parameters? Or do I have to build my own shader? I've never wrote a shader with Unity, so I would prefer a built-in option or an open source / free shader.

# Answer
> 2 votes
After continuing testing different combinations of Shader parameters I got it working like this:

I feel silly because this actually makes sense, so I don't know why I didn't try that...

---
Tags: unity, shaders, vertex, color, transparency
---


# Question
Title: Automatically create C# from manually created game objects
I have created 2 gameobjects along with its properties in the Unity Inspector. I have attached a screenshot below.

For prototyping, I like the Inspector very much, but for runtime I prefer doing everything by scripts. This way nothing can go wrong: I don't have to carry so many files around, and I find it easier to understand everything.

I would now like to change this so that these 2 components are created at runtime by script.

Is there perhaps a way to automatically create the script that would create these game objects?

I would appreciate it very much if I could save some time with such an automatic script creation.

Thank you for any input.

# Answer
> 4 votes
The short answer is no.

The longer answer is noooooooo. Well, it’s actually “almost, but...”

You seem to be mistrustful of Unity and want to do everything manually. Unity is designed to be the opposite of that. Sounds like Unity is not the engine for you in that case.

Some reasons why what you want to do is not a good idea:

* technically impossible. On the loading thread, everything gets created and assigned “at once”, and then OnEnable/Awake/Start are called all “at once”, at the correct time. With a C# implementation, OnEnable and Awake gets called on each component as its added, before any fields are assigned values, and potentially before future components are added, meaning some things may be missing when a component expects them to exist.
* slower. Things are being done on the main Unity thread rather than the loading thread, so everything must be done during update rather than in the background.
* error prone. Accessing assets like fonts, textures, materials, etc. would require manually naming each asset as strings, and those assets would need to be stored in Resources or asset bundles.
* slower again. If you put the assets into Resources folders, they must be loaded on launch, which slows launch time. If you put them in asset bundles, then you must build asset bundles separately whenever any assets change.
* error prone again. If you ever rename a file, you would need to reconstruct the code that references it by name. (Note: using Addressable Assets May mitigate this, but I am not familiar enough with this system to know.)
* larger application. All of your assets would need to go into resources folders. Unity can tell which assets you are using and remove the ones you aren’t during the build. However, no such luck with assets you control manually (i.e. everything, in your case). You may end up with a bunch of unused assets bloating the final app unless you regularly purge unused assets.
* needlessly complex. You’re falling victim to the Not Invented Here problem. Because you don’t trust Unity’s loading system, you are re-inventing it yourself, in a necessarily more error-prone fashion.

# Answer
> 1 votes
It sounds like what you want to do is create a prefab, and load that dynamically from a script. I believe to execute a script you will need an object to which it can be attached. You can add a public field to your script which accepts a GameObject, attach that script to a game object, and drag-and-drop your prefab from the project explorer on to the GameObject's field in the inspector. Once that is done, you may reference that prefab from within the script, and use `Instantiate(myPrefabField)` to create a real GameObject from the prefab, as a template.

Check out this document by Unity

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


# Question
Title: Rendering Problems(Artifacts, Flickering) with the Mirage Solo VR Headset
Im getting some strange flickering artifacts when testing on device (Mirage solo), this problem occurs on Unity 2018.3.2 and Unity 2019.1.2. Its not happening on other devices such as the OculusGo, Google Pixel, Samsung s7,s9. It seems to be only occuring on devices that use Qualcomm Adreno 540 GPU. Has anyone else encountered anything like this if so, did you fix it and how? The Environment is using a custom shader, the robot character is simply using a unity standard shader and there is a hologram at the side(right) which is using a custom shader.

**Hardware:** Snapdragon 835 SoC Qualcomm Adreno 540 GPU

**Video:** https://streamable.com/

**Screenshots:**

Bad:

Good:

# Answer
> 0 votes
Fixed with these settings:

For reference i remained on 2018.3.2f1, due to separate issues found on 2019. Good luck!

---
Tags: unity, rendering, virtual-reality
---


# Question
Title: Spatial Jitter problem in large unity project
I have a very large environment where i am getting very weird view of objects as picture given below:

As you can see there are black lines/spot, maybe the vertex lit problem. Currently I am using Standard specular shader. Remember this problem is only occuring at the end of the project (away from origin like position -17000, 0, 144)

As a workaround i tried to change my shader to Unlit and i found this shader

```
 Shader "Unlit/UnlitAlphaWithFade"
 {
     Properties
     {
         _Color ("Color Tint", Color) = (1,1,1,1)
         _MainTex ("Base (RGB) Alpha (A)", 2D) = "white"
     }

     Category
     {
         Lighting Off
         ZWrite Off
                 ZWrite On  // uncomment if you have problems like the sprite disappear in some rotations.
         Cull back
         Blend SrcAlpha OneMinusSrcAlpha
                 //AlphaTest Greater 0.001  // uncomment if you have problems like the sprites or 3d text have white quads instead of alpha pixels.
         Tags {Queue=Transparent}

         SubShader
         {

              Pass
              {
                         SetTexture [_MainTex]
                         {
                     ConstantColor [_Color]
                    Combine Texture * constant
                 }
             }
         }
     }
 }

```

This shader has almost solve the problem but i have to tweak and set colour of each object as be default it is not according to my expectation.

# Answer
> 1 votes
The object was far from the origin i.e., it was creating **spatial Jitter (SJ)** or wobble effects in mesh. The surprising thing was for me that why it is creating problem at position 17000 of x-axis while unity allow value less than 1,000,000 (not restricted to it actually). The problem has solve through floating origin technique, the general idea is that : You usually move more and more away from the origin (0/0/0), so you should try to keep your camera and/or player/point-of-interest always around the origin, instead of letting it travel to vast distances (ref).

# Answer
> 1 votes
With regard to your question: "The surprising thing was for me that why it is creating problem at position 17000 of x-axis while unity allow value less than 1,000,000 (not restricted to it actually)."

jitter starts to occur earlier than you might expect because the resolution gap of floating point increases (gets worse) almost immediately as you move away from the origin.

Specifically, the resolution ("gap error") for a single precision float at the origin is of the order of 10^-7, then at 2 it doubles (gets worse by 2), doubles at 4 and so on with every power of 2 distance from the origin. Explained in thesis: https://doi.org/DOI:10.13140/RG.2.2.10421.32481, section 2.1. This resolution value is the base gap error in each floating point coordinate variable (x,y,z) and rendering calculations magnify it through multiplication, addition etc. As rendering is a very demanding of accuracy, if your viewpoint is close to where the jitter manifests, you may see it at smaller distances than you expect.

# Answer
> 0 votes
It might be because of your meshes' vertex normals. They are probably wrong. Unity calculates shadows based on vertex normals, which should be perpendicular to the relative face, like this:

If you select the raw mesh in unity, from the project view, and in the inspector you select "recalculate normals" the problem might get fixed. If not, you probably need to remodel the meshes that are corrupted.

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