# Question
Title: Unity Json utility does not serialize DateTime
Like the title said the unity json utility does not seem to allow me to serialize the DateTime structure. Just to clarify the problem is that I'm serializing this class:

```
[Serializable]
public class SaveData {

public Vector3 playerPosition;
public Quaternion playerRot;
public List<Item> inventory;

public DateTime saveTime;

public int playerHealth;

public int strength;
public int attack;
public int defense;
public int agility;

```

}

When I actually write to the json file I get everything but the DateTime and no errors. This is the result:

```
{
"playerPosition": {
    "x": -142.27000427246095,
    "y": -7.000000476837158,
    "z": -112.80999755859375
},
"playerRot": {
    "x": 0.0,
    "y": 0.0,
    "z": 0.0,
    "w": 1.0
},
"inventory": [],
"playerHealth": 100,
"strength": 0,
"attack": 0,
"defense": 0,
"agility": 0
}

```

Is there a way around this?

A little update to this question so that I can show another way I've worked around this problem if the answer below isn't for you.

I was recently working on a similar problem and solved it by doing the follow:

I created a new class called "NewDateTime":

```
[System.Serializable]
public class NewDateTime {
public int second;
public int minute;
public int hour;

public int day;
public int month;
public int year;

public NewDateTime CreateNewDateTime(DateTime dateTime) {
    NewDateTime newDateTime = new NewDateTime();
    newDateTime.second = dateTime.Second;
    newDateTime.minute = dateTime.Minute;
    newDateTime.hour = dateTime.Hour;
    newDateTime.day = dateTime.Day;
    newDateTime.month = dateTime.Month;
    newDateTime.year = dateTime.Year;

    return newDateTime;
}

public override string ToString() {
    return day + "/" + month + "/" + year + " at " + hour + ":" + minute + ":" + second;
}}

```

and then for example when I want to save the date to json I would do something like the following:

```
saveDateTime = newDateTime.CreateNewDateTime(DateTime.Now)

```

it's a rather simple workaround but I thought it might help.

# Answer
> 8 votes
The problem with JsonUtility, is that it doesn't save properties, *just public fields and fields with the \[SerializeField\] attribute*.

You can solve this with another class and some conversion magic, like so:

**Json Serializable Class**

```
[Serializable]
struct JsonDateTime {
    public long value;
    public static implicit operator DateTime(JsonDateTime jdt) {
        Debug.Log("Converted to time");
        return DateTime.FromFileTimeUtc(jdt.value);
    }
    public static implicit operator JsonDateTime(DateTime dt) {
        Debug.Log("Converted to JDT");
        JsonDateTime jdt = new JsonDateTime();
        jdt.value = dt.ToFileTimeUtc();
        return jdt;
    }
}

```

**Usage example**

```
var time = DateTime.Now;
print(time);
var json = JsonUtility.ToJson((JsonDateTime) time);
print(json);
DateTime timeFromJson = JsonUtility.FromJson<JsonDateTime>(json);
print(timeFromJson);

```

**Output**

# Answer
> 0 votes
As it happens, I was just working on a telemetry example for my students, where I used this approach:

```
[SerializeField] long _timecode;
public DateTimeOffset time {
    get {
        return DateTimeOffset.FromUnixTimeMilliseconds(_timecode);
    }
    set {
        _timecode = value.ToUnixTimeMilliseconds();
    }
}

```

This way the serialized form is just a simple 64-bit integer, while consuming code can read/write it using the richer `DateTimeOffset` API. In my case, using the Unix time convention helped ensure I'd get consistent behaviour between my Unity game and a Node.js server.

Anytime I needed the current moment, I'd capture it as `data.time = System.DateTimeOffset.UtcNow;`

# Answer
> -1 votes
I just faced the same problem and I fixed that by using Newtonsoft instead of JsonUtility as a converter.

here is an example

//here we will serialise or deserialize the data

```
public void SaveData
{

        List<Model> models = new List<Model>();
        //just adding some data
        models.Add(new Model { playerHealth = 10, saveTime = DateTime.Now, strength = 50 });

        //here pasing the data that are stoed on that variable into a json format
        string jsonText = Newtonsoft.Json.JsonConvert.SerializeObject(models);
        Debug.Log(jsonText);
}

```

//this is the model

```
public class Model
{
    public DateTime saveTime;

    public int playerHealth;

    public int strength;

}

```

here are result

---
Tags: unity, json
---


# Question
Title: UE4: How to make UProceduralMeshComponent a solid body, not just a surface around volume?
I generated the UProceduralMeshComponent and set collision enabled to ECollisionEnabled::QueryOnly.

But I get ActorEndOverlapEvent if I stop touching the mesh border even if I still inside of mesh body. So, how to make it solid to get this event only if I left from the mesh volume (like in ATriggerBox for example)?

# Answer
I solved it.

First of all, I need to turn off option "Use Complex as Simple Collision"

```
bUseComplexAsSimpleCollision = false;

```

and then I can add simple collision convex hulls:

```
// Create collision simple mesh
for (const TArray<FVector>& Hull : ConvexHulls)
{
    ShapeMesh->AddCollisionConvexMesh(Hull);
}

```

I added few hulls because my shape can be a concave polygon based, so, I need to split it to few convex polygons and add volume for each separately.
> 2 votes

---
Tags: collision-detection, procedural-generation, unreal-4, mesh
---


# Question
Title: Unreal 4: How to save generated UProceduralMeshComponent to level file in editor and load it at runtime?
I have UProceduralMeshComponent that I generate in editor from data entered by level designer. Now I need to save it to level file in editor to load it in runtime without generating new mesh again.

Is it possible to do in Unreal Engine?

# Answer
> 0 votes
It was very simple. I just need to add a UPROPERTY() keyword to my UProceduralMeshComponent field and call generation function only in editor. The generated mesh will be loaded from level file after you save level.

---
Tags: 3d-meshes, unreal, serialization, map-editor
---


# Question
Title: How to implement cylindrical projection?
This question (and particularly, its answer) talked about how traditional, planar projection matches most monitors... except when it doesn't.

Assuming I'm a glutton for punishment, and really, really *must*, at whatever (performance) cost, have accurate projection for a curved monitor, how would I go about coding a cylindrical projection?

Ignore the boring affine transformation from world space to camera space. Assume my input coordinates are X,Y,Z, with the camera at the origin, looking at an arbitrary, fixed vector of your choice (either +x or +y, unless you're feeling evil). Assume that the screen represents a partial cylinder with H denoting the arc length and V denoting the angle between the top and bottom (i.e. the same vfov as in planar projection). How do I go from my input X,Y,Z to the projection onto the cylinder?

Assuming that the cylinder has radius *r*, the expected result should be a coordinate with -π \< x \< π, and where 0,1,1 represents a point at (world) z=*r* whose projection into the XY plane is *r* from the origin.

I am just looking for the math or pseudocode; answers do not need to be in a specific language (e.g. GLSL).

Possible duplicate of this question which didn't receive any answers .

# Answer
The comment on the linked question is correct. If you did ray casting/marching/tracing, you just need to shoot the rays in the desired configuration (i.e. a cylinder) - an the rest of the process would be same as usual for those techniques.

So, if you are familiar with those techniques that tidbit is enough to get you started. And why why do we want those techniques? Because under these projection straight lines may appear curved, which is not posible to accomplish on the vertex shader. So we resource to ray casting and similar techniques.

---

As an alternative, you could do a two pass process: the first pass projects the geometry with a regular perspective projection to a texture, and a second pass renders the texture with the desired distortion (a barrel distortion), which could be approximated by applying the texture to curved geometry. *In fact, if you are interested in the old monitor look, I'd argue, this is the way to go.*

---

If you were doing ray casting/marching/tracing. The direction of the ray would take the x (after normalizing) as an angle. So your ray setup looks something like this (I have tested this in ShaderToy):

```
float camDst = 1.0f / tan(FOV * 0.5 * PI / 180.0);
vec2 screenPos = (fragCoord.xy - 0.5 * iResolution.xy) / iResolution.y;
vec3 rayTarget = vec3(sin(screenPos.x) * camDst, screenPos.y, cos(screenPos.x) * camDst);
vec3 rayDir = normalize(rayTarget);
vec3 rayPos = vec3(0.0, 0.0, 0.0);

```

Notice that here `rayTarget` is a cylinder of `camDst` radius, positioned vertically, centered at the origin.

When it would have usually been like this:

```
float camDst = 1.0f / tan(FOV * 0.5 * PI / 180.0);
vec2 screenPos = (fragCoord.xy - 0.5 * iResolution.xy) / iResolution.y;
vec3 rayTarget = vec3(screenPos.x, screenPos.y, camDst);
vec3 rayDir = normalize(rayTarget);
vec3 rayPos = vec3(0.0, 0.0, 0.0);

```

Notice that here `rayTarget` is a plane, parallel to the XY plane, at `camDst` from the origin. *Yes, the camera is looking toward positive Z. Thanks to this "EvIl" the x and y axis of screen space and camera space are oriented the same way.*

Where:

* `iResolution` is an uniform with the pixel size of the viewport.
* `fraagCoord` is the position of the pixel in normalized device coordinates (they go from `-1.0` to `1.0`).
* `FOV` is an uniform or constant with the field of view in degrees.
* `PI` is a constant with value the of π.

---

Alright, so we have a point in XYZ. And following with the above "EvIl", I'll work the screen coordinates from the above code.

The first line we can keep:

```
float camDst = 1.0f / tan(FOV * 0.5 * PI / 180.0);

```

Then, assume the point was hit a ray (and the camera is at the origin), so we know the direction of the ray:

```
float camDst = 1.0f / tan(FOV * 0.5 * PI / 180.0);
vec3 rayDir = normalized(X, Y, Z);

```

From the code:

```
vec3 rayDir = normalize(rayTarget);

```

We have that:

```
rayDir = normalize(rayTarget)
rayDir = f * rayTarget

```

*We don't know `f`.*

Let us see the components separately:

```
rayDir = normalize(rayTarget)
f * rayTarget.x = rayDir.x
f * rayTarget.y = rayDir.y
f * rayTarget.z = rayDir.z

```

And replace with `rayTarget`:

```
vec3 rayTarget = vec3(sin(screenPos.x) * camDst, screenPos.y, cos(screenPos.x) * camDst);

```

Which gives us:

```
rayDir = normalize(rayTarget)
f * sin(screenPos.x) * camDst = rayDir.x
f * screenPos.y = rayDir.y
f * cos(screenPos.x) * camDst = rayDir.z

```

I'll call `screenPos.x` as `angle` for now:

```
rayDir = normalize(rayTarget)
angle = screenPos.x
f * sin(angle) * camDst = rayDir.x
f * screenPos.y = rayDir.y
f * cos(angle) * camDst = rayDir.z

```

Since `vec2(sin(angle), cos(angle))` must have length of `1`, we can get it like this:

```
vec2(sin(angle), cos(angle)) = normalize(vec2(rayDir.x, rayDir.z))

```

Thus, we can get `screenPos.x` like this:

```
screenPos.x = angle = atan2(rayDir.x, rayDir.z)

```

We can get `f` by either of these means now:

```
f = rayDir.x / (sin(angle) * camDst)
f = rayDir.z / (cos(angle) * camDst)

```

And with `f`, we have `screenPos.y`:

```
screenPos.y = rayDir.y / f

```

So far the code looks something like this:

```
float camDst = 1.0f / tan(FOV * 0.5 * PI / 180.0);
vec3 rayDir = normalized(X, Y, Z);
float angle = atan2(rayDir.x, rayDir.z);
float f = rayDir.z / (cos(angle) * camDst);
vec2 screenPos = vec2(angle, rayDir.y / f);

```

To get the fragment coordinates, we need to undo this:

```
vec2 screenPos = (fragCoord.xy - 0.5 * iResolution.xy) / iResolution.y;

```

Like this:

```
float camDst = 1.0f / tan(FOV * 0.5 * PI / 180.0);
vec3 rayDir = normalized(X, Y, Z);
float angle = atan2(rayDir.x, rayDir.z);
float f = rayDir.z / (cos(angle) * camDst);
vec2 screenPos = vec2(angle, rayDir.y / f);
vec2 fargCoord = (screenPos * iResolution.y) + (0.5 * iResolution.xy);

```

And that `fargCoord` should be the position in pixels on the screen.

---

Some links I found while looking at related questions:
> 1 votes

# Answer
I'm assuming you want to match a Curved Monitor with Cylindrical Projection. (and since you're not asking about spherical projection you are going for a very wide monitor with limited height)

Have you considered using polar coordinates for your input? I think then the game engine would only need the minimal transformations equations to project the "view" to a "cylinder" Monitor.

This would produce a picture without the distorted edges of a rectilinear projection. (with exception of some limited distortion due to height distances) However, you would have to match the FOV (field of view) to the monitor size and curvature to have a proper picture (with limited distortion). So if the monitor is like a quarter of a circle, your matching FOV would be 90 degrees. As you go further from that there will be more distortion. To calculate what part of a circle a monitor is you need to know the radius (most curved monitors I see are like 1800 mm) and the size (length).
> 1 votes

---
Tags: 3d, mathematics, projection
---


# Question
Title: DOTS entity debugger -- trouble inspecting elements within a dynamic buffer
I'm using Unity 2021.2.7f1 with the latest versions of DOTS available.

When I open up the entities debugger "Windows / DOTS / Enities" I can begin inspecting the live component values associated with a chosen entity. However for dynamic buffers each element's data is locked behind a greyed-out Foldout... I can't unfold the UI, and so I'm unable to inspect live data in each element.

I can however see the element values during **edit time** via the Preview window of the inspector GUI.

Does anybody have a solution or workaround to inspect live runtime dynamicBuffer data? Is the entity debugger extendable like inspector GUIs are?

# Answer
As Philipp commented, looks like this is a known issue with the entity debugger and a bunch of other Unity editors in the 2021.2 beta. From discussions on the Unity Forum it seems to have something to do with upgrading UI Toolkit versions with breaking changes that resulted in some regressions, including in the entity debugger.
> 0 votes

---
Tags: unity, gui, unity-dots
---


title: Is OpenGL built on top of OpenCL?

text:
# Question
Title: Is OpenGL built on top of OpenCL?
Does OpenGL use the help of OpenCL to do the GPU calculations for shader and vertex, or OpenGL have another library to do GPU calculations.

# Answer
> 3 votes
**OpenGL is implemented by the GPU vendor as part of their device driver**.

Just to be specific about what OpenGL is and is not.

* It is not a library. Older OpenGL specifications used to start with "OpenGL is a software interface to graphics hardware" and that's probably still the best description.
* It is not open source. OpenGL actually pre-dates the open source movement and the "open" refers to it's status as a *standard*, nothing to do with source code.
* There is not a single OpenGL, instead each GPU vendor has their own implementation.
* It is not software. You can't just arbitrarily download or upgrade your OpenGL. While it is true that software implementations do exist, they are so slow as to be unusable for performance-critical real-time rendering.

Putting it all together the way things work is:

* The GPU does the actual drawing.
* OpenGL provides a way for your program to tell the GPU what to do.
* OpenGL is implemented by the GPU vendor as part of their device driver.
* OpenGL has a published specification.
* Your program doesn't need to know details of the hardware in order to draw stuff.
* If the GPU vendor correctly follows the specification, and if your program correctly follows the specification, everything works.

The part of all of the above that is relevant to your question is **how does the GPU vendor implement OpenGL?** and the answer is typically **we don't know**. So one vendor might implement it on top of another API, another vendor might go direct to the hardware using a DDK, a third vendor might do something else. The point is, **we don't need to know**; all we need to know is that OpenGL is implemented according to it's specification and then we can start writing code.

# Answer
> 3 votes
OpenGL was published in 1992 while OpenCL came out in 2009. The motivation for creating OpenCL was that some people started to abuse certain OpenGL features for solving general computing problems using the vector computing capabilities of GPUs even though those problems had nothing to do with graphics. OpenCL was invented to offer a more direct way to accomplish that.

It's not like one is built on top of the other. They are two alternative routes to access the computing capabilities of the GPU. One is designed for drawing pretty pictures, the other is designed for number crunching.

OpenGL and OpenCL are implemented by the graphics driver, which translates library calls into low-level instructions the GPU can understand. It is very well possible that some driver for some GPU might on some translation layer unify some functions of both APIs into one, so the GPU does not know if the instructions it receives from the driver originate from OpenGL or OpenCL calls. But that's really nothing you as a game developer should be concerned with, because you don't know what GPU with what driver the end-user is going to use.

# Answer
> 2 votes
Short answer - no.

You can add DirectX and Vulkan and others to your list - they are just different APIs that employ GPU resources in different ways.

---
Tags: opengl, opencl
---


title: proper items db design mysql

text:
# Question
Title: proper items db design mysql
I'm working on a game using MySQL as the db. I'm struggling a bit on the database design, this is the part I'm struggling with:

So basically exp\_ups, mystery\_boxes and weapons are entities in the game which have their own table to store information about a specific entity. The user\_... tables contain which item what user has, copy of items can be owned by multiple people. So user 1 and 2 can both have weapon with id 1 but its stored in 2 rows. In user\_weapons (& user\_mystery\_boxes & user\_exp\_ups) additional metadata about that specific copy can be added like time\_acquired and other metadata.

The thing is here, how would I implement a marketplace where users can list their items? Or fetch all the items a specific user has (inventory), this is kinda hard because all items are in their own table with their own incremental id. Ideally I would want to have some sort of item\_id which references to an item but a foreign key can only point to one table. Does anyone have an idea?

Sample data to clarify:

The same applies for the mystery\_boxes and exp\_ups tables (obviously they have different columns but the idea is the same)

# Answer
> 1 votes
Example data model

The idea is, you have a generic item with an item type. For each item type you define an extra table, that gives the attributes to the item you want (mainly weapons, armor). The auction table is now straight forward, just refer to the item id and the other columns can be relevant how your auction works (add start time, end time, current winner, buyout price, etc).

The mystery table is just a collection of item ids to the mystery item that describes the chance to get that item. Once the user would use the item, you would look up which box type he used, load all items corresponding to that one and roll accordingly which item he got.

If you are really against the null value, you could have a helper table that stores the modifications that are done to an item, be it temporary or permanent. Value is either directly like in case of durability or it is the id of the effect. I didn't add an enhancement table, but it could be something temporary like whetstones or weapon oils. With the new table, you can have as many effects on an item as you want. The id in the item\_modification table is the id of the item in your inventory.

Keep in mind the performance of your queries. If you save performance by having something like durability (which will change often) in a table with quick access, there is a real benefit compared of not just having a few null values for items that do not need it. Depending on your player base, the number could grow quickly.

---
Tags: architecture, databases, sql, mysql
---


# Question
Title: Unity Editor Hangs for A Fraction of A Second About Once Per Second
I am having a problem with the Unity Editor. It hangs for a fraction of a second about once per second. I took a video recording of me walking through the default hdrp scene. https://youtu.be/Uz2B85Mq0QE

It's definitely cyclical, every second or so the computer just hangs for a fraction of a second. In the video above, notice how even when I'm not running the Unity scene, my cursor turns into the windows spinning blue circle cyclically every second, just like how the game hangs.

I've tried everything I can think of including disabling antivirus/firewall software, changing the external script editor, etc... I reproduced the bug on more than 1 version of Unity including both LTS and Beta versions. I know it's not my specs, I have an Intel i7-11700K with 16GB of RAM and an Nvidia 3070.

I also ran the Unity Profiler and the task manager and collected the output of these processes in this video https://youtu.be/GHgqP5A3bYE. From the start of the video until the 0:44 mark is the Unity Profiler and from 0:44 until the end is the task manager.

Just for quick reference here is the screenshot of the Unity Profiler clearly indicating extreme cyclical activity spikes.

What is the problem? What could be causing this?

# Answer
I fixed it. The problem was coming from the plugin Github for Unity. I deleted the folder Assets/Plugins/Github and the problems disappeared.
> 1 votes

---
Tags: unity, rendering, nvidia, profiler, hdrp
---


title: Is there a do-while loop in GDscript?

text:
# Question
Title: Is there a do-while loop in GDscript?
Is there a `do ... while (condition)` loop in GDscript? The documentation explains `while` but makes no mention of `do while`.

I have some code that I want to execute at least once, and then continue looping until a condition is met. Using a plain `while` is insufficient because it may not execute at all depending on the value of the condition at the start.

The editor tells me that the following is invalid:

```
  do:
      # a bunch of stuff
  while (condition == true)

```

Do I need to duplicate the "bunch of stuff" (or replace with function call) and run it once directly and *then* loop with a `while` loop (and remember to change both every time I change the code), or is there a do-while-equivalent structure in GDScript?

# Answer
> 9 votes
> Is there a `do ... while (condition)` loop in GDscript?

There isn't. The documentation does not mention anything like that, as you found out.

---

> I have some code that I want to execute at least once, and then continue looping until a condition is met.

You can do something like this:

```
while true:
    # some other code
    if condition:
        break

```

You, of course, don't have to use `break` at the end. You can use this approach to exit early at any point of the loop.

---

> Do I need to duplicate the "bunch of stuff" (or replace with function call) and run it once directly and then loop with a while loop (and remember to change both every time I change the code), or is there a do-while-equivalent structure in GDScript?

Unrolling the first iteration before the loop is viable too, however there isn't much point in doing that in GDScript. And yes, making a function is also an option, which you could call once before the loop. Something like this:

```
iteration()
while not condition:
    iteration()

```

If you are considering making a function, consider also having it return a `bool`, and in the function you can exit early with `return`. You would then use it like this:

```
while iterate():
    pass

```

And if you really want to over-engineer this… Although Godot does not have proper generator functions, it is possible to make a custom iterator.

*But why? Use `break`, it is fine.*

---
Tags: godot, gdscript
---


# Question
Title: Drawing a dynamic indicator for a field of view
My goal is to draw a dynamic indicator for a cube, which represents the field of view. The ideal indicator would look the same as in Metal Gear Solid(the blue ones):

From what I have gathered, I need an angle and a length for the indicator as such for a 50° FoV:

Now my issue is what method should I use to draw the indicator? A procedural mesh or is there a less demanding way of doing this?

# Answer
> 18 votes
I can't give you a Unity-specific answer (sorry!), but I can tell how I would solve this. I would generate a bunch of points on a circle using the blue vector.

First, what is a circle? Well, a circle looks like this:

However, graphics hardware can't really draw perfect circles. You're always going to end up with a polygon approximation:

We do this approximation by using sine and cosine functions. If you remember from trigonometry, a circle is 360 degrees or 2 pi. Sine and cosine functions take a value out of 2 pi and give you a distance either in the x (cosine) or y (sine) axis. A very useful property indeed.

In code:

```
x = (cos(degrees_to_radians(angle));
y = (sin(degrees_to_radians(angle));

```

Now, what you want is not a circle, but a half-circle. Specifically, you want this:

This can be achieved by using an `angle_start` and an `angle_end`. We then loop over this using an `angle_delta` that is calculated by dividing the difference between `angle_start` and `angle_end` over the `quality` we want.

Another useful property of approximating circles with sine and cosine (also known as the "unit circle") is that it can be shrunk or grown using a radius value. So let's add a radius to our pseudo-code:

```
x = (cos(degrees_to_radians(angle)) * radius;
y = (sin(degrees_to_radians(angle)) * radius;

```

How can we use this for our field-of-view cone? Well, we can use the same circle but draw it at different distances:

And when I add a dotted line to connect the two half-circles, it's starting to look like a cone!

Here, we have two radii: `dist_min` and `dist_max`. Our code becomes:

```
x_min = (cos(degrees_to_radians(angle)) * dist_min;
y_min = (sin(degrees_to_radians(angle)) * dist_min;

x_max = (cos(degrees_to_radians(angle)) * dist_max;
y_max = (sin(degrees_to_radians(angle)) * dist_max;

```

However, we also need *two* angles: one for the current step and one for the next step. We'll call these `angle_curr` and `angle_next`. Now our code becomes:

```
x_curr_min = (cos(degrees_to_radians(angle_curr)) * dist_min;
y_curr_min = (sin(degrees_to_radians(angle_curr)) * dist_min;

x_curr_max = (cos(degrees_to_radians(angle_curr)) * dist_max;
y_curr_max = (sin(degrees_to_radians(angle_curr)) * dist_max;

x_next_min = (cos(degrees_to_radians(angle_next)) * dist_min;
y_next_min = (sin(degrees_to_radians(angle_next)) * dist_min;

x_next_max = (cos(degrees_to_radians(angle_next)) * dist_max;
y_next_max = (sin(degrees_to_radians(angle_next)) * dist_max;

```

Now we have four points on our half-circles. Let's store these points as triangles. Here's a diagram that should help clear up how can make triangles out of these four points:

So, what do we need to do draw a cone?

* Determine the start angle and the end angle. This is done using the enemy's direction and field of view variable.
* Determine the quality of our approximation. 15 steps should be good enough for most purposes.
* Loop over the difference between start and end using the delta ((end - start) / quality).
* Convert our angles to four points.
* Convert the four points to two triangles.

When we combine these steps, here's what we will end up with:

In full pseudo-code:

```
int quality = 15;

float dist_min = 0.5f;
float dist_max = 15.f;

vec2 pos = GetEnemyPosition();
float angle_lookat = GetEnemyAngle();
float angle_fov = GetEnemyFieldOfView();

float angle_start = angle_lookat - angle_fov;
float angle_end = angle_lookat + angle_fov;
float angle_delta = (angle_end - angle_start) / quality;

float angle_curr = 0.f;
float angle_next = angle_delta;

for (int i = 0; i < quality - 1; i++)
{
    vec2 sphere_curr;
    sphere_curr.x = cos(degrees_to_radians(angle_curr));
    sphere_curr.y = sin(degrees_to_radians(angle_curr));

    vec2 sphere_next;
    sphere_next.x = cos(degrees_to_radians(angle_next));
    sphere_next.y = sin(degrees_to_radians(angle_next));

    vec2 pos_curr_min = pos + sphere_curr * dist_min;
    vec2 pos_curr_max = pos + sphere_curr * dist_max;

    vec2 pos_next_min = pos + sphere_next * dist_min;
    vec2 pos_next_max = pos + sphere_next * dist_max;

    WriteTriangle(pos_curr_min, pos_curr_max, pos_next_max);
    WriteTriangle(pos_next_max, pos_curr_min, pos_next_min);

    angle_curr += angle_delta;
    angle_next += angle_delta;
}

```

This should create the cone you want. Try playing with the parameters (`dist_min`, `dist_max` and `quality`) to get the effect you want. It should only be a few triangles per enemy, I don't think it's much of a problem to generate this every frame. Only consider optimizing it when it becomes a problem.

# Answer
> 6 votes
Good day y'all!

I've implemented knight666's answer from pseudo-code to Unity-code (C#). Some slight changes were needed but it works like charm, just attach the script to an enemy. I don't know if there are more efficient ways to do some of the things.

One thing worth mentioning is that the number of vertices can be reduced from 4\*quality to 2\*quality+2, since for example triangle 2 and 3 share two vertices. This is true if the circle segment is continuous, but in my application it isn't, which is my I didn't optimize that part :)

Also note that you cannot set `mesh.vertices[i]` or `mesh.triangles[i]`, which is why I used the auxiliary arrays `vertices` and `triangles` (which probably should be declared in global space for speed).

The code is sparsely commented since knight666's awesome answer and pics say it all. The biggest difference is that his answer is in right hand coordinates, whereas Unity works in left hand coordinates, so some sin & cos needed switching places as well as the order of the vertices in the triangles to get the correct normal (y axis in this case)

```
using UnityEngine;
using System.Collections;

public class drawFieldOfView : MonoBehaviour {

    int quality = 15;
    Mesh mesh;
    public Material material;

    float angle_fov = 40;

    float dist_min = 5.0f;
    float dist_max = 15.0f;

    void Start()
    {
        mesh = new Mesh();
        mesh.vertices = new Vector3[4 * quality];   // Could be of size [2 * quality + 2] if circle segment is continuous
        mesh.triangles = new int[3 * 2 * quality];

        Vector3[] normals = new Vector3[4 * quality];
        Vector2[] uv = new Vector2[4 * quality];

        for (int i = 0; i < uv.Length; i++)
            uv[i] = new Vector2(0, 0);
        for (int i = 0; i < normals.Length; i++)
            normals[i] = new Vector3(0, 1, 0);

        mesh.uv = uv;
        mesh.normals = normals;

    }

    void Update()
    {
        float angle_lookat = GetEnemyAngle();

        float angle_start = angle_lookat - angle_fov;
        float angle_end = angle_lookat + angle_fov;
        float angle_delta = (angle_end - angle_start) / quality;

        float angle_curr = angle_start;
        float angle_next = angle_start + angle_delta;

        Vector3 pos_curr_min = Vector3.zero;
        Vector3 pos_curr_max = Vector3.zero;

        Vector3 pos_next_min = Vector3.zero;
        Vector3 pos_next_max = Vector3.zero;

        Vector3[] vertices = new Vector3[4 * quality];   // Could be of size [2 * quality + 2] if circle segment is continuous
        int[] triangles = new int[3 * 2 * quality];

        for (int i = 0; i < quality; i++)
        {
            Vector3 sphere_curr = new Vector3(
            Mathf.Sin(Mathf.Deg2Rad * (angle_curr)), 0,   // Left handed CW
            Mathf.Cos(Mathf.Deg2Rad * (angle_curr)));

            Vector3 sphere_next = new Vector3(
            Mathf.Sin(Mathf.Deg2Rad * (angle_next)), 0,
            Mathf.Cos(Mathf.Deg2Rad * (angle_next)));

            pos_curr_min = transform.position + sphere_curr * dist_min;
            pos_curr_max = transform.position + sphere_curr * dist_max;

            pos_next_min = transform.position + sphere_next * dist_min;
            pos_next_max = transform.position + sphere_next * dist_max;

            int a = 4 * i;
            int b = 4 * i + 1;
            int c = 4 * i + 2;
            int d = 4 * i + 3;

            vertices[a] = pos_curr_min;
            vertices[b] = pos_curr_max;
            vertices[c] = pos_next_max;
            vertices[d] = pos_next_min;

            triangles[6 * i] = a;       // Triangle1: abc
            triangles[6 * i + 1] = b;
            triangles[6 * i + 2] = c;
            triangles[6 * i + 3] = c;   // Triangle2: cda
            triangles[6 * i + 4] = d;
            triangles[6 * i + 5] = a;

            angle_curr += angle_delta;
            angle_next += angle_delta;

        }

        mesh.vertices = vertices;
        mesh.triangles = triangles;

        Graphics.DrawMesh(mesh, Vector3.zero, Quaternion.identity, material, 0);
    }

    float GetEnemyAngle()
    {
        return 90 - Mathf.Rad2Deg * Mathf.Atan2(transform.forward.z, transform.forward.x); // Left handed CW. z = angle 0, x = angle 90
    }

}

```

# Answer
> 0 votes
8 years later and this has helped another coder. I have adjusted knight666's and Rick0r's code to work modularly with a tabletop strategy game I am working on. Though I am having trouble getting it to take a shader, it will only display the color of the shader and not the effect.

```
using UnityEngine;

public class FiringArcMeshGenerator : MonoBehaviour
{
    /// <summary>
    /// Credit to Knight666 (knight666.com) & Rickz0r
    /// https://gamedev.stackexchange.com/questions/31170/drawing-a-dynamic-indicator-for-a-field-of-view
    /// Code modified for modular use by ThomFoxx
    /// </summary>
    [SerializeField] private int _quality = 6;
    private Mesh _arcMesh;

    [SerializeField] private bool _isPrimary;
    [SerializeField] private float _primaryAngle = 90, _auxAngle = 180;

    private float _angleOfFire;

    private float _minDist;
    private float _maxDist;

    public void MeshSetup(ShipInfo ship)
    {
        WeaponInfo weapon;

        if (_isPrimary)
        {
            _angleOfFire = _primaryAngle / 2;
            weapon = ship.Primary;
        }
        else
        {
            _angleOfFire = _auxAngle / 2;
            _quality *= 2;
            weapon = ship.Auxiliary;
        }

        _minDist = weapon.MinRange;
        _maxDist = weapon.MaxRange;

        _arcMesh = new Mesh();
        _arcMesh.vertices = new Vector3[4 * _quality];
        _arcMesh.triangles = new int[3 * 2 * _quality];

        Vector3[] normals = new Vector3[4 * _quality];
        Vector2[] uv = new Vector2[4 * _quality];

        for (int i = 0; i < uv.Length; i++)
            uv[i] = new Vector2(0, 0);

        for (int i = 0; i < normals.Length; i++)
            normals[i] = new Vector3(0, 1, 0);

        _arcMesh.uv = uv;
        _arcMesh.normals = normals;

        GenerateMesh();
        GetComponent<MeshFilter>().mesh = _arcMesh;
    }

    void GenerateMesh()
    {
        float angle_lookat = 0;

        float angle_start = angle_lookat - _angleOfFire;
        float angle_end = angle_lookat + _angleOfFire;
        float angle_delta = (angle_end - angle_start) / _quality;

        float angle_curr = angle_start;
        float angle_next = angle_start + angle_delta;

        Vector3 pos_curr_min = Vector3.zero;
        Vector3 pos_curr_max = Vector3.zero;

        Vector3 pos_next_min = Vector3.zero;
        Vector3 pos_next_max = Vector3.zero;

        Vector3[] vertices = new Vector3[4 * _quality];
        int[] triangles = new int[3 * 2 * _quality];

        for (int i = 0; i < _quality; i++)
        {
            Vector3 sphere_curr = new Vector3(
                Mathf.Sin(Mathf.Deg2Rad * (angle_curr)),
                0,
                Mathf.Cos(Mathf.Deg2Rad * (angle_curr)));

            Vector3 sphere_next = new Vector3(
                Mathf.Sin(Mathf.Deg2Rad * (angle_next)),
                0,
                Mathf.Cos(Mathf.Deg2Rad * (angle_next)));

            pos_curr_min = transform.position + sphere_curr * _minDist;
            pos_curr_max = transform.position + sphere_curr * _maxDist;

            pos_next_min = transform.position + sphere_next * _minDist;
            pos_next_max = transform.position + sphere_next * _maxDist;

            int a = 4 * i;
            int b = 4 * i + 1;
            int c = 4 * i + 2;
            int d = 4 * i + 3;

            vertices[a] = pos_curr_min;
            vertices[b] = pos_curr_max;
            vertices[c] = pos_next_max;
            vertices[d] = pos_next_min;

            triangles[6 * i] = a;       // Triangle1: abc
            triangles[6 * i + 1] = b;
            triangles[6 * i + 2] = c;
            triangles[6 * i + 3] = c;   // Triangle2: cda
            triangles[6 * i + 4] = d;
            triangles[6 * i + 5] = a;

            angle_curr += angle_delta;
            angle_next += angle_delta;

        }

        _arcMesh.vertices = vertices;
        _arcMesh.triangles = triangles;
    }
}

```

---
Tags: unity, procedural-generation, 3d-meshes
---


# Question
Title: Ways to synchronize lists over the network?
Im working on a little plain c# gameserver using an ecs. It follows the principles of the client/server model architecture.

However im often running into the following problem, the server has one or multiple list where items are being added, updated or removed during the frame... and those changes should be broadcasted to all clients at the end of the frame.

So i require some sort of tracking mechanism, i need to track those added, updated or removed items till the end of the frame is reached to send packets.

How is this normally done ? Im glad for any help or tips :)

# Answer
> 1 votes
This is a great question actually, and something I've been struggling with a lot in any multi-player systems I've been trying to design.

I've come-up with the following scheme, but I haven't been able to battle-test it yet, and its definitely more geared towards 'slower' games like an RTS and not to shooters or fighting games.

Instead of making these changes immediately in a system I would introduce the concept of commands. Anything that changes that every client/server needs to know about generates a command. For example if the user presses the 'build' button a BuildCommand should be generated.

That BuildCommand should be sent to the server, the server should verify the requirements for this command (does the player have enough resources?) and then validate that command in a message to all listeners.

Clients handle new validation messages at the beginning of each frame. So the new entities/components are created at that time and present for simulation during the entire frame.

Using this scheme you never directly make changes to your entities/components without the others knowing about it.

To make this scheme work even better you could consider running all clients in lock-step and including a frame-number in the validation message so that every client handles a message in the same frame. Be careful though this will lead your game to run as slow as your slowest/laggiest client.

Not every change to an entity/component needs to generate a command. Sound systems, particle systems, graphical systems, etc.. can basically do their own thing because without the other clients needing to know about it. If your simulation is deterministic you will in general only need commands for things that happened because of user input.

Hope this helps! I'd love to know if you settle on this, or another, strategy and what your reasoning was.

# Answer
> 1 votes
This is usually handled by netcode, so there are already tools available so you don't have to think too much about how to handle your user input that thoroughly. I don't know if you're using Unity, but if you are, FishNetworking and Mirror are pretty solid tools for C#.

If you're still looking to do the netcode by yourself, you would need to implement a state system, based on ticks. The server would send the players the changes of the state of the objects within the system at a regular interval. The state memory is what will keep track of all the changes in the order that they happened so they can send that information at the interval you set up.

---
Tags: c#, networking, .net, entity-component-system
---


# Question
Title: Forcing animations to play in real time, ignoring time scale
When the character dies, an animation plays, and then the scene resets. What I want is that nothing moves/animates except the character and the life bar so I use `Time.deltaTime = 0;` to do this but it also stops my character and the life bar. Is there a way to force a specific animator to use real delta time?

# Answer
> 4 votes
So for those who have the same question, I've found what needs to be modified: On the animator Component, there is a drop-down menu named "Update Mode" which has three options:

* Normal (in-sync with Update method)
* Animate Physics (in-sync with FixedUpdate method)
* Unscaled Time (in-sync with Update method, but uses unscaled time)

Use the third one if you have the same problem as me. Also here's a picture from unity's documentation about the animator component:

EDIT: I don't know why is this happening but in my case I set `Time.timeScale` to `0.01f` instead of `0` and then everything worked as I excepted

---
Tags: unity, c#, animation, animator, deltatime
---


# Question
Title: Why am I getting this " Object reference not set to an instance of an object" error
```
private PlayerHealth ph;

void Start()
{
    ph = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>();
}

private void OnTriggerEnter2D(Collider2D other)
{
    if(other.tag == "PlayerFeet")
    {
        ph.TakeDamage();
    }
}

```

(My player prefab is with tag "Player")

https://prnt.sc/l4QgM7GShe3T

Error: NullReferenceException: Object reference not set to an instance of an object ThornController.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/ThornController.cs:48)

# Answer
I guess line 48 refers to `ph.TakeDamage()` so the problem is that there is no object in your scene with the "Player" tag. Are you sure you set the tag correctly? If the problem still persists please send some screenshots (from the error, the player, etc.)
> 0 votes

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


# Question
Title: Traversing distance over time in Blueprint graph
I am trying to make a set of simplified physics blueprints, very simplified, as an exercise.

I am keeping track of the position of an object and I would like to divide the distance it travels each frame by the time elapsed.

I tried something like this to get the time at the beginning of each TICK event and the time at the end of the same event, subtracting the initial time from the final time but all I get printed is 0.0

Any idea of what might be wrong? I tried using Get Time Seconds but I get the same result.

# Answer
As pointed out in the comments, the Delta Time in the Event Tick returns precisely the value I was looking for
> 0 votes

---
Tags: unreal-4, unreal, blueprints
---


title: Preventing high FPS in Unity

text:
# Question
Title: Preventing high FPS in Unity
We're using a game to control some electronics, sending commands on each `Update`.

We've tried setting the target framerate to 60:

```
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = 60;

```

However, when running, looking at the stats, the FPS sometimes spikes way above 60. I fear that once I build the game, it will run even faster and send commands faster than the controller receiving the commands can handle.

If possible, I would like to prevent the FPS from going above a certain value as reliably as possible (currently, with `targetFrameRate` at 60, it sometimes spikes to over 100, which hasn't been a problem *yet*).

I would prefer not to move the code that sends the messages to a corountine with `WaitForSecondsRealtime` for fear of possible problems that might create...

# Answer
> 1 votes
When you want to limit the rate in which your electronics receive messages, then instead of trying to solve this indirectly by limiting the framerate, I would recommend a more direct approach.

I assume that your code currently looks something like this:

```
class ElectronicsController: MonoBehaviour {

     void Update() {
          SendUpdateToDevice();
     }
}

```

I would solve this problem by adding two variables to the class: The desired time between updates and the last time the device was updated. Then I would add a check to Update to see how much time elapsed since the last update and if it is less than the current time plus the update interval. I would only do an update to the device when that's the case, and then also update the time of the last update:

```
class ElectronicsController: MonoBehaviour {

     public double updateInterval;
     private double lastUpdate;

     void Update() {
          if (lastUpdate < Time.realtimeSinceStartupAsDouble + updateInterval) {
              SendUpdateToDevice();
              lastUpdate = Time.realtimeSinceStartupAsDouble;
          }
     }
}

```

Note that this solution will result in less updates being sent than the update interval would imply, because each update where the time since the last update does not precisely matches the update interval will result in a couple milliseconds being lost. So it can be more understood as a guaranteed minimum time between updates rather than a consistent update interval.

I know nothing about your particular use-case, so I don't know how important it is for you to have a consistent update rate for your electronics. But if you need more consistency, then I would recommend this slightly more complicated code instead.

```
class ElectronicsController: MonoBehaviour {

     public double updateInterval;
     private double lastUpdate;

     void Start() {
         lastUpdate = Time.realtimeSinceStartupAsDouble
     }

     void Update() {

          bool needUpdate = false;

          while (lastUpdate < Time.realtimeSinceStartupAsDouble + updateInterval) {
              lastUpdate += updateInterval;
              needUpdate = true;
          }
          if (needUpdate) {
              SendUpdateToDevice();
          }
     }
}

```

You might notice that it does not set the last update to a new value but adds the interval to it instead. This results in more consistent time-keeping because excess time carries over to the next interval. The code will only skip updates if the game gets too slow to provide the desired update interval (this is the purpose of that `while` loop).

But also note that it might happen occasionally with this code that there are two updates which are in very short succession. This would happen if the new `lastUpdate` time is very close to the next update. You did not tell us if your electronics have some kind of command buffer which might overflow if it receives too many messages over time or if two fast messages are already a problem.

# Answer
> 0 votes
Why not use Unity's FixedUpdate function instead of update? This is based on physics updates per second which is found under settings. Set it to the desired "fps" and move your update logic into fixed update.

void FixedUpdate() { //your code here }

*written on phone, will clean up later*

# Answer
> 0 votes
I usually do something like this:

```
const float interval = 1f/60f;
private float x = interval;

void Update()
{
    x -= Time.deltaTime; // or use real delta time
    if (x <= 0)
    {
        // do something
        // reset x here or use another if statement outside of this one
        x += interval;
    }
}

```

so if you want to call a method 60 times per second then set `x` to `1f / 60f` and as I know it works pretty well if the fps is more than or equal to 60

---
Tags: unity
---


# Question
Title: My First Person Player Capsule Is Always About 6 inches Under The Floor
Here is the problem. This is the exterior of the hallway in which my player capsule is standing. Notice the bottom of the capsule poking through the floor.

This is the interior of the hallway, notice my player capsule standing there

And this is the view from the player's fps camera

I attached a mesh collider to the hallway's interior (named `SpaceshipMain_001-FBXFile2`) so it should simply follow the fbx's visual geometry right? Also I know it's not the player's capsule collider because the player's capsule collider actually extends beyond the bottom of the player capsule.

It's worth noting that the player capsule isn't "stuck." I can walk all over the hallway, it's just that part of the capsule protrudes below the bottom of the floor. I didn't even have a chance to tag the ground level yet to complete the ground check functionality for jumping.

So why is my player capsule sinking below the floor? Is there any way that I can actually see the mesh collider for `SpaceshipMain_001-FBXFile2` in case the collider isn't actually flush with fbx's geometry?

# Answer
I accidentally added 2 capsule colliders. I correctly added 1 to the `First Person Player` prefab object but then added a second one to `Cylinder`. I deleted the capsule collider attached to `Cylinder` and enlarged the capsule collider attached to `First Person Player` because it was way too small. The fact that it was too small caused the collision to happen several inches or maybe a foot above the bottom of the mesh in `First Person Player`
> 0 votes

---
Tags: unity, mesh, collider, meshcollider, character-controller
---


title: Why coroutine gets stopped?

text:
# Question
Title: Why coroutine gets stopped?
Here's my code:

```
IEnumerator SceneIsInChange(AsyncOperation SecondScene)
    {
        Snake.SetActive(true);
        print("1: " + FinalLoop);
        while (!SecondScene.isDone)
        {
            yield return null;
        }
        Snake.GetComponent<Animator>().SetBool("Loaded", true);
        print("2: " + FinalLoop);
        while (!FinalLoop)
        {
            yield return null;
        }
        print("3: " + FinalLoop);
        Time.timeScale = 1;
        Loading = false;
        LoadingScene = null;
    }

```

The problem is that the coroutine gets suspended before `print("2: " + FinalLoop);` line. (But `print("1: " + FinalLoop` works) So the problem should be in the first while loop but I can't find it. There's only one single code in that loop but it's supposed to "wait for one frame before resuming coroutine" so it shouldn't stop the coroutine.

Am I wrong about `yield return null;` meaning or the problem is somewhere else?

# Answer
Thanks to @Hesamom I found a solution:

All you need to do is to add `AsyncOperation.allowSceneActivation = false` so it won't activate itself right after loading, and then change it to `true` once you did all you wanted (usually at the last line of coroutine)
> 1 votes

# Answer
Coroutines are stopped when their corresponding game object is deactivated or destroyed, regarding your code logic, it's possible after the scene change, the game object in previous scene as well as Its coroutine are destroyed

Your assumption about yield return null is also true
> 2 votes

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


# Question
Title: Understanding use of "localUp" in planet mesh generation code
I'm following a tutorial on YouTube about procedural generation of planets. I'm puzzled in some aspects of the code shown. If any of you could explain the following points, I would be very pleased.

First take a look at the algorithm, written in C# for Unity:

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

public class TerrainFace {

    Mesh mesh;
    int resolution;
    Vector3 localUp;
    Vector3 axisA;
    Vector3 axisB;

    public TerrainFace(Mesh mesh, int resolution, Vector3 localUp)
    {
        this.mesh = mesh;
        this.resolution = resolution;
        this.localUp = localUp;

        axisA = new Vector3(localUp.y, localUp.z, localUp.x);
        axisB = Vector3.Cross(localUp, axisA);
    }

    public void ConstructMesh()
    {
        Vector3[] vertices = new Vector3[resolution * resolution];
        int[] triangles = new int[(resolution - 1) * (resolution - 1) * 6];
        int triIndex = 0;

        for (int y = 0; y < resolution; y++)
        {
            for (int x = 0; x < resolution; x++)
            {
                int i = x + y * resolution;
                Vector2 percent = new Vector2(x, y) / (resolution - 1);
                Vector3 pointOnUnitCube = localUp + (percent.x - .5f) * 2 * axisA + (percent.y - .5f) * 2 * axisB;
                Vector3 pointOnUnitSphere = pointOnUnitCube.normalized;
                vertices[i] = pointOnUnitSphere;

                if (x != resolution - 1 && y != resolution - 1)
                {
                    triangles[triIndex] = i;
                    triangles[triIndex + 1] = i + resolution + 1;
                    triangles[triIndex + 2] = i + resolution;

                    triangles[triIndex + 3] = i;
                    triangles[triIndex + 4] = i + 1;
                    triangles[triIndex + 5] = i + resolution + 1;
                    triIndex += 6;
                }
            }
        }
        mesh.Clear();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.RecalculateNormals();
    }
}

```

I will briefly explain the code:

The main objective is to generate 6 Meshes which will form a cube, and then by normalization of vectors generate a sphere. This algorithm takes a "Resolution" value, which will determine the how detailed the sphere will be. Each mesh is conformed by vertices (Vector) which will guide the program to make the triangles that will build the sphere.

My question regard in this part of the code:

```

Mesh mesh;
    int resolution;
    Vector3 localUp;
    Vector3 axisA;
    Vector3 axisB;

    public TerrainFace(Mesh mesh, int resolution, Vector3 localUp)
    {
        this.mesh = mesh;
        this.resolution = resolution;
        this.localUp = localUp;

        axisA = new Vector3(localUp.y, localUp.z, localUp.x);
        axisB = Vector3.Cross(localUp, axisA);
    }

```

I do not understand exactly what is `localUp` and the pair of axes it generates from it.

So the questions would be the following:

* What are `localUp`, `axisA` and `axisB`?
* What are they doing?
* If they have values (coordinates or something like that) where are they getting those.?

# Answer
This code is establishing a local coordinate system in which to perform the mesh generation.

When we want to generate the 6 cube faces, we need to iterate over the rows and columns of a grid to place each vertex. Each time we loop, we need to step "across" a row, or "along" a column of the grid. But since the 6 faces are oriented in different directions, it initially looks like we might have to write 6 versions of the code!

* One for the "**right**" face (facing **x+**), where:
    + moving "across" means stepping in the **z+** direction,
    + moving "along" means stepping in the **y-** direction
* One for the "**top**" face (facing **y+**), where:
    + moving "across" means stepping in the **x+** direction,
    + moving "along" means stepping in the **z-** direction
* One for the "**front**" face (facing **z+**), where:
    + moving "across" means stepping in the **y+** direction,
    + moving "along" means stepping in the **x-** direction
* One for the "**left**" face (facing **x-**), where:
    + moving "across" means stepping in the **z-** direction,
    + moving "along" means stepping in the **y-** direction
* One for the "**bottom**" face (facing **y-**), where:
    + moving "across" means stepping in the **x-** direction,
    + moving "along" means stepping in the **z-** direction
* One for the "**back**" face (facing **z-**), where:
    + moving "across" means stepping in the **y-** direction,
    + moving "along" means stepping in the **x-** direction

(If these definitions for "across" and "along" look arbitrary: they are indeed. There are many possible ways to parametrize 6 grids around a cube - what I've shown above is the convention that the code from the video happens to use)

We don't want to write this 6 times, so instead we make variables to store the different directions that we need to combine to make our vertex positions:

* The direction this side of the cube "faces" we call `localUp`
* The direction "across" a row we call `axisA`
* The direction "along" a column we call `axisB`

`localUp` would be passed to us as a constructor argument. So somewhere else in the code there's probably something that looks like this (or something to the same effect):

```
//                                      localUp          value of localUp
face[0] = new TerrainFace(mesh[0], res, Vector3.right);   // ( 1,  0,  0)
face[1] = new TerrainFace(mesh[1], res, Vector3.up);      // ( 0,  1,  0)
face[2] = new TerrainFace(mesh[2], res, Vector3.forward); // ( 0,  0,  1)
face[3] = new TerrainFace(mesh[3], res, Vector3.left);    // (-1,  0,  0)
face[4] = new TerrainFace(mesh[4], res, Vector3.down);    // ( 0, -1,  0)
face[5] = new TerrainFace(mesh[5], res, Vector3.back);    // ( 0,  0, -1)

```

Each time, we're passing a unit vector pointing directly along one of the 6 cardinal directions in 3D.

We can make the "across" direction `axisA` by "swizzling" this vector - swapping the value in each component with the next one, wrapping around. So `(0, 1, 0)` becomes `(1, 0, 0)` and `(1, 0, 0)` becomes `(0, 0, 1)`.

You can see that if we started out with a cardinal direction, we get back a different cardinal direction (unit length, and perpendicular to what we started with). So that gives us a vector we can use as one direction across our grid.

To get the "along" direction `axisB`, we take the cross product of the two vectors we have so far. This has a nice property: the cross product of two vectors is always perpendicular to both (so in this case, it points along the remaining direction of our grid). And if those vectors were already perpendicular to each other and unit length, our output will be too.

Now, there are two possible vectors perpendicular to our two starting vectors (one `-1` times the other), and which one we get depends on the order of the arguments to `Cross()`. By using one standard order (`localUp` cross `axisA`), we ensure the grid is oriented so that the triangles we're building always point outward, rather than inward. That's why we're using the cross product here instead of another swizzle, which might sometimes pick the wrong perpendicular out of our two choices.

Now that we have these three vectors - what we'd call a "local coordinate basis", we can express the rest of our mesh generation in terms of these vectors: the vertex at coordinates `(u, v)` in our grid should be placed at `localUp + u * axisA + v * axisB`, and this works on all 6 faces, so we don't have to write 6 versions of the function.
> 2 votes

# Answer
I'm not so sure about my answer but here's what I know:

localUp (shown in green) is a Vector - that is perpendicular to the screen - which changes when the object rotates.

axisA is just a copy of localUp but the x and y values are swapped to get the red Vector and axisB is just the cross product of localUp and axisA to find the blue Vector
> -1 votes

---
Tags: unity, c#, algorithm, procedural-generation, planet
---


# Question
Title: Unity how to make raycaster test only against collider in frustum
I'm working on a scene with thousands of object wich have all a collider associated. I'm just testing if my mouse is on top of any collider in a 2D space. The raycasting operation is taking a lot of time (2 ms for a thousand objects) I suspect the stock unity raycaster is testing against every collider even if they are not inside the frustum any way to change that while still using unity raycasting solution?

# Answer
> 2 votes
Unity definitely has some spatial partitions of their own under the hood of all their physics and raycasting systems, it's very unlikely Unity's actually doing a collision check with every single collider in your scene whenever you cast a ray.

How much you optimize from here depends on how constrained your problem is, and how much work you want to put into creating new systems with those constraints in mind.

##### Here's a couple of suggestions

###### 3D raycasting

If you have to keep things in 3D with proper raycasting, try reducing the complexity of your colliders, avoid using MeshColliders in favour of box and sphere colliders. Try adding all the objects that you want to raycast against to their own separate layer and filtering out all other layers when you do a cast. Prefer RaycastNonAlloc to RaycastAll so that you're not allocating new memory that will have to be cleaned up.

###### 2D raycasting

If you're doing everything in 2D, axis-aligned space, then you don't need to use raycasting at all. You can prefer 2D overlap tests, by leveraging Physics2D.OverlapPointNonAlloc or by creating your own simple tests (and spatial partitions). Again, prefer box colliders (AABB tests) and circle colliders over complex colliders, and employ filters on raycast calls.

###### Custom, Jobified

If none of this is enough, raycasting is necessary to your game and you can't amortize the costs via creative design somehow... then I'd recommend creating your own system which collects unity transform and collider data into some NativeArrays, then you can do your own raycast-like thing off the main thread, leveraging multiple cores, cache coherence and the burst compiler.

---
Tags: unity, raycasting, collider, frustum
---


title: Save Texture2D to file in Monogame

text:
# Question
Title: Save Texture2D to file in Monogame
I'm working on a tilesheet builder tool for my game to speed up tile creation, and I need to save a generated texture2D as a png. I've tried using the .SaveAsPng function but it isn't implemented in Monogame.

Is there any way around this in monogame?

**EDIT:** I've tried this:

```
private void SaveTextureData(RenderTarget2D texture, string filename)
    {
        byte[] imageData = new byte[4 * texture.Width * texture.Height];
        texture.GetData<byte>(imageData);

        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        System.Drawing.Imaging.BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
        IntPtr pnative = bmData.Scan0;
        System.Runtime.InteropServices.Marshal.Copy(imageData, 0, pnative, 4 * texture.Width * texture.Height);
        bitmap.UnlockBits(bmData);
        bitmap.Save(filename);
    }

```

but it's giving a weird output, and I don't know why: https://i.stack.imgur.com/dGTxr.png

Thanks for any help!

# Answer
Your code seems like it would work to me, but there are two things you would need to verify:

1. Is the render target's format RGBA? Or is it just RGB?
2. Are you trying to save as a PNG or a BMP? Bitmap.Save() defaults to a BMP image. To save as a PNG, you need to use this overload.

Also, if MonoGame is using the OpenGL renderer, I remember with OpenTK the Bitmap internal format was actually BGRA or something similar (even when specifying PixelFormat.Format32bppArgb), so the byte order may be messed up.
> 3 votes

# Answer
```
 private void SaveTextureData(RenderTarget2D texture, string filename)
        {
            byte[] imageData = new byte[4 * texture.Width * texture.Height];
            texture.GetData<byte>(imageData);

            //Add this
            for (int i = 0; i < imageData.Length; i+= 4)
            {
                byte b = imageData[i];
                byte g = imageData[i+1];
                byte r = imageData[i+2];

                imageData[i] = r;
                imageData[i + 2] = b;
            }

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            System.Drawing.Imaging.BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
            IntPtr pnative = bmData.Scan0;
            System.Runtime.InteropServices.Marshal.Copy(imageData, 0, pnative, 4 * texture.Width * texture.Height);
            bitmap.UnlockBits(bmData);
            bitmap.Save(filename);
            bitmap.Dispose();
        }

```
> 0 votes

---
Tags: xna, monogame, windows
---


# Question
Title: AnimatorUpdateMode.UnscaledTime not working
So using what I found on my other question, I wrote this code:

```
private void Die()
    {
        Animator.updateMode = AnimatorUpdateMode.UnscaledTime;
        EllaAnimator.updateMode = AnimatorUpdateMode.UnscaledTime;
        for (int i = 0; i < Mathf.CeilToInt(LastRemainedHearts / 2f); i++)
        {
            ParentMiddleBelt.transform.GetChild(i).GetChild(1).GetComponent<Animator>().updateMode = AnimatorUpdateMode.UnscaledTime;
            ParentMiddleBelt.transform.GetChild(i).GetChild(1).GetComponent<Animator>().enabled = true;
        }
        Time.timeScale = 0;
        EllaAnimator.SetInteger("RunTo", 8);
        EllaAnimator.SetInteger("PushToward", 5);
        EllaAnimator.SetBool("Death", true);
    }

```

as you can see, there are three animators which I'm trying to change their update mode:

* Animator: the animator on this object
* EllaAnimator: the player's animator
* ParentMiddleBelt.transform.GetChild(i).GetChild(1).GetComponent(): the animator attached to "health bullet"s (see the pictures below)

Animator and EllaAnimator run perfectly fine but for some reason, the third one doesn't.

I used `print()` and inspector to see if the UpdateMode is being changed or not and as it turned out, it does change. So my problem is that regarding UpdateMode being set to unscaled time, why it still doesn't play?

side note: `ParentMiddleBelt` is an empty game object that stores clones of belt(middle) prefab

# Answer
I was trying to mess around a bit and found the answer:

The `ParentMiddleBelt.transform.GetChild(i).GetChild(1).GetComponent<Animator>().enabled = true;` line should have come before `ParentMiddleBelt.transform.GetChild(i).GetChild(1).GetComponent<Animator>().updateMode = AnimatorUpdateMode.UnscaledTime;`

It seems changing properties of a disabled component have no effect
> 0 votes

---
Tags: unity, animator, time
---


title: Unreal Engine: I cant login with EOS

text:
# Question
Title: Unreal Engine: I cant login with EOS
I am giving a shot at trying out EOS. I am running into an error while trying to log in. I have a product and application set up in the online dev portal. Dont know if I have everything right though. I entered all the IDs and secret values into their appropriate places in the EOS plugin area in settings.

I have this in my DefaultEngine.ini

```
[OnlineSubsystemEOS]
bEnabled=true
[OnlineSubsystem]
DefaultPlatformService=EOS
[/Script/Engine.GameEngine]
+NetDriverDefinitions=. (DefName="GameNetDriver",DriverClassName="OnlineSubsystemEOS.NetDriverEOS",DriverClassNameFallback="OnlineSubsystemUtils.IpNetDriver")
[/Script/OnlineSubsystemEOS.NetDriverEOS]
bIsUsingP2PSockets=true

```

And this is how I am logging in

```
FOnlineAccountCredentials Credentials;
Credentials.Id = FString();
Credentials.Token = FString();
Credentials.Type = FString("accountportal");

Identity->OnLoginCompleteDelegates->AddUObject(this, &UEOSLibrary::OnLoginComplete);
Identity->Login(0, Credentials);

```

When I hit login I get a webpage that opens and asks if I want to allow access. I hit accept and what happens is the callback is never called to indicate completion. And the logs indicate that I might be missing something. What verification code and where??

> LogEOSSDK: LogEOSAuth: NewClientToken: Client ClientId: xyz...kJK Access\[Expires: 2022.02.22-22.32.12 Remaining: 7200.67\] State: Valid LogEOSSDK: LogEOSAuth: xyz...kJK result: eyJ...cwQ LogEOSSDK: LogEOSAuth: Launching platform browser for account portal LogEOSSDK: Warning: LogEOS: Error response received from backend. ServiceName=\[OAuth\], OperationName=\[TokenGrant\], Url=\[\], HttpStatus=\[400\], ErrorCode=\[errors.com.epicgames.account.oauth.authorization\_pending\], NumericErrorCode=\[1012\], ErrorMessage=\[The authorization server request is still pending as the end user has yet to visit and enter the verification code.\], CorrId=\[EOS-cuMGvKq4S3GvWUBNVjIbnw-ZJtD\_z3YTx62TxiNJ8Yr2g-ug4LfijbR8Cx2eeMp7E3fA\] LogEOSSDK: LogEOSAuth: NewUserToken: User ClientId: xyz...kJK AccountId: 5f2...f59 Access\[Expires: 2022.02.22-22.32.23 Remaining: 7200.31\] Refresh\[Expires: 2022-08-21T20:32:23.313Z Remaining: 15552000.31\] State: Valid LogEOSSDK: LogEOSAuth: GenerateUserAuth success LogEOSSDK: LogEOSAuth: login/queryuserinfo success LogEOSSDK: LogEOSAuth: Login Tasks Complete: 0 LogEOSSDK: LogEOSPresence: Updating Presence to Online. LocalUserId=\[5f2...f59\] RichText=\[\]

# Answer
Turns out you cant be running the game for it to work. Which is what I was doing. Running as a standalone game I was able to successfully log in.
> 0 votes

---
Tags: c++, multiplayer, unreal-4, online
---


# Question
Title: Wait for a function to return value without impacting framerate
I'm looking to do some possibly heavy calculation in my game. An agent in my game needs to evaluate up to 1000 objects while performing heavy calculations to select his next job.

I want to either offload this to a separate thread (and wait for it to finish) without blocking and causing stuttering on the main Unity thread, or I'd like to use coroutines to spread the heavy calculations over multiple frames.

```
public static Job RequestJob()
{
    Job suitableJob = JobManager.FindSuitableJob(Jobs);
    if (suitableJob != null)
    {
        DequeueJob(suitableJob as PlantCutJob);
        return suitableJob;
    }

    return null;
}

```

I'd like the `JobManager.FindSuitableJob` method to be spread during several frames or multithreaded. This is the method:

```
public static FindSuitableJob (List<Job> jobs)
{
    for (int i = 0; i < jobs.Count; i++)
    {
        if (jobs[i].CheckRequirements())
        {

            return jobs[i];
        }
    }

    return null;
}

```

I have tried making a couroutine, which seems like exactly what I need, but I need to call it outside of a `MonoBehavior` (from just a regular class) which I'm not sure is possible without some heavy workarounds. I have no experience with coroutines or multithreading in Unity and C# so any advice is appreciated.

# Answer
> 0 votes
In my game, I needed to have a character look for available jobs to do, but I didn't want it to evaluate too many jobs in one frame.

My solution was to start a `RequestJob` coroutine which takes an `Action<Job>` as a parameter, and when it's found a job it calls this callback and passes in the job it found. The script from which you call the coroutine subscribes to this callback and does something after the job is received.

Of course, inside the coroutine, I can `yield return null` if too many jobs have been evaluated in one frame.

---
Tags: unity, multithreading, coroutines
---


# Question
Title: How to make a shadow-casting day/night system in 2D URP?
I am trying to achieve a day/night lighting system similar to the game RimWorld. Short preview of what I want can be seen here: https://giphy.com/gifs/VgzcwtjueP7BrYSrXe

Instead of using Global Light 2D, for this sort of system, I assume I need to use Directional Lights or Point Lights.

How can I make it that no matter the map size, the perspective of the light will always remain similar? (looking like the sun rises at east and sets at west)

More importantly, how can I cast shadows for objects in my world? There is a shadow caster 2D component, but most of my shadow casting objects are tiles on a tilemap, which are super light in performance.

I've been able to add ShadowCaster2D to a GameObject, and then attach that GameObject to each individual tile (that needs to cast shadows, such as walls and trees), and it just seems to crush performance. Should I use the built-in ShadowCaster2D for this, or is there another way that is more performant?

# Answer
> 0 votes
I've solved the daylight cycle problem and all my other lighting problems by using the following package from the Unity asset store: Smart Lighting 2D

---
Tags: unity, 2d, lighting, shadows, unity-urp
---


title: How to clear Addressables Cache?

text:
# Question
Title: How to clear Addressables Cache?
I am loading my assets and tile information through YAML files.

While working on the game, I need to quickly change some values and test them in-game, and I can re-load the YAML information without having to restart.

In the old Resources system, this would be done by using AssetDatabase.Refresh(), after which I could re-load the YAML files and get new data. However, Addressables handles this differently. Based on some research and this forum, I've tried the following two options:

```
Addressables.ClearDependencyCacheAsync(allLocations);
Caching.ClearCache();

```

Sadly, neither of these has worked.

How can I clear the cached Addressables data so I can reload it?

# Answer
> 1 votes
I'm not sure if the Unity team has done some updates to addressables, but reloading them seems to work now. I simply clear out my existing `Dictionary` full of loaded assets, and just call the `LoadAssets` method again.

This has been tested in version `2021.2.11f1`.

---
Tags: unity, c#, assets, asset-management, addressable
---


# Question
Title: How to get the physics right, with each paddling of a canoe
I want to create a canoe game, and want the canoe behaviour to be realistic for each paddling. How can I get the paddling effect on the boat right? (I think there is a forward force, plus a sharp rotation force)

These two are examples of canoe games with good physics with each paddling on the canoe:

https://www.google.com/doodles/slalom-canoe-2012

https://apps.apple.com/de/app/canoe-race/id1555043035

* Do I need to add separate Force and Torque, for each paddle?
* Do I need to do it once only or like continuously for a duration of time?
* Do I need to apply the forces with a constant value of force, or do I need to decrease it over time until it fades out?
* Do I need to AddForceOnPosition or just normally apply the force on the default center of mass?
* Do I need to apply force in the direction of the canoe (considering its rotation), or do I need to apply it in a direction regardless of its rotation?
* Is there any other force that I'm missing, besides the forward force, and a sharp rotation force?
* Do I need to adjust drags in any way to get it right?

I'm trying to get it right by trying different parameters, but if you know how the physics actually work, or have any hint about that, that'd help me a lot.

# Answer
> 1 votes
I can't say I've implemented canoe physics before, but you seem to have covered all the major points. In a top down (2D) canoe sim there are basically two forces the a person is in control of (that doesn't include waves or current).

##### the stroke

First there's the force that is added on the stroke -- when a paddle first penetrates and then displaces water in a desired direction. This isn't instantaneous, but perhaps could be abstracted as instant, especially in a more fast-paced arcadey game. Personally I would play around with using an AnimationCurve to test out different force multipliers over time. I imagine the force over time might look something like a standard sound envelope.

This force isn't centered in respect to the boats center of mass, and will therefore lead to torque **about** the paddle. I would try `AddForceAtPosition(paddleForce, paddlePos)`. Hopefully Unity's sim will feel right, but if it doesn't, then I would play around with adding torque artificially.

#### the drag

Then there's the asymmetric drag when a paddle is kept in the water which results in torque and a deceleration. This has the effect of rotating the boat **about** the paddle. In Unity you could model this as a small force going against the direction of the boat at the point of paddle insertion (try `AddForceAtPosition` where the force is some percentage of the current velocity).

There's also always going to be a passive linear inertia on the boat itself, irrespective of whether a paddle is in the water or not, this won't lead to torque however.

##### closing remarks

Leverage Unity's generic physics sim to handle as much as you can, but don't worry about being physically accurate. If you can't get a physically based sim to do what you want, then don't be scared to start adding artificial forces, changing masses or manually setting positions to make system feel better, and work better for you design.

---
Tags: unity
---


# Question
Title: Floating Health Bar Not Displaying Correctly
Currently working on an overhead display of the health bar and ran into this problem and I cannot seem to figure out why its not working correctly. When the player has less than `entity.health.max` the scale is set to 0 instead of the calculated percent.

Code:

```
private void SetHealth(int amount)
{
  currentHealth = amount;
  float displayedHealth = currentHealth / entity.health.max;
  healthBar.transform.localScale = new Vector3(displayedHealth, 1, 1);
}

```

I also tried the following with the same results

```
float displayedHealth = Mathf.Lerp(0, 1, currentHealth / entity.health.max);

```

# Answer
> 1 votes
The solution was to cast both `int` as `float`

`float displayedHealth = (float)currentHealth / (float)entity.health.max;`

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


# Question
Title: Architecture advice: a combo manager with combo displayed on the GUI in Unity
I would like some advice on the architecture I am using, and if there's perhaps a better way to go about doing this / if I am over-complicating things.

I have a combo meter go up on the screen based off successive hits. My high level design is like this:

* `DamageCalculator.cs` : a static class that is used on every successful hit
* `StatsManager.cs` : a singleton that contains a lot of fields relating to stats like `comboCount` (an int that is the current number of combos)
* `ComboGUI.cs` : a component that updates the GUI

The combo counter UI works as follows:

1. When the player successfully hits an enemy more than once, `DamageCalculator.cs` triggers an event `OnCombo()`
2. `StatsManager.cs` is subscribed to the `OnCombo` event, and when this triggers it does `comboCount++`
3. `ComboGui.cs` is also subscribed to the `OnCombo` event, and when this triggers, it updates the UI to show the value of `comboCount`

The code:

DamageCalculator.cs

```
public static Action OnCombo;

// ...

public static void CalculateDamage(...)
{
  // ...
  if ( combo )
  {
    // ...
    OnCombo();
  }
  // ...
}

```

StatsManager.cs

```
public int comboCount

private void OnEnable()
{
  CalculateDamage.OnCombo += IncrementCombo;
}

private void OnDisable()
{
  CalculateDamage.OnCombo -= IncrementCombo;
}

private void IncrementCombo()
{
  comboCount++;
}

// ...

```

ComboGUI.cs

```

private TextMeshProUGUI tmp;

private void OnEnable()
{
    DamageCalculator.OnCombo += SetCombo;
}

private void OnDisable()
{
    DamageCalculator.OnCombo -= SetCombo;
}

// ...

private void SetCombo()
{
    string comboText = StatsManager.Instance.comboCount + " COMBO";
    tmp.text = comboText;  // tmp is a TextMeshProUGUI
}

```

What makes me go like there is probably a better way for this, is that I have no guarantee which events in `StatsManager` and `ComboGUI` will get triggered first when OnCombo fires. So I wonder if there is a pattern or better way of doing this, since it seems to be a pretty "routine" thing in games?

# Answer
> 1 votes
The first thing that hits me is singleton and static classes. You should use them only if it's necessary. Maby it is in your case.

The reason we usually (not always) stay away from statics and singletons is because it easily violates the **SRP** (single-responsibility principle).

Link to SRP

**Composite pattern** seems like a promising idea in your case when dealing with combos. It's a step-by-step pattern which gives more control of each step.

Link to Composite pattern

From what I can see in your code you're trying to use loosely coupled classes. That's great. Follow **DRY** (Don't repeat yourself) principle.

Link to DRY

This is not an exact answer, but I hope it provides an idea of what could lay a solid foundation to your project.

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


# Question
Title: Unity Runtime Surface Snapping (Like Shift+Cntrl in Editor)
I am trying to allow the user of my VR game to move objects around using a pointer, then when holding down a button, snap to a grid and align to the highest surface, essentially replicating the Editor behavior or holding down shift+control and moving around a transform gizmo. (Try it, it's fun!)

I have the grid part down, but can't wrap my head around how to do the surface snapping. Here is the code I have so far. I would appreciate any and all help!

```

// offsetPos is where the VR pointer is.
Vector3 offsetPos = pointer.objectControlPoint.transform.position + cursorOffset;
Vector3 newPos;

if (isSnapping) // Snap to ground code.
{
// I read previously to do this up then down thing, but It's not working as expected
    RaycastHit groundHit = new RaycastHit();
    if (Physics.Raycast(selectedObject.transform.position, Vector3.down, out groundHit))
    {
         RaycastHit objectHit = new RaycastHit();
         if (Physics.Raycast(groundHit.point, Vector3.up, out objectHit))
         {
                Vector3 snapDiff = groundHit.point - objectHit.point;
                snapYPos = snapDiff.y + (selectedObject.collider.bounds.extents.y);
          }
    }
      // worldGrid is a monoBehavior on another object, and gridCellSize is just a float
      float gridPosX = Mathf.Floor(offsetPos.x / worldGrid.gridCellSize) * worldGrid.gridCellSize;
      float gridPosZ = Mathf.Floor(offsetPos.z / worldGrid.gridCellSize) * worldGrid.gridCellSize;
      newPos = new Vector3(gridPosX, snapYPos, gridPosZ); // Sets the target position to the nearest grid cell, with a Y of the snap position.
}
else // If not in snap mode, set target position to just the VR cursor.
{
       newPos = new Vector3(offsetPos.x, offsetPos.y, offsetPos.z);
}

// I know lerp might not be the most efficient, but I like the smooth effect, and it looks good when snapping to the grid...
selectedObject.transform.position = Vector3.Lerp(selectedObject.transform.position, newPos, movementLerpSpeed * Time.deltaTime);

```

The objects I need to be snapping all are different sizes and have their origins in different places, but all do have appropriate box colliders.

Thanks so much!

# Answer
To answer my own question from a while ago, the solution was to use Raycasting to set the position on the ground like in the code above, but then using Transform.Translate to move the object upwards to compensate for the center point not always being at the bottom.
The challenge there is to find the amount to translate by. This can be achieved by using Bounds.Extents.y.
> 1 votes

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


title: SDL2 Mouse Camera Movement

text:
# Question
Title: SDL2 Mouse Camera Movement
I've been trying to build a 3D camera system in SDL2 with OpenGL so that I can use the mouse to look around. With glfw it's possible to trap the mouse in the window, and keep it centered with a library call, so I was looking for something equivalent in SDL2.

In order to process mouse events in the main loop I'm checking for `SDL_MOUSEMOTION`. Searching around the web, I've found that SDL2 allows for mouse trapping with the call to `SDL_SetRelativeMouseMode()`. With this call, though, the mouse is trapped and limited to move within the window, and not just at the center. This causes the mouse to be able to move from the top left corner at `(0,0)` to the bottom right corner at `(WIDTH,HEIGHT)`, and not any further.

I've tried to fix this by repositioning the cursor position with `SDL_WarpMouseInWindow()`, but this generates a `SDL_MOUSEMOTION` event as well, basically resetting any movement I might've tried to do.

How can I fix this?

# Answer
> 4 votes
So your issue seems to be that you are getting invalid data because you are calculating the motion amount yourself. That won't work, since the mouse won't move past the window's border.

So, indeed, start with `SDL_SetRelativeMouseMode(SDL_TRUE);`. This will make sure that you get relative motion data in `SDL_MOUSEMOTION` events.

Now, in your event loop, instead of calculating the offsets yourself, simply use `event.motion.xrel` and `event.motion.yrel` which provide valid offset data even at the border of the window, since you told SDL to use relative mouse mode.

# Answer
> 1 votes
You've to `SDL_SetRelativeMouseMode(SDL_TRUE);` then create static `xpos` and `ypos` variables

```
case SDL_MOUSEMOTION:
// assuming I have a 800x600 Game window, then the result would be:
    static int xpos = SCR_W / 2; // = 400 to center the cursor in the window
    static int ypos = SCR_H / 2; // = 300 to center the cursor in the window
    xpos += e->motion.xrel;
    ypos += e->motion.yrel;
    ...

```

When the Mouse is moved, they're incremented **infinitely** by how much they're moved relatively from the center which can be negative/positive values.

So, You can use these variables for your **3D** Camera to look infinitely around the scene.

# Answer
> 0 votes
This is how i handled mouse events. Maybe it can help you to develop your own solution. This are snippets from my first try of getting SDL2 and OpenGL running.

```
// Setup
bool Mousefirst  = true;
bool MouseMotion = false;

// Mouse moved ?
if (Event.type == SDL_MOUSEMOTION) {
  MouseMotion = true;
  if (!Mousefirst) {
    MouseRelX = Event.motion.xrel;
    MouseRelY = Event.motion.yrel;
  } else {
    Mousefirst = false;
    MouseRelX = 0;
    MouseRelY = 0;
  }
}

```

And here is how the mouse motion was processed: (MouseSense is a float to regulate the sensitivity of your mouse)

```
if (MouseMotion) {
  MouseMotion = false;
  CameraYaw += MouseRelX * MouseSense;
  CameraPitch += MouseRelY * MouseSense;

  // Stuff to limit the camera angles ...

  // Stuff to create the camera viewing matrix ...
}

```

BTW: MouseFirst = true prevents a sudden jump after SDL\_SetRelativeMouseMode(SDL\_TRUE)

# Answer
> 0 votes
the answer of user35344 works nicely but I had some problems getting xrel and yrel values at the borders of window. It worked for me when I added this.

```
SDL_SetHintWithPriority(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1", SDL_HINT_OVERRIDE);

```

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


# Question
Title: Unity DOTS/ECS: Spawning entity programmatically at specific location
I'm interested in learning how to spawn entities from prefabs (from a monobehaviour) at random locations in a scene on a key press. Similar to this video, I'd like to instantiate these objects whenever the player presses a button. Is there a way to randomize the position of the object each time a new one is created?

# Answer
> 4 votes
After you instantiate the entity, try:

```
Entity newEntity =  //TODO: use your newly instantiated entity
//probably set this once when the system is created, or at least outside the Entites.ForEach() loop, otherwise values will always be the same
Random ranGenerator = Random.CreateFromIndex(123456789);

float3 spawnBounds = new float3(10, 10, 10);
float3 ranSpawnPos = ranGenerator.NextFloat3(-spawnBounds, spawnBounds);
Translation ranSpawnTranslation = new Translation() {Value = ranSpawnPos};

EntityManager.SetComponentData(newEntity, ranSpawnTranslation);

```

##### a side note

In general, I would be careful about starting with DOTS stuff if you're new to Unity or programming. Not necessarily because it's harder, but just because there's less documentation out there so it'll be harder to learn and find resources to get over hurdles... that being said, DOTS is very fun :)

---
Tags: unity, entity-component-system, unity-dots
---


title: Help to compose the script correctly

text:
# Question
Title: Help to compose the script correctly
Good afternoon. I have a problem: creating a color setting for the car. I created several Primary game objects, hung my own color on each one. I wrote a simple script, with 6 buttons, each button activates its Primary. There are no errors in the console, but changing colors does not work. I do not know what the reason is

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

public class ColorSettings : MonoBehaviour
{
    public GameObject Car;
    [Header("ColorSettings")]
    public GameObject Primary1;
    public GameObject Primary2;
    public GameObject Primary3;
    public GameObject Primary4;
    public GameObject Primary5;
    public GameObject Primary6;

    private void Awake()
    {
        Primary1.gameObject.SetActive(true);
        Primary2.gameObject.SetActive(false);
        Primary3.gameObject.SetActive(false);
        Primary4.gameObject.SetActive(false);
        Primary5.gameObject.SetActive(false);
        Primary6.gameObject.SetActive(false);
    }

    public void Color1Button()
    {
         Primary1.gameObject.SetActive(true);
         Primary2.gameObject.SetActive(false);
         Primary3.gameObject.SetActive(false);
         Primary4.gameObject.SetActive(false);
         Primary5.gameObject.SetActive(false);
         Primary6.gameObject.SetActive(false);
    }
    public void Color2Button()
    {
         Primary1.gameObject.SetActive(false);
         Primary2.gameObject.SetActive(true);
         Primary3.gameObject.SetActive(false);
         Primary4.gameObject.SetActive(false);
         Primary5.gameObject.SetActive(false);
         Primary6.gameObject.SetActive(false);
    }
    public void Color3Button()
    {
        Primary1.gameObject.SetActive(false);
        Primary2.gameObject.SetActive(false);
        Primary3.gameObject.SetActive(true);
        Primary4.gameObject.SetActive(false);
        Primary5.gameObject.SetActive(false);
        Primary6.gameObject.SetActive(false);
    }
    public void Color4Button()
    {
        Primary1.gameObject.SetActive(false);
        Primary2.gameObject.SetActive(false);
        Primary3.gameObject.SetActive(false);
        Primary4.gameObject.SetActive(true);
        Primary5.gameObject.SetActive(false);
        Primary6.gameObject.SetActive(false);
    }
    public void Color5Button()
    {
        Primary1.gameObject.SetActive(false);
        Primary2.gameObject.SetActive(false);
        Primary3.gameObject.SetActive(false);
        Primary4.gameObject.SetActive(false);
        Primary5.gameObject.SetActive(true);
        Primary6.gameObject.SetActive(false);
    }
    public void Color6Button()
    {
        Primary1.gameObject.SetActive(false);
        Primary2.gameObject.SetActive(false);
        Primary3.gameObject.SetActive(false);
        Primary4.gameObject.SetActive(false);
        Primary5.gameObject.SetActive(false);
        Primary6.gameObject.SetActive(true);
    }
}

```

I made changes to the script, but now there is a problem again. Game objects are activated only after restarting the script

# Answer
> 1 votes
have you tried controlling the color change with a switch statement or if? and bool, maybe your program needs a way to verify if a color was selected and what to do when it is? also make sure you linked the right buttons for the job, especially if you use the new unity system input is slightly different then the old one

# Answer
> 1 votes
Your code is excessively verbose, and this is likely to lead to unexpected behaviours when copy-pasting the same script with minor changes. You can take advantage of data structures and loop statements to manage your GameObject activation/deactivation, and make your logic more flexible and less error-prone.

### Storing GameObjects

You can define your colour presets as an array rather than individual elements:

```
public GameObject[] Primary;

```

The Inspector will let you expand the entries and assign the GameObjects of interest:

The advantage of having your GOs stored in an array is that you can use indices to access them, e.g. `Primary[3]` is your fourth object in the array (array indices start at 0).

### Activating GameObjects

Since you have the same number of elements and buttons, you can just enable the GO of interest when the corresponding button is pressed. This can be achieved by knowing the GO index and looping through all GOs:

```
public void ColorButton(int index)
{
    for (int i = 0; i < Primary.Length; i++)
    {
        Primary[i].SetActive(i == index);
    }
}

```

Here `index` is an arbitrary value you pass as an argument. The function loops through all objects and sets as active only the one whose position in the array is equal to the `index` (`i == index` returns `true`), while deactivating all others (`i == index` returns `false`).

### Binding the UI to the activation logic

To make the above function work on button click, you can select a Button and add an entry to its *On Click ()* event in the Inspector. Then, drag the GameObject that has got your colour management script. Finally, look for the function defined above:

The input field below the function name is the value of `index` you want to pass as an argument when the function is triggered. You can change this value with different values for other buttons.

Each button will invoke the function with a different `index` value, and the `ColorButton()` function will take care of activating/deactivating the corresponding GameObject you assigned.

---
Tags: unity
---