# Question
Title: Unity tiles with wierd border flickering when moving horizontal 2D
I recently made some Tiles using a program called Pyxel Edit to create some placeholder graphics. The problem I'm having is that when I move the camera horizontal the edge of the tiles starts to flicker, however if I move the camera vertical it wont.

This is my settings for the Tilemap, I have sliced them up inside the sprite editor.

This is a gif of what I'm talking about:

The image maybe isn't that clear but if you watch closely you can see some borders appear when I'm moving.

Do anyone know what could have caused this and what could be done to fix it?

EDIT: Second image for clarity:

# Answer
> 0 votes
I have faced this problem earlier.This is because the "Generate Mip Maps" option is on. You need to deselect that option and apply the changes to the sprites.

Mip Maps are pre-calculated, optimized sequences of textures, each of which is a progressively lower resolution representation of the same image. They are intended to increase rendering speed and reduce aliasing artifacts. A high-resolution mipmap image is used for high density samples, such as for objects close to the camera. Lower-resolution images are used as the object appears farther away.

Hence in your case the rendering is shifted to a lower resolution due to which you see the gap between two sprites.

# Answer
> 1 votes
I know that it is an old post but I found a way to fix this issue, so I post it to help people that encounter this bug.

I achieved it by changing the `Pixels per Unit` of the tileset image to `15.99` instead of `16` (or `31.99` instead of `32`...).

That just makes the images a little bit bigger and there are no stripes anymore.

I hope this could help somebody and goodbye!

# Answer
> 1 votes
though @Bic's solution is worked for me on desktops (Mac, Windows) it had no effect on tvOS unfortunately

fortunately using Sprite Atlases solved the issue on all platforms

a Unity thread about this https://forum.unity.com/threads/strange-stripes-and-dots-appear-on-the-tilemap-in-game-mode.1174772/

I did not add the Tiles separately to the Sprite Atlas like on the video, instead added the sprites the tiles were generated from that did the trick perfectly

# Answer
> 0 votes
creat new material\> sprite\> default and check the pixel snap and apply to your tiles

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


title: The colors of Unity 2019 are different

text:
# Question
Title: The colors of Unity 2019 are different
I currently use Unity 2018 LTS, because of my 2019 Unity colours are not really good. For example, the white is not really white but more like grey and the Shadows are really strong too even if I change the Shadow type. Why is this happening?

This is Unity 2019

and Unity 2018-LTS

If I change the Directional Light Color from light yellow to Full White then it is whiter, but it doesn't solve the Shadow problem.

# Answer
> 1 votes
By looking at the bottom right corner of the 2019 picture, I can see that the lighting in your scene is *not auto generated*, which makes the colors unsaturated and dark.
Go to window -\> rendering -\> lighting settings and make sure auto generate is on and now your scene will look normal. Though I'm not sure why this would be off in the first place

# Answer
> 0 votes
Office Batman's answer works, but I also solved this issue by setting my camera to a solid black color backdrop (since ambient pulled from that I think) and disabling the Flare component that I believe got added to the camera when upgrading from 2018. I have not narrowed it down to exactly what solved the issue, but one of these stopped the "washed out colors" effect I had after my upgrade!

---
Tags: unity, lighting, shadows, color
---


# Question
Title: Unity3d custom Frustum Culling - find all points on the near side of a sphere
**Scenario**

I have a custom sphere of 1 million plus vertices that I'm using for an interactive. Looping through 1M+ points per mouse movement is exceedingly costly so I've decided to leverage frustum culling. This helps but all the points on the back-facing side of the sphere are still being looped through which is still very costly.

My plan is to cut the sphere in half with a plane that is perpendicular to the viewing camera's angle. I'll place the sphere origin at the `0,0,0` of the sphere and viola it's cut in half.

**Question**

My issue is that if the plane is at an angle, which it will be 99.9% of the time, how can I verify that a given Vector3 is on the normal side of the plane?

*extra*

* I'm using `GeometryUtility.CalculateFrustumPlanes` to get the frustum bounds
* While writing this question I thought (and plan) to prototype adding my plane "slice" to the frustum boundary planes then using `GeometryUtility.TestPlanesAABB` to determine which points should be rendrered

# Answer
> 0 votes
I came up with the idea to shorten the camera frustum to end at the center of my target group, check all of my object's collider positions against `TestPlanesAABB`, then set the camera frustum back to what it was.

```
public static bool IsColliderVisible(Collider collider, Vector3 targetPos)
{
    UnityEngine.Camera camera = UnityEngine.Camera.main;
    float distanceToCutoff =
        Vector3.Distance(camera.transform.position, targetPos);
    float frustumLength = camera.farClipPlane;
    camera.farClipPlane = distanceToCutoff;
    Plane[] frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera);
    camera.farClipPlane = frustumLength;

    return GeometryUtility.TestPlanesAABB(frustumPlanes, collider.bounds);
}

```

*extra*

I may end up using a nearest-neighbor type algorithm to take a point I know is within view and work form there.

---
Tags: unity, frustum-culling
---


# Question
Title: Make materials higher quality as the user gets closer
**Scenario**

I have a sphere with an low-quality earth texture on it. I also have a much higher quality earth texture (Gigabytes in size) that I can use but it's too performance intensive to use on most devices, especially mobile.

My current plan is to break the higher definition image into tiles (like how google maps does it) and load higher resolution tiles as the user zooms in.

**Question**

Is there a better way to do this?

# Answer
> 0 votes
Ultimately I went with a slippy map and added the following

# Answer
> 2 votes
Sounds like you may want to use the LOD system. It stands for level of detail. You can set different rendering qualities based on the distance you’re viewing it from. It’s really useful for rendering far away things with low quality/high performance while rendering close things with far more detail.

---
Tags: unity, textures, performance, tilemap, image
---


title: Puzzle logic management

text:
# Question
Title: Puzzle logic management
This is my first ever question here; I'm pretty stuck on a certain feature I'm working on in order to learn.

I'm working in Unity 3D. I'm trying to make a set of buttons that work in unison to unlock a door. The general idea is that there's 5 buttons, and the player has to walk on them in a specific order, for the door to open.

Currently, I have the individual buttons working - if the player walks on one, it turns it on and changes the colour, if he walks on the button again, it turns it off and reverts back to the initial colour, so my individual buttons are fine and work both ways (on/off).

Where I am stuck, is creating a relationship between the buttons. So for example, if button 1 is on and the player walks onto button 5, I want button 1 to reset to the off state but I'm totally lost on how to develop a relationship between these individual buttons!

So far, I've theorized that I need an empty game object with a script attached that controls the relationship, and change in state dependent on the order, and I'm guessing that it needs to involve a switch case statement, but beyond that I'm both totally unsure!

# Answer
A generic way to solve this is with two lists.

One list holds the correct answer to the puzzle. It could be initialized from a file, generated procedurally or hard coded - doesn't really matter. The important part is, you have data with the right answer.

The second list holds the player's attempt. Initially it will be empty. As the player steps through the correct sequence of buttons, they will get added to the list. When the player makes a mistake it will get reset.

To process things, every time the player walks off a button, do the following:

* add that button's ID to the attempt list
* loop through the attempt list & compare each entry to the answer
    + if while looping, there's an entry that doesn't match
        - clear the attempt
        - reset the button colors
* if no mismatches were detected & the attempt is the same size as the answer, open the door

The processing code might look something like this:

```
attempt.Add(id);
for(int a=0; a<attempt.Count; a++)
{
   if(attempt[a] != answer[a])
   {
      attempt.Clear();
      ResetAllButtons();
   }
}
if(attempt.Count == answer.Count)
{
  OpenDoor();
}

```
> 2 votes

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


# Question
Title: OnMouse Events stop working when multiple cameras are active
I'm working on 2019.4.9f1 on a 2D project using Universal Rendering Pipeline. The camera settings changed so I'm stating it.

I wrote a `OnMouseEnter` and `OnMouseExit` in a script to manage whenever my mouse cursor is on top of a SpriteRenderer with a collider located at `0,0,0`. I have a main camera located at `0,0,-10`. I've tested the script that manages the `OnMouse` events. It works fine.

**Problem**: But the moment I add a new camera (UI Camera set to Overlay located at `0,0,-10`) in and it is enabled, `OnMouse` events aren't getting called. Disabling the UI camera makes the `OnMouse` events work normally.

**Solutions that have failed:**

1. I've tried setting the tag of the UI Camera to `MainCamera` and set Main Camera's tag to `Default`. https://answers.unity.com/questions/241334/onmousedown-w-multiple-cameras-doesnt-work-right.html
2. I tried making the UI Camera a bit closer to the sprites. https://answers.unity.com/questions/425478/onmousedown-not-firing.html

**I intend to avoid Raycasting and get the `OnMouse` Events to work because I want to fix the problem and not work around it.**

**Question**: Any possible reason why my OnMouse events aren't called?

# Answer
> 2 votes
I found a workaround for those interested.

Before setting your overlay camera to overlay, head to rendering - priority, and set to a number lower than your main camera. After that, you may change render type back to overlay.

OR

Simply set main camera priority to a higher number.

# Answer
> 0 votes
same issue here, my setup is

* base camera with two overlays
* one of them is rendering only UI (UICamera)
* the UI Canvas render mode is "Screen Space - Camera" and the Render Camera is set to the UICamera

in my case the solution was to set the Canvas "Plane distance" greater then 0 (actually i guess something greater needed than the camera clipping plane near value)

hope this helps someone too

---
Tags: unity, events
---


title: Quaternions and Euler Angles

text:
# Question
Title: Quaternions and Euler Angles
I have made a simple animation in blender where the object(Bone in this case) is rotated from 0 to 360 degrees within 40 keyframes I then exported that data(Each keyframe) to glTF which stores the rotation of each keyframe as quaternion. After that i read each keyframe from the file and converted the quaternion(I also normalized the quaternion before that just in case) to XYZ euler angles, however the results are very unexpected and confusing.

This is the output:

```
Quat XYZW: -6.584865E-8, -6.71794E-8, -4.853328E-15, 1.0
maps to Euler(XYZ) In radians: -1.316973E-7, -1.343588E-7, -1.8554003E-14 | In degrees: -7.545699778706759E-6, -7.69819215990934E-6, -1.0630660420387862E-12

Quat XYZW: -6.584723E-8, 0.0065628546, -4.321644E-10, 0.9999785
maps to Euler(XYZ) In radians: -1.316973E-7, 0.013125804, -1.8542322E-14 | In degrees: -7.545699778706759E-6, 0.7520531864073278, -1.0623967938537065E-12

Quat XYZW: -6.5826804E-8, 0.025757458, -1.6961029E-9, 0.99966824
maps to Euler(XYZ) In radians: -1.316973E-7, 0.051520616, -1.823185E-14 | In degrees: -7.545699778706759E-6, 2.9519138441784234, -1.0446080897377453E-12

Quat XYZW: -6.5742256E-8, 0.056824293, -3.741812E-9, 0.99838424
maps to Euler(XYZ) In radians: -1.3169732E-7, 0.113709845, -1.8772983E-14 | In degrees: -7.545700592928757E-6, 6.515094187466668, -1.0756126741124562E-12

Quat XYZW: -6.5525505E-8, 0.0989473, -6.515556E-9, 0.9950927
maps to Euler(XYZ) In radians: -1.3169729E-7, 0.19821896, -2.0836097E-14 | In degrees: -7.545698964484761E-6, 11.357109632076618, -1.1938204425972884E-12

Quat XYZW: -6.5091555E-8, 0.15120457, -9.956626E-9, 0.9885025
maps to Euler(XYZ) In radians: -1.3169729E-7, 0.3035735, -1.861474E-14 | In degrees: -7.545698964484761E-6, 17.3934797025985, -1.0665460355383746E-12

Quat XYZW: -6.43445E-8, 0.21251643, -1.3993929E-8, 0.9771575
maps to Euler(XYZ) In radians: -1.3169728E-7, 0.42829898, -2.1480152E-14 | In degrees: -7.545698150262762E-6, 24.539723923622546, -1.2307220789639523E-12

Quat XYZW: -6.31839E-8, 0.2815993, -1.8542945E-8, 0.9595321
maps to Euler(XYZ) In radians: -1.3169729E-7, 0.5709209, -2.1111827E-14 | In degrees: -7.545698964484761E-6, 32.71135712398392, -1.2096185822782078E-12

Quat XYZW: -6.15112E-8, 0.35693273, -2.350355E-8, 0.9341301
maps to Euler(XYZ) In radians: -1.3169728E-7, 0.7299645, -3.3372332E-14 | In degrees: -7.545698150262762E-6, 41.823884741007696, -1.9120937992588885E-12

Quat XYZW: -5.923645E-8, 0.43674588, -2.8759136E-8, 0.89958495
maps to Euler(XYZ) In radians: -1.3169728E-7, 0.90395635, -3.4464144E-14 | In degrees: -7.545698150262762E-6, 51.79288392900523, -1.9746500140954907E-12

Quat XYZW: -5.6284716E-8, 0.51902527, -3.4177116E-8, 0.854759
maps to Euler(XYZ) In radians: -1.3169728E-7, 1.0914207, -3.0811074E-14 | In degrees: -7.545698150262762E-6, 62.533796946051744, -1.765344512671221E-12

Quat XYZW: -5.260214E-8, 0.60155135, -3.9611358E-8, 0.79883415
maps to Euler(XYZ) In radians: -1.3169719E-7, 1.2908835, -1.2859481E-13 | In degrees: -7.545693264930771E-6, 73.9621787483438, -7.367939727230888E-12

Quat XYZW: -4.8161187E-8, 0.68195695, -4.490595E-8, 0.7313923
maps to Euler(XYZ) In radians: -1.3169702E-7, 1.50087, -3.0508725E-13 | In degrees: -7.54568349426679E-6, 85.99351599018624, -1.748021205393232E-11

Quat XYZW: -4.2964448E-8, 0.7578121, -4.990091E-8, 0.6524729
maps to Euler(XYZ) In radians: 3.1415925, 1.4216864, -3.1415927 | In degrees: 179.999991348578, 81.45663113589697, -180.00000500895632

Quat XYZW: -3.704698E-8, 0.82672364, -5.4438644E-8, 0.56260824
maps to Euler(XYZ) In radians: 3.1415925, 1.1950747, -3.1415927 | In degrees: 179.999991348578, 68.47273522183704, -180.00000500895632

Quat XYZW: -3.0476517E-8, 0.8864487, -5.837146E-8, 0.46282688
maps to Euler(XYZ) In radians: 3.1415925, 0.96236306, -3.1415927 | In degrees: 179.999991348578, 55.13934194304214, -180.00000500895632

Quat XYZW: -2.335154E-8, 0.9350088, -6.156907E-8, 0.35462454
maps to Euler(XYZ) In radians: 3.1415925, 0.72502494, -3.1415927 | In degrees: 179.999991348578, 41.54086902255905, -180.00000500895632

Quat XYZW: -1.5797392E-8, 0.97079647, -6.3925626E-8, 0.23990472
maps to Euler(XYZ) In radians: 3.1415925, 0.48453543, -3.1415927 | In degrees: 179.999991348578, 27.761834928724795, -180.00000500895632

Quat XYZW: -7.960307E-9, 0.9926662, -6.5365725E-8, 0.12088809
maps to Euler(XYZ) In radians: 3.1415925, 0.24236898, -3.1415927 | In degrees: 179.999991348578, 13.886719710062323, -180.00000500895632

Quat XYZW: 7.731664E-15, 1.0, -6.584865E-8, 2.3468012E-8
maps to Euler(XYZ) In radians: 3.1415925, 4.6936023E-8, -3.1415927 | In degrees: 179.999991348578, 2.6892360289340074E-6, -180.00000500895632

Quat XYZW: -7.920893E-9, -0.9927389, 6.5370514E-8, 0.120289244
maps to Euler(XYZ) In radians: 3.1415925, -0.24116248, -3.1415927 | In degrees: 179.999991348578, -13.81759221924627, -180.00000500895632

Quat XYZW: -1.5651457E-8, -0.9713415, 6.396153E-8, 0.23768824
maps to Euler(XYZ) In radians: 3.1415925, -0.47997037, -3.1415927 | In degrees: 179.999991348578, -27.500276249553743, -180.00000500895632

Quat XYZW: -2.305319E-8, -0.9367149, 6.168141E-8, 0.3500934
maps to Euler(XYZ) In radians: 3.1415925, -0.7153417, -3.1415927 | In degrees: 179.999991348578, -40.98605958646809, -180.00000500895632

Quat XYZW: -3.0003555E-8, -0.89016205, 5.861596E-8, 0.45564413
maps to Euler(XYZ) In radians: 3.1415925, -0.94619143, -3.1415927 | In degrees: 179.999991348578, -54.21277555571114, -180.00000500895632

Quat XYZW: -3.6401097E-8, -0.83331436, 5.4872622E-8, 0.55279946
maps to Euler(XYZ) In radians: 3.1415925, -1.1714399, 3.1415927 | In degrees: 179.999991348578, -67.1185614264228, 180.00000500895632

Quat XYZW: -4.216858E-8, -0.76805305, 5.0575256E-8, 0.6403863
maps to Euler(XYZ) In radians: 3.1415925, -1.3900026, -3.1415927 | In degrees: 179.999991348578, -79.64128296772347, -180.00000500895632

Quat XYZW: -4.7255202E-8, -0.6964209, 4.5858375E-8, 0.7176336
maps to Euler(XYZ) In radians: -1.3169738E-7, -1.5407987, 0.0 | In degrees: -7.545703849816751E-6, -88.28126053192533, 0.0

Quat XYZW: -5.163706E-8, -0.62053615, 4.0861455E-8, 0.78417784
maps to Euler(XYZ) In radians: -1.3169742E-7, -1.3388525, -1.2364265E-13 | In degrees: -7.545706292482747E-6, -76.71059905903273, -7.0842017918353375E-12

Quat XYZW: -5.531615E-8, -0.5425092, 3.572349E-8, 0.84004986
maps to Euler(XYZ) In radians: -1.316973E-7, -1.1468425, -3.4545395E-14 | In degrees: -7.545699778706759E-6, -65.70923385346072, -1.979305341354779E-12

Quat XYZW: -5.8318243E-8, -0.4643712, 3.057821E-8, 0.8856407
maps to Euler(XYZ) In radians: -1.316973E-7, -0.965849, -2.4987489E-14 | In degrees: -7.545699778706759E-6, -55.33907033475165, -1.4316776537211207E-12

Quat XYZW: -6.0689615E-8, -0.38801494, 2.5550252E-8, 0.9216531
maps to Euler(XYZ) In radians: -1.3169732E-7, -0.7969536, -2.5416875E-14 | In degrees: -7.545700592928757E-6, -45.6620788092451, -1.4562796829062145E-12

Quat XYZW: -6.2493015E-8, -0.31515533, 2.0752546E-8, 0.9490401
maps to Euler(XYZ) In radians: -1.3169732E-7, -0.6412406, -1.773355E-14 | In degrees: -7.545700592928757E-6, -36.740379847442306, -1.0160575447920945E-12

Quat XYZW: -6.380327E-8, -0.24730308, 1.6284568E-8, 0.9689382
maps to Euler(XYZ) In radians: -1.3169729E-7, -0.49979177, -1.2143506E-14 | In degrees: -7.545698964484761E-6, -28.63595912360844, -6.957716214363101E-13

Quat XYZW: -6.470256E-8, -0.18575978, 1.22320225E-8, 0.9825952
maps to Euler(XYZ) In radians: -1.316973E-7, -0.3736901, -1.5264296E-14 | In degrees: -7.545699778706759E-6, -21.410865491258477, -8.745797402829878E-13

Quat XYZW: -6.5275735E-8, -0.13162617, 8.6673975E-9, 0.99129945
maps to Euler(XYZ) In radians: -1.3169732E-7, -0.2640185, -1.8401186E-14 | In degrees: -7.545700592928757E-6, -15.127146096360107, -1.0543102956962941E-12

Quat XYZW: -6.56057E-8, -0.08582368, 5.6513647E-9, 0.99631035
maps to Euler(XYZ) In radians: -1.316973E-7, -0.17185877, -1.8029164E-14 | In degrees: -7.545699778706759E-6, -9.846782344310256, -1.0329950079242779E-12

Quat XYZW: -6.5769136E-8, -0.049127325, 3.234959E-9, 0.9987925
maps to Euler(XYZ) In radians: -1.3169728E-7, -0.09829421, -1.7849729E-14 | In degrees: -7.545698150262762E-6, -5.631843579191415, -1.0227141133972815E-12

Quat XYZW: -6.583243E-8, -0.022202317, 1.4619833E-9, 0.9997535
maps to Euler(XYZ) In radians: -1.3169732E-7, -0.04440828, -1.911468E-14 | In degrees: -7.545700592928757E-6, -2.5444070424923027, -1.0951905372995666E-12

Quat XYZW: -6.58476E-8, -0.0056411726, 3.714543E-10, 0.9999841
maps to Euler(XYZ) In radians: -1.316973E-7, -0.011282405, -1.859742E-14 | In degrees: -7.545699778706759E-6, -0.6464341826508654, -1.0655536652056328E-12

Quat XYZW: -6.584865E-8, 2.0243377E-8, -1.061E-14, 1.0
maps to Euler(XYZ) In radians: -1.316973E-7, 4.0486754E-8, -1.8554003E-14 | In degrees: -7.545699778706759E-6, 2.319720102041324E-6, -1.0630660420387862E-12

```

As seen after it reaches 90 degrees, it goes backwards but instead of x, z staying at ≈ 0 they're set to PI and -PI (or 180 and -180) what i expected was x, z staying at ≈ 0 and y going from 0 to 360 because the keyframes i only rotated 0-360 degrees in the y axis in blender.

I am not sure why this happens, my desired result is x, z staying at ≈ 0 and y going from 0 TO 2PI for example(implying 0-360 degrees)

I also highly doubt the conversion to euler xyz is wrong because i tried both wikis implementation of it and JOML's(math library for opengl in java)

Converted code of DMGregory's answer that is producing NaN for some values

```
    private Vector3f getEuler(Quaternionf q) {
        double PI = Math.PI;

        Vector3f transformedForward = new Vector3f(2 * q.x * q.z, 2 * q.y * q.z - 2 * q.w * q.x, MathUtils
                .sq(q.w) + MathUtils.sq(q.z) - MathUtils.sq(q.x) - MathUtils.sq(q.y));

        double yaw = PI + Math.atan2(-2 * (q.x * q.z + q.w * q.y),
                q.x * q.x + q.y * q.y - q.z * q.z - q.w * q.w);

        double pitch = Math.asin(2 * (q.w * q.x - q.y * q.z));
        Vector3f noRollRight = new Vector3f(q.w * q.w + q.z * q.z - q.x * q.x - q.y * q.y, 0, -2 * (q.x * q.z - q.w * q.y))
                .normalize();

        Vector3f noRollUp = transformedForward.cross(noRollRight);

        Vector3f transformedUp = new Vector3f(2 * (q.x * q.y - q.w * q.z),
                q.w * q.w + q.y * q.y - q.x * q.x - q.z * q.z,
                2 * (q.w * q.x + q.y * q.z));

        double roll = Math.acos(transformedUp.dot(noRollUp)) * -Math.signum(transformedUp.dot(noRollRight));

        return new Vector3f((float) yaw, (float) pitch, (float) roll);
    }

```

```
6.283185, -0.79695374, NaN for (-3.880E-1 -6.192E-8 -2.607E-8  9.217E-1)
6.283185, -0.64124054, NaN for (-3.152E-1 -6.376E-8 -2.117E-8  9.490E-1)

```

First 3 values are the euler angles(yaw, pitch, roll) and the quaternion is in the paranthesis(in XYZW form)

Debugging the value of noRollUp, transformedUp for the first example above:

```
noRollUp: (-1.375E-7  6.989E-1 -7.152E-1),
transformedUp: ( 9.610E-8  6.989E-1 -7.152E-1)
for Quaternion (-3.880E-1 -6.192E-8 -2.607E-8  9.217E-1)
Result:
6.283185, -0.79695374, NaN for (-3.880E-1 -6.192E-8 -2.607E-8  9.217E-1)

```

I can't immediately see anything wrong with it.

After clamping the input of acos for roll to -1 - 1, that issue is resolved:

```
        double roll = Math.acos(MathUtils.clamp(transformedUp.dot(noRollUp) * -Math.signum(transformedUp
                .dot(noRollRight)), -1f, 1f));

```

# Answer
> 0 votes
You can write your own quaternion to Euler angle routine that puts the wrap-around in a different place.

Since you haven't specified your coordinate system, I'll show an example with a Unity-style x+ right, y+ up, z+ forward scheme, and a Z X Y Euler angle rotation order (from most local to most global).

First we'll take your quaternion and see where it places the object's forward vector:

$$\begin{align} \vec f^\prime = q \vec f q^{-1} &= (x, y, z, w)(0, 0, 1, 0)(-x, -y, -z, w)\\ &= (xi + yj + zk + w)(1k)(-xi - yj - zk + w)\\ &= (xi + yj + zk + w)(yi - xj + wk - z)\\ &= (2i(xz + wy) + 2j(yz - wx) + k(w^2 + z^2 - x^2 - y^2) + 0)\\ \vec f ^\prime &= (2xz+2wy, 2yz-2wx, w^2 + z^2 - x^2 - y^2) \end{align}$$

We can then get the yaw angle from this vector in the range \\$0 - 2\pi\\$ with:

```
yaw = PI + atan2(-2 * (q.x * q.z + q.w * q.y)
                  q.x*q.x + q.y*q.y - q.z*q.z - q.w*q.w);

```

And the pitch angle in the range \\$\frac {-\pi} 2 - \frac \pi 2\\$ with:

```
pitch = asin(2 * (q.w*q.x - q.y*q.z);

```

If we had zero roll, then our right vector would be:

```
noRollRight = normalize(q.w*q.w +q.z*q.z - q.x*q.x - q.y*q.y, 0, -2 * (q.x*q.z - q.w*q.y));

```

And our up vector would be:

```
noRollUp = cross(transformedForward, noRollRight);

```

Then we can repeat the calculation above to work out our actual up vector:

```
transformedUp = ( 2 * (q.x*q.y - q.w*q.z),
                  q.w*q.w + q.y*q.y-q.x*q.x - q.z*q.z,
                  2 * (q.w*q.x + q.y*q.z) );

```

And the roll angle between \\$-\pi - \pi\\$ is then:

```
roll = acos(dot(transformedUp, noRollUp)) * - sign(dot(transformedUp, noRollRight));

```

There may be additional simplifications/optimizations you can do, but that basic recipe shows how you can make your own quaternion to Euler angle conversion function with the wrap-around thresholds at your chosen locations.

---
Tags: rotation, quaternion, euler-angles
---


title: Drawback of painters algorithm:

text:
# Question
Title: Drawback of painters algorithm:
We know that to scan convert any polygon first we need to pass any 4 tests of Painter's algorithm.

Suppose I have two polygon S1 and S2, which order is S1-\>S2.we see that all 4 tests are failed. See the below image where projections on the xy plane is overlapping. So we need reorder the polygons and tests further whether it will be passed any of the 4 tests or not. After reordering (S2-\>S1)if we see again 4 tests are failing and xy projection overlapping, it may go into infinite loop. But book says this type of positioned polygon(S1, S2) never go into infinite loop.

My question is where I did mistaken to understand the things? Why after reordering S1,S2 never go into infinite loop if there may be projection overlapping?

Note:Reference 1 ,Reference 2

# Answer
> 1 votes
> But book says this type of positioned polygon(S1, S2) never go into infinite loop.

Does it? The sample you've shown us says:

> **It is possible** for the algorithm just outlined to get into an **infinite loop** if one or more surfaces alternately obscure each other, as in Figure 11. In such situations, the algorithm would continually rearrange the ordering of the overlapping surfaces.
>
> To avoid such loops, we can flag any surface that has been reordered to a farther depth position so that it cannot be moved again. If an attempt is made to switch the surface a second time, we divide it into two parts to eliminate the cyclic overlap. The original surface is then replaced by the two new surfaces, and we continue processing as before.

So, it seems to me that the book specifically calls out that infinite loops are a risk when you have polygons that fail the first test, as shown in the diagram (and all other tests). And it also tells you what to do about it.

If the book elsewhere claims that this infinite loop cannot occur for a specific case, that has not been shown in the excerpts that you've included in your question.

---
Tags: 3d, graphics, projection, depth-buffer, visualization
---


# Question
Title: Finding controller's rotation about arbitrary axis
I'm trying to simulate knobs in a virtual reality environment where the user can grab a knob and twist it with the controller. Essentially what I'm trying to do is translate the global rotation of the controller into an angle about the normal axis of the knob. I've got it working when the normal of the knob is along the z axis, as I can simply read the z rotation of the controller, but things get dicey on other axes. Part of the issue is that there are multiple Vector3 rotations to express any given orientation and the system will jump between them at spots. I'm really at a loss here, if anyone could point me in the right direction I'd be very grateful.

# Answer
Let's construct a coordinate frame oriented along the axis of the knob:

```
Quaternion knobToWorld = Quaternion.LookRotation(knobAxis, knobZero);

```

...where "knobAxis" is the world space axis of rotation of the knob, pointing into the surface it's mounded on, and `knobZero` is the direction of some reference point in the knob's range - like where the knob's default / zero setting should sit.

We can then take an arbitrary direction and map it into "knob space" with this:

```
Quaternion worldToKnob = Quaternion.Inverse(knobToWorld);
Vector3 directionInKnobSpace = worldToKnob * inputDirection;

```

This transforms a vector into one whose xy components correspond to the vector's projection into the knob's rotation plane.

Now you can take some direction from the controller, like its up vector, and project it into knob space. All that really matters here is that you pick a direction that won't be held parallel to the rotation axis. You can then find this vector's rotation clockwise from the direction you designated as "knob zero" with:

```
float angleFromZero = Mathf.Atan2(directionInKnobSpace.x, directionInKnobSpace.y) * Mathf.Rad2Deg;

```

You can record this angle when the user first grabs the knob, and then compute the angle difference on any subsequent frame to determine how far the knob has been twisted.
> 0 votes

---
Tags: unity, rotation, virtual-reality
---


title: SDL2 memory leak

text:
# Question
Title: SDL2 memory leak
I've been creating a 2D game in sdl2 in C and within my main game loop, I have found a section of code that causes a massive memory leak in my program, roughly leaking 100MB of memory per second.

The relevant code is below:

```
renderTexture(textBox(buffer[0], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 20, 240, NULL);
renderTexture(textBox(buffer[1], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 287,240, NULL);
renderTexture(textBox(buffer[2], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 554,240, NULL);
renderTexture(textBox(buffer[3], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 821,240, NULL);

renderTexture(textBox(buffer[4], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 20,450, NULL);
renderTexture(textBox(buffer[5], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 287,450, NULL);
renderTexture(textBox(buffer[6], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 554,450, NULL);
renderTexture(textBox(buffer[7], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 821,450, NULL);

renderTexture(textBox(buffer[8], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 20,660, NULL);
renderTexture(textBox(buffer[9], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 287,660, NULL);
renderTexture(textBox(buffer[10], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 554,660, NULL);
renderTexture(textBox(buffer[11], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, 821,660, NULL);

```

When this segment is placed into the main game loop as follows the memory leak occurs:

```
  while (testState == 1) {
        renderTexture(textBox(buffer[0], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, cooridnates[0][0], cooridnates[1][1], NULL);

        SDL_RenderPresent(renderer);

        while (SDL_PollEvent( & buttonPress)) {
            // get global mouse state for all subroutines to use
           // SDL_GetMouseState( & xMouse, & yMouse);
            if (SDL_GetMouseState( & xMouse, & yMouse) & SDL_BUTTON(1) == 1) {
                for(Z = 0; Z <= 11; Z++) {
                    if (isPressed(boundaries[Z][0],boundaries[Z][1],boundaries[Z][2],boundaries[Z][3]) == 1) {
                        boxState[Z] = 1;
                    } else boxState[Z] = 0;
                }
            }

            //asm
            if (xMouse > 10 && xMouse <= 210 && yMouse > 10 && yMouse <= 210) {
                if (SDL_GetMouseState( & xMouse, & yMouse) & SDL_BUTTON(1) == 1) {
                    renderTexture(asmSheet, renderer, 10, 10, & asmClips[0]);
                    saveFile = fopen(savePath, "w");
                    for(Z = 0; Z <= 11; Z++){
                        fprintf(saveFile,"@\n%s\n",buffer[Z]);
                    }
                    fclose(saveFile);
                } else {
                    renderTexture(asmSheet, renderer, 10, 10, & asmClips[1]);
                }
            } else {
                renderTexture(asmSheet, renderer, 10, 10, & asmClips[2]);
            }

            //start
            if (xMouse > 210 && xMouse <= 410 && yMouse > 10 && yMouse <= 210) {
                if (SDL_GetMouseState( & xMouse, & yMouse) & SDL_BUTTON(1) == 1) {
                    renderTexture(startSheet, renderer, 210, 10, & startClips[0]);

                } else {
                    renderTexture(startSheet, renderer, 210, 10, & startClips[1]);
                }
            } else {
                renderTexture(startSheet, renderer, 210, 10, & startClips[2]);
            }
            if (xMouse > 410 && xMouse <= 610 && yMouse > 10 && yMouse <= 210) {
                if (SDL_GetMouseState( & xMouse, & yMouse) & SDL_BUTTON(1) == 1) {
                    renderTexture(stopSheet, renderer, 410, 10, & stopClips[0]);
                    //stop
                } else {
                    renderTexture(stopSheet, renderer, 410, 10, & stopClips[1]);
                }
            } else {
                renderTexture(stopSheet, renderer, 410, 10, & stopClips[2]);
            }
            if (xMouse > 610 && xMouse <= 810 && yMouse > 10 && yMouse <= 210) {
                if (SDL_GetMouseState( & xMouse, & yMouse) & SDL_BUTTON(1) == 1) {
                    renderTexture(stepSheet, renderer, 610, 10, & stepClips[0]);
                    //step
                } else {
                    renderTexture(stepSheet, renderer, 610, 10, & stepClips[1]);
                }
            } else {
                renderTexture(stepSheet, renderer, 610, 10, & stepClips[2]);
            }

            renderTexture(tnode0, renderer, 10, 220, NULL);
            renderTexture(tnode1, renderer, 277, 220, NULL);
            renderTexture(tnode2, renderer, 544, 220, NULL);
            renderTexture(tnode3, renderer, 811, 220, NULL);

            renderTexture(tnode4, renderer, 10, 430, NULL);
            renderTexture(tnode5, renderer, 277, 430, NULL);
            renderTexture(tnode6, renderer, 544, 430, NULL);
            renderTexture(tnode7, renderer, 811, 430, NULL);

            renderTexture(tnode8, renderer, 10, 640, NULL);
            renderTexture(tnode9, renderer, 277, 640, NULL);
            renderTexture(tnode10, renderer, 544, 640, NULL);
            renderTexture(tnode11, renderer, 811, 640, NULL);

            for(Z = 0; Z <= 11; Z++) {
                if (boxState[Z] == 1) {
                    if (buttonPress.type == SDL_TEXTINPUT || buttonPress.type == SDL_KEYDOWN) {
                        if (buttonPress.type == SDL_KEYDOWN && buttonPress.key.keysym.sym == SDLK_BACKSPACE && strlen(buffer[Z]) > 1) {
                            buffer[Z][strlen(buffer[Z]) - 1] = '\0';
                            renderTexture(textBox(buffer[Z], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, cooridnates[Z][0], cooridnates[Z][1], NULL);
                        } else if (buttonPress.type == SDL_TEXTINPUT) {

                            strcat(buffer[Z], buttonPress.text.text);
                            renderTexture(textBox(buffer[Z], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, cooridnates[Z][0], cooridnates[Z][1], NULL);

                        }
                        if (buttonPress.key.keysym.sym == SDLK_RETURN) {
                            strcat(buffer[Z], "\n ");
                            renderTexture(textBox(buffer[Z], TTF_OpenFont(fontLocation, 14), color, renderer, 200), renderer, cooridnates[Z][0], cooridnates[Z][1], NULL);
                        }
                    }
                }
            }
        }
        //update frame
    }
    IMG_Quit();
    SDL_Quit();
}

```

I have already tried to destroy the textures using `sdl_destroytexture`, but it doesn't seem to help. Can anyone suggest a way to fix this?

the textBox function is as folows:

SDL_Texture *textBox(char tempBuffer[], TTF_Font* font, SDL_Color color, SDL_Renderer *renderer, int maxLength){
    int w,h;
    //TTF_SizeText(font, tempBuffer, &w, &h);
    SDL_Surface * Surface = TTF_RenderText_Blended_Wrapped(font, tempBuffer, color, maxLength);

    if(Surface == NULL) {
        logSDLError("TextboxCreate");
    } else {
    SDL_Texture * Texture = SDL_CreateTextureFromSurface(renderer, Surface);
    if(Texture == NULL) {
        logSDLError("TextboxCreate");
    } else {
        return Texture;
        }
    }
}
```
</code></pre>

# Answer
**The problem is that you're calling `TTF_OpenFont` every frame, and you only need to load a font once.** `TTF_OpenFont` is a very intensive function that unsurprisingly uses a lot of memory, because it's only designed for one use. It would be a good idea to read the documentation for more on how it's intended to be used. (Documentation link.)

The best approach here is to save your fonts somewhere as a field and only open them once at the initialization stage of your program, and then pass that font to your rendering functions each time you want to draw a text box with that font on the screen.

Like this:

```
TTF_Font* Font = TTF_OpenFont("Arial.ttf", 18);

```

And then when you need to use it to create a text surface object for rendering (`SDL_Surface`), you can simply pass in the initialized font object.

```
SDL_Surface* Surface = TTF_RenderText_Blended_Wrapped(Font...);

```

You'll also need to call `TTF_CloseFont` in your destructor to free up the memory when the font is no longer needed, depending on how you've implemented all of this.
> 3 votes

---
Tags: sdl, sdl2, c
---


title: Libgdx desktop windows resize

text:
# Question
Title: Libgdx desktop windows resize
I have tried to make game with libgdx

I want to create 3x3 grid in the middle of screen I ran the desktop project, it seems that not much problem at all, but if I resize the windows the 3x3 grid move towards the lower left of the screen (I want to make it always in the center of screen regardless of the screen size change)

What are the problem in my code, I am a new to game developing.

```
public class GameScreen implements Screen {

    MyGdxGame game;
    SpriteBatch batch;
    Texture img, item;

    public GameScreen(MyGdxGame game) {
        this.game = game;

        batch = new SpriteBatch();
        // a 640x480 image for testing background position
        img = new Texture(Gdx.files.internal("640Wx480H.png"));
        // a 64x64 image for grid item
        item = new Texture(Gdx.files.internal("badlogic.jpg"));
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        Gdx.gl.glClearColor(1, 1, 1, 1);
        batch.begin();
        batch.draw(img, 0, 0);
        float itemSize = item.getWidth();
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                batch.draw(item, itemSize * i + (Gdx.graphics.getWidth() - (itemSize * 3)) / 2, itemSize * j + (Gdx.graphics.getHeight() - (itemSize * 3)) / 2);
            }
        }

        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void show() {
    }

    @Override
    public void hide() {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void dispose() {
        img.dispose();
        item.dispose();
    }

}

public class MyGdxGame extends Game {

    GameScreen mainGameScreen;
    private Viewport viewport;
    private OrthographicCamera camera;

    @Override
    public void create() {
        camera = new OrthographicCamera();
        camera.setToOrtho(false, 640, 480);
        viewport = new FitViewport(640, 480, camera);
        mainGameScreen = new GameScreen(this);
        setScreen(mainGameScreen);
    }

    public void resize(int width, int height) {
        viewport.update(width, height);

    }

    public void render(float delta) {
    }

    public void dispose() {

    }
}

```

# Answer
> 3 votes
It seems that you set up a Camera and a Viewport but are not using them.

On `resize()` of the `MyGdxGame` class, the camera should be updated also:

```
public void resize(int width, int height) {
        viewport.update(width, height);
        camera.update();
    }

```

Then, this should be inside your `render(float delta)` method before the `batch.begin()`:

```
batch.setTransformMatrix(game.getCamera().view);
batch.setProjectionMatrix(game.getCamera().projection);

```

For that to work, create a getter for the camera on the `MyGdxGame` class.

Maybe there's something else missing (I'm doing it off the top of my head), but there's a start.

# Answer
> 1 votes
Many years later...

I found that resetting the camera with `setToOrtho(false, width, height);` keeps the projection the correct size.

```
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0.25f, 0.25f, 0.25f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();

    stage.act();
    stage.draw();
}

@Override
public void resize(int width, int height) {
    super.resize(width, height);
    camera.setToOrtho(false, width, height);
}

```

It is worth noting that I create the camera like this:

```
float width = Gdx.graphics.getWidth();
float height = Gdx.graphics.getHeight();

camera = new OrthographicCamera();
camera.setToOrtho(false, width, height);
camera.update();

```

---
Tags: libgdx
---


title: Triggers VS coroutine performance?

text:
# Question
Title: Triggers VS coroutine performance?
So I am using unity and wondering if I have an agent going to move to a position say Agent A moves to position B in x seconds guaranteed (avoids all physics or things that could disrupt the path). When agent A gets to his destination I want to trigger some effect C.

I was thinking you could do this same sequence with both colliders that are trigger and coroutines but wouldn't doing it with coroutines be more efficient and if so by how much ?

# Answer
Physics is usually the most complex part in a comparison. however, triggers aren't really physics, they're just collision detection which is quite fast for primary shapes. On the otherhand, coroutine doesn't need half the calculation triggers need. In fact, the only calculation a coroutine needs is some TIME behind the scenes, so, **coroutines are much faster than collision detection**, however, depening on your case, you might want to use the trigger way because you are literally looking for a collision detection. It's not that heavy even on mobiles.
> 1 votes

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


# Question
Title: Why does my enemy go the other way when the player moves more than a few pixels away from (0, 0)?
My enemy initially goes to the player when the game starts, but when the player moves away from its starting position, it goes away.

Code:

```
// taken from https://gamedev.stackexchange.com/questions/50978/moving-a-sprite-towards-an-x-and-y-coordinate?answertab=votes&newreg=00cf6f4d9b50405dbea4cd1e5b328e87

// Rotate us to face the player
this.rotation = Math.atan2(obj.y - this.y, obj.x - this.x);

// Move towards the player
this.x += Math.cos(this.rotation) * this.speed;
this.y += Math.sin(this.rotation) * this.speed;

```

Note: the images are rectangular.

# Answer
> 0 votes
if you want it to go towrds `obj`, do

```
let dir = {
    x: obj.x - this.x,
    y: obj.y - this.y
};

let length = Math.sqrt(dir.x*dir.x + dir.y*dir.y);

this.x += dir.x * this.speed / length;
this.y += dir.y * this.speed / length;

```

You should also take into account the deltatime for same speed per different fps

---
Tags: javascript
---


# Question
Title: Need help on finding the algorithm for getting the FlipX, Y and TextureRotation of my DirectionalAnimation class
I've created a class called DegreeAnimation, which is basically an implementation of my CustomAnimation class, but works with other directions, there are 2 constructors for this class, one where the algorithm sets all the ranges by themselves and assigning textures to them, starting from east and ending at the topmost of southeast, and another one that takes in ranges manually when it's needed, like in mine, as i need to divide the ranges like this and not like this:

Even so, since i cant just do 240° - 70°, as it would wrap backwards, so there are 2 ranges for the same texture, also that with the current implementation, there are small gaps inbetween like 60°-61° but that isn't really the problem here as i will fix them sooner or later, the problem here is that, in order to properly render them as i want, there needs to be 3 variables, the `textureRotation`, and whether it will be flipped or not all inside the function: `flipX`, `flipY`, and initial values for the assets namely as, `needsFlipX`, `needsFlipY` and `initialRotation` (the direction the sprite looks at in its texture form), also, in this code i have converted +-180 degree notation to +360 cause that's what atan2 works with. I am also unable to just hardcore those values, as i actually want some degree of rotation feeling in my game, I'm still yet to implement the getter values of `initialRotation`, `needsXFlip` and `needsYFlip` in the `CustomAnimationAndRange` data class, but please see the code as if those were implemented. A video to show what happens, and i guess you can imagine what I actually intended.

Tileset: https://stealthix.itch.io/rpg-nature-tileset Player: https://pixel-boy.itch.io/ninja-adventure-asset-pack

outside my most probably wrong range sets, you must have noticed that something is very out of the place, and I hereby ask for help on fixing it. Also, one has to absolutely call thattexture.flip(false,false) as it carries on due to referencial implementation of this in java. Also, there are many stuff that I explicitly left out broken as i was going to delete them later after i implemented this, but I couldnt.

```
class DegreeAnimation {
    /**
     * I literally have no idea why some require flips and some don't
     */
    data class CustomAnimationAndRange( val customAnimation: CustomAnimation,
                                        val range: ClosedFloatingPointRange<Float>,
                                        val initialRotation: Int = 0,
                                        val needsXFlip : Boolean = false,
                                        val needsYFlip : Boolean = false)
    var internalTimer: Float
    get() {
        return animations[0].second.internalTimer
        // will crash if the index-0 of the animationsTemp is null
    }
    set(value) {
        animations[0].second.internalTimer = value
    }

    var currentFrame: Int
        get()  = animations[0].second.currentFrame
        set(value) {
        animations[0].second.currentFrame = value
        }
    val frameAmountCache: Int
        get() = animations[0].second.frameAmountCache

    val timingArray: Array<Float>?
        get() = animations[0].second.timingArray

    val isOneTexture: Boolean
        get() = animations[0].second.isOneTexture

    val atLastTexture : Boolean
        get() = animations[0].second.atLastTexture

    var isLooping : Boolean
        get() = animations[0].second.isLooping
        set(value)
        {
            animations[0].second.isLooping = value
        }

    internal val cachedTimePerFrame: Array<Float>?
        get() = animations[0].second.cachedTimePerFrame

    var paused : Boolean
    get() = animations[0].second.paused
    set(value) {
        animations[0].second.paused = value
    }

    var animations : Array<Triple<ClosedFloatingPointRange<Float>, CustomAnimation, Int>>
    private var delegate : Sprite? = null
    val rotation : Float?
        get() {
            if(delegate == null) return null
            if(delegate!!.rotation < 0)
                return delegate?.rotation!! + 360
            else
                return delegate?.rotation
    }

    /**
     * if this isn't updated in getTexture for some reason there will be huge discrepancies
     */
    var textureRotation : Float = 0f
        get(){
            return field
        }
        set(value) {
        field = value
        }
    /**
     * The first element of animation is taken as the ultimate example for al land will be used for so
     * The arguments go from counter-clockwise, starting at east (0°) ending at topmost of south-east (360°)
     */
    fun update(delta: Float)
    {
        animations[0].second.update(delta)
    }
    var usesAutoDegree = false
    /**
     * if flipOver180Textures is set to true, ABSOLUTELY call flip(false, false) AFTER **USING** the texture
     */
    fun getTexture(rotation : Float? = this.rotation, flipOver180Textures: Boolean = false) : TextureRegion
    {
        rotation!!
        for(i in animations.indices)
        {
            if(animations[i].first.contains(rotation))
            {
                var initial = animations[i].third
                textureRotation = initial + rotation - animations[i].first.start
                var outputNeedsFlipX : Boolean = ?
                var outputNeedsFlipY : Boolean = ?
                if(rotation > 180 && flipOver180Textures)
                    return animations[i].second.
                    getKeyFrame(currentFrame).apply {    //i havent integrated needsXFlip to the animation[] yet
                        this.flip(false.xor(animations[i].needsXFlip), true.xor(animations[i].needsYFlip)) } // please act as if
                else                                                                            // it has been
                    return animations[i].second.getKeyFrame(currentFrame)
            }
        }
        for(i in animations.indices) // this tries to fill in the gaps after automatic assignation or something else
        {
            if(i != animations.size-1)
            {
                if(animations[i].first.endInclusive.rangeTo(animations[i+1].first.start).contains(rotation))
                {
                    if(rotation > 180 && flipOver180Textures)
                        return animations[i].second.getKeyFrame(currentFrame).apply {  flip(true, true) }
                    else
                        return animations[i].second.getKeyFrame(currentFrame)
                    // todo: implement rounding for inbetween i.end, i+1.start and return it like so
                }
            }

        }
        return Globals.ItemTextures["null"]!! // if none found
    }
    constructor(sprite: Sprite? = null, vararg animation: CustomAnimation)
    {
        for(i in 1 until animation.size)
        {
            if(!animation[i].timingArray.contentEquals(animation[0].timingArray!!))
            {
                Console.log("the length of animation aren't the same, or they aren't equal to the animation[0]")
            }
        }
        var animationsTemp :  Array<Triple<ClosedFloatingPointRange<Float>, CustomAnimation, Int>?> = Array(animation.size){null}
        var partSize = 360f/animationsTemp.size
        for(i in animationsTemp.indices)
        {
            if(i == 0)
            {
                animationsTemp[0] = Triple(0f.rangeTo((i+1)*partSize), animation[i], 0)
            }
            else
            {

                animationsTemp[i] = Triple(((i*partSize)+1).rangeTo((i+1)*partSize), animation[i], 0)
            }
        }
        var tempIterator = animationsTemp.iterator()
        animations = Array(animationsTemp.size){tempIterator.next()!!}
        delegate = sprite
        usesAutoDegree = true
    }
    constructor(sprite: Sprite?,
                vararg customAnimationAndRange: CustomAnimationAndRange)
    {
        usesAutoDegree = false
        for(i in 1 until customAnimationAndRange.size)
        {
            if(!customAnimationAndRange[i].customAnimation.timingArray.
                contentEquals(customAnimationAndRange[0].customAnimation.timingArray!!))
            {
                Console.log("the length of animation aren't the same, or they aren't equal to the animation[0]")
            }
        }
        var animationsTemp :  Array<Triple<ClosedFloatingPointRange<Float>, CustomAnimation, Int>?>
        = Array(customAnimationAndRange.size){null}
        for(i in animationsTemp.indices)
        {
            animationsTemp[i] = Triple(customAnimationAndRange[i].range,
                customAnimationAndRange[i].customAnimation,
                customAnimationAndRange[i].initialRotation)
        }
        var tempIterator = animationsTemp.iterator() // this part is not required, but I want a non-nullable animation
        animations = Array(animationsTemp.size){tempIterator.next()!!} // collection, also filterNotNull might also work
        delegate = sprite                            // but I mean we are sure that they are non-nullable, so we use !!
    }                                                // so fearing filterNotNull slipping some stuff is useless
}

```

this code assumes that the properties of all CustomAnimations are the same other than textures so it takes \[0\] as the ultimate example, if requested, I will post the details of my CustomAnimation class, I didnt post it at the first place because this wall of text is littered enough, also that I think that the naming convention of that class is well enough, the most imporant of them all is the GetTexture() function, and this is what my main class looks like if I only took things related to this:

```
        player = Entity() // Entity : Sprite
        degreeAnimation = DegreeAnimation(player,
            DegreeAnimation.CustomAnimationAndRange(
                Globals.Animations["player.walkRight"]?.invoke()!!,
                0f.rangeTo(60f)),
            DegreeAnimation.CustomAnimationAndRange(
                Globals.Animations["player.walkRight"]?.invoke()!!,
                300f.rangeTo(360f)),
            DegreeAnimation.CustomAnimationAndRange(
                Globals.Animations["player.walkUp"]?.invoke()!!,
                60f.rangeTo(120f), 90, needsXFlip = false, true),
            DegreeAnimation.CustomAnimationAndRange(
            Globals.Animations["player.walkLeft"]?.invoke()!!,
                120f.rangeTo(240f), 300),
            DegreeAnimation.CustomAnimationAndRange(
            Globals.Animations["player.walkDown"]?.invoke()!!,
            200f.rangeTo(300f), 270)
        )

    render(delta: Float)
    {
        var aaa = degreeAnimation.apply { update(delta) }
        mainBatch.draw(aaa.getTexture()  , player.x, player.y,
        player.getWorldOriginX * player.readOnlyScaling.x , player.getWorldOriginY * player.readOnlyScaling.y,
            player.getWorldSizeX, player.getWorldSizeY, player.scaleX,
            player.scaleY, aaa.textureRotation)
        aaa.getTexture().flip(false,false)
        player.setOriginCenter()
        player.rotation = degreesToMouse(player)
    }
    fun degreesToMouse(arg: Entity) : Float
    {
        var radians = atan2(Gdx.input.y.toDouble() - player.screenPosition.y + player.originY * player.readOnlyScaling.y /*+ player.originY * player.readOnlyScaling.y*/,
            Gdx.input.x.toDouble() - player.screenPosition.x + player.originX * player.readOnlyScaling.x /*+ player.originX * player.readOnlyScaling.x*/)
        return  -(radians * (180 / Math.PI)).toFloat()
    }

```

# Answer
> 3 votes
See Asking and, because I know you've been linked it previously, The Good Asker. No-one is going to fix all of your code for free regardless of where you ask. It would be beneficial for us all to create a new project with the bare minimum of what you're trying to achieve.

It's not very clear what you're asking, but here's a basic example of changing a sprite and flipping it, similar to Pokémon on the Game Boy. It does what your diagram says explicitly not to do, but if it only showed the up/down frame when facing exactly up or down (I think that's what you want but it doesn't really make sense if not limited to a set number of directions) we wouldn't see it very clearly.

```
SpriteBatch batch;
Texture up, down, right;
Sprite player;

@Override
public void create () {
  batch = new SpriteBatch();

  up = new Texture("up.png");
  down = new Texture("down.png");
  right = new Texture("right.png");

  player = new Sprite(right);
  player.setOriginCenter();
}

@Override
public void render () {
  ScreenUtils.clear(Color.GRAY);
  batch.begin();

  // Set the sprite's angle
  float angle = Gdx.graphics.getFrameId() % 360;
  player.setRotation(angle);

  // Flip horizontally if facing left
  player.setFlip(angle >= 90 && angle <= 270, false);

  // Set appropriate texture for side view, up and down
  if (angle >= 45 && angle <= 135) {
    player.setTexture(up);
  } else if (angle >= 225 && angle <= 315) {
    player.setTexture(down);
  } else {
    player.setTexture(right);
  }

  player.draw(batch);
  batch.end();
}

```

| up.png | down.png | right.png |
| --- | --- | --- |
|  |  |  |

---
Tags: libgdx, algorithm, trigonometry
---


# Question
Title: Discrepancy between ArticulationBody indexing and drive target list
My player is at the moment an ArticulationBody setup that looks like the lower half of a person: a waist, two thighs, and two shins. I'm currently just implementing moving the thighs, and my code works fine for the left thigh. But, instead of *OnRightLegPos()* moving the right thigh, it moves the left shin.

I've run just about everything in my code through Debug.Log and all the values make perfect sense, so the only thing left I can assume is that there is a discrepancy between the ArticulationBody's indices and it's drive target List.

(I can link my unity project if that's worth looking at)

public class PlayerClass : MonoBehaviour
{
    private Transform _thighL;
    private Transform _thighR;
    private Transform _shinL;
    private Transform _shinR;

    private ArticulationBody _articulationBody;
    private List<float> _drTargets = new List<float>();
    private List<int> _dofIndices = new List<int>();

    private ArticulationBody _thighLJoint;
    private ArticulationBody _thighRJoint;
    private ArticulationBody _shinLJoint;
    private ArticulationBody _shinRJoint;

    // Start is called before the first frame update
    void Start()
    {
        _thighL = transform.Find("LThigh");
        _thighR = transform.Find("RThigh");
        _shinL = _thighL.transform.Find("LShin");
        _shinR = _thighR.transform.Find("RShin");

        _articulationBody = GetComponent<ArticulationBody>();
        _articulationBody.GetDofStartIndices(_dofIndices);
        _articulationBody.GetDriveTargets(_drTargets);

        _thighLJoint = _thighL.GetComponent<ArticulationBody>();
        _thighRJoint = _thighR.GetComponent<ArticulationBody>();
        _shinLJoint = _shinL.GetComponent<ArticulationBody>();
        _shinRJoint = _shinR.GetComponent<ArticulationBody>();
    }

    void OnLeftLegPos(InputValue value)
    {
        int ind = _dofIndices[_thighLJoint.index];
        _drTargets[ind + 1] = value.Get<Vector2>().y;
        _drTargets[ind + 2] = value.Get<Vector2>().x;
        _articulationBody.SetDriveTargets(_drTargets);
    }

    void OnRightLegPos(InputValue value)
    {
        int ind = _dofIndices[_thighRJoint.index];
        _drTargets[ind + 1] = value.Get<Vector2>().y;
        _drTargets[ind + 2] = value.Get<Vector2>().x;
        _articulationBody.SetDriveTargets(_drTargets);
    }
}
```

# Answer
Well I never found the reason for the issue, but remaking my player object from scratch fixed the issue.
> 0 votes

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


# Question
Title: LibGDX latest, Ubuntu 20.04, OpenJDK 11, Gradle 6.7.1 - Unsupported class file major version 60
LibGDX latest, Ubuntu 20.04, OpenJDK 11, Gradle 6.7.1

Using above systems and first got below error -

```
Exception in thread "LWJGL Application" java.lang.NoClassDefFoundError: Could not initialize class org.lwjgl.Sys

```

Tried correcting it by changing below -

```
api "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"

```

to

```
api "com.badlogicgames.gdx:gdx-backend-lwjgl3:$gdxVersion"

```

But now getting -

```
Could not run phased build action using connection to Gradle distribution 'https://services.gradle.org/distributions/gradle-6.7.1-bin.zip'.
Build file '<build.gradle project path>'
Could not compile build file '<build.gradle project path>'.
startup failed:
General error during semantic analysis: Unsupported class file major version 60
java.lang.IllegalArgumentException: Unsupported class file major version 60
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:196)
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:177)
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:163)
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:284)

```

Any help would be appreciated !

# Answer
> 1 votes
Sounds like it's using Java 16 (major version 60), which Gradle 6 doesn't support, instead of 11 (major version 55). The latest version you can use with Gradle 6 is Java 15, though bear in mind that's not a long-term support release like 8, 11 and 17 are.

gdx-setup projects do not support Gradle 7 at this time (13 December 2021). If you use the gdx-liftoff setup tool, Gradle 7 and Java 16/17 can be used.

It would probably be a good idea to check the JDK settings in your IDE, though you can uninstall 16 if you don't need it or do `sudo update-alternatives --config java` to change the system-wide default Java version (note: this won't change `JAVA_HOME` \- see How do I set environment variables? for setting that).

---
Tags: libgdx, gradle
---


# Question
Title: What is the pixels to units property in Unity sprites used for?
I'm starting to learn Unity for 2D development.

So, I am importing several sprites into the game, and I couldn't help but notice that there is a "pixels to units" property, by default on `100`. I normally set it to `1`. Is there a reason why I would need to have this value different than `1`? Or, more generally, is there a reason to have multiple sprites with different

# Answer
> 29 votes
100 pixels per unit would mean a sprite that's 100 pixels would equal 1 unit in the scene. It's simply a scale to say how many pixels equal one unit. This can affect things like physics. A lower pixels to units setting would require more force to move one pixel than a higher pixels to units setting.

Yes, there may be times where you'll want to manipulate the pixels per unit. If you have a tile sheet of 16x16 tiles, you may want to consider setting the pixels per unit to 16 so that you can easily snap tiles together in a scene, for example.

# Answer
> 13 votes
Answering the question in your title, units in Unity are arbitrary. It's just a number; the most common interpretation is that 1 unit means 1 meter, but that's just the most commonly agreed upon value. You could decide 1 unit = 1 foot, or 1 unit = 1 inch, etc.

As for why you would use the default setting of 100 pixels, it's because the physics system doesn't like values that are too large. If you set 1 unit = 1 pixel, then the physics system would be moving objects hundreds of units per frame, and the physics calculations tend to break down in that situation. By setting 1 unit = 100 pixels, then physics will be moving objects more like a couple units per frame.

# Answer
> 0 votes
The time you would have to change the Cell Sizes or Scale depends on the size of your tiles. So let's say that you have tiles that are smaller than the usual 100 PPU (Pixels per unit) that you need to resize your Tilemap's Grid cells. To resize your Tilemap's grid cell sizes, go to Grid in the Hierarchy \> Grid in the Inspector \> Cell size. Divide your tile pixel size by 100. For example, if I have 16x16 pixel sized tiles, the Cell sizes in the X and Y columns will be 0.16. Hope this helps.

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


# Question
Title: What if 3D model voxels/polygons where limited like pixels?
First, let me clarify that I don't understand much about programming, neither about 3D modelling. And I couldn't think or find a better place to ask this, but I hope I don't make too many mistaken assumptions.

But I'm still quite ignorant about 3D modelling in general, **I don't even know the difference between then and polygons, for example**.

* **Pixels and Vectors:**

So, from the little I think I know, pixels are limited amounts of information that tells the monitor how to light a certain number of LED's. So if they are resized, they lose quality. While a Vector is somewhat of a calculation of a certain shape and/or colour (I **think**), so even if they are resized, they won't lose graphical quality.

* **About Voxels/polygons:**

So, from what I could understand about Voxels/Polygons is that they are more "closer" to Vectors than to pixels in the sense that they can be re-scaled, twisted and textured in any way you want without losing quality.

* **The Question:**

So, taking into consideration what a pixel and a Voxel is, it would be possible to make Voxels work more (if not the same) as pixels?

What I mean is that, while Voxels are more or less the calculus of a three-dimensional shape in a space, there could be a way of making this three-dimensional shape be a limited amount of information? Or this is more closely related to Polygons?

My conception is that since these 3D information are not changeable, just like a pixel, you wouldn't need as much processing power to render these things. But you wouldn't be able to do much either, since they wouldn't be able to be interacted with like a voxel.

I don't know if I was clear enough, but let's just say that the idea is to fill a certain space with X number of pixels, but three-dimensional, without the use of 3D model programs.

Like a 3D jpeg image, but without the "filling".

* **The (possible) function:**

Well, while you wouldn't be able to make day and night cycles, solids, fluids and whatsoever, it could be used in really niche applications where you really don't want to use a lot of processing power. Just like a flash game, so to speak.

Or Voxels are already just like this?

# Answer
One useful way to create and utilize voxel data is to have the underlying data of an object simply be a list, array, vector, whatever, of numbers, colors, etc. From this *voxel* data, which is analogous to a 3d version of a 2d image, you can create a renderable mesh made of *polygons* using some algorithm like Marching Cubes or perhaps like Minecraft: loop over all the voxels, for each one check the adjacent voxels, and for every adjacent clear space add a quad (or two triangles) polygon with the color and/or texture of the corresponding voxel data. Either way, short of using raytracing (which is a simple concept to understand but can be pretty advanced to implement), you will likely store the data as voxels but create a mesh around this data made of polygons to render it.

To directly answer the question, voxels (when rendered as cubes) can behave exactly like pixels and act as a sort of 3d image. The voxel data is not necessarily the same as what gets rendered on the screen, however; think of it as more of a point cloud of numbers, that you have to wrap a mesh of your choice around. There are smooth ways to do this, like Astroneer's terrain, or more blocky, such as MagicaVoxel models and Minecraft terrain.

What you're describing is exactly how voxels already behave, but understand that short of raytracing you will have to use 3d Polygon rendering to display the data.
> 1 votes

---
Tags: 3d, voxels
---


# Question
Title: Given a set of points with color values, finding a gradated color value from a given position
I guess the verb form of gradient is "gradate" and not "gradiate"?

Hi! I have a set of 2D points (actually 3D, but we can ignore the Y axis unless it's trivial) bound to color values. I'd like to know, given an arbitrary point in space, what the color would be if there was a smooth gradient between all of the defined points.

Here's a visual of what these points might look like.

In the above image, I would expect the color value to be an approximately equal mix between the Red, Cyan, Yellow and Purple points that surround the gizmo's location, since it lies approximately central to these four points.

This is a bit more complicated than I originally anticipated, because:

* Simply averaging all of the points and weighting by distance will not work. If I ask for the color at the red point's exact position, I want red's exact color - with zero influence from any other point.
* Likewise, if I'm inside the "quad" of 4 of the closest points, there should be no influence from points outside of that quad - as the surrounding points should "block" their influence.

I'm guessing this isn't a particularly unique problem, so if this algorithm has a name, feel free to let me know what it is and I'll chase it down! I'm having a surprising amount of difficulty Googling an example - possibly because I just don't have the right keywords.

Thanks!

# Answer
> 3 votes
An idea that occurs to me would be to use something like Voronoi cells to split the area by color, and sort of blend them into each other. Essentially past the border between two colors use a smooth falloff to weight either intruding color. I'm not quite sure how to go about actually implementing such a thing though. You could also create a mesh of triangles between all the points and then sample the point's color as a sum of every triangle's blended color at that point, also with a falloff for how relevant each triangle would be for the point. This might actually be easier than my first method. Finally, you could adjust the weights so that not only distance but being closest is a contributing factor, such that other colors fall off rapidly by not being closest.

---
Tags: mathematics, algorithm, vector, interpolation
---


title: How can I draw gizmos only at runtime?

text:
# Question
Title: How can I draw gizmos only at runtime?
```
private void OnDrawGizmos()
{
    for(int i = 0; i < waypoints.Count; i++)
    {
        Gizmos.color = Color.green;
        Gizmos.DrawSphere(waypoints[i].position, 0.1f);
    }

    if (nextWayPoint != null)
    {
        Gizmos.color = Color.red;
        Gizmos.DrawLine(transform.position, nextWayPoint.position);
    }
}

```

It's drawing in color the first two spheres already in the editor but I want it to start drawing the spheres only when running the game not in the editor.

# Answer
```
private void OnDrawGizmos()
{
    if(Application.isPlaying)
    {
       //do stuff
    }
}

```
> 2 votes

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


# Question
Title: how do place UI in code at bottom screen?
I am struggling to figure out how I can add a UI prefab on screen in code so that it appears "anchored" at the bottom center of the screen. I realize this might be a common question. I apologize. Googling has not given me an answer yet. Most answers do not show me how to do it in code. Some referenced anchors but I do not see anchor fields or properties on my types. It might be I do not understand the terminology correctly to find the answer.

It's likely the problem is this line **control.transform.position = Vector3.zero** but I do not know how to fix it.

This is how I make the prefab appear on screen. It is currently centered on screen.

```
public class PopupHandler : IPopupHandler
{

    public Canvas Canvas { get; set; }

    public void ShowPopup(GameObject popup)
    {
        if (null == popup)
            return;

        var control = Canvas.Instantiate<GameObject>(popup);
        control.SetActive(true);

        control.transform.position = Vector3.zero;
        control.transform.localScale = Vector3.one;
        control.transform.SetParent(Canvas.transform, true);
    }
}

```

Here's the prefab constructions:

# Answer
> 1 votes
So as I said in the comments you'd want to access the UI's RectTransform component rather than it's Transform component.

Then you can set the anchors of the component to the center-bottom, after that you can calculate where it should be positioned.

```
public class PopupHandler : IPopupHandler
{

    public Canvas Canvas { get; set; }

    public void ShowPopup(GameObject popup)
    {
        if (null == popup)
            return;

        var control = Canvas.Instantiate<GameObject>(popup);
        control.SetActive(true);

        RectTransform RectTransform = control.GetComponent<RectTransform>();
         //set the anchors to the center - bottom of the bar
        RectTransform.anchorMin.Set(0.5f, 0);
        RectTransform.anchorMax.Set(0.5f, 0);

        control.transform.SetParent(Canvas.transform);

        //width = Screen width halfed minus rect width half
        //height = 0 (for bottom) + half of rect height
        RectTransform.anchoredPosition = new Vector3(Screen.width / 2 - RectTransform.rect.width / 2, 0 + RectTransform.rect.height / 2, 0);
        control.transform.localScale = Vector3.one;
    }
}

```

I created a test scene and it seems to work fine for me, but in my scene the canvas it is parented to takes up all available screen space so I can use Screen.width and Screen.height, you may need to use the Canvas width and height if yours doesn't.

---
Tags: c#, gui, unity-ui
---


# Question
Title: What is a pattern to manage execution order of C# delegates in Unity
**Note:**

I have two Managers: First one creates 2d block upon click. The other one, upon click, grabs a block for dragging. The reason I need them to run in specific order is because newly created block should be instantly grabbed.

**Original question:**

I have two managers that respond to the InputManager events. They both should do something when `InputManager` raises `mouse0DownEvent`. I need the BlockManager delegate to happen first. I have `DragManager` and `BlockManager` that subscribe to same event in `InputManager`: `mouse0DownEvent`, but this does not give me controll over the execution order.

My ideas:

1. I am thinking of creating separate event in `InputManager`, but then `InputManager` would have to know about the other managers which would cause dehermetization.
2. I could also create separate manager to wrap `InputManager` events but this would look like overengineering to me.

Whould would be a unity way of doing this?

Thanks!

# Answer
When you have multiple event receivers reacting to the same event but it still matters in which order they process an event, then that usually means that you are not actually dealing with one event but with two.

The first event being `mouse0DownEvent` handled by the `BlockManager` and the second a `blockCreatedEvent` which gets Invoked by the `BlockManager` and then needs to be handled by the `DragManager`.

This also solves two other problems:

1. How you communicate the newly created block from the BlockManager to the DragManager: By passing it to the blockCreatedEvent.
2. How you deal with the case that the player clicked in a situation where they are unable to create a block: You just don't invoke the second event.
> 2 votes

# Answer
I did something similar by just having a tree of listeners. So the event is passed to the root of the tree, then it's processed and passed down to the children recursively.
> 1 votes

---
Tags: unity, design-patterns, delegates
---


# Question
Title: How not to multiply real time and bake shadows? (Unity)
I have one Light Source ( Directional Light ) with Mixed Mode. Lighting Mode in Lighting Window I seted to Subtractive.

What the problem looks like

How I would like the shadows to blend. How to achieve this effect?

# Answer
> 1 votes
Answer - Change RealTime Shadow Color in Environment Tab in Lignting Window so that the color matches the baked shadow color

---
Tags: unity, rendering, shadows, shadow-mapping, lightmap
---


# Question
Title: What is the Unity way to ensure that calling "initializing" events in managers happen after subscribing to them?
Example of the situation from the title:

I have manager `A` and `B`.

I subscribe to `B`'s event: `E`, in `A`'s `Start` function.

I invoke `E` in `B`'s `Start` function.

If `A`'s `Start` function is called earlier then there is a problem: the initializing event has not yet been subscribed, therefore nothing is called.

What is "the Unity way" of solving this?

Using `Awake` just to solve this seems like an overkill for me, same with setting Script Execution Order".

# Answer
Why do you think using Awake is overkill? The documentation says that this is one of the purposes of Awake:

> you should use `Awake` to set up references between scripts, and use `Start`, which is called after all `Awake` calls are finished, to pass any information back and forth.

Setting up event subscriptions is a perfect example of "setting up references between scripts".

So "the Unity way" is to set up all your event subscriptions in `Awake` and then invoke any initialization events in `Start`.

---

There were some comments asking what to do if two phases of initialization isn't enough. Perhaps because you have event subscriptions which can not be set up before some initialization event has happened and which have handlers which then invoke initialization events of their own.

If that's the case: Are you sure that using events is even the right architectural pattern for all of the things you are trying to do? The reason why you use events is usually because you can't predict if and when things are going to happen. With initialization, that's not the case. You know it's going to happen exactly once and it's going to happen at startup.

So when you have complex dependencies in your game state initialization, then perhaps events are not actually the right tool for that. What you might actually need is a single, monolithic master initialization routine in form of a method which calls all the initialization steps of your game state in a deterministic order.

"But what about loose coupling" you ask? Well, when your code relies on objects A and B being initialized in a specific order, then you already have a tight coupling between A and B. So you already lost that battle.
> 2 votes

---
Tags: unity, initialization
---


# Question
Title: Needs help on actually making the trigonometric function work as intended
```
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import kotlin.math.*

class Player : Entity // Entity : Sprite
{
    var cursor : Sprite
    var cursorDistance : Float = 1f

    constructor(animationInfo:  HashMap<String, CustomAnimation>,
                initialX : Float =0f,
                initialY: Float = 0f) : super(animationInfo, initialX, initialY)
    {
        cursor = Sprite(Textures.idleArrow)
        cursor.setPosition(this.x, this.y)
//        cursor.setOriginCenter()
    }
    override fun updateLogic(delta: Float)
    {
        var degree = degreesToMouse(returnRadians = true)
        var curX = cursorDistance * cos(degree) + (x + getWorldOriginX)
        var curY = cursorDistance * sin(degree) + (y + getWorldOriginY)
        cursor.setPosition(curX, curY)
        cursor.setOriginCenter()
        cursor.rotation = degreesToMouse(cursor.x * TILE_WIDTH + cursor.originX,
            screenYPoint = cursor.y * TILE_HEIGHT + cursor.originY,
            returnRadians = false)
        println("cursor rotation: ${cursor.rotation}, degree: $degree")
    }

    override fun gameDraw(batch: SpriteBatch) {
        super.gameDraw(batch)
        batch.draw(
            cursor, cursor.x, cursor.y, cursor.originX / TILE_WIDTH, cursor.originY / TILE_WIDTH,
            (cursor.regionWidth / TILE_WIDTH.toFloat()), (cursor.regionHeight / TILE_HEIGHT.toFloat()),
            cursor.scaleX, cursor.scaleY, cursor.rotation)

    }
}

```

<pre><code>    fun degreesToMouse(arg: Entity = this, returnRadians: Boolean = false) : Float
    {
        var radians = atan2(
            Gdx.input.y.toDouble() - arg.screenPosition.y + arg.originY * arg.readOnlyScaling.y,
            Gdx.input.x.toDouble() - arg.screenPosition.x + arg.originX * arg.readOnlyScaling.x)
        if(!returnRadians)
            return  -(radians * (180 / Math.PI)).toFloat()
        else
            return radians.toFloat()
    }
    fun degreesToMouse(screenXPoint: Float, screenYPoint: Float, returnRadians: Boolean = false) : Float
    {
        var radians = atan2(
            Gdx.input.y.toDouble() - screenYPoint,
            Gdx.input.x.toDouble() - screenYPoint)
        if(!returnRadians)
            return  -(radians * (180 / Math.PI)).toFloat()
        else
            return radians.toFloat()
    }```

</code></pre>

this is all the related code, the only important place is the updateLogic function, thanks to help of some people, i got that `cos(degree)` `sin(degree)` etc. however currently it doesn't work at all like i intended, i intended for it to work like this:

but currently it is like this:

as you can see, nor does the arrow look at the mouse cursor, nor would the line and the point at the ring interact if a line was drawn between center and mouse, I need a bit of help on that part. There are a lot of conversions and divisions like TILE\_WIDTH etc. those are there because I need to use a `FitViewport` and a Tile Renderer, Tilewidth and TileHeight are 32, and those need conversion

# Answer
> -1 votes
thanks to the help of @DMGregory and the people who helped me initially make this code, found the answer to make that cursor thing orbit around the player according to the position to the mouse:

```
        var degree = degreesToMouse(returnRadians = true)
        var curX = (cursorDistance * cos(degree)) + (x + getWorldOriginX)
        var curY = (cursorDistance - (cursorDistance * sin(degree))) + (y + getWorldOriginY) - 1
        cursor.setPosition(curX, curY)

```

`cursorDistance` is the obvious variable, `x` is in the viewport units so it doesnt get conversion, `getWorldOriginX` and `getWorldOriginY` returns originX-Y / TILE\_WIDTH-HEIGHT as those arent initially in world units but pixel units as it is based of the texture, and to make that arrow point towards the cursor i did:

```
cursor.rotation = degreesToMouse() + 270

```

---
Tags: java, libgdx, geometry, trigonometry, kotlin
---


# Question
Title: Arrange UI images in half circle (180 degrees) in Unity
Im basicly looking to create this image:

I have all these parts and black background as a separate image so the ideal thing would be to place them with border between them but I could also probably make parts with border. The thing is I would need to turn these images on and off base on input ( think of them a some kind of health bar). Also if there is any other way to do this pleas let me know like some custom fill or something. I could probably arrange them by hand but I think that is kind a hacky solution and it would take forever.

Example of a part:

I try using this code that I found on similar post:

```
 private void arrangeImages()
{
    for (int i = 0; i < imgParts.Length; i++)
    {
        float angle = i * Mathf.PI / imgParts.Length;
        Vector3 newPos = new Vector2(Mathf.Cos(angle) * radius, Mathf.Sin(angle) * radius);

        imgParts[i].rectTransform.position = newPos;

    }
}

```

But the this is how it turns out:

# Answer
> 1 votes
Ended creating a full circle and just did normal radial fill to half value. Here is a circle example:

And then I just fill it to specific value taking in consideration segments. Here is sample code I put together.

```
public static void FillHalfCircle(float value, int segments,Image fillImage)
    {
        if (value > segments)
            value = segments;

        float valueToFill = (0.5f/ segments) * value;

        fillImage.fillAmount = valueToFill;

    }

```

---
Tags: unity, unity-ui
---


# Question
Title: Why specular reflection portion changes when we move in different direction?
We know that in Specular reflection rays reflected off surface at inverse angle;so camera position matters;creates bright highlights.

I have taken one image where specular reflection is seen(Here angle between surface normal and incident light is small) :

But when we move right(from my last photo taking place) I see the below image where previous specular portion has moved to right w. r. t fixed marker:

My question is why specular reflection portion is changing it's position while object and light source is remain at same place? Where I have mistaken to understand specular reflection?

N. B. -when light incident on specular portion with some angle in first image, but when I move the angle of incident is same with first image angle in different places of surface like second image. That's why see specular reflection.But my question is how this angle of light incident is same in the second case inspite of light sources and object is fixed.

# Answer
The specular highlight (labelled "specular" on the pictures you provided) is an specular reflection of the light source. It happens where the rays from the light source are reflected directly - with little or not scattering - into the camera.

For reflection, how light is scattered depends on:

* The material. In particular, how rough or smooth the surface is.
* The angle with the normal of the surface, respect to the position of the light and the camera.

Which means that whether or not a point is part of the specular highlight depends on:

* The normal of the surface *on the point*.
* How rough or smooth the surface is *on the point*.
* The direction to the light source *from the point*.
* The direction to the camera *from the point*.

---

Let us come up with some names.

Let us say we are considering a point `P` which is on the surface of the object. *And we would do this for every visible point, but we are going to consider one point at a time.*

And let us say the normal at the point `P` is `n`. *I'll be assuming that `n` is a unit vector (a vector of length `1`).*

Let us say the light source is at position `S`. And the camera is at position `C`.

So the position of the light source relative to the point is `S - P`. And thus the direction of the light from the point is:

```
l = normalize(S - P)

```

Which is equivalent to:

```
l = (S - P) * 1/length(S - P)

```

Where `*` denotes scalar product. So we are scaling the vector `S - P` by the inverse of its length. Which gives us a unit vector in the same direction.

Similarly, the position of the camera relative to the point is `C - P`. So the direction of the camera from the point is:

```
v = normalize(C - P)

```

Which is equivalent to:

```
v = (C - P) * 1/length(C - P)

```

*By the way, `length` (a.k.a `norm`, which is also represented with vertical bars `|`) would be the Pythagoras' theorem. It extends naturally to 3D like this: `length = sqrt(x*x + y*y + z*z)`, where `sqrt` is the square root.*

Now, the question is how close direction to the camera from the point compared to the ideal reflection direction. And whether or not it is close enough to be an specular highlight.

*This picture is taken from the article: Warp3D Nova: 3D Lighting - Part 1 by Hans de Ruiter.*

We can compute the ideal reflection direction `r` starting with the direction to the light `l`, and the normal `n`. Such that the incident angle (the angle between `l` and `n`) and the reflection angle (the angle between `r` and `n`) are equal.

With the formula for vector reflection (*under the assumption that `n` and `l` are unit vector*) we have:

```
r = n * 2(l·n) - l

```

Where `·` denotes dot product.

Then we can ask what is the angle between `r` and `v`:

```
angle = angle_between(r·v)

```

Which we can compute using the inverse cosine function (`acos`) and the dot product (*under the assumption that `R` and `V` are unit vectors*).

```
angle = acos(r·v)

```

*I have explained the relationship between cosine and the dot product on my answer to "When are oblique triangles used in game development?". You may also be interested in How to Work With Arbitrarily Oriented Vectors.*

---

Finally there will be some `max_angle` which depends on how smooth the surface is. And the point is in the specular highlight if `angle < max_angle`.

Well, actually, that is a simplification. In reality, it is not that there is a `max_angle`. It is that the intensity of the reflection decays with the `angle` until we disregard it. And how fast the intensity decays with the angle depends on how smooth the surface is.

*You can confirm in the photos in question that area near the specular highlight is also bright, just not as much.*

*Varying roughness (from left to right, rough to smooth). This picture is taken from the article Physically Based Rendering in Filament.*

This is because a rough surface does not reflect all the incoming rays in the same direction. Roughness here would be a representation of micro-imperfections in the surface.

*A systematic illustration of light scattering at a randomly micro rough surface. This picture is taken from the scientific article Matt Polyurethane Coating: Correlation of Surface Roughness on Measurement Length and Gloss.*

Instead of simulating the micro-imperfections of the surface, we encode them as macro properties of the material (such as roughness) which characterize the behavior of the light reflecting on it. We need to consider how realistic we want to generate the pictures, and also how computationally expensive is it to do it. *In particular in video games, where we have a limited time to generate each frame.*

---

About the situation depicted in the photos in question is that for the position of the light, the position of the camera, and the position, orientation and geometry of the object. There might be some point or points that get a very intense specular reflection, and we call that a specular highlight.

And if we change any of those variables (the position of the light, the position of the camera, and the position, orientation and geometry of the object) the set of points that get that very intense specular reflection is going to be different.

Thus, translating or rotating the object changes what points have the specular highlight. And so does moving the camera, or moving the light source.

---

Let us consider the situation where only we moved the camera.

The object and the light source remain in the same place. Thus the angle of the incident light is the same for every point. However, in one position of the camera some points reflect into the camera at the ideal angle. And in the other position, some different set of points reflect the light into the camera at the ideal angle.

To put it in the terms defined above. If we don't move the object or the light source then for every point `n` and `l` remain the same, and thus `r` also remains the same. However, if we moved the camera then `v` would change. So, in one position of the camera some points have a very small angle between `v` and `r`. And in the other position, some different set of points have a very small angle between `v` and `r`. As a consequence we see the specular highlight in a different place.
> 3 votes

---
Tags: lighting, reflection-rendering, shading, global-illumination, specular
---


# Question
Title: How to simplify a 2D mesh with messed up topology while keeping as much of the shape as possible and as efficiently as possible?
I'm trying to figure out a way to simplify any 2D mesh during runtime in Unity with broken up topology so that it will have more uniform topology and retain as much of its original shape as possible.

Here is a basic example of a circle with messed up topology:

Here is what I'm looking to achieve after applying simplification:

I also want this to work for any 2D mesh whether it's concave or convex. I've currently tried using the Marching Squares approach to reform the mesh but the results are too blocky and sharp.

How would I go about doing this? What might be the most efficient algorithms? Are there any existing libraries that I could look at to mess around with?

# Answer
> 0 votes
I see two ways to do this. However, I don't expect anything to be really fast, you might want to do this asynchronously.

* Figure out the perimeter shape, simplify it, and fill in the shape
* Iterate over pairs of vertices, and if they are very close together, do one of two things:
    1. Merge them together
    2. Move them further apart

The second option can be applied iteratively, while I think the first option is simpler, so let's talk about that one.

To figure out the perimeter, find a vertex where the angles of triangles around it does not add up to 360 degrees, meaning it can't be completely surrounded by triangles. Then, move along the edge, this would be done by finding the edge on the clockwise side of the gap of triangles.

Once you have this line, simplify it: For each pair of vertices, if they are very close together, merge them.

This is a simple approach, and you can of course take the curvature of the line into account too: straight line segments can be simplified even if the vertices are further apart.

Then, you can fill in the shape with a grid of triangulated squares or hexagons and connect the perimeter vertices with the closest one of the fill-in vertices.

This will not result in a perfect distribution of vertices, but it will have a way lower vertex count than the original. You can also run a couple steps of a mass-spring simulation (with the perimeter pinned) to relax the infill, if you have the time.

Some pseudo-code:

edgePoints = points where all neighbors, sorted by angle relative to the point, are connected to either adjacent neighbor.

```
var edgePoint = vertices.Where(vertex => {
    var neighbors = GetNeighbors(vertex).OrderBy(pt => (pt - vertex).Angle).ToList();
    for(var i = 0; i < neighbors.Count; ++i)
    {
        if (neighbors[i] is not connected to neighbors[(i + 1) % neighbors.Count])
            return true;
    }
    return false;
}).First();

// To walk around the edge, take the neighbor of each point that is on the clockwise side of the disconnected neighbors.

```

I hope this simple explanation is enough for you to figure out what to do!

---
Tags: unity, mesh, triangulation
---


# Question
Title: Where does this orange tint come from after baking LightMap?
My settings:
Unity version - Unity 2021.1.12f1
Lightmap Lighting Mode - Bake indirect
Render Path - URP
All Objects in Scene are marked as static.

If you move objects aside, then under them there is such a orange silhouette . How to remove these orange track under objects? Why do they appear?

# Answer
That's the indirect lighting you baked.

Because of the presence of the boxes, some of the surrounding bluish sky light is blocked from falling in those areas, making the surfaces there appear darker and less blue (more orange).

But also, some light bounces off of the orange boxes, taking on an orange colour, and lands in nearby areas, giving them an additional orange tint.

The parts underneath the objects should not be visible in gameplay, because the objects are "static" - you've made a promise to the engine that they are *never* going to move from their baked positions during gameplay. If these are objects that you need to move, then they should not be marked static.

These combined effects - simulating the blocking of light and the transport of coloured reflected light to nearby surfaces - is what indirect lighting and global illumination are designed to do. If you don't want these effects, then you might want to turn off any global illumination and stick to simple direct lighting.
> 2 votes

---
Tags: unity, rendering, lightmap
---


title: Unity3D Tests - Edit Mode vs Test Mode

text:
# Question
Title: Unity3D Tests - Edit Mode vs Test Mode
I have been reading about Edit Mode vs Play Mode testing and I'm not seeing any real reasons of why I would use Play mode testing over Edit mode testing. My assumption is that edit mode is better for writing tests and play mode is more for when testing is finalized.

What might sway someone to use one mode over the other?

# Answer
I'm finding out that

* `UnityEngine.SceneManagement` only works in Play Mode
* Edit Mode tests seem to only run from the Test Runner directly

Biggest take-aways

* Play Mode testing seems most beneficial and accurate to UX
* Edit Mode seems to be for pre-commit style testing eg. run smoke tests whenever the editor is modified

My favorite article on Unity game testing is by Ray Wenderlich

# Better Answer

Use **EditMode** tests for Unit tests.

* Unit Testing
* Integration Testing
* Functional Testing

Edit Mode is out-of-game so it works great for quick testing. Especially if your game is really big then edit mode keeps you from losing compile time over and over again while still being able to make sure your building blocks are intact.

Use **PlayMode** tests for

* End-to-End Testing
* Acceptance Testing
* Performance Testing
* Smoke Testing

With Play Mode you're in game and are really capturing the user's experience in your tests. On a small interactive you really could put all your tests here.

All in all, learn the various testing types then mix-and-match to what works best for your specific application.

My favorite "quick" article on various testing types

**Additionally**

If your unity project is part of a continuous integration project (cicd) then you can use headless unity with unlocked fps as part of your validation.
> 0 votes

---
Tags: unity, unit-testing
---


# Question
Title: Setting joint angle from a slider makes joint spin continuously
I use sliders to change the rotation angle of my joint, like this:

```
a = sliderx.GetComponent<Xslider>().sl.value;
b = slidery.GetComponent<Yslider>().sl.value;
headjoint.transform.Rotate(a, b, 0);

```

After I slide the bar, the joint continues rotating around and won't stop.

It's like it's doing

```
a += value

```

and not

```
a = value

```

Shouldn't the slider give me a single definite number?

Why? Do I need to use Euler angles?

# Answer
> 1 votes
You are calling the wrong method for what you want to do.

As you can see explained in the documentation, `Transform.Rotate` applies an *incremental* rotation to an object, *on top* of whatever rotation it already had.

It explicitly promises to do a `a += value`

So if you want `a = value` then *don't use this function*, because it does not do that!

You want something like this instead:

```
headjoint.transform.localEulerAngles = new Vector3(a, b, 0);

```

or

```
headjoint.transform.localRotation = Quaternion.Euler(a, b, 0);

```

Notice that these both express `a = value` instead of `a += value`.

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