# Question
Title: How does Terraria generate such large worlds initially?
I understand how large worlds can be rendered and drawn efficiently by splitting things into chunks, but as I understand it Terraria generates the entire world when you first create it.

The largest world size available in Terraria is 8400 x 2400 which would be a total of 20,160,000 tiles.

Is the entire world generated in one go? Like for example having a large array with 20,160,000 tiles and then saving it to a file when it's finished? Or would the world generation itself do it chunk by chunk?

Just looking for help to find out what the best method would be to approach this as I'm not really sure.

# Answer
When the world generates, you'll see various texts appearing while waiting. These texts aren't random, the world is actually processing what the text says.

I've seen a video that showcases how the world generation looks like behind the scenes. So that gives you a rough idea how it's creation works: (https://www.youtube.com/watch?v=bF-\_AeRRbmU)

It starts out with the surface, and the variation of the dirt and stone, then it start making caves, increasing in size each time. After that you'll also see sections been converted to biomes (jungle and ice specifically), and then more detailed structures, like granite, cabins and the dungeon happens afterwards.

The world is technically generated in one go, but it keeps generating new parts over itself, and finetuning the details afterwards.

As for rendering, while the world is loaded all at once, it will only draw (or render) the blocks when you're close to it. so when you're moving fast, you sometimes see the tiles ahead of you needing some time to appear.
> 9 votes

# Answer
Couple of additions to Steven's informative answer, at a technical / processing level... speaking here in a general sense of the techniques used to generate large worlds (not Terraria specifically).

**Generating the initial space**

Firstly, there are fast block copies (`memcpy` / `memset` in C) used to allocate the initial memory (2D array) representing the world. The entire initial world can consist of zeroes, or `struct`ures all of whose members are set to zero. This could represent either sky or ground. Let's assume the whole maps start as sky, so zeroes represent empty space. This is a very fast operation. If the entire 20 million tile map uses 4 bytes per tile, that is 80MB - large, yes - but not ridiculously so by any modern measure. Expect milliseconds or less to allocate such a large space to main memory (RAM).

Terrain can be rapidly written (& read) in a couple of ways.

* `memset`, or series of `memset`s on a 2D array, most of which resides in main memory (RAM) + regular array access to read; you could even chunk this into smaller arrays (but many of them) to operate on smaller areas. Still, this is not particularly efficient; see below.
* instead, the whole world may be represented as RLE columns, running from top to bottom. This makes access much faster, since an entire column of 2400 high can be represented as nothing but a min value (2 bytes), max value (2 bytes), and the tile type (typically 1 byte) = 5 bytes total. Less data = less time to access it. If you have earth (basic stone) and sky in the same column, that's 2 such entries = 10 bytes. For the whole map then, before you have started making elaborate details, that's 10 bytes * 8400 = 84000 bytes, or about 84kB. That's miniscule, and fits into CPU L1 cache on pretty much all systems, making access super fast. Now let's imagine you have at least 50 different terrain variations (types) per column, then that is 50 * 84kB = +- 4MB. Still very small.

Data access speeds improve enormously when a dataset becomes small enough to fit into CPU L1 & L2 cache, as in RLE, rather than our RAM-sized (80MB) 2D array representation.

**Generating detail**

We could read from our RLE-encoded world map and temporarily copy areas into a small 2D array (for example 100x100) to create a pyramid, a small dungeon, a village etc. Once work is done, we copy these back into the RLE structure using an optimal function we've built for that purpose. What this means is that 99%+ of the entire world space is ignored as we elaborate in *just that small area*. As the world is gradually generated, we probably touch less than 20% of the entire world space.

**The general principle in such games / worlds is...**

"Don't explicitly specify (in memory) what can be safely assumed."

This is the principle which RLE (and other spatial subdivision / compression techniques) rely on.
> 7 votes

# Answer
@Steven and @Engineer both provided fantastic information, but I'd like to add one additional note regarding world generation commonly used for games like Terraria and Minecraft (and many others) that increase the performance of these things - **noise**.

In many cases, a world seed is provided that is used for noise functions. Those noise functions can provide information in layers for things like biomes, cave systems, locations of objectives or special objects, and really pretty much anything. The beauty of that is that the entire world, even if "generated" in one go, doesn't need to be held entirely in memory during or after the generation process because the game can calculate what is at a specific coordinate (whether that's a single tile, or a chunk) simply by running the algorithm.

In the case of worlds like Terraria, it might make alterations to the base noise function to make certain things "work" or "feel right". Those alterations can be saved per-chunk on another layer of data that overrides the default noise generated terrain - similar to how a game would save any changes made by the player, directly to each chunk of data.

If designed well, the initial generation, including alterations, could be done per-chunk across multiple threads, with each thread processing one chunk at a time. I suspect Oxygen Not Included does something similar with its world generation, though I cannot say for sure.

If you're using Unity (or don't mind using Unity as a learning tool), there's an absolutely fantastic course on Udemy that guides you through creating a Minecraft clone and is pretty fantastic about showing how to work with chunks and using noise to manufacture a world. While it's geared toward a Minecraft-like world that is more or less infinite (and therefore generates chunks only as needed), the same principles can be used for a finite world space. Really, any courses from Penny de Byl are worth the time.
> 3 votes

---
Tags: procedural-generation
---


# Question
Title: Should building interiors be in separate scenes in Unity?
I have an overworld with multiple buildings in it. Each building has a separate interior model with ~500 triangles. I was wondering if it would be better for performance to store the interiors in the same scene, and teleport the player to them, or if I should make a new scene for each interior and load that when a player enters the building?

Each have their own drawbacks and challenges, so I was wondering what the general consensus was about the topic.

# Answer
> 3 votes
#### Making sure your problem is a problem

First I would just load everything in the same scene all at once and see if that's actually a problem. 500 triangles is tiny for the interior of a building in the context of a modern computer, are you using high-res textures or targeting super low end devices? You might realize everything can be loaded simultaneously and synchronously and avoid these problems altogether.

#### Ok so there's a (memory) problem

Especially if you're targeting low end mobile devices, memory constraints may pose a problem. In that case you'll only want to load the interior of buildings when you need them.

##### Seamless

I would try to intelligently load scenes in place asynchronously and additively first to avoid loading bars and maintain a sense of continuous space. But it depends on what type of game you're making if this is worth the technical complexity of a seamless experience. You could use Scenes to do this, or Asset References (using Asset Bundles).

##### Loading Bar ▓▓▓░░░░░░

If immersion and seamlessness aren't particularly important, then progress bars and synchronous loading are the simplest option. Maybe you actually want interiors to be bigger than they appear from the outside, in which case you'll have to do the character teleporting strategy anyways.

---
Tags: unity, scene
---


# Question
Title: UE4 - storing complex actors in Game Instance
I want to make a game where I can hold tools in my hand and inventory. Obviously I want to pass them between levels and maybe even game sessions. Question is, how would I do that?

With simple variables like amount of money or HP, all I do is store a variable in the Game Instance. But what about, for example, a tool that has more data, like the class type, durability, maybe value? Even worse, whole array of them?

The way I use that in game is, there's an actor representing the tool. But even if I store array of those in the game instance, the actors get destroyed while changing level and the array just points empty memory. I could just spawn new ones by using the class type - but that is not enough for me.

My idea is to create something... maybe a struct, that would hold the information and then recreate the inventory item actors according to the data in the struct.

My questions: What are other ways to do it? and Is there something fundamentally wrong with the way I'm storing the items in my inventory now?

# Answer
What I did is to create a Struct for each object to be saved and then recreate it at begin play from what's loaded in the game instance.

Every object that has to be saved tells the game instance his last state in this way:

and whenever you save, the game instance provide saving those parameters:

Whenever begin play start every object retrieve his starting info from game instance (properly updated with last saved status) and rebuild himself.

---

In that way it works very well, we use level streaming and this logic seems to be solid, our Save Game entity has arrays to collect every object considering only what's important to save the state.
> 2 votes

# Answer
You can store an actor in the gameinstance as well. You can add your actors to toot AddToRoot() so they will not be destroyed.
> 0 votes

---
Tags: unreal-4
---


# Question
Title: How do you encourage players to do hard things?
I'm working on an app that teaches real-life skills by pitting players against each other to compete in skill improvement tasks. The problem is, players have a number of different tasks they're working on at the same time, and the better they get at one task, the more they'll want to choose that task over others as the easiest way to get points.

I'm thinking of tweaking the scoring so that it rewards players for doing things that are difficult for them, but I'm having trouble coming up with a reasonable way of implementing this. How do you motivate players to do hard things?

Ideas so far:

* I like models grounded in solid math, though models grounded in intuition are great too. What about using time-weighted data about player performance to predict the likelihood of a player attaining the score they did, and rewarding them based on how unlikely the performance was? Vaguely like Elo for single-player games, where a player is "beating" their achieved score as opposed to beating another player. Super complex though.
* Much simpler way of doing the above. Use time-weighted data to calculate descriptive statistics of the user's scores so far, then score the user based on the z-score of their performance, probably scaled exponentially to account for difficulty at the extremes. One sigma above expected? 10 points. Two sigmas? 100 points. Three sigmas? 1000 points.

# Answer
A good way to encourage the player to explore all the features of your game are **achievements**. Log achievements for mastering all the different skills at different levels. In order to tease the players completionist instincts, create an achievement screen which shows both the obtained and unobtained achievement badges.
> 2 votes

# Answer
A way to encourage players to do different things is to discourage them in doing always the same thing.

As they "do the same task", reduce the benefit gained from this task until they have accomplished enough of the other tasks.

E.g. with tasks of type A, B, C, at the start, each have a score multiplier of 1, then, as they perform a task of a specific type, reduce the multiplier by 0.1 for tasks of that type, until they get to, say, 0.5. Once every task type has its multiplier down to 0.5, reset everything back to 1.

---

Another way would be to have a personalized rotating daily bonus. If Player A seems to never do Task B, when they start their game session, tell them that they'll earn bonus points or some kind of reward if they perform Task B today.

---

Another way would be to increase a cost to do the easier tasks: a high demand task will cost more; you could reward them with "coins" when they do less popular tasks, and have them "pay" with coins to do more popular tasks.

---

Yet another simple way would be to put a hard limit on how many times they can repeat the same task per period of time. They can perform task C only three times per day, after that, they'll need to find another task to try.

---

That being said, if your users do a specific task to get *points*, the questions is, why do you give points in the first place. Users will do anything/everything to *get points*, they'll optimize their gameplay in order to *get points*. Maybe you should reconsider the concept of points and go with something already suggested by the previous answer, or go with a scoring system that cannot be compared, e.g. unlocking *hats* or other cosmetics instead of giving points.
> 2 votes

---
Tags: mathematics, game-design, leaderboards, scoring, motivation
---


title: How do I distinguish edge vertices?

text:
# Question
Title: How do I distinguish edge vertices?
I'm trying to displace the vertices highlighted in red but the way I'm selecting the vertices for displacement is by a distance radius based on the position I click with my mouse and I end up selecting the blue vertices. I want to only select the vertices up until the edges and not passed that. Other than distance, I don't know how to select a batch of vertices. How would I go about this?.

# Answer
> I want to only select the vertices up until the edges and not passed that.

If you define a segment from the vertex to the position you click, and that segment intersects the edge, then it is beyond the edge.

Let `P` be the point you click, and let `S` the list of edge vertex. Then iterate over the points in `S`, for each vertex `V`, define a segment from `P` to `V`. And check if that segment intersects the edge:

```
for (int index; index < S.length(); index++)
{
    var V = S[index];
    // Radius check
    if (distance(P, V) > radius)
    {
        continue;
    }

    // Intersection check
    var ok = true;
    for (int start_index; j < S.length(); j++)
    {
        var end_index = (start_index + 1) % S.length();
        if (start_index == index || end_index == index)
        {
            continue;
        }

        var start = S[start_index];
        var end = S[end_index];
        if (intersect_segments(a_start=P, a_end=V, b_start=start, b_end=end))
        {
            ok = false;
            break;
        }
    }

    if (!ok)
    {
        continue;
    }

    // passed all checks
    selection.add(V)
}

```

Consider this example:

In the example, all the colored segments go to edge vertex within the radius. The green is the closest vertex. The cyan is adjacent to the green, and there are no intersections to it. The blue are the other points within radius that have no intersections. And the red and magenta are the points within radius that have intersections.

The above approach would select green, cyan, and blue. Not the red and magenta, because they fail the intersection check.

---

If you need the selection to be contiguos, then Charly has the right idea. However, I'd argue he is missing the intersection check. Without it, it would select the green, the cyan, and the magenta from the example image above.

Find the edge vertex closest to where you click. From there you want to check both forward and backwards along the edge until you find a vertex that fail the radius test.

```
var best_index = -1;
var best_distance = double.PositiveInfinity;
for (int index = 0; index < S.length(); i++)
{
    var V = S[i];
    var found_distance = distance(P, V);
    if (found_distance < best_distance)
    {
        best_distance = found_distance;
        best_index = index;
    }
}

// Check forward
for (int i = 0; i < S.length(); i++)
{
    var index = (best_index + i) % S.length();
    var V = S[i];
    // Radius check
    if (distance(P, V) > radius)
    {
        break;
    }

    // Intersection check
    // …

    // passed all checks
    selection.add(V)
}

// Check backward
for (int i = 0; i < S.length(); i++)
{
    var index = (best_index - i) % S.length();
    var V = S[i];
    // Radius check
    if (distance(P, V) > radius)
    {
        break;
    }

    // Intersection check
    // …

    // passed all checks
    selection.add(V)
}

```

From the example image I shown above, this should only select the green and the cyan. Because after that the other adjacent points fail the intersection check or the radius check.

*And you would extract the checks, and presumably there is a more succinct way to write this code (I'm assuming you are using C# since you mention Unity in comments, and thus you can use Linq). I leave that to you.*
> 2 votes

# Answer
You're right to use distance, but you also need to incorporate the connectedness of the vertices in your algorithm. To do this you'll want to use some sort of recursive breadth first or depth first search algorithm that stops recursing if the vertices are outside the given radius from the root vertex or point of selection.

##### The Algo

1. Find the closest vertex to your selection point
2. Recurse through the root vertex's children
3. Stopping if the child is outside the selection radius
> 0 votes

---
Tags: vertex
---


title: Unity - Make child not scale on X

text:
# Question
Title: Unity - Make child not scale on X
I have a character that can move **left** and **right**.

Whenever it changes direction the character's **localscale x** is **multiplied by -1**.

The code looks like this:

```
private void Flip()
    {
        // Switch the way the player is labelled as facing.
        m_FacingRight = !m_FacingRight;

        // Multiply the player's x local scale by -1.
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }

```

When it **flips** **all children flip** aswel. The **character** has a **sprite** child (a white bubble), which in turn has a **Text Mesh Pro child**.

This is the hierarchy:

And this is the result:

https://media.giphy.com/media/0H0rGKsksURbDcRqvo/giphy.gif

Is there a way to prevent the text from flipping on x?

# Answer
> 1 votes
I'd recommend setting up your character like this:

* Root character object (with character control script, rigidbody, etc)
    + Character collision object (contains collider(s))
    + Character visual object (contains sprite renderer(s), animator, etc)
    + Text bubble object (contains white circle and text)

When you flip your character, flip only the "visual" child object, leaving the physics representation, text, and root object unchanged.

This structure gives you a lot of freedom to play with the visual object - like adding dynamic squash & stretch - without impacting legibility or gameplay logic.

---
Tags: unity
---


# Question
Title: unity c# issue unable to get perfect position of a enemy in unity c# script using transform.position
when I command or set an enemy to go left and then at reaching a particular state or position i say my enemy to go right but it is not going right and not reaching to perfect position here is the code I think there is no issue in the code but it is not working properly so here are some images of the code

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

public class enem : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = transform.position + new Vector3(-3f, 0f, 0f)* 1 * Time.deltaTime;
        if (transform.position.x > -29)
        {
            transform.position = transform.position + new Vector3(3f, 0f, 0f) * 1 * Time.deltaTime;

        }
    }
}

```

# Answer
> 0 votes
What happens here is:

1. The object moves left while its position is larger than -29.
2. Then it notices that its over the -29 mark and moves to the right for one frame
3. But on the very next frame, its position is larger than -29 again, so it moves left again

So the object keeps oscilating around the -29 point.

What you need is:

1. a variable to store the information whether the object is in the "move-left" state or the "move-right" state
2. two checks to see if the condition for changing direction is true and if so change the value of the variable
3. Move the object left or right depending on the value of the variable.

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


# Question
Title: Control a specific material property in a mesh renderer?
I want to animate a mesh which has 4 materials, all of them are using the same shader. now, I want to animate the "emission" property of material\[0\] and material\[2\], but not material\[1\] and material\[3\].

But on the animation window, I can only find one "emission" property,

1,I guess, this "emission" controls all 4 materials?

2,I also found "Material Reference\[x\]" property(x = 0,1,2,3), but, adding one of those property doesn't give me "sub property of emission"

So, what should I do? thanks I use Unity 2019.4.28.

# Answer
I don't know how to control each emission property in a separate manner, as I also found out that there's only one set of emission property and they affect all correspondent materials (materials of the same shader) at the same time.

I did manage to figure out that the 'Mesh Renderer. Material reference\[x\]' found in the animation property can be used to redirect different materials to its material slot. This is as in: If I had 2 or more materials, I can drag and drop them into the animation dopesheet to tell the mesh renderer which one to use. Also by doing this, no new materials will be instantiated even if a shared user already exists, unlike doing so by script.
> 0 votes

---
Tags: unity, animation
---


# Question
Title: Term for compositing textures according to colors in an index texture mask?
I have utilized a tool for a number of years that uses a "masking" technique to 'texture' a 2D graphic, by which it checks a series of solid colors to specify where to 'draw' textures in a final render. I have seen one other example of this in my searches on Google, and even that did not explain exactly what was happening or the name of this process. It seems to be used for creating sprites or video game graphics, as the only example I was able to find online was a gamedev postmortem discussing how they applied 'texturing' to some of their sprites. All I can do is show an example using the software I have (Which itself, barely explains what this process is called, just the way it works within the context of the software)

So in this case, the solid colors Black, Gray, Blue, and Green (In the "Mask" window at the bottom left) correspond to where specific textures/colors are going to be drawn in the final Hourglass graphic. There are additional colors available to use in this particular software, but I cannot for the life of me find any other software that does something like this. Let alone the name of the particular "colored mask/index" technique. It is capable of doing several other things by reading the colors in a mask, including rendering textures at angles or curves with the same kind of process.

The company I purchased the software from no longer exists, so there is no way to even contact them about their own software. Any ideas what this is even called? Or does anyone know any alternative way to do something like this?

# Answer
In terms of game dev, what you've described sounds somewhat like multi-texturing: blending of multiple textures on the same surface. Texture splatting is a related idea, though it usually more concerned with blending textures in a seamless manner.

With multi-texturing, usually the source textures are keyed to a particular color channel (red, blue, green and possibly alpha) and the weight of each channel is used to blend the source textures into a final result. For instance, a pixel that had an RGB value of (255, 192, 64) would be 50% texture 1, 37.5% texture 2 and 12.5% texture 3.

In contrast, your example appears to be the color strictly as in index and the final result looks more like a form of digital compositing. Some programming APIs (such as Java's 2d graphics API) support complex compositing operations \- by chaining together a series of compositing operations, you could get the desired result.

Unrelated to game dev: screentones are used in comics & manga as an alternative to hatching; some software used in those workflows might have a tool or feature that would replicate the effect you are looking for.
> 2 votes

# Answer
I refer to it as an index material since you're basically using each channel within an image as an index for masking out different things other than displaying an actual image.
> 1 votes

---
Tags: graphics, terminology, art, graphics-design
---


# Question
Title: Combining two objects to give you one more elaborate one
I'm looking for some help to someone throw me a light on this problem I'm having. We're making a clothing game where you got to grab a "cloth" and a "string" and bringing them to the sewing table to give you one sort of garment. We've already made a list of items but are not sure of how to combine them, what you get in return, or even how to detect which one is the one you have grabbed.

Thank you in advance.

# Answer
> 0 votes
First you need to detect that there actually are a string and an cloth near the sewing table at the same time. I would do that by adding colliders to all of them and making the collider of the sewing table a trigger.

I would then write a script for the sewing table which uses the `OnTriggerEnter` and `OnTriggerExit` event methods to keep track of which items are currently within the trigger area.

When that script detects that both a cloth and a string are present, then I would use the `Destroy` method to remove both of them and then use the `Instantiate` method to spawn the garment item as a new game object.

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


# Question
Title: Can I cache and edit Unity RaycastCommands?
I'm simulating a LiDAR and am working to optimize the code. In following along with the RaycastCommand documentation, I have the core functionality working and I'm trying to optimize it.

I see where the commands and results are being created as NativeArrays with the Temp allocator, so I made them member variables and initialize to the correct size with the Persistent allocator on Start and Dispose them OnApplicationQuit.

However, this still leaves me `new`-ing thousands and thousands of RaycastCommands every Update. I'd like to initialize the commands once and then just iterate through the NativeArray and change the from and direction properties, which are **public** according to the documentation, but I'm getting an error that I can't do that when I try.

I'm trying to move the LiDARs through the scene, so I need the origin (`from`) and `direction` to change, but I don't want to keep calling all those `new` commands - is there some way to cache and edit the commands that I'm not noticing? I can't tell why `from` and `direction` are public if I'm not allowed to set them.

I've done years of Unity development in Windows with Visual Studio and have recently moved to Linux and VS Code and the auto complete is frankly awful by comparison. It's making it hard for me to look through the autocomplete options for possible alternatives.

# Answer
> 1 votes
The code I was trying to use looked like:

```
NativeArray<RaycastCommand> commands;
<code to initialize commands>

<loop through the commands>
    commands[currentIndex].from = transform.position;
    commands[currentIndex].direction = dir;

```

And the error was:

> error CS1612: Cannot modify the return value of 'NativeArray.this\[int\]' because it is not a variable

As described here, (modifying it to be specific to my case)

> This is because \[the raycast command\] is a value type (struct).

Because of this, when you access the \[`from` or `direction`\] property you're accessing a copy of the value held by the class, not the value itself as you would with a reference type (class), so if you set the \[`from`\] property on it then you're setting the property on the copy and then discarding it, leaving the original value unchanged. This probably isn't what you intended, which is why the compiler is warning you about it.

I defined a temp variable outside the loop and use that to hold the current command while I modify the parameters, then tuck that back into the NativeArray:

```
RaycastCommand temp;
<loop>
    temp = commands[currentIndex];
    temp.from = transform.position;
    temp.direction = dir;
    commands[currentIndex] = temp;

```

.... and, as @DMGregory predicted, it didn't make any difference at all.

I had included the step where I'm doing the rotation math with the command setup Profiler section, and it seems like the rotation math is actually what's bogging down this process.

---
Tags: unity, raycasting, unity-dots
---


# Question
Title: What is a efficient way for adding and removing vertices and indices in C++?
So I have this middle-large mesh that is composed from vertices and respective indices. At some point I need to add new ones and remove some. But that brings me into trouble. Because if I have, for example, a 10k array (or vector) of indices and I want to remove one with index `n`, I have todo lot of processing on the array:

a) Find `n` b) Slice `n` c) Slice the respective Vertex from other array (the easiest part) d) Shift the array e) Shift the indices (worst part). If I remove 6, 7 needs to become new 6, 8 new 7 and so on...

Another strategy is to recreate Vertex and Index arrays/vectors every time something changes, but that isn't efficient neither.

# Answer
One thing you can do is defer the deletion of vertices.

Replace a "removed" vertex's data with NAN values, but leave it where it is, and record its index in a separate small collection of "open slots".

Any triangles referring to the removed index will be discarded by the GPU, because of the NANs propagating through the rasterization calculation. But you can also swap such triangles with the last valid triplet of indices in the list to get a contiguous buffer of only valid triangles without shifting the entire array down, and that way you don't send invalid ones to the GPU at all.

There is a small overhead to this, due to storing/transferring "dead" vertex data that's not going to be used, but if you're already pushing 10 k vertices and only deleting dozens or hundreds at a time, this probably won't impact the performance significantly.

Whenever you want to add new vertices, you can check the "open slots" and overwrite them with the new vertex information, inheriting the old unused index. Just make sure you've cleared out any triangles that were referencing the unused vertex, if any.

If your open slots list ever exceeds a threshold size, you can then take the time to re-optimize your mesh data (potentially on a background thread), shifting down the valid vertices to consecutive indices and rebuilding the indices array to match. The advantage is that you don't need to do this eagerly with every small change if they're frequent, and you can continue using the old up-to-date but slightly-less-than-optimal version while you wait for the background process to clean it up, instead of stalling your core update loop every time the mesh is edited.
> 2 votes

---
Tags: c++, shaders, vertex-arrays
---


# Question
Title: CPU / GPU usage are both below 100% - what is bottlenecking my game?
I've been developing a C++ OpenGL game for the last couple of months.

A few weeks ago I was profiling the game and I noticed that the GPU usage was almost at 100% (with the framerate uncapped). I added a new feature and the GPU usage capped at arround 35% (also with the framerate unlocked).

At first I thought that this was about CPU bottleneck, but the CPU was also around 35% usage.

I was expecting the framerate to lower after that update (and it did, from about 2000 to 600) but I thought that the CPU / GPU usage would still be high.

Having the GPU usage this low makes me think that I should be getting more FPS.

Is this behaviour normal, or did I do something wrong?

# Answer
> 1 votes
As @Vaillancourt pointed out, even though the CPU wasn't getting high usage percentage, one of it's cores was. I guess it's time to improve the multi-threading of my game!

---
Tags: opengl, performance, profiling
---


title: UVs Distored When Importing Mesh?

text:
# Question
Title: UVs Distored When Importing Mesh?
The first image shown below is of part of my mesh in Blender, and the second is of that same part of the mesh in UE4. For whatever reason, the UVs are distorted and glitchy once imported into UE4. I've tried flipping normals, made sure no UVs are overlapping, re-importing the mesh in a bunch of different ways, and turning on full precision UVs, but nothing seems to fix it. If anybody knows how to fix this, please let me know. Thanks! :)

# Answer
Blender and unreal engine read the meshes in a different way, I don't know the geometry of your object, but sometimes when you have n-gons, sometimes even quads, blender triangulates the mesh in a different way from unreal causing this artifacts in the UV channel. You can fix it using a triangulate modifier on blender, in this way you tell precisely how to read the mesh to unreal.
> 3 votes

---
Tags: textures, unreal-4, blender, uv-mapping
---


# Question
Title: Save current pose snapshot of a skeletal mesh as a new animation sequence asset from blueprint
What I'm trying to do is create a Blueprint Utility tool that lets me create an Animation Sequence asset to save the current Pose Snapshot of a skeletal mesh.

I see there's Create Asset node from Asset Tools Actor but I have no clue on how to create the factory to make it (same with Create Asset with Dialog).

I'm currently trying by using the LE Extended Standard Library that provides the Engine of many Factory blueprints, but whenever I try to save it, the engine crashes and I cannot investigate the error. A possible issue could be linked to the **calling context**? I'm not sure about that one and I didn't find an answer on UE4 forums.

What I would like to achieve is to create an asset like this:

by providing the Pose Snapshot (collection of bones and transforms) of the selected actor:

# Answer
If the intent is to save a Snapshot Pose to use it later, a way to do it, that worked for me, is saving it in a proper slot and load it whenever needed (in my case at begin play). The blueprint utility would look like this:

Loading at begin play and setting the pose as starting pose:

Where "Load Pose" handles the starting Skeletal Pose and the Anim instance sets it as current:
> 0 votes

---
Tags: unreal-4, skeletal-animation, blueprints
---


# Question
Title: Why the transform is not looking at the target?
The goal is to make smooth rotating look at.

The parent object is my character have a Rigidbody.

The script is attached to the character parent. I make a reference to the character child name head.

I have a cube as the target the cube is rotating around the character with random height.

The character is never looking at the cube. I tried to change from LateUpdate to Update I tried to add a child of the head empty gameobject and reference the empty gameobject but still the character head is not rotating to the target.

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

public class SmoothLookAt : MonoBehaviour
{
    public Transform leadObj;
    public Transform lookAtTarget;
    public float damping = 6;
    public bool smooth = true;

    private void LateUpdate()
    {
        if (lookAtTarget)
        {
            if (smooth)
            {
                // Look at and dampen the rotation
                var rotation = Quaternion.LookRotation(lookAtTarget.position - leadObj.position);
                leadObj.rotation = Quaternion.Slerp(leadObj.rotation, rotation, Time.deltaTime * damping);
            }
            else
            {
                // Just lookat
                leadObj.LookAt(lookAtTarget);
            }
        }
    }

    private void Start()
    {
        // Make the rigid body not change rotation
        if (leadObj.GetComponent<Rigidbody>() != null)
            leadObj.GetComponent<Rigidbody>().freezeRotation = true;
    }
}

```

It seems to be working if I reference the head directly as leadObj and inside LateUpdate the problem is that I have to set the damping value to 260.

Why I need to set the damping value to be so high ?

And how can I make that the head will rotate to the target with automatic speed depending on the target moving speed ? So if I don't set any damping value for example 0 or null it will automatic calculate the needing speed to rotate facing the target ?

I see now another problem. If I set the damping value to 100 for example the character head is stuttering the head will look at the target but will stuttering. I want that if the damping value is 100 or lower than rotate the leadObj with a delay facing the target. Something like when a turret is rotating facing a missile and if the missile is moving too fast the turret is rotating with some delay because he rotate slower. How can I do it ?

This is working using Lerp. But why if I set for example the duration value to 0 it's not affecting the speed of the leadObj rotation ?

The leadObj keep rotating same speed facing the target even if the duration is 0.

What am I missing ?

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

public class SmoothLookAt : MonoBehaviour
{
    public Transform leadObj;
    public Transform lookAtTarget;
    public float duration;
    public bool smooth = true;

    private float t = 0.0f;

    private void Start()
    {
        // Make the rigid body not change rotation
        if (leadObj.GetComponent<Rigidbody>() != null)
            leadObj.GetComponent<Rigidbody>().freezeRotation = true;
    }

    private void LateUpdate()
    {
        if (lookAtTarget)
        {
            if (smooth)
            {
                t += Time.deltaTime;
                float s = t / duration;

                // Look at and dampen the rotation
                var rotation = Quaternion.LookRotation(lookAtTarget.position - leadObj.position);
                leadObj.rotation = Quaternion.Lerp(leadObj.rotation, rotation, s);
            }
            else
            {
                // Just lookat
                leadObj.LookAt(lookAtTarget);
            }
        }
    }
}

```

# Answer
> 1 votes
The method you are looking for is `Vector3.RotateTowards(current, target, maxRadiansDelta)`.

This method allows you to take one direction and move it towards a different direction, but limit the amount of degree by which the rotation can change. And when you multiply that number of degree by Time.deltaTime, then you get exactly what you want: A constant rotation towards the desired direction.

```
Vector3 current = transform.forward;
Vector3 to = leadObj.position - transform.position;
transform.forward = Vector3.RotateTowards(current, to, turnSpeed * Time.deltaTime)

```

Where `turnSpeed` is a `float` measured in radians per second.

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


# Question
Title: 2D Camera Movement Temporal Reprojection
Having an Orthographic Camera with its View Projection Matrix given from the current and last frame, how to reproject the previous frame to the new one?

# Answer
> 1 votes
Some years late I needed it again and finally solved it. For some reason the translation was inversed so I fixed that by inversing the scale but it shouldn't be needed

```
float2 halfRes = ((float2)texResolution - 1f) * 0.5f;
float4x4 ndc = float4x4.TRS(new float3(halfRes, 0f), quaternion.identity, new float3(-halfRes, 1f));
float4x4 projMat= mul(ndc, mul(_camera.projectionMatrix, _camera.worldToCameraMatrix));

float4x4 reprojMat = mul(previous, inverse(projMat));
previous = projMat;

```

and in shader simply

```
float2 oldPos = mul(ReprojectMatrix, float4(pos, 0, 1)).xy

```

# Answer
> 0 votes
currently i'm tracking the separate camera data and calculating a reprojection matrix like this (dirty "just make it work" code)

```
    Vector3 pos = cam.transform.position;
    Vector3 diff = lastPos - pos; // pos delta
    diff = Vector3.Scale(diff, new Vector3(1f / (cam.orthographicSize * 2f * cam.aspect), 1f / (cam.orthographicSize * 2f), 1f)); // world to uv scale
    float relscale = cam.orthographicSize / lastsize;
    float relrot = cam.transform.eulerAngles.z - lastrot; // needs aspect ratio correction in shader then maybe it works
    Matrix4x4 reprojectmat = Matrix4x4.TRS(-diff, Quaternion.Euler(0f, 0f, relrot), new Vector3(relscale, relscale, 1f));

```

and in the shader a simply edit the uv by the created matrix

```
    uv = mul(_Reprojection, float4(uv - 0.5, 0.0, 1.0)).xy + 0.5; // -/+ 0.5 to center scale / rotation

```

this works for translation and scaling right now (not for rotation) but is for sure not the best way to do it

# Answer
> 0 votes
Im not sure is worth for u or not but at least try once unity cinemachine asset.. Cinemachine

After important try 2d camera.

For more information plz check this breakeys tutorial. enter link description here

---
Tags: unity, shaders, hlsl
---


title: Prevent Player from Moving During Jump

text:
# Question
Title: Prevent Player from Moving During Jump
I am new to Unity, and am trying to make a simple 2D platformer from this video, and I am trying to modify it to prevent the player from being able to switch directions during a jump. Right now, you can jump and then move. I want to freeze the left/right player controls and give control of the players location FULLY to the rigidbody. Can anyone help? I can update with any additional info y'all need.

Here is my player controller script:

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

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D rb;
    public float speed;
    public float jumpForce;
    private float moveInput;

    private bool isGrounded;
    public Transform feetPos;
    public float checkRadius;
    public LayerMask whatIsGround;
    private bool upKeyPressed;
    private bool upKeyHeld;
    private bool upKeyUp;

    private float jumpTimeCounter;
    public float jumpTime;
    private bool isJumping;

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

    void FixedUpdate()
    {
        moveInput = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
    }

    void Update() {
        isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);

        upKeyPressed = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow);
        upKeyHeld = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow);
        upKeyUp = Input.GetKeyUp(KeyCode.W) && Input.GetKeyUp(KeyCode.UpArrow);

        if(moveInput > 0 && isGrounded == true) {
            transform.eulerAngles = new Vector3(0, 0, 0);
        } else if(moveInput < 0 && isGrounded == true) {
            transform.eulerAngles = new Vector3(0, 180, 0);
        }

        if(isGrounded == true && upKeyPressed) {
            isJumping = true;
            jumpTimeCounter = jumpTime;
            rb.velocity = Vector2.up * jumpForce;
        }

        if(upKeyHeld && isJumping == true) {

            if(jumpTimeCounter > 0) {
                rb.velocity = Vector2.up * jumpForce;
                jumpTimeCounter -= Time.deltaTime;
            } else {
                isJumping = false;
            }

        }

        if(Input.GetKeyUp(KeyCode.UpArrow)) {
            isJumping = false;
        }
    }
}
```
</code></pre>

# Answer
> 1 votes
Did you try checking whether you're grounded before applying the horizontal input to the velocity?

(You should also be applying your jump hold logic at the same time, not in Update, so held jumps are handled consistently regardless of framerate)

```
void FixedUpdate()
{
    Vector2 newVelocity = rb.velocity;

    isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
    if (isGrounded) {
        moveInput = Input.GetAxisRaw("Horizontal");
        newVelocity.x = moveInput * speed;
    }

    if (isJumping) {
        upKeyHeld = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow);

        if(upKeyHeld) {
            if(jumpTimeCounter > 0) {
                // Don't name a variable "force" if it's measuring "speed".
                newVelocity.y = jumpSpeed;
                jumpTimeCounter -= Time.deltaTime;
            } else {
                isJumping = false;
            }
        }
    }

    rb.velocity = newVelocity;
}

```

You'll probably also want to change your jumping lift-off code so that it doesn't reset the horizontal velocity to zero:

```
if(isGrounded == true && upKeyPressed) {
    isJumping = true;
    jumpTimeCounter = jumpTime;
    rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
}

```

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


# Question
Title: No project in visual studio using unity created
As I have sometimes problems with intellisense in visual studio using unity, I searched for some answers. It was almost every time pretty much the same: Reloading the project. But in my solution explorer, there is not even a project showing that I could reload. Are you able to manually create the project or are there some reasons for that behavior?

ps: I just updated unity from version 2017.3.0f3 to 2018.1.0f2, may that be the problem? (I'm using visual studio 2017 (I'm updating at the moment on version 15.7.1) community)

edit: What I've tried so far:

1. Simply re-launching Visual Studio by double-clicking on the script file inside unity (-\> DMGregory)
2. reloading the project
3. reimport all in the asset-explorer inside unity (S. Tarik Cetin)
4. deleting the .sln file to force Unity to regenerate them from scratch (-\> Ed Marty) + opening the solution from inside Visual Studio

Doing the last point created - as intended - a new solution, but there is still no project created, as you can see in the following picture (Projektmappe = solution). That's how the solution looks like. While opening the script from Unity, it shows the message in the following picture. Translation: "The following files were stated in the command line: \[source path (name censored)\] These files were not found and are not loaded."

When trying to open a script from a different (new) Project, it showed the same message, which leads to a new problem: Even in new unity projects, the solution cannot be opened, and the scripts are all assigned to a certain solution ("solution1"), which is the one that was generated. (Even scripts from different projects end up in the same solution!)

So at the moment, I have no idea what else to do. Is there something simple I'm just missing? Or should I reinstall one of the 2 programs? Or might the update of unity be the problem? (exact versions mentioned above)

If there's any extra information needed, please just mention it in the comments. (I'm not so sure what might be helpful and what isn't)

# Answer
It seems there is a problem with asmdef files in Unity 2018 with Visual Studio 2017, you'll need an update.

https://developercommunity.visualstudio.com/content/problem/88183/error-when-unity-launches-visual-studio-2017-to-ed.html

https://developercommunity.visualstudio.com/content/problem/130597/unity-intellisense-not-working-after-creating-new-1.html

https://forum.unity.com/threads/issues-with-visual-studio-unity.514304/

You can try the following:

* Update your Visual Studio 2017 to the latest version. (v15.7.1)

This will most likely solve your problem. If not:

* Delete asmdef files from packages folder of Unity. But this may cause your project to not compile if you have a dependency on those packages. The folder should be in C:\Users\ {UserName}\AppData\Local\Unity\cache\packages\packages.unity.com
> 5 votes

# Answer
Happened to me too. Solved it by setting Visual Studio as the default 3rd party tool as scripts editor in Unity's preferences.
> 6 votes

# Answer
It happened to me too. I solved it by updating visual studio.Try installing the latest version.
> 2 votes

# Answer
I wasn't able to find anything that specifically targeted the problem you described. It's possible that this might be an issue that occurs only from updating one of the products from one version to another. As a general troubleshooting solution, try the following:

1. Back up your work!
2. Uninstall Unity.
3. Uninstall Visual Studio
4. Reinstall Visual Studio using the most recent stable version available.
5. Reinstall Unity using the most recent stable version available.
> 1 votes

# Answer
Have you tried simply deleting the .sln and .csproj files from the root directory of your project? That’s will force Unity to regenerate them from scratch if they got mangled somehow Unity doesn’t recognize as a problem.
> 0 votes

# Answer
You might inadvertently fix this problem by reinstalling everything but this potential solution is worth 30 seconds to try. It worked for me. Within Unity: Edit -\> Preferences -\> External Tools -\> External Script Editor -\> Change "Open by file extension" to Visual Studio).
> 0 votes

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


# Question
Title: Keeping two triangles with different scale attached during rotation
I'm making a simple Lunar Lander clone. The ship is a triangle, and I'm trying to draw the exhaust fumes of the ship.

I'm wondering how to draw the exhaust so it's always relative to the ship. I'm currently trying to offset it's x and y position on the screen by using the following code:

```
if (m_state == State::Thrust) {
    // Calculate position for small triangle
    float flameSize = SHIP_SIZE / 2;
    glm::vec2 flamePosition = shipPosition;

    float cos = glm::cos(glm::radians(m_rotation));
    float sin = glm::sin(glm::radians(m_rotation));

    float dx = 0;
    float dy = SHIP_SIZE;

    flamePosition.x = cos * dx - sin * dy + m_position.x;
    flamePosition.y = cos * dy + sin * dx + m_position.y;

    m_pRenderer->Render(flamePosition.x, flamePosition.y, flameSize, flameSize, 180.0f + m_rotation, glm::vec3(1.0f, 0.0f, 0.0f));
}

```

However I'm not getting the desired result:

The small exhaust triangle is always off by some offset. It's worth nothing that **when I don't scale** the exhaust triangle, it rotates correctly, so I think that could have something to do with the issue but I can't see how that would effect the positions I'm calculating. For reference, here is the code I use to render:

```
m_pShader->use();
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(x, y, 0.0f));

model = glm::translate(model, glm::vec3(0.5f * height, 0.5f * width, 0.0f));
model = glm::rotate(model, glm::radians(rotation), glm::vec3(0.0f, 0.0f, 1.0f));
model = glm::translate(model, glm::vec3(-0.5f * height, -0.5f * width, 0.0f));

model = glm::scale(model, glm::vec3(width, height, 1.0f));

m_pShader->setMat4("transform", model);
m_pShader->setVec3("uColour", colour);

glBindVertexArray(m_vao);

glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);

```

I'm wondering what is the correct way to keep smaller triangle attached to the bottom of the bigger one?

Thanks.

# Answer
> 0 votes
If I understand you correctly you have a problem with drawing models relatively to each other (you write about fumes, but it's exhaust pipe that is problematic, isn't it?).

It's usually done by creating a hierarchy of objects via their transforms.

What you conceptually want to do is:

1. render a ship relatively to the world and
2. render the exhaust relatively to the ship.

That's commonly done by 'parenting' children objects to parent objects. To do that you have to create a transformation matrix for the exhaust relative to the ship (this will be constant in your case). Then you create a transformation matrix of a ship relatively to the world (dynamic, based on it's position and rotation). Now when drawing objects you multiply transformation matrices in a proper order. Remember that translation, rotation and scale must be applied in that specific order (left to right), and so do have to be the chained parents

Assuming your scales of objects are 1.0 you could draw things like that ( where `VP` is camera's view-projection matrix and `TRS` is Translation, Rotation and Scale respectively):

ship: $$VP \\;\cdot\\; T\_{ship}R\_{ship}S\_{ship} \\;\cdot\\; \<vertices\>$$ exhaust: $$VP \\;\cdot\\; T\_{ship}R\_{ship}S\_{ship} \\;\cdot\\; T\_{exhaust}R\_{exhaust}S\_{exhaust} \\;\cdot\\; \<vertices\>$$

Remember, that when parent is scaled, children objects can behave weirdly. The weirdest things are rotations, because they in reality get stretched into ellipses. You could skip scales in the matrix multiplication chain for children objects. You will have to properly adjust the translation taking parent scale into account though. The exhaust could then become

exhaust: $$VP \\;\cdot\\; T\_{ship}R\_{ship} \\;\cdot\\; T'\_{exhaust}R\_{exhaust}S\_{exhaust} \\;\cdot\\; \<vertices\>$$

where $$T'\_{exhaust}$$ would take `height of parent/2 * parent's scale` into account.

Here you have a (unnecessarily long) tutorial about transformations: https://learnopengl.com/Getting-started/Transformations

If you later want to draw fumes later you can think about them as 'cloud objects' spawned at the position of the exhaust, but not parented to the ship.

---
Tags: opengl, c++, rotation, scale
---


title: Cant compile raylib project with Physac

text:
# Question
Title: Cant compile raylib project with Physac
I'm trying to learn how to use raylib with physac, however I'm quite new to using a c++ compiler and after a few hours trying to get a minimal example working, I came here seeking your help.

here is my main.cpp file:

```
#include "raylib.h"
#include "physac.h"

int main()
{
    const int WINDOW_WIDTH = 800;
    const int WINDOW_HEIGHT = 400;

    InitWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "example");
    InitPhysics();
    SetTargetFPS(60);

    while (!WindowShouldClose())
    {
        UpdatePhysics();
        BeginDrawing();
        ClearBackground(BLACK);
        EndDrawing();
    }

    CloseWindow();
    ClosePhysics();
    return 0;
}

```

when trying to run the file, I get the following errors:

```
undefined reference to `InitPhysics'
undefined reference to `UpdatePhysics'
undefined reference to `ClosePhysics'

```

this leads me to believe I'm missing some sort of library, here's my g++ command:

```
g++ source/*.cpp -o bin/final.exe -O2 -Wall -Wno-missing-braces -I include/ -L lib/ -lraylib -lopengl32 -lgdi32 -lwinmm

```

My include folder only contains physac.h and raylib.h and my lib folder contains libraylib.a. My guess is that I need some other lib file or some other flag on the compiler, but I can't figure out what.

# Answer
> 0 votes
Ok, I figured it out and I'll post the answer here in case anyone needs it.

The implementation of physac is not on any library, it is directly within the .h file itself, it's just commented out (actually, it's behind an `#if defined`, but the `#if defined` is not true unless you edit the header file).

If you were to try and uncomment the implementation, every time you include the header file, you would redefine the implementation, which would cause an error, so what I did was copy the implementation portion of the header into a `physac.cpp` file and put that into my source folder.

Not sure if that's the best way to do it, but it is for sure the way that worked for me.

## EDIT

Ok, so as user @Vaillancourt explained, the correct way to do this is to `#define PHYSAC_IMPLEMENTATION` before including physac.h, however it's important to do so only on one file.

---
Tags: c++, raylib
---


# Question
Title: Why the transform is not rotating back smooth to his original starting rotation using lerp?
```
using System.Collections;
using UnityEngine;

[RequireComponent(typeof(Animator))]
public class Test : MonoBehaviour
{
    public Transform lookAtTarget;
    public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
    public float duration;
    public float duration1;

    private float t;
    private float t1;
    private Quaternion rot;

    private void Start()
    {
        t = 0;
        t1 = 0;
        rot = transform.rotation;
    }

    void LateUpdate()
    {
        Vector3 forward = transform.TransformDirection(Vector3.forward);
        Vector3 toOther = lookAtTarget.transform.position - transform.position;

        if (Vector3.Dot(forward, toOther) < 0)
        {
            t1 += Time.deltaTime;
            float s = t1 / duration1;

            transform.rotation = Quaternion.Lerp(transform.rotation, rot, curve.Evaluate(s));
        }
        else
        {
            t1 = 0;

            t += Time.deltaTime;
            float s = t / duration;

            var targetRotation = Quaternion.LookRotation(lookAtTarget.transform.position - transform.position);
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, curve.Evaluate(s));
        }
    }
}

```

In the if part the transform is like "jumping" at once to the original rotation and there make some lerping or not doing at all and I want that it will lerp smooth slowly from it's current rotation back to the original rotation(rot).

Same effect when turret is cool down when there is no target so the turret smoothly return to his original rotation.

I tried also :

```
transform.rotation = Quaternion.Lerp(transform.rotation, rot, s);

```

But the same problem remains.

Tried this :

```
using System.Collections;
using UnityEngine;

[RequireComponent(typeof(Animator))]
public class Test : MonoBehaviour
{
    public Transform lookAtTarget;
    public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
    public float duration;

    private float t;

    private void Start()
    {
        t = 0;
    }

    void LateUpdate()
    {
        t += Time.deltaTime;
        float s = t / duration;

        Vector3 forward = transform.TransformDirection(Vector3.forward);
        Vector3 toOther = lookAtTarget.transform.position - transform.position;

        if (Vector3.Dot(forward, toOther) < 0)
        {
            transform.rotation = Quaternion.Lerp(, transform.rotation, curve.Evaluate(s));
        }
        else
        {

            var targetRotation = Quaternion.LookRotation(lookAtTarget.transform.position - transform.position);
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, curve.Evaluate(s));
        }
    }
}

```

Update :

my player object name is kid\_from\_space this screenshot show the player settings in the inspector :

The player have a Rigidbody and also animtor components too.

That is why the script use LateUpdate instead Update.

The script is attached to the player head child object :

This object have the script that make object rotate around the player :

This screenshot is of the child of the object Rotate Around the Target is the basketball in the screenshot the basketball is rotating aorund the player :

This is the script that is attached to the player head :

```
using System.Collections;
using UnityEngine;

public class LookAtTarget : MonoBehaviour
{
    public Transform target;
    // Keep this low to make the tracking tight for small target movements.
    public float lookChangeDuration = 0.1f;

    // Use this to limit our top rotation speed when making a big turn.
    // It's measured in "approximately" radians per second.
    public float maxLookSpeed = 5f;

    Vector3 lookVectorVelocity;
    Vector3 originalLookDirection;

    private void Start()
    {
        originalLookDirection = transform.forward;
    }

    void LateUpdate()
    {
        Vector3 desiredLook = (target.position - transform.position).normalized;

        if (Vector3.Dot(desiredLook, transform.forward) < 0)
        {
            desiredLook = originalLookDirection;
        }

        var look = Vector3.SmoothDamp(transform.forward,
                                      desiredLook,
                                      ref lookVectorVelocity,
                                      lookChangeDuration,
                                      maxLookSpeed);

        transform.rotation = Quaternion.LookRotation(look);
    }
}

```

This script is attached to the Rotate Around object :

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

[ExecuteAlways]
public class SimpleRotate : MonoBehaviour
{
    public List<TextMeshProUGUI> uiText = new List<TextMeshProUGUI>();

    public GameObject objToRotateAround;
    [Header("The axis by which it will rotate around")]
    public Vector3 axis;
    [Header("Angle covered per update")]
    public float angle;
    public float upperLimit, lowerLimit, delay;

    private float height, prevHeight, time;

    // Update is called once per frame
    void Update()
    {
        transform.RotateAround(objToRotateAround.transform.position, axis.normalized, angle);
        time += Time.deltaTime;
        if (time > delay)
        {
            prevHeight = height;
            height = Random.Range(lowerLimit, upperLimit);
            time = 0;
        }

        transform.position = new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z);
    }
}

```

The result is that the player head is not rotating at all not looking at the target at all. The player head stay all the time in natural original rotation view.

I found that if I disable the Animator that attached to the player the head will keep rotating nonstop 360 degrees looking at the target. With the Animator turned on enabled true the head is not rotating at all.

This is the player animator controller settings. Grounded is a blend tree :

This screenshot is of the Grounded blend tree the top animation is the HumanoidIdle and this is also the default animation play when running the game :

# Answer
> 2 votes
Apart from the obvious where you never reset your `t1` value to zero at the start of a new motion...

You're still using the exponential ease-out lerp I told you about previously. Whenever you use the pattern:

```
current = lerp(current, target, sharpness);

```

...you create a negative feedback loop. (See how "current" appears as both the input AND the output?)

That makes the lerp behave fastest when the object first starts moving, then slow to a crawl as it gets closer to its target. Combined with an ease-in-out curve being passed to the `sharpness` parameter (which is more like a rate of change, not a measure of progress), and you get a very strange motion that is not at all what you intended, leaping up to the target value much faster than your provided duration:

One way you can solve this is by storing some state about when you started this motion and which way you were facing at the time:

```
if (Vector3.Dot(forward, toOther) < 0)
{
    // Snapshot our initial rotation only when we *begin* our return journey.
    if (returnProgress < 0f) {
        returnProgress = 0f;
        rotationBeforeReturning = transform.rotation;
    }

    returnProgress = Mathf.Clamp01(returnProgress + Time.deltaTime/returnDuration);

    // Note that "transform.rotation" does not appear on the right-hand side.
    // That means we're no longer using an exponential ease-out lerp, and the
    // last parameter really is a measure of progress, not a diminishing rate of change.
    transform.rotation = Quaternion.Lerp(rotationBeforeRetuning,
                                         originalRotation,
                                         curve.Evaluate(returnProgress));
} else {
    // Terminate the attempt to return to the original orientation,
    // so that we re-start it from scratch the next time we lose sight.
    returnProgress = -1f;

    // The rest of your else case goes here...
}

```

But actually I think you can reimplement your whole script more simply using the built-in `SmoothDamp` function, which handles an ease-in-out movement toward a target, maintaining a continuous velocity (so eg. a character's head doesn't suddenly lurch or snap to an abrupt stop).

There's no `Quaternion.SmoothDamp` to damp rotations directly, but we can use `Vector3.SmoothDamp` to damp our look direction as it moves around the unit sphere, then construct a quaternion from that.

```
public class EasedLookAt : MonoBehaviour {

    public Transform target;
    // Keep this low to make the tracking tight for small target movements.
    public float lookChangeDuration = 0.1f;

    // Use this to limit our top rotation speed when making a big turn.
    // It's measured in "approximately" radians per second.
    public float maxLookSpeed = 5f;

    Vector3 lookVectorVelocity;
    Vector3 originalLookDirection;

    private void Start() {
        originalLookDirection = transform.forward;
    }

    void LateUpdate() {
        Vector3 desiredLook = (target.position - transform.position).normalized;

        if (Vector3.Dot(desiredLook, transform.forward) < 0) {
            desiredLook = originalLookDirection;
        }

        var look = Vector3.SmoothDamp(transform.forward,
                                      desiredLook,
                                      ref lookVectorVelocity,
                                      lookChangeDuration,
                                      maxLookSpeed);

        transform.rotation = Quaternion.LookRotation(look);
    }
}

```

In terms of your use of the site, I notice you've left a long chain of zero-vote, unanswered, or deleted questions - quite a few struggling with different aspects of this look mechanic.

I would recommend asking fewer questions that say "my code is broken, why / how do I fix it?" - if your code is broken, it might not be the best starting point for accomplishing your goal. Fixing one problem might just reveal another, and focusing on individual bugs can distract from the opportunity to find a better overall strategy.

Instead, I would recommend trying to ask goal-focused questions. For example:

> How to look at a target and return to neutral when it's out of sight, with easing?

As you can see above, an answer to such a question can actually be much simpler than playing whack-a-mole trying to fix all the problems with a broken script.

And they're usually more pleasant to answer, too, so you might find you get better engagement from other users with this strategy.

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


# Question
Title: How to share a game created with the free version of Game Maker Studio 2?
I've recently downloaded Game Maker studio for free and made my first game. Now, I'd like to share it with others.

I tried to use the "Export" button and it only creates a duplicate project. If I click the "Create executable" button, it says "Packages cannot be built for the selected platform" in an error box.

I looked up how to make a `.exe` file and how to create an application, but the "Create application" button from the file directory doesn't exist in my version of Game Maker Studio 2. Some said that the error message when creating a `.exe` file is caused by a UWP license issue, but I don't know what a UWP license is or how to change it.

So, how do I create a sharable game file that isn't a project file? And, if the "Create executable" button is the only way, why can't packages be built for my "platform"?

My IDE is v2.3.4.580 and my runtime is v2.3.4.442.

# Answer
Your current problem with creating executables is due to the licence you're using, not (necessarily) the UWP export configuration.

The Free license for GameMaker Studio 2 gives you full access to the IDE (i.e. usage and assets limitations were removed) and lets you use the application for testing and learning purposes. You can't build game executables and share them with other people though.

This is the Free license description from the YoYo Games website:

> ### Free
>
> **GameMaker Studio 2**
> Unlimited access to the IDE (integrated development environment) and learning materials.

When you *export* a project, GMS2 creates an *exact* copy of the project–which includes ALL assets, configuration files and local settings–in a directory of choice. This way, you can 'clone' a game project without the need to manually browse and copy/paste all files, some of which may be unnecessary (e.g. IDE temp files).

If you want to share the game with fellow developers, the above is the way to go. But, if you want to *release* the game for others to play, that's a different matter. You will need an Indie or Enterprise licence, for they include what they call Desktop/Web/Mobile 'exports' but are actually platform-specific **build** plug-ins.

According to the YoYo Games website, the cheapest license you can get is:

> ### Indie
>
> **GameMaker Studio 2**
> Unlimited access to the IDE (integrated development environment) and learning materials.
> **Desktop Exports**
> Windows, macOS, and Linux platforms exports.
> **Web Export**
> HTML5 platform export.
> **Mobile Exports**
> iOS, Android, Amazon Fire, Android TV, and tvOS platforms exports.
> **UWP Export**
> Universal Windows Platform (includes Xbox One Creators program) exports.
> 2 votes

---
Tags: game-maker-studio-2
---


title: Reduce the number of skills

text:
# Question
Title: Reduce the number of skills
I have some special moves in my pixel art RPG game that I call "skills," similar to the skills in Cross Code. You can unlock them by earning points and points will be obtained when you reach the next exp level.

Skills are divided into subgroups in this way: weapon - element - type - level

From each of those subgroups (containing 3 level-one skills and 3 level-two skills), you can choose 1 level-one skill and 1 level-two skill(you can change them whenever you want)

Obviously, you won't get them at the beginning of the game. level-one skills will be unlocked in the middle of the game and later on, level-two skills will be unlocked. and when they become unlocked, you can use points to purchase them.

Level-two skills are just level-one skills with some modification (but it doesn't exactly look like its level-one)

"Types" determine how the skill acts and they are: attack - defense - dash - co-op

So, with 4 weapons and 8 elements and 4 types and 2 levels, and 3 skills in each level, there will be a total of 768 skills and it's A LOT. does anyone knows how to reduce this huge number?

I can't reduce the number of elements or weapons.

# Answer
768 different attacks sounds like a lot of development work. But by cutting some corners, you can reduce the development effort considerably:

* Reuse: Use the same art assets in different ways to get more out of them. Like by creating a large projectile by just putting together a cluster of small projectiles. Or using the same flame particle sprite for both a ball of fire and a ray of fire. Or using the same character animation frames for different actions.
* Recolors: Two skills which use the same graphic assets, but in a different color. This trick allows you to get a lot more bang for the buck in your art department.
* Reskins: Skills which look different but are mechanically identical. This still eats into you art budget, but it saves you on two other fronts. The first is programming effort, because the two skills will likely be able to share most of their code. The second is balancing effort, because when one of the skills is balanced, the other one is too.
* Renumbers: Two or more skills which look and work in the same way, but use different numbers. Either one is a strictly better version of the other (would work with your leveled skill system) or it's a matter of tradeoffs. Like, for example, the alternative version is stronger but slower.
* Passive skills: Skills which don't actually do anything except increasing a couple numbers while they take up a skill slot. A rather boring way to pad out the skill list, but usually very easy way to create skills in bulk once you created the necessary architecture.
> 1 votes

---
Tags: game-design, rpg, development-speed
---


# Question
Title: What is yet another explanation of the difference between sprites and tiles?
I'm making a game where it came to adding a base tile class, but I already have a sprite one, which does the same at first glance. Rasterizers are the ones I should have started with but I missed quite a few points in 2D graphics.

Can you explain the difference with a couple of examples?

# Answer
> 10 votes
Basically, a *sprite* is an image. It can be used in variety of ways in a computer game. A *tile*, on the other hand, is a bundle of data that might *refer to* a sprite.

A tile probably also contains properties like blocking information (can you walk over this tile?) or path cost information that a sprite itself doesn't need or which don't make sense for it. Or a tile might have multiple sprites (for different tile states, such an intact and a destroyed wall).

Consequently, if you already have a sprite type in your code, a good way to represent your tile might be:

```
struct Tile {
  Sprite * image;

  // ...other data...
};

```

(Although I used a pointer for clarity, you can also use some other form of reference to a sprite, often this is done to keep `Tile` small.)

---

Historically, the difference was a little more drastic: a tile was generally part of the background and a sprite was generally part of the foreground. The background elements were mostly-fixed and mostly-immobile, while the foreground elements moved. Limited processing power necessitated the significant distinction; this is not really the case any more, so you can build your tile maps out of sprites if you want.

# Answer
> 1 votes
A sprite and a tile are really both bunches of data and doesn't have to be tied to a piece of graphic (in case they need to be invisible for example).

A sprite is a (graphical) object that can be moved around on the screen freely and individually.

A tile (also called a "character" on older computers and video game systems) on the other hand is part of a grid which it can never leave, so it can never move around individually (otherwise it would be a sprite and not a tile). This grid of tiles (usually called a background or pattern layer) can be moved around so that all tiles move around together, this is known as scrolling. Moving the background to the left is the same thing as scrolling it to the right (since the "camera" is moving to the right in that case). A background is made up of an array of tiles usually called a "tilemap" or a "name-table".

A sprite may have data for position (X and Y), size, flipping state (horizontal and vertical), graphic index (what refers to its graphic, this is also called a "name") and certain other things like an enable flag (for disabling it when not in use) and display priority used to determine if it is to be displayed above or below a tilemap. All sprite objects are usually stored in an array called a Sprite Attribute Table or SAT.

A tile on the other hand doesn't need position attributes, since its position is determined from its position in the tilemap. It just needs a graphic index (AKA "name" and that's why the tilemap is sometimes called a "name-table" as its often just a table of tile "names") and possibly flipping information if you want your tiles to be flippable. A single tile can't be disabled, only be made invisible (by giving it a fully transparent graphic texture). The whole background can be disabled though. Tile size is also a global thing for the whole background layer, so there is no need for size information for each tile either.

You can have multiple backgrounds drawn over each other, each with their own scroll offsets, making the backgrounds individually scrollable. Though the top "backgrounds" are technically foregrounds, we still tend to call them backgrounds for historical reasons (the classic TMS9918 video chip could not display sprites below the single background layer). There can also be several layers of sprites above, below and between the backgrounds based on each sprite's priority attribute.

Example of Sprite attributes:

```
struct Sprite {
  Graphic* spritesheet;                //pointer to the spritesheet texture
  int name;                            //sprite index in spritesheet
  int x;
  int y;                               //sprite position
  int priority;                        //sprite display priority
  int w;
  int h;                               //sprite dimensions
  bool flip_h;
  bool flip_v;                         //sprite flip state
  bool enable;                         //sprite enable flag
};

```

Example of tile attributes:

```
struct Tile {
  Graphic* tilesheet;                  //pointer to the tilesheet texture
  int name;                            //tile index in tilesheet
  bool flip_h;
  bool flip_v;                         //tile flip state
};

```

This is a simple example for strictly simulating hardware sprites and tiles as used in older computers and video game system video chips. A modern game might have collision information and more game-related information included with the tile and sprite data (solid information, damage floor etc). In classic video chips all tiles in a tilemap may have to share the same tilesheet, but here I gave each tile the possibility to use any tilesheet by giving a tilesheet pointer to each tile.

In more modern terms, "tiles" are still elements in a grid while "sprites" have come to be used more as a generic term for almost any type of texture, but especially a texture tied to an object such as a software sprite or software tile. But it's good to know that they are really two different hardware graphics systems invented for the sake of doing (limited) manipulation of screen information with very little memory usage.

---
Tags: sprites, tiles, terminology
---


# Question
Title: Rotation matrix for a model where the forward axis is not +X
I'm trying to convert a normalized unit vector, representing an entity heading, into a rotation matrix for rendering.

The problem is that I'm using an (apparently) unusual forward vector for my entities. I use right-hand axes, with +Z pointing up and +Y pointing forward. *(Rationale: My game has units moving across a map, and it's easier for me to deal with the map as X/Y positions with a +Z height)*

Whenever I try to look up the math for building the rotation matrix, the examples always assume my forward vector is +X, which gives the wrong result. The math assumes my entity is facing +X, and so my entities look like they're moving sideways.

I've also tried a (temporary) 2D approach using atan2, but again it assumes angle 0 (forward) is +X, with the same result.

How does the math for a "look rotation" matrix work for an arbitrary axis? Or, if it's easier, are there examples of building this sort of matrix using a right-hand +Y axis?

# Answer
> 2 votes
You still handle it in the usual way. Make 3 perpendicular unit vectors (an orthonormal basis), expressing the directions your object's local axes should point after rotation:

```
// Forward
Y = forwardHeading;

// Right
X = Normalize(Cross(Y, (0, 0, 1));

// Up
Z = Cross(X,Y);

```

And then use these three vectors as the columns of a matrix:

$$\vec {\text{rotated}} = \begin{bmatrix}X\_x & Y\_x & Z\_x\\X\_y & Y\_y & Z\_y\\X\_z & Y\_z & Z\_z\\\end{bmatrix} \vec{\text{unrotated}}$$

Or, if you use a multiplication convention with the matrix on the right, use these vectors as the rows of your matrix instead of the columns.

You can verify that if you substitute any of the standard basis vectors `(1, 0, 0)`, `(0, 1, 0)`, or `(0, 0, 1)` for that \\$\vec{\text{unrotated}}\\$ variable, you get out your corresponding rotated basis vector, `X`, `Y`, or `Z`. That means that any linear combination of those standard basis vectors (ie. any point in 3D space) gets transformed to the matching linear combination of your rotated basis vectors (ie. it gets rotated to match the object's desired orientation).

You can use `atan2` for this too - even though we conventionally label the arguments `y, x`, that does not restrict you to using those named axes in those slots. You can swizzle your coordinates any way you like to get the 0 angle and direction of positive rotation to match your intended scheme. So for example `atan2(-forward.x, forward.y)` will give you a yaw angle of 0° when pointing toward y+, 90° when pointing toward x-, and -90° when pointing toward x+, consistent with right-handed rotation about z+.

---
Tags: rotation, matrix, c, glm, axis
---


# Question
Title: What is an alternative solution to the problem of polygon collider2D not following character (animation)movement?
A 2D game and a bird's eye view of the character. This character, who has a knife in his hand, swings the knife by waving his arm, just at this time, I look at "polygon collider2d" from the unity "scene" tab and it does not follow the character's arm or knife. Therefore, the character's knife, arm go into the wall or don't damage the enemy. Because the polygon collider2d is only scaled when the character is in the "idle" state.

My question is right here, do I need to add polygon collider2d separately for each frame of my attack animation and make them active/passive while the animation is playing?

Doesn't doing this degrade performance? I couldn't find an alternative solution.

Solution Edit : The only way to solve this problem is to keep our sprites in separate pieces and prepare the animations we want from unity's own animation window.

Note: In the classical method, we can create animation by dragging and dropping the ready frames to our object, but in this case the collider will not follow the object.

# Answer
> 0 votes
I think what you are trying to do is make melee combat for your player. You should look in physics2d section of overlapping circles and stuff. But you can also look up brackeys tutorial for melee combat which explain everything perfectly. https://www.youtube.com/watch?v=sPiVz1k-fEs

---
Tags: unity, animation, character, collider, polygoncollider2d
---


# Question
Title: How to make Ai use ouMouseDown() and onMouseUp() function in unity?
I want to make an ai for my game.

Currently my game controller uses onmousedown and onmouseup functions and some other factors?

My game is for two players on same screen but you don't always have someone to play game with so I wanna design Ai for that. How can I go about to design Ai for something like that?

# Answer
Do you find it difficult to translate AI strategies into user input? Or those methods are inaccessible for some reason?

If yes, then one way you can solve this is by not putting your game logic into `onMouseDown` and similar functions. If you keep the general logics separate, those input functions will just invoke the needed logics code (or maybe queue some actions, if you're going for a more robust approach). By itself it's not very different, you just have your code in another function now and have to call it. But on the other hand, your AI now does not need to create "input events" and can perform in-game actions directly (or, again, queue them).

Once you think about strategy for your AI from the point of implementation, you will see, that it needs to interact with your game world anyway. For example, even to press buttons, your AI needs to know what's going on in the game world. It needs access to your game state and it needs to be able to observe/read all the values that affect its actions. And if AI has all that, it can just as well affect that state, without producing mouse click events.
> 0 votes

---
Tags: unity
---


# Question
Title: VS code sometimes doesn't recognize Unity APIs
Unity debugger plugin and C# plugin are installed but Visual Studio Code does not recognize Unity APIs. Intelisense does not work. How can I fix?

# Answer
I had the same problem happen to me several times in my last project. You should first check the usual solution : Go to Preferences -\> External tools and set vs studio as external script editor (of course make sure that in visual studio you have Tools for unity installed.) Now if that is already set, witch probably is, you can click Regenerate project files that fixed it for me.
> 1 votes

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


# Question
Title: How to calculate speed of a moving object in unity
Currently I am trying to calculate the speed of an object here is the below code snippet:

```
void Start ()
{
  StartCoroutine( CalcVelocity() );
}

IEnumerator CalcVelocity()
{
  while( Application.isPlaying )
  {
    // Position at frame start
    prevPos = transform.position;
    // Wait till it the end of the frame
    yield return new WaitForEndOfFrame();
    // Calculate velocity: Velocity = DeltaPosition / DeltaTime
    currVel = (prevPos - transform.position) / Time.deltaTime;
    Debug.Log( currVel );
  }
}

```

I am not sure if it is the correct way to do this? Did it suppose to provide Meters per second speed?

# Answer
You are calculating the negation of the object's velocity (same speed, opposite direction).

This isn't any different in Unity than it is in all the rest of linear algebra. If you want a vector *from* A *to* B, that's B - A, not A - B.

So your code should read:

```
currVel = (transform.position - prevPos) / Time.deltaTime;

```

And of course

```
speed = currVel.magnitude;

```

The speed and velocity are measured in world units per second. So if you think of one unit in your game world as being one metre, then this is metres per second.

To ensure you get a valid speed on the first loop of this coroutine, you will need to ensure you start it *before* the script that moves the object — otherwise you may get a false zero for the first frame.
> 0 votes

---
Tags: unity, mathematics
---


# Question
Title: What do you call an image of images? (And how does it get utilized?)
I wondered if anyone knows the terminology in which a Video Game uses an image with sets of ideas such as icons, graphical texts, and/or background images. Essentially, an 'All-In-One' image.

Likewise, how does the program utilize this 'All-In-One' image? I only know how to load images in separate files. Does it use some special cropping and load it as an individual image to a variable?

I appreciate any help you can provide.

P.S. I only have background knowledge in PyGame and Panda3D; hopefully, I can understand what you mean if you speak Unity.

---

**Edit:** Here are two examples that can give further clarification; would they still be called spritesheets? Also, #1's original filetype is .dds whilst #2 is .rgb; is there a contrast in using .png instead?

**Example #1** \- In Battlefield 2142, this is what the U.I. looks like in-game:

A subset of U.I.s comes from this file:

**Example #2** \- In TLOPO, this is what text looks like:

From what I can understand, it uses this image:

# Answer
> 2 votes
Stomf is right that one term is "spritesheet". But another more broad term is "atlas". Atlas sounds more relevant when talking about ones for fonts, as fonts usually aren't referred to as sprites.

# Answer
> 0 votes
The term you're looking for is 'Spritesheet'. Most languages will have libraries or built in functions which can import them.

I'm not familiar with pygame/panda3D, but once you know what to search for, it's easy enough to find relevant resources:

https://stackoverflow.com/questions/20109487/how-do-i-use-sprite-sheets-in-pygame

---
Tags: image, terminology
---


# Question
Title: Rotating an object around a rotating object
Im trying to build a model for the solar system in OpenGl, and I got the planets to move around the sun, but can't get the satellites to move around their planet. I can't share my code since this an university assignment, but my current 'orbiting' angle is `2 * glm::radians(180.0f) * (time / body.orbitPeriod)` , where `time` is a constant that is given to us, `body` is the planet and `.orbitPeriod` is how long it takes for a planet to complete an orbit.

# Answer
> 0 votes
Same code for orbiting a planet around the sun, just replace the position of the sun with that of the planet you want to revolve around. Here's a simple 2D example using degrees, I imagine you're calculations are a bit different but might give you some idea.

```
angle = 360 * ((time %% satellite.orbitPeriod) / satellite.orbitPeriod)

satellite.x = body.x + COS(angle) * satellite.orbitDistance
satellite.y = body.y + SIN(angle) * satellite.orbitDistance

```

---
Tags: 3d, rotate
---


# Question
Title: Confirming whether a user has drawn a character correctly
This is a follow-up post to this post: How can I check if a player-drawn line follows a path?. I'm having difficulty implementing the said feature and I believe it's because of a lack of math background.

In particular, the later components of the explanation are a bit confusing to me.

> The direction of the projected vector might not actually be important. If you just sum \>together the lengths of the projected vectors and compare them to the total length of \>the line segment, that will tell you what fraction of it is covered. (Except in odd \>cases—see §Limitations below).

In my mind this means

1. breaking down a character into line segments, converting them to 2d vectors
2. breaking down a user draw character into line segments, converting them to 2d vectors
3. mapping each user drawn line segment (now 2d vectors) to the closest character line segments
4. using projection for each one of those mapped line segments
5. summing up the projections and comparing it to the total length of all 2d vectors of the character

Is my assumption of what the writer is talking about correct? Or am I misinterpreting what is meant by the last bit.

# Answer
> 0 votes
Keep It Simple.

---

We can simplify the problem by focusing in only one segment. Once we solved it for one segment, we do that for a set of segments. We can define a coordinate system for the segment that makes it easier to check the distance from the input.

However, we still need to deal with how much of the segment has been painted. We could define a set of ranges (at the start only one range) that represent the segment. Then, on each input motion figure out what range of the segment it covers and substract it from the set (note: a range minus another range might result in two, one or zero ranges) until we have the empty set…

But keep it simple. It is easier to divide the segment into smaller segments, and only worry if each one of then got an input position near or not.

Well, we could instead define a series of points, and then check distance to those points. That way we can avoid the coordinate system I was talking about earlier…

Hmm… It would be good to put those points in a quad tree, so it is easier to find which point is near the input. S you don't have to to check distance to all them. Or better yet, put them on a grid. Then, you can just go to the grid based on the input position and see if there is a point there.

Well, that is a bitmap. You could have two low resolution monochrome bitmaps. One is how the character should look, and on the other you paint. Then you iterate over the pixels and see if all the pixels of the former are painted on the latter.

Except, if you only care if you painted all the pixels, you don't need to iterate over all the pixels to check. You can just keep count.

---

Have two low resolution monochrome bitmaps. The bitmap A is how the character should look. And you will paint on the bitmap B. *Neither is what you show to the user.* You also need the count of how many pixels are painted in A.

Take the input position, map it to the coordinates of the bitmaps, read from B. If it is painted in B, there is nothing to do. If it isn't, then paint it, then read from A. If it is painted in A, then decrease the count. Once the count reaches zero, the user is done.

---

Of course, don't loose track of the fact this method presuposes the character should have a given size, shape, position and orientation.

---
Tags: algorithm, vector, hand-drawn
---


# Question
Title: How to update constant buffer patially in OpenGLES
I am wondering what does glMapBufferRange actually do?

I am accessing my constant buffer like this way:

```
Uint8* builtInBuffer = (Uint8*)glMapBufferRange(buffer, 0, builtInBuffer->GetSize(), GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT | GL_MAP_UNSYNCHRONIZED_BIT);

```

However, when reading builtInBuffer , all data set preiously are lost. What happend? Does glMapBufferRange always clear all data in the range?

# Answer
> 2 votes
This can be expected behaviour.

When you map a buffer you are given a pointer, but there are no guarantees that this pointer is to the actual buffer data storage. In particular, since you specified the write and unsynchronized bits, it's OK for the pointer to be to any arbitrary memory which is then written to the actual buffer when you unmap or flush.

In particular, note from the documentation:

> No GL error is generated if the pointer is used to query a mapping which excludes this (GL\_MAP\_READ\_BIT) flag, but the result is undefined and system errors (possibly including program termination) may occur.

If you want to read a buffer, map it for reading, not for writing.

---
Tags: opengl, rendering, opengl-es
---


# Question
Title: Player rotation recalculation causes jittering on edges
When my player walks around a circular planet everything works well, but when my planet is a shape like a cube or a dodecahedron, even with smoothed edges, my character jitters if I walk slowly on the edge.

That is because I raycast downward and set my characters rotation to be perpendicular with the normal. If im on the edge, the ray hits a different side of the shape than the one I stand on, causing my player to rotate to that new side, even if the angle between the face I stand on and the one I hit is 179°. So when My character rotates, the face I hit with the ray becomes the one I was standing on before, causing me to rotate back and forth between 2 faces.

Here is a beautiful scheme of what I mean:

I tried using SphereCast instead of Raycast, but it didn't work. How can I limit the back and forth rotations ?

Here is the script for the raycast:

```
void Update(){

```

...

```
 if (Physics.Raycast(rayStart, GetDirection(IsGrounded, GravityChangeHitPoint), out RaycastHit hit, Mathf.Infinity, layerMask))
    {
        Debug.DrawLine(transform.position, hit.point,Color.red);
        Quaternion matchSurface;

        if (GravityChangeHitPoint == GravityCenter.position)
            matchSurface = PlayerLookRotation(transform.forward, hit.normal);
        else
            matchSurface = PlayerLookRotation(transform.forward, -GetDirection(IsGrounded, GravityChangeHitPoint));

        Quaternion cam = Quaternion.Euler(0, Input.GetAxis("Mouse X") * sensitivityX, 0);

        if (!IsGrounded)
            transform.rotation = Quaternion.Lerp(transform.rotation, matchSurface, Time.deltaTime * damping) * cam;
        else
            transform.rotation = matchSurface * cam;
    }
}

Quaternion PlayerLookRotation(Vector3 approximateForward, Vector3 exactUp)
{
    Quaternion zToUp = Quaternion.LookRotation(exactUp, -approximateForward);
    Quaternion yToZ = Quaternion.Euler(90, 0, 0);

    return zToUp * yToZ;
}

```

# Answer
> 0 votes
Using orthogonal distance to/from the cube edge as input parameter `t`, you may want to linearly interpolate your character's local euler angle around a single axis, or else spherically interpolate your character's rotation. That is, your final rotation will be smoothly interpolated between 0.0 and 1.0 of the rotation between your first plane's angle and your second plane's angle.

The problem with both of these approaches, is that the result could still look unnatural on a sharp-edged cube. In that case I would smooth the geometry at the edges of the cube mesh as well, but this depends very much on your requirements.

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


# Question
Title: Unity world curve shader graph, how to start curving from a specific distance?
I've made simple world curving shader following some online tutorials and cleaning few things up. It's doing its job, however I have small issue where it curves objects that are very close to a camera. So, I am trying to figure out how to start curving only if objects are certain distance form the camera, lets say 20 units or more?

Below is a sub-graph I use to output a value for a vertex position i.e. curve world shader, this is the one I need to figure out how to modify

# Answer
> 1 votes
Before you feed the z position into the Power node, subtract your minimum curving distance from the z to get a signed difference, and then run that through a Max node to take the greater of 0, or that z difference. Then pipe that clamped z value into the Power node.

If your camera is looking in the -z direction, then you'd do something similar, but *add* the minimum curving distance and then run it through a *Min* node instead. Either way, what you're doing is moving the vertex of the parabola forward or back along the z axis, then clamping everything closer to the camera to zero so you only see the further branch of the parabola.

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


# Question
Title: Runtime NavMesh Builder source mesh combined mesh is skipped because it does not allow read access
I'm getting this error:

> Runtime NavMesh Builder source mesh combined mesh is skipped because it does not allow read access

I checked all the models and it has the read permission. I also noticed, that in some cases unchecking the static checkbox helps and I'm getting a smaller amount of these errors.

# Answer
I fixed it by setting every object in my scene to non-static. The problem was, that the NavMesh Builder was trying to combine static and non-static meshes.
> 1 votes

# Answer
An alternative way to fix this is to change in NavMeshSurface/Use Geometry from Render Meshes to Physics Colliders.
> 1 votes

---
Tags: unity, ai, mesh, navmesh
---