title: How to tile a texture

text:
# Question
Title: How to tile a texture
I'm creating a simple program in C# and now i'm trying to slice an image into multiple tiles similar to a grid pattern so it does not get stretched when drawing to different resolutions.

What i'm trying to achieve:

* I want the image to be sliced into multiple tiles.
* I need the image to be scaled to the dimension of a specified rectangle.
* I need the image to be drawn without losing the aspect it had before being scaled.

Below is the code i currently have, at the moment it does not scales the image correctly and it seem that the image is losing its aspect. Also, note that i'm using an Matrix to scale the graphics object to a certain resolution.

```
public static List<RectangleF> TileRectangle (this RectangleF rectangle, int rows, int columns)
{
    var rectangles = new List<RectangleF>();

    float width  = rectangle.Width / rows;
    float height = rectangle.Width / columns;

    for (int x = 0; x < columns; x++)
    {
        for (int y = 0; y < rows; y++)
        {
            rectangles.Add(new RectangleF(rectangle.X + (width * x), rectangle.Y + (height * y), width, height));
        }
    }

    return rectangles;
}

public void Draw (Graphics graphics)
{
    graphics.MultiplyTransform(ResolutionMatrix());
    graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
    graphics.PixelOffsetMode = PixelOffsetMode.Half;

    var destination_slices = new RectangleF(0, 0, 512, 512).TileRectangle(3, 3);
    var source_slices = new RectangleF(0, 0, this.image.Width, this.image.Height).TileRectangle(3, 3);

    for (int i = 0; i < source_slices.Count; i++)
    {
        graphics.DrawImage(this.image, destination_slices[i], source_slices[i], GraphicsUnit.Pixel);
        Debug.WriteLine(source_slices[i]);
    }
}

```

At the moment this code is causing the following problems:

* The image scales correctly only in the horizontal direction.
* The image does not maintains its aspect when scaled.
* When changing the columns and rows to different values, the drawing becomes sliced.

The drawing code produces the following output for the "source slices" when sliced in 3 by 3 tiles:

```
X=0,Y=0,Width=63,333332,Height=16,333334
X=0,Y=16,333334,Width=63,333332,Height=16,333334
X=0,Y=32,666668,Width=63,333332,Height=16,333334

X=63,333332, Y=0, Width=63,333332, Height=16,333334
X=63,333332, Y=16,333334, Width=63,333332, Height=16,333334
X=63,333332, Y=32,666668, Width=63,333332, Height=16,333334

X=126,666664, Y=0, Width=63,333332, Height=16,333334
X=126,666664, Y=16,333334, Width=63,333332, Height=16,333334
X=126,666664, Y=32,666668, Width=63,333332, Height=16,333334

```

Here is a image to describe the results i'm expecting:

I believe there might be a simple solution for this, so could someone post a direct answer with the code to accomplish these tasks?

# Answer
> 1 votes
I did a brief implementation of a 9 slicer in Pygame, but the same ideas should be easily applicable in any capable rendering framework since it's the ideas here that are the key.

This implementation always preserves the size of the corner pieces, and the height of the top and middle slices, and the width of the left and right slices. Holes are filled by repeating the pieces instead of scaling them, which means that your slices should be drawn in a way where they can be cut at any point. If scaling is desired instead, it'd be of course possible to just render the non-corner pieces with a scaling destination rectangle.

I didn't do much to think about more clever ways to handle the cropping of the pieces, so I ended up writing separate logic for the horizontal, vertical and middle parts.

First, you want to precalculate the source rectangles for the individual slices:

```
rectangles = (
    pygame.Rect(0, 0, padding, padding),
    pygame.Rect(padding, 0, width - 2 * padding, padding),
    pygame.Rect(width - padding, 0, padding, padding),

    pygame.Rect(0, padding, padding, height - 2 * padding),
    pygame.Rect(padding, padding, width - 2 * padding, height - 2 * padding),
    pygame.Rect(width - padding, padding, padding, height - 2 * padding),

    pygame.Rect(0, height - padding, padding, padding),
    pygame.Rect(padding, height - padding, width - 2 * padding, padding),
    pygame.Rect(width - padding, height - padding, padding, padding),
)

```

There's nothing special going on here, just hardcoded positions for the slices based on a single padding value, which indicates the size of the corner slices. If your corner slices aren't squares, it's of course easy to adjust this to use separate vertical / horizontal paddings. `width` and `height` are the size of the source image.

With the source rectangles, we can now implement a method that takes in a destination rectangle `destination`. I started by checking that there's at least room to draw the corners; You might want to handle this more gracefully:

```
dest_middle_width = destination.width - 2 * self.padding
dest_middle_height = destination.height - 2 * self.padding

assert(dest_middle_width >= 0 and dest_middle_height >= 0)

```

The corners are now trivial: just draw then into their correct places (if you're unfamiliar with Python, `blit` takes in the source image, destination position and source rectangle called `area`):

```
target.blit(self.surface, (destination.left, destination.top), area=self.rectangles[0])
target.blit(self.surface, (destination.right - self.padding, destination.top), area=self.rectangles[2])
target.blit(self.surface, (destination.left, destination.bottom - self.padding), area=self.rectangles[6])
target.blit(self.surface, (destination.right - self.padding, destination.bottom - self.padding), area=self.rectangles[8])

```

It's also worth noting that here the destination size of the rendered pieces is always the same as the source pieces.

Then we do a pass over the width of the middle piece, and render the top and bottom slices:

```
middle = self.rectangles[4]

# Top and bottom
for x in range(0, dest_middle_width, middle.width):
    width = min(middle.width, dest_middle_width - x)

    top_area = pygame.Rect(self.rectangles[1])
    top_area.width = width
    target.blit(self.surface, (destination.left + self.padding + x, destination.top), area=top_area)

    bottom_area = pygame.Rect(self.rectangles[7])
    bottom_area.width = width
    target.blit(self.surface, (destination.left + self.padding + x, destination.bottom - self.padding), area=bottom_area)

```

The key here is the `min(middle.width, dest_middle_width - x)` part, which makes sure that the last slice we draw to fill the desired middle piece width is clipped properly.

The slices for left and right are handled just as top and bottom, but instead the iteration is over the vertical axis, and of course coordinate calculations adjusted accordingly.

Now all that remains is the middle piece, which is just a combination of iterating over both the vertical and horizontal axes:

```
# Middle
for x in range(0, dest_middle_width, middle.width):
    width = min(middle.width, dest_middle_width - x)
    for y in range(0, dest_middle_height, middle.height):
        height = min(middle.height, dest_middle_height - y)
        area = pygame.Rect(middle)
        area.width = width
        area.height = height
        target.blit(self.surface, (destination.left + self.padding + x, destination.top + self.padding + y), area=area)

```

And here's the result using a destination size that is not a multiple of the piece sizes:

---
Tags: c#, mathematics, textures, tiles
---


title: How to draw a box in Unity Runtime?

text:
# Question
Title: How to draw a box in Unity Runtime?
I'm currently working on an AR application that is able to measure volume. The functionality is required to draw a box is in the gif attached to this. I have tried to generate instantiating 3 points in a horizontal plane and then calculate the 4th point by vector calculations by this function.

```
Vector3 GetFourthPointPosition(Vector3 p1Transform, Vector3 p2Transform, Vector3 p3Transform)
{
    var OA = p1Transform;
    var OB = p2Transform;
    var OC = p3Transform;
    var OD = OC + OA - OB;
    GetFourthPoint(OA, OB, OC, OD);
    return OD;
}

```

Then, after that, I'm enabling a vertical plane and disable the horizontal plane to avoid adding points on the same axis. The last point is to calculate the height. After that, I'm instantiating 3 other points to generate the point view.

```
private void GetCompleteCube(Vector3 p1Transformation, Vector3 p2Transformation, Vector3 p3Transformation, Vector3 p4Transformation)
    {
        var height = Vector3.Distance(p3Transformation, p4Transformation);
        var length = Vector3.Distance(p1Transformation, p2Transformation);
        var width = Vector3.Distance(p2Transformation, p3Transformation);
        var invPointTransform = clone.transform.position;

        var p5Transformation = new Vector3(p1Transformation.x, p1Transformation.y + height, p1Transformation.z);
        var p6Transformation = new Vector3(p2Transformation.x, p1Transformation.y + height, p1Transformation.z);
        var p8Transformation = new Vector3(invPointTransform.x, invPointTransform.y + height, invPointTransform.z);

        InstantiatePoints(p1Transformation, p1Transformation, p3Transformation, p4Transformation, p5Transformation, p6Transformation, invPointTransform, p8Transformation);
    }

private void DrawCubeLineRendere(Vector3 p1Transformation, Vector3 p2Transformation, Vector3 p3Transformation, Vector3 p4Transformation, Vector3 p5Transformation, Vector3 p6Transformation, Vector3 p7Transformation, Vector3 p8Transformation)
{
        Vector3[] vertexPositions = new Vector3[] { p1Transformation, p2Transformation, p3Transformation, p7Transformation, p4Transformation, p5Transformation, p6Transformation, p8Transformation };
        lineRenderer.positionCount = vertexPositions.Length;
        lineRenderer.SetPositions(vertexPositions);
}

```

I'm tried using a line renderer t0 visualize the cube but the outcome is very odd. Does not lining to form a cuboid. it looks like this.

Can anybody help me to figure out what I have done wrong?

# Answer
Instead of using a single line renderer, this uses 4 (you can go back for to 1 if you feel like it). Input are the first three points and the height (which you can as well later calculate/ generate on the fly).

The forth point is generated by simply subtracting the provided first three points.

Next we are generating with the cross product a normal vector and just use the corner pieces + the new normal vector + height to generate the other 4 points.

```
private void SetLineRenderer(LineRenderer lineRenderer, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) {
        Vector3[] vertexPositions = { p1, p2, p3, p4};
        lineRenderer.positionCount = 4;
        lineRenderer.loop = true;
        lineRenderer.SetPositions(vertexPositions);
    }

public void DrawCube(Transform p1, Transform p2, Transform p3, float height) {
        p4.position = p3.position + p1.position - p2.position;
        Vector3 crossProduct = Vector3.Cross(p2.position - p1.position, p4.position - p1.position).normalized * height;
        p5.position = p1.position - crossProduct;
        p6.position = p2.position - crossProduct;
        p7.position = p3.position - crossProduct;
        p8.position = p4.position - crossProduct;
        SetLineRenderer(l1, p1.position, p2.position, p3.position, p4.position);
        SetLineRenderer(l2, p5.position, p6.position, p7.position, p8.position);
        SetLineRenderer(l3, p1.position, p4.position, p8.position, p5.position);
        SetLineRenderer(l4, p2.position, p3.position, p7.position, p6.position);
    }

```

The circles are just for visual debugging if the math is right. If you want to draw in a single line renderer, you could pass the points p1, p2, p6, p2, p3, p7, p3, p4, p8, p4, p1, p5, p6, p7, p8. Loop does not need to be true but would not make a difference.
> 2 votes

---
Tags: unity
---


# Question
Title: How can I detect when the mouse cursor is over a button?
Not clicked event but over the button event ? I want that when the mouse cursor is on the button call a function.

When I click on the button it's calling the function playing a sound. I tried to add a Pointer Enter event calling the same function but it's not playing the sound when the mouse cursor is above the button.

This is the function :

```
public void MouseClick(string buttonType)
    {
        if (buttonType == "Controls")
        {
            transform.GetComponent<AudioSource>().Play();
            controlsMenu.SetActive(true);
            menuNumber = 6;
        }

        if (buttonType == "Graphics")
        {
            transform.GetComponent<AudioSource>().Play();
            mainMenuCanvases.SetActive(false);
            GeneralSettingsCanvas.SetActive(false);
            graphicsMenu.SetActive(true);
            menuNumber = 3;
        }

        if (buttonType == "Sound")
        {
            transform.GetComponent<AudioSource>().Play();
            mainMenuCanvases.SetActive(false);
            GeneralSettingsCanvas.SetActive(false);
            soundMenu.SetActive(true);
            menuNumber = 4;
        }

        if (buttonType == "Exit")
        {
            transform.GetComponent<AudioSource>().Play();
            Debug.Log("YES QUIT!");
            Application.Quit();
        }

        if (buttonType == "Options")
        {
            newGameClicked = true;

            transform.GetComponent<AudioSource>().Play();
            menuDefaultCanvas.SetActive(false);
            GeneralSettingsCanvas.SetActive(true);
            menuNumber = 2;
        }

        if (buttonType == "NewGame")
        {
            newGameClicked = true;
            transform.GetComponent<AudioSource>().Play();
            mainMenuCanvases.SetActive(false);
            menuDefaultCanvas.SetActive(false);
            newGameDialog.SetActive(true);
            menuNumber = 7;
        }
    }

```

# Answer
If you look at the way you called `MouseClick` in the inspector you passed the "NewGame". In the pointer event you didn't pass anything. Your MouseClick function plays a sound only if one of those if conditions has been matched. With an empty string no if condition will match and nothing will happen.

If you want the same sound to play as it does on click, you should write in the inspector something like "NewGamePointerEnter", and in the on click function add a new if expression that will match and play the sound, with the same line you wrote before.

```
if (buttonType == "NewGamePointerEnter")
{
    transform.GetComponent<AudioSource>().Play();
}

```
> 0 votes

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


# Question
Title: How to read a sparse Octree sequentially, like a 3D array?
Is it possible to read a sparse Octree like a regular 3D grid:

```
for(z)
  for(y)
    for(x)

```

...and still benefit from skipping large empty areas?

I need this for a rolling cache, that always retains corner data from previous cells. This is not possible with **regular** Octree traversal as it goes deep in every octant and overfills the cache needed for sequential octants. But is possible with sequential grid traversal.

Caching example:

ReuseCell& get_reuse_cell(Int3_64 pos) {
  uint32 j = pos.Z & 1;
  uint32 i = pos.Y * maxX + pos.X;
  return cache[j][i];
}
...

Array<std::vector<ReuseCell>, FixedAllocation<2>> cache;

...

struct ReuseCell {
    Array<uint32, FixedAllocation<4>> vertices;
    ...
};
```
</code></pre>

# Answer
To skip all those unwanted nodes, I think what you're looking for is a *sparse* but *contiguously-allocated* octree, which can be easily indexed by `(x, y, z)`. You also seem to want sequential ordering.

For this, with a maximal tree i.e. what you call a **regular** tree, we use something like Morton ordering to rapidly and sequentially index into the 1D array representing the tree, with just a few arithmetic or bitshift operations. This works fine when we've allocated the full tree, because Morton assumes the full range of indices for that size of tree, are available in the array.

However, once we shorten the tree array to only as many nodes as we actually use (say 40%, but even 99%), then Morton indexing throws array out-of-bounds errors. At first, this apppears to be a catch-22 situation. Good news: it's really not.

What we have to do is to build our tree into a maximal tree structure *first*, one that *can* be Morton-indexed. Then extract all relevant nodes and do some array index indirection.

* While building the maximal tree, we mark which nodes were actually *used* (versus just being "present"). Keep track of the Morton indices to those nodes, in a separate vector / list (`vector.push_back()`). This is the reverse-mapped LUT in array form via `vector.data()`.
* Create the forward-mapped lookup table (maybe `std::unordered_map<uint32, uint32>`) which maps the Morton index (which we will use to access using `(x,y,z)`) to the index used to store the node in the compact array. This is simply a reversal of the keys to value, and values to keys, from the vector above.

We then read / write our sparse / compact tree array as follows (assume a quadtree for simplicity):

```
//...up here we do reverse and forward mapping...

Node sparseTree = new Node[nodesUsed];

uint32 mortonIndex = pos.Y * maxX + pos.X;
uint32 sparseIndex = mortonToSparse[mortonIndex]; //forward LUT
Node node = sparseTree[sparseIndex];

```

**Note on performance**

Iterating a 1D array using Morton order (or Hilbert curves) is one of the fastest possible data access arrangements since it preserves locality of data for CPU cache.

I never use double- or triple-nested loops to iterate `(x,y,z)`. Even if you set constant upper bounds on those loops, the nesting alone has me question whether the compiler will unroll these loops - and if they remain nested, walks can potentially be very slow due to conditional branches.

Rather always iterate in 1D over the tree array:

```
for (uint32 sparseIndex = 0; sparseIndex < sparseTreeLength; sparseIndex++)
{
    uint32 mortonIndex = sparseToMorton[sparseIndex]; //reverse LUT

    uint32 x = mortonIndex % maxX;
    uint32 y = mortonIndex / maxX; //maybe use floor()

    ...
}

```
> 3 votes

# Answer
One strategy you can use is to make your leaf nodes "chunks" of cells. For example, Minecraft uses 16x16x16 cell chunks if I recall correctly.

This gives you a coarser granularity for caching and a slightly shallower octree to manage, while keeping most of the benefits of skipping large empty areas. The chunks can also map to individual meshes/blocks of vertex data that you can LOD or cull as a whole for rendering efficiency.

Next, make your cache an array of references to say 2x2x4 adjacent chunks, acting as a sliding window into your octree. You can fill this cache with the corner of the start of your search with 2 octree traversals, taking all up-to-8 leaf nodes from the final parent cell into your cache in each traversal in one fell swoop.

Following Engineer's lead, I'll demonstrate this with a 2D analogue:

You can access all 30x30x60 cells on the interior this window, along with all of their neighbours along the outer faces in case you need to do any adjacency-based logic, using only the chunks in cache - no need to go back to the octree for each adjacent lookup. Iterating down your row in a 30x30 "pipe" like this will also give you better data locality than scanning along the entire width of the octree in a single-cell line then looping back to visit the same neighborhoods again but 1 cell over.

When you want to shift this sliding window down the row as your iteration proceeds, you need just 1 additional octree traversal to bring the next 2x2x2 chunks into cache, rather than 32x32x32 traversals to look up individual cells. You can fast-forward this window sliding past swaths of empty chunks.

Because you're doing so few full octree traversals, you can also cache the ancestor chain leading to the latest search, and start your next search from lower in the chain if you like.

However, I think you might find that using an algorithm designed for iterating over data in octree format natively might work better in the long run than trying to shoehorn it into a sequential access model. To help you find such an algorithm, we'd need to know what you're currently using this sequential iteration for.
> 1 votes

# Answer
Re your updated question. Since per-layer rolling cache may not work for an octree... and caching is not actually necessary to solve the problem which is efficient access to vertices...

Try a Morton or Hilbert-ordered, sparse spatial hashmap of `vertex`. This should give you amortised `O(1)` reads across all non-co-located vertices. It should also eliminate the need for caching.

Buckets constituting this hash should correspond to spatial (x,y,z) locality within your octree. Thus, unlike the regular `std::*map`s, as you read in a local volume within the tree, you will typically also be reading within the same bucket (or 4-8 local buckets if you are reading on octree boundary), which thereby roughly approximates the rolling / per-layer cache in the original Transvoxel concept (at least, it will be far better for random access and depth-first walks) - if these buckets exist near one another within a single contiguously allocated structure, you're golden. Read more here:

> ...for a normal hash table, a good hash function distributes keys as evenly as possible across the available buckets, in an effort to keep lookup time short. The result of this is that keys which are very close (lexicographically speaking) to each other, are likely to end up in distant buckets. But in a spatial hash we are dealing with locations in space, and locality is very important to us (especially for collision detection), so our hash function will not change the distribution of the inputs.

This concept is well-known in GIS applications, so you may wish to search in GIS libraries for a suitable C++ implementation. (I think my fellow users and I have already speculated enough on your questions, so best you seek the correct implementation for yourself.) You may also want to look into perfect spatial hashing.

Just a thought, it doesn't really matter that much how large the spatial hash is: What matters is the bucket size and their proximity to one another within the larger hashmap allocation.

Another benefit to such a map is that implicitly disallows duplicate vertices at the same location, since the key is formed from the (x,y,z) coordinates. Thus only one instance of `vertex` can by keyed at each location.

**Depthwise caching**

You could optimise by selecting a maximum node size to cache within, and temporarily caching all those vertices within a smaller hash (potentially?) as you begin walking down the tree. But I doubt this would gain you much. I would strongly suggest the simplest solution first (above) and see how that performs for you before taking additional steps to optimise - since that's all caching is.

I would then suggest doing this chunk-wise, as DMGregory suggests - one octree per chunk, allowing for a sliding window.
> 0 votes

---
Tags: algorithm, octree
---


# Question
Title: How can I build an accurate 15-bit Highcolor RGB palette
I want to recreate an accurate version of a 15-bit RGB color palette (PC Highcolor, SNES, Playstation 1), storing each color from the palette as a standard 6 digit hex code.

With each color component using 5 bits, this gives us available values of 0-31. Mapping that to a standard 0-255 color range needed for the hex code seems trivial, however when I do my palette seems to be subtly off from the examples I've found online.

When mapping the values I've tried both rounding and flooring to the closest match but neither quite match. My output when looping through the first few values of the red component gives me:

Rounding:

`#000000, #080000, #100000, #190000, #210000, #290000, #310000, #3a0000, #420000...`

Flooring:

`#000000, #080000, #100000, #180000, #200000, #290000, #310000, #390000, #410000...`

Whereas in the example palettes I've found I get:

`#000000, #080000, #100000, #180000, #210000, #290000, #310000, #390000, #420000...`

At first I considered that the example palette may have been wrong, or that the image compression used on the image may have effected the values, but it seems to be the same for all of the examples I've found.

While this might seem a trivial detail and the colors would likely be indistinguishable, I'm keen to understand if there was a hardware or software limitation on the original devices which causes these discrepancies when computing the original palette. I'm also wondering if it's actually a fence post problem in my code.

Update: Here is the Javascript code I wrote to generate a color cube based on bit depth. `rgbToHex` is just a util that does what it says on the tin :)

The differences posted above about `round` and `floor` refer to the int conversion done on the r, g, b values before passing to `rgbToHex`. From the article cited in my answer below, I now believe the issue is to do with data loss during bit depth conversions and that while the code below produces a "perfect" linear interpolated color cube, this wasn't possible on the original hardware.

const MAX_RGB = 255;
const BITS_PER_CHANNEL = 5;

const numPosts = Math.pow(2, BITS_PER_CHANNEL);
const numSpaces = numPosts - 1;

let rIndex, gIndex, bIndex;
const colors = [];

for (bIndex = 0; bIndex < numPosts; bIndex++) {
  for (gIndex = 0; gIndex < numPosts; gIndex++) {
    for (rIndex = 0; rIndex < numPosts; rIndex++) {
      const r = (rIndex / numSpaces) * MAX_RGB;
      const g = (gIndex / numSpaces) * MAX_RGB;
      const b = (bIndex / numSpaces) * MAX_RGB;
      const color = rgbToHex(Math.round(r), Math.round(g), Math.round(b));
      colors.push(color);
    }
  }
}
```
</code></pre>

# Answer
> 4 votes
It took a little while to stumble across and my understanding of bit operations is limited, but this discrepancy appears to be due to the data loss suffered when converting values from 24-bit to 15-bit and back again. As described here.

The relevant part of that article describes the conversion algorithm like so (where color is an integer in the range 0 - 32767):

```
R = ((color       ) % 32) * 8
G = ((color /   32) % 32) * 8
B = ((color / 1024) % 32) * 8

```

However for white (32767), this will produce an RGB triplet of (248,248,248) NOT (255,255,255). This is because, to quote:

> So the final output is (248, 248, 248). Uh-oh, 24-bit RGB white is (255, 255, 255) not (248, 248, 248). Apparently, what happened is there was a precision loss during the conversion. Think about it, if you convert a 24-bit value into a 15-bit you would have loss some precision. The three least significant bits are lost in each component. Thus, the extra precision that 24-bit color provides is lost and is unrecoverable.

This range is then stretched to fill the 255 range afterwards, which accounts for the original noted discrepancies:

> A naïve approach would be to do a multiplication and division scaling:

```
R = (255 * R) / 31;
G = (255 * G) / 31;
B = (255 * B) / 31;

```

> A faster approach is:

```
R = R + R / 32
G = G + G / 32
B = B + B / 32

```

> This seems strange at first glance, but what happens is that you replicate the top three bits of each component into the bottom three bits (which, as stated above, are empty after conversion). This, if you think long enough about it, has the effect of stretching the color values into the full (0,0,0) -\> (255,255,255) range.

---
Tags: algorithm, color, palette
---


# Question
Title: how to add overall collider to a bunch of circles or boxes?
I have 3 circles (2D) they all have circleCollider2D. what I want is to make a collider that make border around them. I can't express which type of collider I need, so I put example image below. Red lines are the collider I want.

# Answer
> 1 votes
Check out the PolygonCollider2D. It allows you to create a collider with any shape you want.

Another option which is less flexible but might be more performant in your particular case could be to create a CompositeCollider2D and a Rigidbody2D and then create three child game-objects, each one with a BoxCollider with "Used by Composite" enabled.

Update by Rashad: I used Polygon collider to solve the problem. You can see image below

---
Tags: unity, 2d, collider
---


# Question
Title: Problems with collision order of resolution
I have two objects, A and B, and I need help to solve the following problem about the collision resolution order:

A and B are moving with the same speed, and they don't move both at the same time

1. A tries to move to where it should be, and I do the collision test
2. A collision is detected, and A is moved outside of collision
3. Then B moves after this, and a gap appears between then

I tried resolving the collision of A by discouting the velocity of B, but this fails if B collides on it's path, and A moves inside of it.

Are there any algorithm that can solve this problem? And also when working with multiple objects moving in a row just like A and B.

Also, my objects don't have any mass or elasticity, they are supposed to just move and get out of collision using simple AABB.

# Answer
Basically you're going in the wrong order. If it's just A and B or a few objects like that, I would first iterate through each object with no collision and skip any that have collisions, then iterate through all the ones that had collisions, hopefully they will then be resolved. But if you have a lot of these objects like a train, then you need to change the order in which this is done.
> 0 votes

---
Tags: collision-detection, physics, collision-resolution
---


# Question
Title: Low FPS in Unreal engine, but GPU usage is low as well
I am running an Unreal Engine 4 project which has many high quality assets. My computer is fairly strong:

* CPU: AMD Ryzen 5 3600 6-Core
* GPU: GeForce RTX 3060 SSD: Lexar 500GB NM610 M.2 NVMe SSD
* RAM: 2 HyperX Fury DDR4 8 GB RAM = 16 GB RAM in total
* Motherboard: Gigabyte Technology, A520M DS3H AC
* OS: Windows 10 Home

At certain points my fps drops down to 30, sometimes a bit lower. In windows task manager under the 'performance' tab, I see that my graphics cards only has about 5% usage. However, when I run the 'nvidia-smi' command in command prompt, under 'volatile GPU-utilization' I get 100% usage. What is the actual usage of my graphics card? Should I disregard what windows task manager is saying?...

# Answer
Unreal has built in profiling tools to help you identify where the bottleneck is. Open the console and type `stat unit` and it will show you times in milliseconds for the CPU (both the game thread and the draw thread) and the GPU. See https://docs.unrealengine.com/4.27/en-US/TestingAndOptimization/PerformanceAndProfiling/StatCommands/#unit for details and a list of all the stat commands.

Also note that Unreal will limit the frame rate to about 62 FPS by default, which isn't always helpful when testing performance. You can use the console command `t.maxfps 500` to change that limit to 500 FPS. You can also change it permanently in the project settings.
> 1 votes

# Answer
stumbled upon this forum thread: https://linustechtips.com/topic/1034616-task-manager-not-reporting-correct-gpu-usage/ I think windows task manager is outputting the incorrect usage. I remember owning a laptop from years ago that always said my RAM usage was maxed out. I think windows task manager is not built well!
> -1 votes

---
Tags: graphics, unreal-4, windows, gpu, nvidia
---


# Question
Title: How to handle player slowness while moving up and down in a Top Down game with angled ortho camera and angled sprite due to stretching of ground?
So i'm making a 2D top down game setup in 3D using tilted Sprites and angled orthographic camera.

My camera setup is as shown.

In my game I have the floor flat on the X/Z plane with walls/characters rotated +45 degrees about the X axis. The orthographic camera is pointing down also at 45 degrees about the x axis, parallel with my walls/characters.

As a result, I dont see any distortion for players/characters since they face the camera directly on, while the ground however sees a distortion of sqrt(2) shorter. This makes sense considering how an orthographic camera works. To fix this, I've made my Tilemap set up with X:1 Y:1 Z:Sqrt(2) so that each tile is stretched on the Z axis by Sqrt(2) to compensate for this distortion.

All looks well with only one problem now... foreshortening with regards to movement: Forward and backwards movements of objects/characters along the z axis are perceived to be slower than movements left/right on the x axis. This makes sense because while each tile is perceived to be a square in the camera view thanks to scaling Z on the tilemap by sqrt(2), the real world tile is, well, sqrt(2) times taller than its width, so obviously it takes longer to travel forwards / backwards.

How do i correct this?

# Answer
> 2 votes
Myself, I'd recommend getting rid of the stretching and leaning in your game world.

Make the tilemap uniformly scaled 1x, and make any upright characters/walls/trees stand perpendicular, not leaned over.

That way both the z and y axis are equally foreshortened in your camera's view by a factor of \\$\frac 1 {\sqrt{2}}\\$.

Then, modify your camera's projection matrix to add a vertical scale factor of \\$\sqrt{2}\\$ to compensate. This applies the stretching in the render step alone, so it does not interfere with your gameplay/movement logic or force you to do fiddly things like leaning sprites diagonally.

In Unity it would look something like this:

```
Matrix4x4 mat  = camera.projectionMatrix;
mat[1, 1] = Mathf.sqrt(2) / camera.orthographicSize;
camera.projectionMatrix = mat;

```

# Answer
> 0 votes
If the tile is `sqrt(2)` times taller than wide, then multiply z-axis motion by `sqrt(2)`

---
Tags: 2d, 3d, camera, sprites, perspective
---


# Question
Title: How to make my Unity project deterministic for replays?
I am working on an arcade-style 2D shmup and recently started implementing a replay system that allows players to view their runs of the game.

I use the technique of recording input each `FixedUpdate()` and rerunning the game as a simulation, reading the saved input each frame and processing it in the core game loop as if it was real-time input from the player.

This requires an extremely deterministic game, and in order to get perfectly synced movement and scoring in the replay, I have had to shift to a paradigm of using exclusively `FixedUpdate()` and `Time.fixedDeltaTime`.

I don’t mind this, as I now have 100% reliable replays with no desyncing.

My question concerns whether some of the techniques I used to port my game to the deterministic `FixedUpdate` paradigm are problematic, or if there are better ways to achieve the same effect.

For example, previously I relied heavily on coroutines yielding using `WaitForSeconds()`. This method is underpinned by normal `Update()` loop and so introduced indeterminism into the game leading to desyncs.

To fix it, I still use coroutines, but any time I need to wait, I do it by waiting for *n* number of calls of `FixedUpdate()`. For example,

```
for (int i = 0; i < 60; i ++)
{
    yield return new WaitForFixedUpdate();
}

```

This seems to be working just fine to keep the game deterministic, but I wonder if there’s a more straightforward way, or if there are potential issues this type of technique might cause?

In general, are there any other techniques or pitfalls I need to be aware of to keep my game deterministic enough for perfectly synced replays?

# Answer
> 0 votes
After more tinkering, I think I can safely say that using

```
for (int i = 0; i < 60; i ++)
{
    yield return new WaitForFixedUpdate();
}

```

works fine in coroutines to preserve determinism.

That said, there were a few other things I needed to change, and others attempting to move to a FixedUpdate paradigm should be aware of them.

In many of my coroutines, I was sometimes using `yield return null`. This will yield until the next call of `Update()`, which is problematic. I had to convert these lines to yield return new `WaitForFixedUpdate()`.

Finally, I am making heavy use of the DOTween library for tweening. By default, all of the tween update using `Update()`, but I discovered that you can easily set all of them to update during `FixedUpdate()` using

```
    // set Global tween settings
    // NOTE: this is easiest way to make sure all tweens are only
    // updating in fixed update,
    // rather than manually setting tween.SetUpdate(UpdateType.Fixed)
    DOTween.Init();
    DOTween.defaultUpdateType = UpdateType.Fixed;

```

---
Tags: unity, c#, timestep, fixed-timestep, replays
---


# Question
Title: Raycasting in GameMaker Studio 2 to implement hitscan weapons?
I'm working on a 2D top-down shooter game in GameMaker Studio 2, featuring different weapons and obstacles all around the levels.

Since I don't need a high degree of simulation, I'm implementing simple physics for character movement and interaction (e.g. weapons, bullets, doors...) myself via GML rather than using the dedicated physics library.

Currently, shooting works as follows:

* The player **presses** the Left Mouse Button.
* A bullet object **spawns**, according to the current weapon.
* The bullet **starts moving** towards the mouse position at a given velocity.

Right now, the gameplay works quite well. However, I wanted to create different weapons with unique features, including different **bullet speeds**. And here's my problem.

I tried to increase bullet velocity values, but they started behaving strangely: When shooting against objects, hits occur slightly before visual contact. Sometimes, bullets 'warp' beyond small objects or corners as if a collision hasn't been detected at all.

There are two schematics, one for the general case:

And one for the collision with thin objects:

I think this is due to my code checking for collisions for given positions rather than sweeping along the expected motion trajectory. And, this doesn't work well with laser weapons and sniper rifles, since players expect them to be precise when shooting.

My initial implementation was the following:

*Create Event:*

```
b_damage = 25;
b_velocity = 100;
b_direction = point_direction(x, y, mouse_x, mouse_y);

```

*Step Event:*

```
var _xvel = lengthdir_x(b_velocity, b_direction);
var _yvel = lengthdir_y(b_velocity, b_direction);

var _coll = instance_place(x + _xvel, y + _yvel, obj_CollisionParent);

if ( _coll == noone )
{
    // No collision occurred, bullet can travel
    x += _xvel;
    y += _yvel;
}
else
{
    // Destroy bullet (shows sparks)
    instance_destroy();
    // Deal damage if an enemy was hit
    if ( _coll.object_index == obj_Enemy )
    {
        scr_DealDamage(_coll, b_damage);
    }
}

```

I then tried to increase precision by subdividing the collision check into smaller steps:

*Step Event:*

```
var _xvel = lengthdir_x(b_velocity, b_direction);
var _yvel = lengthdir_y(b_velocity, b_direction);

var _coll;
var _steps = 10;

for (var i = 0; i < _steps; i++)
{
    _coll = instance_place(x + _xvel/_steps, y + _yvel/_steps, obj_CollisionParent);

    if ( _coll == noone )
    {
        // No collision occurred, bullet can travel for 1/_steps distance
        x += _xvel / _steps;
        y += _yvel / _steps;
    }
    else
    {
        // Destroy bullet (shows sparks)
        instance_destroy();
        // Deal damage if an enemy was hit
        if ( _coll.object_index == obj_Enemy )
        {
            scr_DealDamage(_coll, b_damage);
        }
    }
}

```

Now, collision is more precise, yet it's far from perfect. I still cannot use high velocity values without increasing the number of `_steps`. Also, 100 collision checks per step for dozens of bullets seem too much for my CPU. I would like to improve this aspect of my game.

I would like to use a raycast-like function, similar to Unity's `Physics.Raycast`. I need to find the final impact position with a low computational effort so that I can make bullets travel instantly, draw impact particles at the right position, and show realistic bullet trails.

# Answer
Without using a physics library, collision check works the old way: **collision masks**.

These are binary images, which GMS uses to perform collision checks between two instances at a time. If they overlap (i.e. if pixels from both images align), then a collision occurs. Since this approach is pixel-based, there are no vectors to work with, and we cannot define an actual raycast function–there's no such a thing as a 'ray' in pixel world!

### 'Pixel-casting'

Despite the above issues, we can exploit the collision check system and some maths to find a way to approximate a solution to the problem:

> Given a **distance** and a **direction**, find the **closest contact point** against some objects.

In the past, YoYo Games provided some sample code in GMSX demos and different blog articles (such as this one). There's a function using `collision_line()` to compute the first contact along a segment. It is intended to be saved as a Script and called via GML. We can re-write it as follows:

```
// Internals
var xfrom = argument0;
var yfrom = argument1;
var xto = argument2;
var yto = argument3;
var obj = argument4;

// Probing distance
var dx = 0;
var dy = 0;

// Get the first hit
var first_instance = collision_line(xfrom, yfrom, xto, yto, obj, true, true);

// If hit, find the exact hit point
if (first_instance != noone)
{
    // Init probing distance
    dx = xto - xfrom;
    dy = yto - yfrom;
    // Start the search algorithm down to the pixel level
    while ( (abs(dx) >= 1) || (abs(dy) >= 1) )
    {
        // Bisect the probing distance
        dx /= 2;
        dy /= 2;
        // Check along the new collision line
        var instance = collision_line(xfrom, yfrom, xto - dx, yto - dy, obj, true, true);
        // If something is hit, keep track of it and reduce the total distance to check for
        if (instance != noone)
        {
            first_instance = instance;
            xto -= dx;
            yto -= dy;
        }
    }
}

// Set return array
var return_array = array_create(3, -1);
return_array[0] = first_instance;
return_array[1] = xto - dx;
return_array[2] = yto - (dy * 2);
return return_array;

```

Results:

This function implements a form of bisection method and adapts it to find the best solution. It ensures it will stop since it either finds no collision or a collision within a geometric constraint (the pixel-level size of our probing distance). It works as follows:

* The whole distance `(xfrom, yfrom)``(xto, yto)` is checked for collisions. If none is detected, the function returns the special object `noone`.
* If a collision occurs, the best approximation must be found.
    + During the first loop, it checks for collisions in the first half of the line, `(xfrom, yfrom)``(xto - dx, yto - dy)`. This is because it first assigns values to `dx` and `dy`, and then divides them by 2, therefore finding the distance from the midpoint of the line.
    + If a collision occurs, it occurred in the first half of the line (thus, the first quarter of the original line, starting from `(xfrom, yfrom)`). Else, the initial collision occurred in the further half of the line, then it must look for it beyond the line midpoint. This is done by keeping the current `dx` and `dy` and re-assigning values for `xto` and `yto`.
    + Continue the search by subdividing the probing distance, until both its components go below 1, i.e. we reached the pixel-level precision.
* Return an array containing the latest object detected, and the X and Y coordinates (in room space) where the line intersected its collision mask.

### Considerations

I tested this function under different conditions and found out that it typically converges, and finds a 'correct' solution, within 10 to 20 loops. If you double the check distance, you may need only one additional iteration, since you're splitting in half the total distance at each iteration.

Additional code can be added to include an upper limit to the number of total iterations:

```
var max_loops = 10;
var loops = 0;

...

while ( ( (abs(dx) >= 1) || (abs(dy) >= 1) ) && (loops < max_loops) )
{
    ...

    loops++;
}

...

```

While this ensures halting within a max number of cycles, it doesn't guarantee the solution found is acceptable, if a good approximation is what you need.

Finally, there are some edge cases in which the function returns the right object but the wrong collision point (that is, slightly further from the expected position):

This is due to the discrete nature of pixels, and especially **rasterization**. When reducing the collision line length, its original orientation isn't necessarily preserved and its pixels may move slightly around. This is likely due to the line-drawing algorithm GMS uses to draw pixels, whose implementation we don't know.

But, this is a minor inconvenience that is unlikely to occur (or to be noticed, at least) during a fast-paced shooting game. If need be, such a glitch could be concealed with appropriate use of graphic effects such as sparks or smoke. :)
> 0 votes

---
Tags: game-maker, raycasting, bullet-physics, game-maker-studio-2
---


title: Applying angular velocity to quaternion

text:
# Question
Title: Applying angular velocity to quaternion
I am reading Game Physics Engine Development by Ian Millington currently. In his book, he represent an orientation of rigid body by quaternion. I don't understand the formula where he apply angular velocity to the quaternion. The formula is

$$ q\_{new} = q\_{0} + \frac{t}{2} * w * q\_{0} $$

where w is the angular velocity in quaternion representation.

$$ w = \begin{bmatrix} 0\\ w\_{x}\\ w\_{y}\\ w\_{z} \end{bmatrix} $$

He doesn't explain where the formula come from. Currently I apply this method in my physics engine where I compute the angular rotation then convert it to quaternion and multiply it. It is slower than the above operation because of the sine, cosine and square root operation when converting the rotation to quaternion. Can someone explain to me where did the formula above come from? I understand basic quaternion operation like representing axis angle by quaternion and rotating a vector by quaternion.

# Answer
In the following I use a vector hat to represent a quaternion and a unit vector hat to represent a unit quaternion.

Let q(t) represent the quaternion rotation at any point in time. Let r be a quaternion representing the rotation traveled through in the time period delta t. Then we have:

$$\hat q(0)=\hat q\_0$$ and $$\hat q(\Delta t)=\hat r\hat q\_0$$

If we realize that the change from time zero to time delta t is linear we can get:

$$\hat q(t)=\hat r^{t/\Delta t}\hat q\_0$$

Using Euler's Formula we obtain:

$$\hat r=e^{\frac{\theta}{2}\hat u}$$

For some angle theta and axis of rotation u (Note that u has no real part and is a "pure" quaternion). This leads us to:

$$\hat r^{t/\Delta t}=exp(\frac{\theta}{2}\hat u\frac t {\Delta t})$$

Plugging this in we obtain:

$$\hat q(t)=exp(\frac{\theta}{2}\hat u\frac t {\Delta t})\hat q\_0$$

Taking the derivative of both sides we obtain:

$$\hat q'=\frac {\theta \hat u} {2 \Delta t} exp(\frac{\theta}{2}\hat u\frac t {\Delta t})\hat q\_0$$ $$\hat q'=\frac {\theta \hat u} {2 \Delta t}\hat q$$

If we note that: $$\frac \theta {\Delta t} = w$$

For some scalar w. This represents the magnitude of the angular velocity. The axis of rotation is the vector given by u (u has no real part).

Or we could put it more bluntly if we say that:

$$\vec w=w\hat u=w\_x i+w\_y j+ w\_z k$$

This gives us:

$$\hat q'=\frac 1 2 \vec w \hat q$$

Now the formula that you are citing is actually not exact but only approximate......You can say for "small" delta t's that:

$$\frac {\Delta \hat {q}} {\Delta t} \approx \frac 1 2 \vec w \hat q$$

And since delta t is small we can choose any value within that time period for q, so we choose the one we already have:

$$\frac {\Delta \hat {q}} {\Delta t} \approx \frac 1 2 \vec w \hat q\_{old}$$ $${\Delta \hat {q}} \approx \frac 1 2 \vec w \hat q\_{old} {\Delta t}$$ $$\hat q\_{new} \approx \frac 1 2 \vec w \hat q\_{old} {\Delta t} + \hat q\_{old}$$ $$\hat q\_{new} \approx (\frac 1 2 \vec w {\Delta t} + 1)\hat q\_{old}$$

The formula you link to comes from solving the differential equation and is an exact formula
> 3 votes

# Answer
I finally found a very clear derivation, here: https://fgiesen.wordpress.com/2012/08/24/quaternion-differentiation/

It's by Fabian Giesen (ryg) of demo-scene fame.
> 1 votes

# Answer
The formula from the book looks wrong.

Try putting `t = 1, W = [ 0, 0, 2*Pi ]` into the formula. That input represents 1 complete revolution around Z axis, and the output should be identity quaternion, yet the formula returns something very far from identity.

Here’s my attempt. It’s in C# but I hope it’s simple enough to adopt to any other language.

```
/// <summary>Apply angular velocity to the quaternion</summary>
public Quaternion rotate( Vector3 angularVelocity, float deltaTime )
{
    Vector3 vec = angularVelocity * deltaTime;
    float length = vec.Length();
    if( length < 1E-6F )
        return this;    // Otherwise we'll have division by zero when trying to normalize it later on

    // Convert the rotation vector to quaternion. The following 4 lines are very similar to CreateFromAxisAngle method.
    float half = length * 0.5f;
    float sin = MathF.Sin( half );
    float cos = MathF.Cos( half );
    // Instead of normalizing the axis, we multiply W component by the length of it. This method normalizes result in the end.
    Quaternion q = new Quaternion( vec.X * sin, vec.Y * sin, vec.Z * sin, length * cos );

    q = Multiply( q, this );
    q.Normalize();
    // The following line is not required, only useful for people. Computers are fine with 2 different quaternion representations of each possible rotation.
    if( q.W < 0 ) q = Negate( q );
    return q;
}

```
> 0 votes

# Answer
Sort of in response to Soonts answer, but also for other people that may wonder, like I did, I found that the formula does work after an implementation in Unity, C#. I am sorry if "reviving" this is considered bad input.

Inputting `W = [0, 0, Pi/2, 0]` (`[x, y, z, w]` format) and letting `t` be the delta time between screen refreshes (`Time.deltaTime`), does yield a rotation of 90° in 1 second around the Z axis in the correct, trigonometric, direction.

An input of `W = [0, 0, Pi, 0]` does yield the same rotation, but with an angle of 180°, for instance.

Finally, inputting `W = [Pi, Pi, Pi, 0]` yields rotations in the correct directions on all axes, and made the test game object return to its original starting orientation after 1 second, as it should.

My attempt is very naive, and doesn't account for any specific scenarios where the angular velocity is too small or the such (but as far as I tested, down to `1e-06` at least, the rotation still executes normally. I did not test lower values, as it would take forever):

```
void UpdateTransform()
{   // transform.rotation is the game object's orientation quaternion in the game's worldspace. 'angular_velocity' is defined as a Quaternion of (x, y, z, w) parameters.

    transform.rotation = SummedQuaternion(ScaledQuaternion(angular_velocity, Time.deltaTime / 2) * transform.rotation, transform.rotation);
}

Quaternion ScaledQuaternion(Quaternion quaternion, float scale)
{
    Quaternion scaled_quaternion = new Quaternion(quaternion.x * scale, quaternion.y * scale, quaternion.z * scale, quaternion.w * scale);

    return scaled_quaternion;
}

Quaternion SummedQuaternion(Quaternion quaternion_alpha, Quaternion quaternion_beta)
{
    Quaternion summed_quaternion = new Quaternion(quaternion_alpha.x + quaternion_beta.x, quaternion_alpha.y + quaternion_beta.y, quaternion_alpha.z + quaternion_beta.z, quaternion_alpha.w + quaternion_beta.w);

    return summed_quaternion;
}

```
> 0 votes

---
Tags: quaternion, physics-engine
---


# Question
Title: Parent object does not rotate on its own axis with its children. How do I fix it?
My parent object components: Rigidbody2D and the script I shared below.

Children(Head, Body, Arm, Backpack...): There is only collider. There is no rigidbody2D. (I want the parent object to use the children's colliders, so I haven't add a rigidbody)

I want all my objects to rotate smoothly on their own axis. In the script below, it does not rotate on its own axis.

```
[SerializeField] public DynamicJoystick joystick;
public float speed;
Vector2 move;
public Rigidbody2D rb;

//Smoothly Turn
float _z;
float angle;
float turnSpeed = 15f;

void FixedUpdate()
{
    move.x = joystick.Horizontal;
    move.y = joystick.Vertical;
    float x = joystick.Horizontal;
    float y = joystick.Vertical;
    angle = Mathf.Atan2(y, x) * Mathf.Rad2Deg;

    if (angle != 0)
    {
        _z = angle;
    }

    Quaternion rotate = Quaternion.AngleAxis(_z, Vector3.forward);
    rb.transform.rotation = Quaternion.Slerp(rb.transform.rotation, rotate, turnSpeed * Time.fixedDeltaTime);
    rb.MovePosition(rb.position + move * speed * Time.fixedDeltaTime);

}

```

# Answer
> 1 votes
When I gave a gizmo to my parent object, I saw that the gizmo wasn't in the center of my parent object. So the character is turning, but instead of rotating on its own axis, it rotates around the gizmo. I simply moved all the children to the center of my parent object (right in the middle of the gizmo) and the problem was solved.

# Answer
> 0 votes
Have you tried Rigidbody2D.MoveRotation ?

Example (press any key to rotate the object to 10 degrees):

```
[DisallowMultipleComponent]
public class Rotate : MonoBehaviour
{
    [SerializeField]
    private float _angleVelocity = 10f;

    private Rigidbody2D _rigidbody;
    private bool _rotate;

    private void Awake()
    {
        _rigidbody = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        if (Input.anyKey)
            _rotate = true;
    }

    private void FixedUpdate()
    {
        if (!_rotate)
            return;

        _rigidbody.MoveRotation(_rigidbody.rotation + _angleVelocity * Time.fixedDeltaTime);
        _rotate = false;
    }
}

```

It is recommended to read the input data using the `Update` method since it is called every frame.

---
Tags: rotation, quaternion, gameobject, rigidbody, hierarchy
---


title: Error CS0234 and CS0236 in Unity

text:
# Question
Title: Error CS0234 and CS0236 in Unity
I'm trying to make a simple button perform an action when pressed. Initially I was using vscode, but as I couldn't solve the problem, I switched to visual studio 2017. For some reason the error persists.

**The button has been removed from this link:**

https://www.c-sharpcorner.com/article/unity-change-scene-on-button-click-using-c-sharp-scripts-in-unity/

**Button code (internet sketch):**

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

public class SceneChanger: MonoBehaviour {
    public void Scene1() {
        SceneManager.LoadScene("Scene1");
    }
    public void Scene2() {
        SceneManager.LoadScene("Scene2");
    }
    public void Scene3() {
        SceneManager.LoadScene("Scene3");
    }
}

```

**Button code (my code):**

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Windows.Forms;

public class botaoJogar : MonoBehaviour
{
    public Button btn_Jogar;

    void Start()
    {
        Button btn = btn_Jogar.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
        Debug.Log("You have clicked the button!");
    }
}

```

**Image of the construction in unity:**

**Before, I was able to solve the CS0236 error using the answers from this link:**

https://stackoverflow.com/questions/2883505/the-type-or-namespace-name-button-could-not-be-found-are-you-missing-a-using

The answer says to add the line `using System.Windows.Forms;` to the button code, but for some reason, now in visual studio, this error doesn't go away.

**Errors:**

> Assets\botajogar.cs(4,22): error CS0234: The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)
>
> Assets\botajogar.cs(8,12): error CS0246: The type or namespace name 'Button' could not be found (are you missing a using directive or an assembly reference?)

**Some community links, which I accessed:**

https://stackoverflow.com/questions/42000798/how-do-i-add-assembly-references-in-visual-studio-code

https://stackoverflow.com/questions/49805204/adding-reference-to-another-project-from-visual-studio-code

https://stackoverflow.com/questions/2883505/the-type-or-namespace-name-button-could-not-be-found-are-you-missing-a-using

https://stackoverflow.com/questions/47412796/system-windows-forms-assembly-reference-in-vs-code

https://stackoverflow.com/questions/46582847/creating-a-windows-forms-application-in-c-sharp-using-dotnet-new

https://stackoverflow.com/questions/40562192/windows-form-application-on-visual-studio-code

https://stackoverflow.com/questions/48496542/forms-does-not-exist-in-the-namespace-system-windows

**Other links:**

https://docs.microsoft.com/en-us/visualstudio/ide/how-to-add-or-remove-references-by-using-the-reference-manager?view=vs-2019

https://docs.microsoft.com/pt-br/dotnet/csharp/language-reference/compiler-messages/cs0246

I don't know what to do anymore, I feel like I tried to do everything I could, but windows forms simply don't work. Visual studio 2017 has no bugs, just unity.

**Installation I did in visual studio 2017:**

# Answer
Nothing in the script you've shown references "Button", so you've either shown us the wrong code, or you've linked a misleading Q&A page/quoted a misleading error unrelated to the root problem.

You do not want to use a Windows Forms button in Unity, because you are not building a Windows Forms application. You're building a Unity game.

You more likely want to use a Unity UI button. That's found in the `UnityEngine.UI` namespace, as a quick search of the Unity documentation will tell you.

Try `using UnityEngine.UI;` if you want to reference UI components like buttons.
> 0 votes

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


# Question
Title: How do I port a game made with Scratch, Pygame, or JavaScript to the Switch?
I've been making my own games in many different languages (mainly Scratch, Python 3 with Pygame, and JavaScript), but, so far, *none* of them have been ported to the Nintendo Switch. How can I do this?

# Answer
Searching for Scratch on Switch turns up this this list of officially rejected suggestions:

> **2.7 Scratch for video game consoles**
>
> The Scratch Team does not have the resources to put a Scratch editor onto a video game console. This includes making a Scratch editor for Nintendo Switch, 3DS, Xbox, and Playstation consoles.

Searching JavaScript on Switch turns up this way to access the web browser on the Switch and point it to an existing web page with JavaScript on it. It might not support all JavaScript features your games use, mind.

Searching for PyGame on Switch turns up this guide to developing homebrew in Python using nx-python.

When starting a new project, be sure to do these kinds of searches for yourself to get your initial leads, then ask here if you need help with a specific step along the way.
> 1 votes

---
Tags: javascript, python, pygame, porting, nintendo
---


title: Simulating a small world with Box2D

text:
# Question
Title: Simulating a small world with Box2D
I would like to use Box2D to simulate a small world, with entity sizes around 1cm (0.01m), some smaller than that.

Box2D's FAQ says twice:

> Your moving objects should be between 0.1 - 10 meters.

> You should try to get your moving objects in the range 0.1 - 10 meters, with 1 meter being the sweet spot.

I cannot simply multiply all my numbers by 100, because the simulation would become unrealistic (very slow gravity etc).

Is it possible to simulate my world using Box2D?

---

I'm wondering for instance if it would be possible to scale all the numbers by 100 and transform all the forces and the velocities I apply to the bodies (including gravity) by some factor.

# Answer
> 1 votes
You can decide to measure your game in cm instead of m.

So you'll take a 1.0 unit of distance inside your Box2D world and interpret it as 1.0 cm.

A velocity of 1.0 you'll then interpret as 1.0 \\$\frac {cm} s\\$ = 0.01 \\$\frac m s\\$.

A force of 1.0 you'll interpret as 1.0 \\$\frac {kg \cdot cm} {s^2}\\$ = 0.01 \\$N\\$.

To fix the "gravity too slow" problem, set the gravity to -981 \\$\frac {cm} {s^2}\\$ (ie -9.81 m/s times 100 cm/m).

As long as you're consistent with how you're using and interpreting your numbers, this all works with non-meter scales. too. Meters are just the most conventional/intuitive option.

---
Tags: box2d, physics-engine
---


# Question
Title: Cannot access private member declared in class
I have a class definition as such:

```
UCLASS()
class HORROR1_API UMyComplexObjectTest : public UObject
{
    GENERATED_BODY()

    public:

    UMyComplexObjectTest();
    UMyComplexObjectTest(int32 x, int32 y);

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyComplexTest")
    int32 row = 3;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyComplexTest")
    int32 col = 3;

    void setRow(int val);
};

```

And I am trying to create an instance of it in another class via :

```
UMyComplexObjectTest test1 = UMyComplexObjectTest();

```

This results in me getting the error :

```
Error   C2248   'UMyComplexObjectTest::UMyComplexObjectTest': cannot access private member declared in class 'UMyComplexObjectTest' Horror1 C:\Users\dogan\Documents\Unreal Projects\Horror1\Source\Horror1\Private\MazeGeneratorC.cpp  41

```

I am wondering if anyone can help me identify, why my constructor is still private under this circumstances. Thanks in advance!

# Answer
I believe that the reason you're getting this error is because UE4 has stylized C++, if you go to "MyComplexObjectTest.generated.h" you can find the constructor declared as private in there. If you wanna create an object you need to use NewObject(outer), in this case that would be:

```
itemPtr = NewObject<UMyComplexObjectTest>(outer);

```

I recommend you research more about the subject because C++ programming tends to be quite different when doing it in UE4. Hope this helps :)

(I will leave the link I used for clarification maybe it will also help: https://stackoverflow.com/questions/58235175/create-uobject-from-another-class-with-constructor#58257876 )
> 3 votes

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


# Question
Title: Why does my manual code bone rotation not work when a animation is active/playing?
So, I have a rigged character and created a simple walk animation in blender and export it as gltf 2.0 to godot. And in godot I also via code rotate a bone of that rigged model. The bone rotates correctly when there is no walk animation active/playing.

But the moment I walk the bone which I rotate via code doesn't rotate. And I think it's cuz the Animation overrides the bone rotations ? I tried deleting the keyframe for that particular bone in both godot and blender but that didn't work. Anyone know how I can make both my code rotation of the bone and the animation work simultaneously ? If there is a better way or I am doing wrong please let me know.

# Answer
> 0 votes
Answering from the top of my head: You need to change which pose you use.

You don't want to set the same that the animation sets because it overwrites it. Instead use a different pose. They compose into the final position. See How to get global world coordinates of bone in Godot GDscript and .translated function not working in Godot / best way to change position of bone.

If I recall correctly you need to use custom pose (`set_bone_custom_pose`), because the animation sets the pose (`set_bone_pose`).

---
Tags: godot
---


# Question
Title: How to get the up direction given a point and rotation
TLDR: **I'm asking for the direction of the up vector of an entity that can rotate in JavaScript that has a `x`, `y`, and `rotation` (in radians).**

---

I'm using a JavaScript game library. It doesn't have a `transform.up` like that of Unity. I've been looking around and I ended up with a source code reference of Unity stating the following:

```
public Quaternion rotation;
public Vector3 up { get { return rotation * Vector3.up; } }

```

And looking at the multiplication between the Quaternion and Vector3.up:

```
// Rotates the point /point/ with /rotation/.
public static Vector3 operator*(Quaternion rotation, Vector3 point)
{
    float x = rotation.x * 2F;
    float y = rotation.y * 2F;
    float z = rotation.z * 2F;
    float xx = rotation.x * x;
    float yy = rotation.y * y;
    float zz = rotation.z * z;
    float xy = rotation.x * y;
    float xz = rotation.x * z;
    float yz = rotation.y * z;
    float wx = rotation.w * x;
    float wy = rotation.w * y;
    float wz = rotation.w * z;

    Vector3 res;
    res.x = (1F - (yy + zz)) * point.x + (xy - wz) * point.y + (xz + wy) * point.z;
    res.y = (xy + wz) * point.x + (1F - (xx + zz)) * point.y + (yz - wx) * point.z;
    res.z = (xz - wy) * point.x + (yz + wx) * point.y + (1F - (xx + yy)) * point.z;
    return res;
}

```

More importantly, the quaternion x, y, z, & w are not in radians and are values between 0 and 1.

But my issue starts with that I have an object that has a `x`, `y`, and `rotation` (in radians). What math and code will I be needing in order to determine that this direction is indeed the up vector of this object? See photo below:  Pls note that I am not asking "how to rotate around a pivot point"

# Answer
> 0 votes
This is just an application of the Unit Circle.

If your forward/right direction is

```
(cosine(angle), sine(angle))

```

then a perpendicular to that is

```
(-sine(angle), cosine(angle))

```

or

```
(sine(angle), -cosine(angle))

```

Depending on your coordinate system conventions, one of these will be the up vector and the other the down vector, so choose the one that points in the direction you want to label "up".

Notice that this is just swapping the components of your forward/right vector and negating one of them. So if you already have a forward/right vector you're using for movement/etc, you can compute the up vector from it without any trig functions.

If you want a 0 angle to point in a different direction than the mathematical standard (0 radians = rightward, increasing counter-clockwise), you can similarly swap and negate the sines and cosines as needed to use that angular convention instead. In future, don't forget to specify the angular convention you use in your question itself.

---
Tags: mathematics, javascript
---


# Question
Title: How do you create a power-up system that isn't welded to the Player script?
I have various powerups in my game that do different things. They are handled through ScriptableObjects for their UI sprites, descriptions, names, duration, etc. They have a begin, tick, and end state. What I'm doing right now is basically checking in the player which name is your currently active powerup, and then doing different things depending on that like moving the player, turning off gravity, etc. I'd like the actual code for each powerup to not be tied in the player script but ScriptableObjects do not have a way to do "custom" code per instance of the ScriptableObject. I think I would have to have a ScriptableObject for the pickup data and then some other script to handle the actual processing. I do not know how to tie them together so the player can find out the logic for the pickup though besides a "powerup solver" that would find whichever script that corresponds to the powerup you have, but that seems not ideal.

# Answer
> 1 votes
One option would be to implement each active powerup as a separate MonoBehaviour which you can attach to any gameObject. That gameObject can be the player, or it can be any other gameObject. So you automatically get the ability for *anything* to receive powerups, as long as it has has the components that powerup depends on. Not just the player.

So when a gameObject has the "Double move speed" powerup, then you add the "DoubleMoveSpeed" component to said gameObject using AddComponent and later remove it via Destroy. The "Begin", "Tick" and "End State" logic can be moved into the Unity event methods `Start`, `Update` and `OnDestroy` respectively. Those will be called automatically by the engine.

That DoubleMoveSpeed component would of course be dependent on the component which handles movement speed in your game. When you are smart, you don't have a `PlayerController` god-object which does everything a player can do, but instead create a separate reusable component for every mechanic. Like a `Movement` component which you assign to anything that moves.

# Answer
> 0 votes
I think what you're looking for are Singleton, using this make a `PowerManager.cs`(or some name of your liking), then you can reference this Manager throughout your whole game/project.

---
Tags: unity, c#, effect-modifier
---


title: Vector Rotation - Casting a Cone

text:
# Question
Title: Vector Rotation - Casting a Cone
I'm working on an obstacle avoidance system in unity, and my thought is to cast a sphere along the velocity; if it hits, draw a ring of spheres around that one and repeat until max ring count or a clear path is found.

2D example

To accomplish this, I'm currently rotating the vector up and then rotating again using the velocity as the axis of rotation, and casting a sphere along the new vector.

working example

This works fine (although I'm not sure how performant it is) until the initial direction is not one of the cardinal directions.

what's happening when things go wrong

My understanding is that after the following line, rotatedVector would be a vector of equal magnitude to ray, but pointing in a new direction that could be described as having rotated about the velocityDirection a number of degrees equal to the magnitude of velocityDirection.

```
var rotatedVector = Quaternion.Euler(velocityDirection) * ray;

```

But that only seems to be happening when the velocityDirection is aligned with +- World.up, forward, or right.

Any ideas as to what's happening or how I can accomplish this goal?

Code to DrawGizmos

```
public int NumRings = 3;
private void OnDrawGizmosSelected()
{
    Vector3 velocityDirection = transform.forward * MaxSpeed;
    NumRings = Mathf.Clamp(NumRings, 0, 6);

    Gizmos.color = Color.cyan;
    for (int i = 0; i < NumRings; i++) {
        Vector3 rotationAxis = Vector3.Cross(velocityDirection, velocityDirection + Vector3.up).normalized * Mathf.Atan(i*2/ MaxSpeed) * Mathf.Rad2Deg;
        Vector3 probe;
        if (rotationAxis.magnitude > 0) {
            probe = Quaternion.Euler(rotationAxis) * velocityDirection;
        } else {
            probe = velocityDirection;
        }

        int numProbes = i == 0 ? 1 : 6*i;
        rotationAxis = velocityDirection.normalized;
        for (int j = 0; j < numProbes; j++) {
            var test = Quaternion.Euler(rotationAxis * 360 / numProbes * j) * probe;
            Gizmos.DrawLine(transform.position, transform.position + test);
            Gizmos.DrawWireSphere(transform.position + test, 1f);
        }
    }
}

```

# Answer
@DMGregory pointed out that the vector rotation function I was looking for was Quaternion.AngleAxis.

Changing var test to the below resulted in the desired behavior.

```
var test = Quaternion.AngleAxis(360 / numProbes * j, rotationAxis) * probe;

```

Thanks again @DMGregory
> 1 votes

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


# Question
Title: How can I save a scene which consists of continuing text?
I am trying to make a simple book reading app. In scene, it will show only one word from the book every 0.5 seconds. What I want is, when I click pause then quit the game or just back to Main Menu and after returning to Main Menu, when I click to Read Book button, I want to continue from the word I left off. Below is a part of code which will be shown after clicking Read Book button.

```
void Start()
{
    textFile = (TextAsset)Resources.Load("FirstBook");
    string texts = textFile.text;

    StartCoroutine(Show(texts));
}
IEnumerator Show(string book)
{
    yield return new WaitForSeconds(1f);

    string[] splitArray = book.Split(' ');
    text = GameObject.FindWithTag("BookText").GetComponent<Text>();

    for (int i = 0; i < splitArray.Length; i++)
    {
        text.GetComponent<Text>().text = (splitArray[i]);
        yield return new WaitForSeconds(0.5f);
    }
}

```

And below is what I used in my AppManager gameobject for pausing.

```
private bool paused;
public void ChangePaused()
{
    if (Time.timeScale == 1 && paused == false)
    {
        Time.timeScale = 0;
    }
    else
    {
        Time.timeScale = 1;
    }
}

```

My English is not that good so I am having difficulties to explain my problem, if you can't understand what I need I will try to explain better. Briefly, when I click pause it will keep the word I left off, and then I will back to Main Menu, I will click Read Book button and I will continue from the word I left off. How can I do this?

# Answer
As @Zibelas suggests I think what you're looking for is saving and loading a value and an easy way to do that is by using PlayerPrefs.

When pausing or OnApplicationQuit() `PlayerPrefs.SetInt($"{bookName}", currentWordIndex);`

when loading book `currentWordIndex = PlayerPrefs.GetInt($"{bookName}", 5);`
> 1 votes

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


# Question
Title: 2D sprite is 'blinking' when animation is playing
When I fire a bullet, instead of frames 4 and 6, the sprite selector in the sprite renderer component says "Missing (Sprite)" and 'blinks' for a frame, not showing anything.

# Answer
> 1 votes
Check what layer the sprite is on. Make sure it's not on the same layer as the background. Otherwise it might occasionally draw behind the background instead of in front, making it look like it's blinking.

# Answer
> 0 votes
This sounds like an issue with your script.

If you are using a script to cycle through your sprites, make sure that the variables containing your sprites are assigned.

# Answer
> 0 votes
This problem occurs when you have two objects lying in the same layer.

Changing the 'order in layer' in the objects Sprite Renderer fixed this for me. 0 for the layer you want at the backmost and higher value for objects you want at the front.

---
Tags: unity, 2d, animation, sprites
---


# Question
Title: How can I make my Camera's RenderTexture output have a transparent background?
I'm writing a 3D game using Unity 2017.1.0b1. I have a disabled Camera that takes a "snapshot" of the current scene and stores it in a RenderTexture when a button is clicked. I then display the RenderTexture in a RawImage within my scene.

This works, except that the output from the Camera into the RenderTexture doesn't take into account the alpha value of the Camera's clear color.

Here's a snapshot of how my disabled Camera is configured. Notice the Background property has an alpha value of 0:

Here's a snapshot of what the RenderTexture (displayed using a RawImage) looks like in the game. The blue square is the RenderTexture:

How can I make the Camera render into the RenderTexture with a transparent background? I didn't expect the blue background to show up in the RenderTexture since its alpha value is 0.

# Answer
I had the same problem and realized that my RenderTexture had a depth of 24, so no alpha. Here's a piece a code that to allows me to take a picture of a 3d model to use it as a sprite, with no background:

```
public Camera Camera3D;
public int ImageSize;
public Sprite Result;

private RenderTexture mRenderTexture;

public void SetTarget(Transform target)
{
    mRenderTexture = new RenderTexture(ImageSize, ImageSize, 32);
    Camera3D.targetTexture = mRenderTexture;
    transform.SetParent(target, false);
    Camera3D.Render();
    transform.SetParent(null, false);
}

private void OnPostRender()
{
    if(mRenderTexture != null)
    {
        RenderTexture.active = mRenderTexture;
        var virtualPhoto = new Texture2D(ImageSize, ImageSize, TextureFormat.RGBA32, false);
        virtualPhoto.ReadPixels(new Rect(0, 0, ImageSize, ImageSize), 0, 0);
        virtualPhoto.Apply();

        RenderTexture.active = null;
        Camera3D.targetTexture = null;

        Result = Sprite.Create(virtualPhoto, new Rect(Vector2.zero, new Vector2(ImageSize, ImageSize)), Vector2.zero);

        mRenderTexture = null;
    }
}

```
> 2 votes

# Answer
For Unity 2019.4 I needed to set one camera as an overlay camera via... "Camera Component" --\> "Render Type" --\> Overlay. Secondly, I needed to take the other camera and add a stack element in it's Camera Component (at bottom) then select my Overlay Camera to add to the stack.
> 2 votes

# Answer
If you want to layer cameras on top of each other and use the lower layered camera as the "background" to the other cameras, you need to set the Clear Flags of the higher layer cameras to Depth Only.

In your case, your background camera should be at a lower depth (ex. -1) than the camera in the provided screenshot (which is 0). Your camera in the screenshot should have its clear flags set to depth only and your background camera should have solid colour as its clear flags variable.

Relevant Unity manuals here and here.
> 1 votes

# Answer
https://forum.unity.com/threads/using-render-textures-on-a-ugui-image-panel-or-button.272332/

User called 'byrne' posted this OverlayBlend shader. Use it for the RawImage material.

```
Shader "Custom/OverlayBlend" {
Properties {
    _MainTex ("Texture1 (RGB)", 2D) = "white" {}
    _Color ("Main Color", Color) = (1,1,1,1)
}

Category {
    Tags {"RenderType"="Opaque" "Queue"="Transparent"}
    Lighting Off
    BindChannels {
        Bind "Color", color
        Bind "Vertex", vertex
        Bind "Texcoord", Texcoord
    }

    //screen 1 - (1 - a) * (1 - b)

    SubShader {
        Pass {
            ZWrite Off
            Cull Off
            Blend One One
            BlendOp Sub
            SetTexture [_MainTex] {
                constantColor (1,1,1,1)
                Combine constant
            }
        }

        Pass {
            ZWrite Off
            Cull Off
            Blend Zero OneMinusSrcColor
            BlendOp Add
            SetTexture [_MainTex] {
                constantColor [_Color]
                Combine texture * constant
            }
        }
        Pass {
            ZWrite Off
            Cull Off
            Blend One One
            BlendOp Sub
            SetTexture [_MainTex] {
                constantColor [_Color]
            }
            SetTexture [_MainTex] {
                constantColor (1,1,1,1)
                Combine constant, previous
            }
        }
    }
}

```

}
> 0 votes

# Answer
Obviously this is only 2 years late, but you can just change the settings to allow transparency, after rigging the camera properly like everyone has already said, by changing the colour settings from whatever it is now, to R32G32B32A32, because I think it needs to be 32 bit to allow transparency potentially. I was capturing stuff for a render texture, but I had to change the shape of what I was capturing, but stuff from my game was getting in the spaces that the shape didn't take up, so I just did this and it worked.

Again, sorry this is late but if someone comes on this thread, they can see it I guess ¯\_(ツ)\_/¯
> 0 votes

---
Tags: unity, camera, transparency, alpha, rendertexture
---


# Question
Title: Unity 2D - Raycast not colliding with collider in very specific circumstances
I've been trying to work out what could be causing this bug for days now but can't figure it out for the life of me.

I'm trying to make a fish avoid the walls of it's tank in a Unity game I'm creating by: using circle colliders to notify the fish when it hits a wall, making the fish then send out a ray in all 4 cardinal directions towards identical (although obviously with different positions/rotations) boundary colliders, then finding the ray with the shortest distance to know which edge to move away from.

My issue is that generally when my fish is facing left, the ray cast to the right returns null, and vice versa when the fish is facing right (the ray to the left will return null). The only rare exception I've to this has been when the fish is facing left and in the right half of the tank, in that case it will not find the left collider. **In all cases, it will not find either the left or right collider.**

The white circle visible in the screenshots is "Outer Sensor" and the red circle is "Inner Sensor", both have a Circle Collider 2D component. The red boxes visible are the boundaries, these are all identical and each have a Box Collider 2D component.

The method for detecting the closest edge is as follows:

```
string FindClosestEdge()
    {
        string guid = System.Guid.NewGuid().ToString().Substring(0, 4);

        Debug.DrawRay(transform.position, Vector2.up, Color.red, 1, false);
        Debug.DrawRay(transform.position, Vector2.right, Color.green, 1, false);
        Debug.DrawRay(transform.position, -Vector2.up, Color.yellow, 1, false);
        Debug.DrawRay(transform.position, -Vector2.right, Color.blue, 1, false);

        Dictionary<string, RaycastHit2D> distances = new Dictionary<string, RaycastHit2D>();

        float closestEdgeDistance = 999;
        string closestEdge = null;

        RaycastHit2D up;
        RaycastHit2D right;
        RaycastHit2D down;
        RaycastHit2D left;

        up = Physics2D.Raycast(transform.position, Vector2.up, layerMask);
        right = Physics2D.Raycast(transform.position, Vector2.right, layerMask);
        down = Physics2D.Raycast(transform.position, -Vector2.up, layerMask);
        left = Physics2D.Raycast(transform.position, -Vector2.right, layerMask);

        distances.Add("up", up);
        distances.Add("right", right);
        distances.Add("down", down);
        distances.Add("left", left);

        foreach (var item in distances)
        {
            Debug.Log(guid + " " + item.Key.ToUpper() + " ray collided with: " + item.Value.collider.gameObject.name  + " at a distance of: " + item.Value.distance);
            if (item.Value.distance < closestEdgeDistance)
            {
                closestEdge = item.Key;
                closestEdgeDistance = item.Value.distance;
            }
        }

        distances.Clear();
        Debug.Log(guid + " Closest edge: " + closestEdge);
        return closestEdge;
    }

```

The below screenshots show the Unity editor in two cases of this happening, and the results of some testing I just tried:

**Please let me know if you need any further info to figure this out, any help would be greatly appreciated!**

# Answer
Upon further investigation, it seems that I was experiencing the same issue described in this previous GameDev question.

Hope this helps anyone encountering a similar problem.
> 0 votes

---
Tags: unity, 2d, collision-detection, raycasting
---


# Question
Title: using a starting and ending point, how can i find how far in-between those two points a third point is?
quick diagram to explain what i mean. i have a start and an end, the third point can be anywhere in space, but i need to calculate from 0-1 how far they are in-between these two points.

The points are 3d but im only using two axes if that matters.

The answer to this is probably pretty simple but i cant think of it and i cant find the right search terms to find anything that helps me.

# Answer
The point projected onto the Start-End segment can be found using the dot product operator to perform a scalar projection:

In your scenario, let's call \\$P\\$ the *Point*, \\$S\\$ the *Start*, and \\$E\\$ the *End* points. If \\$P'\\$ is the projection of \\$P\\$ onto the segment \\$\overline{SE}\\$, its length is:

$$ \overline{SP'} = \overline{SP} \space cos \theta = \mathbf{p} \cdot \mathbf{l} = \mathbf{p'} $$

where \\$\theta\\$ is the angle between the vector \\$\mathbf{p}\\$ (pointing from \\$S\\$ towards \\$P\\$) and the vector \\$\mathbf{l}\\$ (pointing from \\$S\\$ towards \\$E\\$, thus the segment itself).

Depending on the implementation, you need some additional math first to find out the length of those vectors before performing dot product on them, which in Unity's C# is something like:

```
float projP = Vector3.Dot(P-S, E-S);

```

Finally, you can compute the 0-1 value of where \\$P'\\$ lies when between \\$P\\$ and \\$E\\$, by normalising the length of \\$\mathbf{p'}\\$ over \\$\mathbf{l}\\$:

$$ \hat{\mathbf v}=\frac{\mathbf p'}{\\|\mathbf l\\|} $$

Or:

```
float percentage = projP / (E-S).magnitude;

```
> 2 votes

---
Tags: mathematics, vector
---


# Question
Title: What does "Write Defaults" in the animation state inspector actually do?
In my Unity project, I had an issue recently where a tool which autogenerated animation controller layers caused issues with existing layers because it was generating layers with Write Defaults set to OFF, but the existing layers were full of states where it was set to ON.

On talking with others, I gather that mixing these two settings in the same controller causes chaos.

But the thing is, if that were *truly* the case, the UI would reflect that. It would just be a single checkbox on the entire controller, and I wouldn't be able to set it differently on every single node. Yet I can, so there must be a use case for mixing them.

Unity defaults this checkbox to ON, suggesting that they recommend that.

VRChat, on the other hand, recommend setting it to OFF.

So I don't know who is right on this but it creates an annoying situation where if I want to follow VRChat's recommendations I have to manually uncheck a checkbox on every single animator node, which isn't great UX.

So what I'm wondering is, exactly what does this checkbox do that makes a *mix* of the two settings break stuff, while setting everything to OFF or everything to ON apparently works fine together. Does it exist solely to torment new developers who don't expect that the editor has extreme quirks?

# Answer
This is one of those questions you can answer with a search.

For me, the third result is the official documentation, stating:

> **Write Defaults**: Whether or not the AnimatorStates writes back the default values for properties that are not animated by its Motion.

And the second result is this thread including a quotation from a Unity developer about why they chose to default it to ON:

> In 5.0 we have added a property on the State to "Write back default values". Meaning that if turned on, it will write back the default values of all animated properties ( on a Controller wide-basis) that are not animated in that State.
>
> By default, its "on", so we don't change the behavior that we had before.
>
> So if you want the non-animated properties of a State to keep the value it had previously, simply turn it off.

So it looks like the default ON was chosen for backward compatibility with versions before 5.0, so as to not break pre-5.0 assets/projects that relied on this behaviour, not because they recommend it be left ON in every project. (If it were meant to *always* be left on, they would not have added the option to turn it off!)

If compatibility with VR Chat is important to your project today, then follow VR Chat's current recommendations, not a backward compatibility concession that was made for an ancient version of the engine from half a decade ago.
> 3 votes

# Answer
As the documentation says, this setting decides what happens with those values which are not animated by *this* state, but are animated by *another* state in the same layer of this animation controller. When you switch it on, those values are reset back to the default upon entering this state. When you switch it to off, they retain whatever values they had after exiting the previous state.

Regarding the conflicting recommendations regarding "always on" and "always off": It is perfectly possible to mix both behaviors in the same animation controller, and there certainly are use-cases for it. But for consistency reasons, it can be useful to stick to either one or the other as your default setting for your project and only choose the other when you have a good reason. It makes it easier for you to form a mental model regarding how animation state transitions work in *your* game.
> 4 votes

---
Tags: unity, animation, animator
---


# Question
Title: Character bounces when platform goes up and down
I have **a player character** with a few `2D Colliders` and a `Rigidbody 2D` attached to it.

When sitting on a **platform** the **player character** can **control the platform** via a lever **and move it up and down**.

This is a short video to showcase the mechanic:

https://media.giphy.com/media/lqgvOWkKyS7euwJwLx/giphy.gif

You can notice the character **bouncing** when the platform moves down. The platform movement is done via a Tweening library (DOTween).

How exactly can I make the **player character** to **stick to the platform** instead of bouncing around?

# Answer
As suggested by @Nikaas, there are apparently two common approaches to solve this, one by **making the player character a child of the platform** and the other one to **add platform movement to the character's own movement**.

I decided to go with the first approach and it works wonders.

If anyone also encounters this issue, here is my code that should be attached to the platform. The `objectToAttach` gameobject is a reference to the player character. I will not comment it as I believe most of the functions are very self-explanatory.

```
using UnityEngine;

public class AttachChildOnTouch : MonoBehaviour
{
    [SerializeField] private GameObject objectToAttach;

    public GameObject GetObjectToAttach()
    {
        return objectToAttach;
    }

    public void SetObjectToAttach(GameObject objectToAttach)
    {
        this.objectToAttach = objectToAttach;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            objectToAttach.transform.SetParent(this.transform);
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            objectToAttach.transform.parent = null;
        }
    }
}

```
> 1 votes

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


title: Roads rendering over 3D terrain

text:
# Question
Title: Roads rendering over 3D terrain
I've got a 3D terrain that consists of many heightmap-based tiles. I need to render multiple roads over the tile. By now I simply subdivide road into tile pieces then generate a decal per each tile. But decals are pretty expensive on memory. Is there any better solution than using decals or baking roads into the tile texture? (Target application should work on mobile device with OpenGL ES 2.0 support)

# Answer
> 2 votes
An alternative to incorporating the roads into your terrain texture is to model them as separate geometry, for example as triangle strips. The problem with *that* is you want the road geometry to be very close to the terrain geometry, which leads to depth ambiguity. Sometimes the terrain will appear in front of the road, and that may change (flicker) as the camera moves. In some OpenGL applications it is possible to force one “layer” to be in front by drawing in two sequential passes, and turning off depth testing for the second layer:

```
// Draw terrain.
[...]

// Draw roads.
glDisable(GL_DEPTH_TEST);
[...]
glEnable(GL_DEPTH_TEST);

```

However this may not work for you since you may have roads behind terrain that you **do** want to to be occluded. If so, baking your roads into the terrain textures may be the best approach. But then the road surface will always have slope parallel to the terrain. Or possibly, modeling the roads as separate geometry, and lifting them above the terrain by such a large amount that the depth ambiguity goes away.

# Answer
> 0 votes
A good solution is to use multi-texturing and a blend map to add road texture onto the terrain. Check out this excellent tutorial for further details

https://www.youtube.com/watch?v=-kbal7aGUpk

---
Tags: graphics, opengl-es2, terrain
---


# Question
Title: Unity Property Drawer: getting a reference to the property and to its "owner" behaviour?
I've created the **MyProperty** class to be used on **MyBehaviourScript** as a public member:

```
[Serializable]
public class MyProperty
{
    public int Min;
    public int Max;

    public void MyMethod(MyBehaviourScript owner)
    {
        ...
    }
}

```

I've managed to draw a button in its **PropertyDrawer**:

```
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
    EditorGUI.PropertyField(position, property, label, true);
    if (EditorApplication.isPlaying && property.isExpanded)
    {
        if (GUI.Button(new Rect(...), "Text"))
        {
            // todo: call the property's MyMethod method
        }
    }
}

```

And when I **click the property's button**:

I'd like to call the property's **MyMethod** method with its "owner" **MyBehaviourScript** as a **parameter**. (I don't know the exact terminology here)

But I don't know how could I get **a reference to the property and to its "owner"**.

Is this possible? If so, how? Thanks!

# Answer
This seems to do the trick:

```
[CustomPropertyDrawer(typeof(MyProperty))]
public class MyPropertyDrawer : PropertyDrawer
{
    MyProperty targetProperty;

    public override void OnGUI(
       Rect position,
       SerializedProperty property,
       GUIContent label
    ) {
        if (targetProperty == null)
             targetProperty = (MyProperty)GetPropertyInstance(property);

        if (GUI.Button(new Rect(position), "Text")) {
            var owner = (MyBehaviourScript)property.serializedObject.targetObject;
            targetProperty.MyMethod(owner);
        }
    }

    public System.Object GetPropertyInstance(SerializedProperty property) {

        string path = property.propertyPath;

        System.Object obj = property.serializedObject.targetObject;
        var type = obj.GetType();

        var fieldNames = path.Split('.');
        for (int i = 0; i < fieldNames.Length; i++) {
            var info = type.GetField(fieldNames[i], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (info == null)
                break;

            // Recurse down to the next nested object.
            obj = info.GetValue(obj);
            type = info.FieldType;
        }

        return obj;
    }
}

```

Note however that if you enforce that the argument to `MyMethod` must always be a `MyBehaviourScript`, then you can't use this property and its drawer with any type not derived from `MyBehaviourScript`, so you might be able to implement this more simply as part of a `CustomEditor` for `MyBehaviourScript` instead of a `PropertyDrawer` for the individual property.
> 1 votes

---
Tags: unity
---


# Question
Title: Why does my deformed mesh's outer shape look awkward when none of the inner mesh vertices seem to be moved passed the outer vertices?
I'm trying to deform my mesh but the vertices cause these straight edges to occur where the inner mesh passes the outer mesh and create an awkward shape.

Why does the orange outline of the mesh not match the vertex distribution? The red squares are the outer mesh vertices and the black are the inner vertices and none of the inner vertices seem to pass the outer vertices so why is it creating this shape? What possible approaches are there to fix this?

# Answer
Look at the bottom two orange vertices, for example, marked with arrows below. They're part of a triangle that includes another vertex that's been pushed a long distance away from them, marked with a blue arrow.

When you moved your vertices, it looks like you didn't change the triangulation of your mesh, so the yellow triangle that joined these three vertices got stretched all the way from one end of the U bend to the middle.

A single triangle can't bend. All it can do is make a flat plane between the straight-line edges joining its three vertices. If those straight lines cut diagonally across an area that you'd prefer to be a smooth bend, there's no intermediate points within that span to tell the GPU that you want it to do something else.

So: when deforming your mesh, avoid creating long skinny triangles like this. Or, if you need to move vertices far away from their neighbours, you may want to look into adaptive subdivision and re-triangulation, to change your mesh topology so any long span like this is broken up into smaller triangles that better follow the curve you want.
> 1 votes

---
Tags: vertex
---


# Question
Title: How do I work with Runtime Virtual Textures in UE5?
I just created a Runtime Virtual Texture, but when I double click to edit it, I get no options at all.

How can I reach the options and work with it, what am I missing here?

# Answer
> 1 votes
So, I just needed to press Window =\> Details and it opened the options back up. Not really sure what happened there (if I accidentally closed it or not).

---
Tags: unreal, unreal-5
---