# Question
Title: How to implement a dial control that snaps to increments?
How can I implement snapping via code? I have this 2d circle that the players rotate via drag and it works like a rotating dial. The best way to describe what I wanted to achieve is similar to a clock hand snapping to the hour numbers. I'm a total beginner and haven't actually learned anything about quaternions.

This is the my code , im using a raycast to detect if the dial is clicked/dragged.

```
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector3.forward);

    if (Input.GetMouseButtonDown(0))
    {
        if (hit.collider && hit.collider.GetComponent<Rotate2d>())
        {
            deltaRotation = 0f;
            previousRotation = angleBetweenPoints(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition));
        }
    }

    else if (Input.GetMouseButton(0))
    {
        if (hit.collider && hit.collider.GetComponent<Rotate2d>())
        {
            currentRotation = angleBetweenPoints(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition));
            deltaRotation = Mathf.DeltaAngle(currentRotation, previousRotation);

            if (Mathf.Abs(deltaRotation) > deltaLimit)
            {
                deltaRotation = deltaLimit * Mathf.Sign(deltaRotation);
            }

            previousRotation = currentRotation;
            hit.collider.gameObject.transform.Rotate(Vector3.back * Time.deltaTime, deltaRotation);

        }
    }

```

I forgot to add, here is my angle between points method.

```
   float angleBetweenPoints(Vector2 position1, Vector2 position2)
{
    Vector2 fromLine = position2 - position1;
    Vector2 toLine = new Vector2(1, 0);

    float angle = Vector2.Angle(fromLine, toLine);

    Vector3 cross = Vector3.Cross(fromLine, toLine);

    // did we wrap around?
    if (cross.z > 0)
    {
        angle = 360f - angle;
    }

    return angle;
}

```

# Answer
> 1 votes
First, you can simplify your angle method:

```
public static float DegreesCCWFromRight(Vector2 center, Vector2 pointer) {
    var direction = pointer - center;
    return Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
}

```

Then just round the result to your desired number of increments.

```
if (hit.collider && hit.collider.GetComponent<Rotate2d>())
{
    Vector2 mouseWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    float angle = DegreesCCWFromRight(transform.position, mouseWorld);

    const float incrementCount = 6;

    angle = Mathf.Round(currentRotation * incrementCount/360)
                    * 360/incrementCount;

    transform.localEulerAngles = new Vector3(0, 0, angle);
}

```

---
Tags: unity, c#, input, mouse
---


# Question
Title: Apply an offset to a camera rotating around an object
I have a camera that rotates around an object ***to simulate the rotation of this object.*** To do this, I simply move my camera to the object before making my rotation and then translate it back:

```
void Update()
{
        distanceToTarget = Vector3.Distance(camera.transform.position, myObject.center);
        transform.position = myObject.center;

        transform.Rotate(Vector3.up, horizontalRotationValue);
        transform.Rotate(Vector3.right, verticalRotationValue);

        transform.Translate(new Vector3(0f, 0f, -distanceToTarget));

        centeredPosition = transform.localPosition;
        ...

```

My problem comes from the fact that I would like to also be able to have an offset of the view of my camera in relation to the object. All this while continuing to simulate the rotation of my object by rotating the camera around.

After my current rotation logic, the object is still in the center of the view. So at the first iteration of my rotation, I save the difference between the centered position on the model and the offset camera.
`offsetToCenter = transform.localPosition - centeredPosition;`

So, I hope to be able to use this offset to shift my camera again after it has rotated. However, the recorded offset no longer corresponds to the offset on the local space of the camera since it has rotated.
`transform.localPosition += transform.localRotation * offsetToCenterPosition;`

The rotation works well but not the position. There is a step that I must be doing wrong or that is missing. I think it comes from the conversion of `offsetToCenterPosition` with the new rotation of my camera.

# Answer
> 0 votes
It was indeed coming from the `offsetToCenterPosition` calculation. Thank you DMGregory.

Here is the full answer:

```
void Update()
    {
        distanceToTarget = Vector3.Distance(camera.transform.position, myObject.center);

        transform.position = myObject.center;

        transform.Rotate(Vector3.up, horizontalRotationValue);
        transform.Rotate(Vector3.right, verticalRotationValue);

        transform.Translate(new Vector3(0f, 0f, -distanceToTarget));

        centeredPosition = transform.localPosition;

        transform.localPosition += transform.localRotation * offsetToCenterPosition;
    }

void UpdateOffsetToCenterPosition() //called on first iteration
    {
        offsetToCenterPosition = Quaternion.Inverse(transform.localRotation) * (transform.localPosition - centeredPosition);
    }

```

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


# Question
Title: How to do local mirroing of object from the camera point of view?
I would like to render an object as if mirrored but on its own world position and with a mirrored orientation being camera view dependant. Something like the billboarding but keeping the 3D shape and showing it mirrored. I don't want to change my current culling when rendering it as it will be during regular scene rendering. See the picture below for expected result. Thanks in advance for your help.

# Answer
A solution to this is to precalculate on CPU DepthMin and DepthMax for the object in a constant buffer. I was already using it for sorting the object back to front for some needs. Then apply some local transform to the object (if the mesh origin is 0,0,0) before the WVP operation and use the result to have a specific Depth. Then do Depth = DepthMax+DepthMin-Depth to "revert locally" the depth. With this equation when Depth = DepthMax it becomes DepthMin and vice versa all over the \[DMax,DMin\] interval.

I'm using this "revert" depth as fallback for hard case ray miss in SSR with some nice results to be improved. Using this method pixels from front faces difficult to hit can be found. I'm now twiking this to have the additional transform begin oriented according to the direction of the camerapos to objectpos to have a result consistant all over the screen. Like the billboard I was mentioning.
> 0 votes

---
Tags: camera, transformation
---


title: Remaining artifacts in SSR methods

text:
# Question
Title: Remaining artifacts in SSR methods
I a previous post (Scaling and offset problems with screen space reflexion in DX11) I was fnally able to produce SSR with several methods (ray marching/McGuire/Mirror like). These techniques have all their own limits producing some articfacts like "holes" for overlapping object not in the same z and not close enougth or other problems.

Can someone help me in some ways to resolve these various artifacts shown in the answer picture in this previous post. Did someone knows if these holes in McGuire code can be handled? I’m thinking of something like these algorithms were you can remove someone in a photo and replace it by the surrounding scene.

# Answer
Solutions.

First I suggest reading the thesis from Anthony Paul Beug (Screen Space Reflexion Techniques, 2020) that summarizes and compares several SSR techniques with code for DX and which gives several ideas for artefacts.

In the picture panel A is the initial McGuire SSR method I implemented. The holes marked white are due to overlapping objects. For instance, the blue dot hides the green ball that hides the vertical plane. The plane has thus a hole due to the overlapping green ball in the main scene. The only way to deal with this is to create an additional layer to store the missing information for occluded pixels (panel B). The artefacts marked in yellow are from the bottom of the object where things starts to be invisible for the camera or the ray march is not able to hit the pixel. I have to say that I did not understand why the ray is able to hit the top of the sphere correctly but not the bottom. This can be fixed somehow (panel C) but is not perfect at the moment (panel D) as some deformed shapes appear when far from screen centre or still incomplete pixel detection.

The first problem is thus solved (panel B) by adding extra render targets to store the hidden pixels. Before this I’m sorting object back to front on the cpu. For this I pretransform the object boundingbox (WVP) to obtain screen data XYZ. Z is used first for back to front sorting (mandatory for the correct final drawing). XY are used to calculate the bounding square for each object in screen space to determine intersections between objects. Intersecting object are then Z compared to know who is overlapped. An object overlap flag is incremented each time an object is overlapped. This overlap flag is part of the constant buffer object. In addition the DepthMin and DepthMax of the object are also stored in the cbuffer for later use. The cbuffer for mesh is like this:

```
 typedef struct _CBMESH
 {
      XMMATRIX mWorld;
      XMMATRIX mIT_VW; //Inverse Transpose View*World for view space normals
      XMMATRIX mMirror; //used for « depth mirror » calcul.
      XMFLOAT4 FactorColor;
      XMFLOAT4 D1D2DMinDMax; //D1 = 1 if overlap = 1 else 0;
      //D2 = 1 is overlap > 1 else 0; DMin/max DepthMin/Max mentioned earlier.
      DWORD Flag; //for specific coloring treatment
      XMFLOAT3 pad; //unused
   }CBMESH, *LPCBMESH;

```

In this scene (panel E) object can have 0 (white square), 1 (red) more than one (green) overlaps. At rendering time all objects are drawn in the main layer 1 (albedo +normal view space + regular depth buffer).

Objects overlapped once are drawn in the second layer (albedo+normal view space + specific depth map channel R). Objects overlapped more than one are drawn in the third layer (albedo+normal view space + specific depth map channel G). An extra map is used for “depth mirror” value explain later. Yes 8 targets at the end. Maybe there is a better way to proceed. It was mentioned that up to 4 layers may be needed. This is similar to the depth peeling method described on NVidia web site but here I select layer based on the overlap count. As I’m using multitarget rendering for all the preparation process I have independent blend for each target. Layer 1 (albedo+normal) has opaque setting and the other SRC\_ALPHA/INV\_SRC\_ALPHA colour blend. Specific depth maps are filled with 1 and then using OP\_MIN for RG colors similar to COMPARISON\_LESS. Object are drawn in all targets whatever the settings so we need to make some “invisible” in 2nd and 3rd layer. This is where D1D2DMinDMax is used like this :

```
    Output.Color2 = float4(Color,D1D2DMinDMax.y); //3rd layer shows object only if they have overlap > 1 (alpha is set to D1D2DMinDMax.y=1, object visible else not visible).

```

Same for the normal in 3rd layer. D1D2DMinDMax.x set alpha for 2nd layer. A the same time the specific depth map is filled using also D1D2DMinDMax.xy:

```
    Output.Color6 = float2(1-D1D2DMinDMax.x+Input.Pos.z*D1D2DMinDMax.x,1-D1D2DMinDMax.y+Input.Pos.z*D1D2DMinDMax.y);//put 1 if not visible (remember we do OP_MIN) or the depth value if visible. R is layer 2 and G layer 3.

```

During SSR ray march all 3 depth information are evaluated in the McGuire method to find the best SceneZMax value.

The final problem is the ray missing the bottom of the objects. I thought using GatherRed on main depth buffer to sample 4 depths at once but can’t get it working correctly. I solved the problem (partially, panel C/D) with a “mirrored depth” value. The idea is to mirror locally the depth of the object to give better chances to the ray to hit the pixel. First I prepare a “billboard” matrix using the direction from camera to the object position.

```
   gBillBoard = XMMatrixRotationAxis(V, -Roty);//V is the direction, RotY is the camera rotation, the sign seems not important).

```

Then I store gBillBoard\*WVP in the mMirror member of the cbuffer mesh. In the VShader I calculate:

```
  output.PosM = (input.pos, mMirror).

```

PosM.z/PosM.w is the alternative Depth. Then I fill the mirror depth map with the locally mirrored depth using the two last member zw of D1D2DMinDMax (because of the precision the precalculated sum did not work properly) :

```
Output.Color7 = D1D2DMinDMax.w+D1D2DMinDMax.z-Input.PosM.z/Input.PosM.w;

```

This simple operation makes Z=DMin becoming DMax and vice versa all over the interval resulting in a “local mirrored depth”. The result is not perfect as shown in panel D. The shape is better preserved when at screen centre. The more at the screen boundaries the higher the shape is deformed. I hope someone can help me find a better matrix to solve this deformation problem.

At the end the FPS rate is \>70 in the worst case and around 90 in the best after removal of some unnecessary shader instructions. Using B5G6R5 format for albedo/normal extra layers improves the FPS a little while maintaining sufficient quality and reducing a little the bandwith. No blur is made.
> 0 votes

---
Tags: directx, raymarching
---


# Question
Title: How to motivate movement through the city in a D&D / Pokémon GO -like game?
My goal is to create a game that is sort of a combination between Dungeons & Dragons and Pokémon GO.

The main goal of the game will be to have the players move through my city, in real life, and complete quests at several locations, making their characters stronger by interacting with other people in different places in the real world.

Like in D&D, players will create characters with a backstory. They can then create a party or venture out by themselves. Character creation will happen at the guild house, a local games story, where a GM will be present. The GM will then sent the players out on quests to other locations, another GM will be at each location to assist the players and make sure everything happens in an ethical manner.

An example quest would be to slay a dragon somewhere in the city. That dragon could be located at a nearby bar, where another GM would be ready to make the players fight the dragon. Obviously I'd get permission from the bar owner first.

Another important aspect of the game is to have several guild houses at different locations in the city, these guilds would oppose and fight each other for ... something ... Maybe eventually with the goal to open my own bar as a guild house.

What I'm struggling with most at the moment is finding a good reason to sent players out into the city to different locations.

In Pokémon GO it makes sense, you walk around trying to find Pokémon on your phone.

But for this there seems to be no real reason to send the players out. Why not just have the 2nd GM at the next table to fight the dragon instead?

So I'm looking for a good reason to have the players move throughout the city.

I want this because it's what I loved about Pokémon GO, going to different locations and interacting and meeting different people. It just doesn't really make much sense with my concept so far. Sure I could just say that's the way it is, but I'd rather find a strong motivation for it.

Maybe it could be as simple as having to pick up a physical item, even if just a piece of paper, at the location and bring it back?

Eventually I would like to create a complete digital platform for this, that can automatically assign/complete quests at different locations. For now I'm going to use GMs at different locations.

Obviously it's going to take some time to build up this concept, recruit players and GM's, ...

Would love to hear some thoughts and ideas.

# Answer
*Pokemon Go!* and its technological predecessor *Ingress* are played by many people because they gamify exploration of the real world. They give the player an excuse to go to places they never been to before.

You could market your game as an opportunity like that. Just instead of exploring generic landmarks, it could be a guide for the RPG culture of your city. By bringing people to hobby stores, rpg-friendly bars, RPG groups at community centers and other cool venues the beginner role-playing enthusiast never realized exist in their city.

In that way it would benefit both the players as well as the businesses which participate in the game.

How would this be justified in-universe? Well, if a quest giver in an RPG world tells you to slay a dragon, that dragon won't be sitting at the table next to them. It will be in its lair, which will require some traveling to get to. Having the player travel when their character has to travel can be easily sold as a feature increasing immersion. So it makes sense that the "dragon's lair" is represented by the bar at the other side of town.
> 0 votes

# Answer
You could draw inspiration from various FPS game modes.

Capture the Flag could be great fun in a Pokemon Go format... every Clan has a flag, and it's usually at their Clan base. But someone could try to steal it, by battling people near the Clan House and then if they defeat several of them... they capture the flag.

Another option is to more directly draw inspiration from Pokemon Go and create collectibles that you win in combat with NPCs. They wouldn't have to be monster collectibles - they could also be weapon, armor and spell collectibles. You could win them in combat, or embark upon more elaborate quests to earn them.

If you want to meet people in person, it'd probably be best to have a specific day where people can play the game. Make it a big deal, and promote it through social media channels and local D&D groups. That way you're more likely to get a critical mass going...

Sounds like a fun project. Good luck!!
> 0 votes

---
Tags: game-design, rpg, augmented-reality, geolocation
---


# Question
Title: How to load an FBX animation file in ASSIMP?
I have an example from a LearnOpenGL tutorial which loads the animations. Now, I want to use that to render FBX animation, but the result is totally wrong.

What I want is simply to load an FBX animation with the human skeleton from Mixamo.

Are there any examples of it?

# Answer
We have a simple example in the assimp-repo. You can find it here: Simple Snake as a FBX-File

It is just a snake with a simple skeleton with the following form:

```
parentbone -> childbone -> childbone -> ...

```

You can use it to test you bone-implementation.

The examples used in the most tutorials are containing animations for characters. The snake contains just one tree with some vertices modified by the vertex-weights stored in the aiMeshes.

When this example works try your human.
> 2 votes

---
Tags: opengl, assimp
---


title: Fast zoom in and out in Unity Editor

text:
# Question
Title: Fast zoom in and out in Unity Editor
Is it possible to zoom out and zoom in in Unity Editor in Scene View faster than just with the help of scroll wheel on the mouse? I hope there are exist some shortcut for that. Am I right?

# Answer
All you need to do is double-click the object you wish to get close to, in the `Hierarchy` view. This will rapidly advance the camera to that object's position. You can then use mouse wheel to adjust zoom.

Other than this, I don't believe there is anything like hotkey-assigned zoom levels, unfortunately.
> 4 votes

# Answer
In `Scene` view.

For Windows:

1. To enter fast zoom mode hold `Alt` \+ move mouse holding `Right Mouse Button`.
2. Press `F` to **Focus** on `Game Object`.
3. Press `Shift` \+ `F` to **Focus** on `Game Object` and follow it automatically.
4. Hold `Right Mouse Button` and move with `WASD` \- the more time you spend doing it the faster speed of movement you will get.

Note, that the more you zoom you might notice that zoom slowed down. To better address this problem first do `2-nd` step and then try `1-st` one.

For Mac:

It should be the same.

---

*In future releases of Unity we will have ability to set up our own short-cuts with a nice graphical interface.*
> 7 votes

# Answer
The following worked for me using version 2020:
Pressing the `F` key on a terrain object reset the mouse sensitivity.
> 2 votes

# Answer
Holding `Right Mouse Button` button and scrolling the `scroll wheel` will let you adjust the `WASD` speed.
> 1 votes

# Answer
To *zoom out* quickly, you can double click an object on the scene hierarchy with no (sprite) renderer attached for example. This will save you from having to use your mouse wheel for a long time.

To *zoom in* quickly you can double click on the object with (sprite) renderer where you want to zoom in to
> 0 votes

---
Tags: unity, scene, view, ide
---


# Question
Title: Rotating dials with increments, one works and the others doesn't. Why?
I have 4 dials that rotate by increments when the players drag them. They all exactly have the same code, but I can't figure out why only one of the dial works as intended (dial 2). My code stops working as intended on other dials when I change the increment count to 4, the other dials rotate a quarter and then stops to move when I drag them.

Here's my class attached to the dial.

```
public class Rotate2d : MonoBehaviour
{
    float previousRotation;
    float currentRotation;

    void Update()
    {
        RotateObject();
    }

    public static float DegreesCCWFromRight(Vector2 center, Vector2 pointer)
    {
        var direction = pointer - center;
        return Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    }

    //v2 rotate with incremental snapping
    private void RotateObject()
    {
        Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector3.forward);

        if (Input.GetMouseButtonDown(0))
        {
            if (hit.collider && hit.collider.GetComponent<Rotate2d>())
            {
                previousRotation = DegreesCCWFromRight(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition));
            }
        }

        else if (Input.GetMouseButton(0))
        {
            if (hit.collider && hit.collider.GetComponent<Rotate2d>())
            {
                currentRotation = DegreesCCWFromRight(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition));
                previousRotation = currentRotation;

                Vector2 mouseWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                float angle = DegreesCCWFromRight(transform.position, mouseWorld);

                const float incrementCount = 4;

                angle = Mathf.Round(currentRotation * incrementCount / 360)
                                * 360 / incrementCount;

                hit.collider.gameObject.transform.localEulerAngles = new Vector3(0, 0, angle);

            }
        }

```

Here's my Project Hierarchy

Here's each dials inspector

# Answer
> 1 votes
The problem is that each `Rotate2d` has its own independent life cycle, which means that `Update` will be executed 4 times per frame. If the mouse points to any dial, the four scripts will trigger the corresponding logic.

fix: Determine whether the hit target is the dial itself.

```
public class Rotate2d : MonoBehaviour
{
    float previousRotation;
    float currentRotation;

    void Update()
    {
        RotateObject();
    }

    public static float DegreesCCWFromRight(Vector2 center, Vector2 pointer)
    {
        var direction = pointer - center;
        return Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    }

    //v2 rotate with incremental snapping
    private void RotateObject()
    {
        Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector3.forward);

        if (!hit.collider)
        {
            return;
        }
        var hitRotate2d = hit.collider.GetComponent<Rotate2d>();
        if (hitRotate2d != this)
        {
            return;
        }

        if (Input.GetMouseButtonDown(0))
        {
            previousRotation = DegreesCCWFromRight(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition));
        }
        else if (Input.GetMouseButton(0))
        {
            currentRotation = DegreesCCWFromRight(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition));
            previousRotation = currentRotation;

            Vector2 mouseWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            float angle = DegreesCCWFromRight(transform.position, mouseWorld);

            const float incrementCount = 4;

            angle = Mathf.Round(currentRotation * incrementCount / 360)
                            * 360 / incrementCount;

            hit.collider.gameObject.transform.localEulerAngles = new Vector3(0, 0, angle);
        }
    }
}

```

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


# Question
Title: Visual Joystick moving faster than my finger. why?
First of all, here's the video of what my problem really is. (Sorry for bad quality)

As you can see, the red circle is the center of the visual joystick. The green one indicates my finger and the white circle is the handle of my joystick.

As you can see it works but the handle goes faster than my finger, I don't know why this happens

Here's the code for setting the handle's position:

```
            RawDirection = Input.GetTouch(CurrentFingerID).position -
                (Vector2)BGRect.position;

            if (RawDirection.magnitude > BGRect.sizeDelta.x / 2)
                RawDirection = RawDirection.normalized * BGRect.sizeDelta.x / 2;

            HandleRect.anchoredPosition = RawDirection;

```

meaning of the variables:

* `CurrentFingerID` is used to save which finger is on the joystick currently.
* `BGRect` is the RectTransform attached to the BG (see the pic below)
* `HandleRect` is the RectTransform attached to the Handle (see the pic below)

And these are BG and Handle:

BG and Handle settings:

I think `RawDirection` should be divided by some number to fix this issue. Any help is appreciated and feel free to ask for additional info

# Answer
It looks like I should have used `RectTransformUtility`:

```
RectTransformUtility.ScreenPointToLocalPointInRectangle(ResponseArea, Input.touches[CurrentFingerID].position, null, out FingerPositionInRect);
RawDirection = FingerPositionInRect - ((BGRect.anchorMax + ResponseArea.sizeDelta) - BGRect.anchoredPosition;

```

(`ResponseArea` is the RectTransform of the Joystick)
> 3 votes

---
Tags: unity, mobile, joystick
---


# Question
Title: How should I implement the idea behind this abstract class setup in a Unity-Friendly/Inspector-Usable way?
First up, the name of the question is terrible and I am open to suggestions. For context: I'm still relatively new to C#/Unity and it's hard to ask questions properly when I don't know the terminology. I'm reasonably experienced in Java/Python/javascript though so I'm not new to programming in general. Also since I have no idea how to ask this question in a structured way I'm just going to show all the relevant stuff and hopefully someone who understands it can put succinctly what I'm trying to ask.

I have this struct:

```
[System.Serializable]
public struct FieldLayer3D {
    public  Vector3        position;
    public  Quaternion     rotation;
    public  Vector3        scale;
    [SerializeReference] public  FieldGeneric3D field; //this is where we have a problem
    public  BlendType      blendType;
    public  float          opacity;
    public  Channel        channel;
    public  float          smoothParameter;
    public  NormaliseType  NormaliseType;
    public  float          bias;
    public  bool           invertLayer;
}

```

My plan was to use arrays of these to define some procedurally generated content and let me combine noise and patterns in ways similar to graphics programs combine layers of images. I need the larger class that will contain an array of FieldLayer3Ds to be serializable so I can save/load my work. The FieldGeneric3D typed variable "field" is what defines the type of noise/pattern/whatever and FieldGeneric3D is an abstract class defined as follows:

```
[System.Serializable]
public abstract class FieldGeneric3D {
    //These are the fields for "FieldLayer3D"
    public abstract float FieldAt(Vector3 p);
}

```

The reason I defined it this way is because each field needs its own set of variables that are different from each other, but will always value types like Vector3 or float such as in these two examples:

```
[System.Serializable]
public class FieldSDFBox3D: FieldGeneric3D {
    public Vector3 boxSize;
    public FieldSDFBox3D(Vector3 boxSize) { this.boxSize = boxSize; }
    public override float FieldAt(Vector3 p) { return PatternGenerator.Sample_SDF_Box(p, boxSize); }
}
[System.Serializable]
public class FieldSimplex3D : FieldGeneric3D {
    public int seed;
    public FieldSimplex3D(int seed) { this.seed = seed; }
    public override float FieldAt(Vector3 p) {
        NoiseGenerator noiseGenerator = new NoiseGenerator(seed);
        return noiseGenerator.Sample_Simplex(p);
    }
}

```

However, this is what I see when I use the FieldLayer3D struct in a MonoBehaviour:

I was expecting something analogous to how materials work that you could drop in one of the script files that defines the appropriate class and I was HOPING that after you dragged in the script it would let you mess with public variables for the instance of the object.

Solutions I've thought and the issues with them:

1. Just use an enum instead of this class structure thing and let whatever object is controlling the field generation handle it. This doesn't work because I need to be able to set variables for each layer and the types of variable are different depending on the type of field.
2. Make FieldGeneric3D inherit from ScriptableObject and create assets for every layer I ever want to make. This is problematic because can you imagine how messy and clunky things would get in a program like photoshop if every time you wanted to add a layer you needed to save it as a new separate file? This just isn't workable, and the same goes for making it a MonoBehaviour because then I need to fill my scene with dummy GameObjects for every layer of noise. I also think these would be difficult to simplify and serialize. It is possible Ill make the parent class that combines and stores these layers a ScriptableObject because I'd like the combination to be a savable asset without too much trouble but I'm leaning towards using JSON for the whole saving and loading of layers.
3. Use the enum approach but just include a bunch of null variables that are only ever read from if the correct type of layer is used. This isn't ideal for extensibility in the future because I'll need to update things in multiple places. It also means that if I add a new type of FieldGeneric3D with new variables I'll need to add those variables to the FieldLayer3D class which might break saving/loading for all the ones I've already saved. I also don't know much about writing my own editor or anything so going about and conditionally hiding all the unused variables sounds like something that could result in issues if I implement it wrong. Leaving them all always visible is not ideal because I need other people to be able to use this tool without too much confusion or reading of manuals.
4. Some fancy custom editor shenanigans. Seems like it would take a long time to learn how to do properly, so I was trying to just make simple classes and hope Unity would understand my intent.

**The ultimate question is this I suppose: How do I achieve what I want to achieve, within the Unity ecosystem in such a way as to be editable in the inspector, save/loadable, understandable by other people, and without future additions becoming a major headache?**

Also, I have seen this How do I expose a field of an abstract type to the Inspector? question and the only thing I could see there of help was "Composition over Inheritance" but I'm not sure how that would be applied here.

To clarify, I am willing to do any of the four ideas I had if the answer is just that that is the best option available to me.

# Answer
One possible solution is that instead of having it as a field in this class, have it as a separate monobehaviour component that inherits from an abstract class or interface. You can then get a reference to it using GetComponent(). GetComponent is a lot more friendly to interfaces and abstract classes.

So then instead of dragging a reference in the inspector, you add a brand new component next to it. And then that component could have its own specific references if needed.

I suspect this might be a possible solution that encompasses the idea of “composition over inheritance” since you are composing the behaviour using monobehaviour components that can be swapped out in a more Unity friendly way.
> 1 votes

# Answer
One simple way to get this behaviour out of the box is to make your `FieldGeneric3D` inherit from `ScriptableObject`:

```
public abstract class FieldGeneric3D : ScriptableObject {
    //These are the fields for "FieldLayer3D"
    public abstract float FieldAt(Vector3 p);
}

```

Then for each subclass, add a menu item that lets you create an instance of that class.

```
[CreateAssetMenu(fileName = "NewSimplexField.Asset", menuName = "Field/Simplex")]
public class FieldSimplex3D : FieldGeneric3D {
    public int seed;
    public FieldSimplex3D(int seed) { this.seed = seed; }
    public override float FieldAt(Vector3 p) {
        NoiseGenerator noiseGenerator = new NoiseGenerator(seed);
        return noiseGenerator.Sample_Simplex(p);
    }
}

```

This will add a "Field" subfolder to the asset creation menu you get when you right-click in the project window, and you can create new asset files corresponding to fields there. Each one is an asset you can select like a texture, and configure its public/serialized properties in the inspector.

You no longer need the `[SerializeReference]` attribute, because `ScriptableObject` references are serialized automatically.

This also makes it easy to re-use the same field settings in different combinations, but the downside is that you need to make a new asset for every unique choice of field parameters. You also need to click on the individual assets to configure them, rather than doing so in-line within your array, though various folks have written extensions to add the in-line editing functionality.

---

An alternative is to write your own custom inspector for this `FieldGeneric3D` type that presents an interface to choose a subclass and draw that subclass's inspector fields. Here's a rough sketch of how that could be done, but it has room for improvement:

```
using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(FieldGeneric3D))]
public class FieldGeneric3DDrawer : PropertyDrawer
{
    // For a simple example, I'm hard-coding the field types as enum values.
    // A more robust approach would use reflection to find all matching types.
    public enum FieldType : int {
        None,
        FieldSimplex3D,
        FieldRadial3D,
        FieldBox3D
    }

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        float height = EditorGUIUtility.singleLineHeight;

        if (property.isExpanded) {
            // Note where this property ends and the next one begins.
            var endMarker = property.Copy();
            endMarker.NextVisible(false);

            // Descend into the first nested child property.
            var nested = property.Copy();
            if (nested.NextVisible(true) && !SerializedProperty.EqualContents(nested, endMarker)) {
                do { // For each child property, accumulate its height.
                    height += EditorGUI.GetPropertyHeight(nested, nested.isExpanded);
                } while (nested.NextVisible(false) && !SerializedProperty.EqualContents(nested, endMarker));
            }
        }

        return height;
    }

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        // Using BeginProperty / EndProperty on the parent property means that
        // prefab override logic works on the entire property.
        EditorGUI.BeginProperty(position, label, property);

        // Draw a drop-down to select what type of field we want.
        var currentType = GetTypeID(property);
        var newType = (FieldType)EditorGUI.EnumPopup(position, label, currentType);
        if (newType != currentType) {
            // If the user changes the field type, assign a new instance of that type.
            property.managedReferenceValue = MakeDefault(newType);
            property.serializedObject.ApplyModifiedProperties();
        }

        // Draw a fold-out if this type has child properties.
        if (property.hasVisibleChildren) {
            var foldZone = position;
            foldZone.height = EditorGUIUtility.singleLineHeight;
            property.isExpanded = EditorGUI.Foldout(foldZone, property.isExpanded, " ");

            // Draw those properties, if folded-out.
            if (property.isExpanded) DrawChildren(position, property);
        }

        EditorGUI.EndProperty();
    }

    void DrawChildren(Rect position, SerializedProperty property) {
        // Inset our drawing inside the folded-out region.
        int indent = EditorGUI.indentLevel;
        EditorGUI.indentLevel++;

        position.y += EditorGUIUtility.singleLineHeight;
        position.height -= EditorGUIUtility.singleLineHeight;

        // Note where this property ends and the next one begins.
        var endMarker = property.Copy();
        endMarker.NextVisible(false);

        // Descend into the first child property.
        var nested = property.Copy();
        nested.NextVisible(true);
        do { // For each child property, draw its inspector widgets in a stack.
            EditorGUI.PropertyField(position, nested);

            // Advance the positioning of the next property by how much space this one took up.
            float height = EditorGUI.GetPropertyHeight(nested, nested.isExpanded);
            position.y += height;
            position.height -= height;
        } while (nested.NextVisible(false) && !SerializedProperty.EqualContents(nested, endMarker));

        // Return the indent to where we found it.
        EditorGUI.indentLevel = indent;
    }

    // Helper method to get the type of field as an enum value.
    static FieldType GetTypeID(SerializedProperty property)
    {
        var typeName = property.managedReferenceFullTypename;
        if (string.IsNullOrEmpty(typeName)) return FieldType.None;

        typeName = typeName.Substring(typeName.LastIndexOf(' ') + 1);

        return (FieldType)System.Enum.Parse(typeof(FieldType), typeName);
    }

    // Helper method to make a new instance of a field class given an enum type ID.
    static FieldGeneric3D MakeDefault(FieldType fieldType)
    {
        switch (fieldType)
        {
            case FieldType.FieldSimplex3D: return new FieldSimplex3D();
            case FieldType.FieldBox3D: return new FieldBox3D();
            case FieldType.None: return null;
            default: throw new System.NotImplementedException($"Unknown field type {fieldType}.");
        }
    }
}

```

Place this script in a folder called "Editor" and modify it to support your collection of field types. It will handle drawing appropriate controls when a reference to `FieldGeneric3D` is encountered in any inspector.

This method saves you from explicitly creating new assets for each field instance - instead, these instances are created implicitly. But this also means that the instances are not shared: if you have many scripts that all need the same base noise field, they'll each possess their own unique copy.
> 1 votes

---
Tags: unity, c#, serialization, inheritance
---


# Question
Title: How to Force Refresh Texture2D/Sprite when Programmically Modified using Editor Script?
Here is some code called using a custom button in the component inspector:

```
// created off-screen:
// Texture = Texture2D, width = int, height = int

SpriteRenderer.sprite = Sprite.Create(Texture, new Rect(0, 0, width, height), new Vector2(0, 0));

```

Long story short, I am programmatically creating a Texture2D and applying it to my SpriteRenderer. I 100% know the code works because, once I run the game, the SpriteRenderer displays the exact Texture2D I programmatically created. The issue is when I click my "generate" button in the component inspector, the texture is not displayed in the scene.

When I click on my SpriteRenderer in the inspector, I can see a "box" representing the texture's bounds as if it's not loaded? The size changes for each generation, so I know it knows the size of the texture? But I can't find a way to force it load except for actually running the game. Once I run the game, the texture displays just fine. Even after I stop the game, the editor shows the texture just fine until I generate it again. As if there's something about running the game that refreshes it?

Is there something I'm missing? Something to force the scene or SpriteRenderer to display in editor?

# Answer
Had to call `Texture2D.Apply()` after modifying the texture using `SetPixel`. Whoops.
> 1 votes

---
Tags: unity, sprites, editors
---


title: Why nobody creates shared world games?

text:
# Question
Title: Why nobody creates shared world games?
Vast majority of modern network games use "lobby" conception: when limited amount of players connect to a single lobby server and play the game in isolation from everyone else who is not in thу same lobby.

Were the any attempts to create a game where players would have had one shared world to play altogether? If no, what are the major problems which made that idea non-viable?

# Answer
Yes there are games, and yes there are problems.

Listen, light has a set speed. Even if the connection were at light speed all the way from client to server (which probably it isn't), it takes time for information to go from one place to the other.

But I can't explain that better than Grace Hopper: Admiral Grace Hopper Explains the Nanosecond.

That time the information needs time to travel adds latency (which is a component of "lag"). Another source of latency is that the server needs to process the information of every player. The server has only so many CPU cores… And yes, I'm counting a data center where you have rows of stacks of computers. That gets expensive.

Furthermore. Each player has to receive information about what all the other players are doing in that same area. And that can be a lot when areas that get crowded. So the server (and the client) need a large transference rate (which you might mistakenly refer as bandwidth), and large transference rate is also expensive (low transference rate is the other component of "lag").

---

Games with a single coherent world available world wide exist. Except they often don't have real-time physics between players. The less real-time interaction they can get away with, the better. That way if there is some lag between them, it isn't a problem. To this category belong a few select MMOs, where people walk through each other. Although they still need to deal with crowded areas, and they cope with it in multiple ways (including limiting the number of players a player can see).

*Albion Online praises itself on having "one massive, sprawling world". My personal experience with it is huge lag on crowded towns.*

Because of that, games which are available world wide would prefer to have multiple servers for different geographical regions.

Ok, I hear you, surely we can have a single coherent world per region, right? That is much more manageable, and much more common. Although, even for these regions real time physics between everybody is not practical. If we can limit the number of players that can interact with each other at a time, it is much more manageable. So we don't see as many huge open worlds as networks of maps. Or, again, no real-time physics between players.

You may also be interested in: Time Dilation (Eve Online). *Yes, they have multiple servers.*

---

There are other considerations for game design. For example, competitive games should strive for good match making. Because the game is interesting when the skill level of the players is similar. If you have highly skilled players vs beginners, the beginners get wiped and discouraged from continuing playing and the highly skilled players get bored, so the player base would dwindle.

Also consider that if the maps of the game are not huge, and it makes sense to have a maximum number of players per map, then lobbies makes sense.

By the way MMORPGs also suffer of something similar to the match making issue. You don't want high level players in the areas intended for lower level players. A variant of this happens for other cooperative multiplayer games: the high level players do everything (e.g. kill all the monsters) and leave nothing for the low level players. So, instead, you want people to move to other areas as they level up. A consequence of that is that the players with the highest levels will run out of content (it takes time for developers to add new areas for them). *In competitive games, the players are the content.* Sometimes players want to start over just to have something to do while they wait for more content… They would welcome another server where they could do that without messing with their higher level characters (although allowing players to have multiple characters and switch between them would also work, developers also need to consider if that breaks the game design or economy).

And please consider that not having this hube world for everybody also lower the requirements for the players (they don't need to download/load huge maps, and they don't need to have the transference rate for the information of as many players), which means more people can actually enjoy the game.

And do not forget that having lobbies also allows players to have private sessions with only the people they want. *Yes, people enjoy that. No troll and no griefers for a while can be good. Also games can be useful to strengthen bonds with people.*
> 3 votes

---
Tags: networking, server, unity-networking, open-world
---


# Question
Title: Player is able to interact with objects but enemy isn't able to
Newbie here, I have a player script that interacts with objects just fine and I made an enemy script for the same object and it gets completely ignored:

Below there are 4 scripts. The `Player.cs` is player movement, `Enemy.cs` is enemy movement, `Speed.cs` gives the player a speed boost when they touch the green object named `Speed` and `enemySpeed.cs` is *TRYING* to give the enemy a speed boost when it touches the green object named `enemySpeed`. Those last two are both attached to the green game object.

Player.cs :

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

public class Player : MonoBehaviour
{
    public float moveSpeed = 10f;
    void Update()
    {
        Vector3 position = transform.position;
        if (Input.GetKey("w")){
            position.y += moveSpeed * Time.deltaTime;
        }
        if (Input.GetKey("s")){
            position.y -= moveSpeed * Time.deltaTime;
        }
        if (Input.GetKey("d")){
            position.x += moveSpeed * Time.deltaTime;

        }
        if (Input.GetKey("a")){
            position.x -= moveSpeed * Time.deltaTime;

        }
        transform.position=position;
    }
}

```

Enemy.cs :

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

public class Enemy : MonoBehaviour
{
    public Transform player;
    private Rigidbody2D rb;
    private Vector2 movement;
    public float moveSpeed = 5f;
    // Start is called before the first frame update
    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 direction = player.position - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x)*Mathf.Rad2Deg;
        rb.rotation = angle;
        direction.Normalize();
        movement=direction;
    }
    private void FixedUpdate(){
        moveCharacter(movement);
    }
    void moveCharacter(Vector2 direction){
        rb.MovePosition((Vector2)transform.position + (direction*moveSpeed*Time.deltaTime));
    }
}

```

Speed.cs :

```
using UnityEngine;

public class Speed : MonoBehaviour
{
    public float speedIncrease = 5f;
    private void OnTriggerEnter2D(Collider2D collision){
        if (collision.CompareTag("Player")){
            GameObject player = collision.gameObject;
            Player playerScript = player.GetComponent<Player>();
            if (playerScript){
                playerScript.moveSpeed += speedIncrease;
                Destroy(gameObject);
            }
        }
    }
}

```

enemySpeed.cs :

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

public class enemySpeed : MonoBehaviour
{
    public float speedIncrease=5f;
    private void OnCollisionEnter2D(Collider2D collision){
        if (collision.CompareTag("Enemy")){
            GameObject enemy=collision.gameObject;
            Enemy enemyScript=collision.gameObject.GetComponent<Enemy>();
            if(enemyScript){
                enemyScript.moveSpeed+=speedIncrease;
                Destroy(gameObject);

            }

        }
    }
}

```

I'm also getting this error that happened when I finished making `enemySpeed.cs`:

I have is trigger checked on for the enemy rigidbody2d because when it touches the player with is trigger off, then it will kick the player and the player will start gliding across the map like its on ice or in space.

I come from the Blender Stack Exchange where we provide all resources we feel are relevant to the question so let me know if I left anything out or included too much.

# Answer
Turns out I made a beginner mistake. I mistakenly used `OnCollisionEnter2D` instead of `OnTriggerEnter2D`.
> 0 votes

---
Tags: unity, c#, 2d, rigidbody, rigid-body-dynamics
---


# Question
Title: How can I fix "the referenced script on this Behaviour is missing" warnings?
One of my game objects used to have a script that I have now deleted on purpose. Now it keeps saying this message as a warning:

> The referenced script on this Behaviour is missing!

How can I rid of that?

# Answer
> 3 votes
Remove the missing reference from your GameObject. You attached your script to something, remove the now missing component, and done.

# Answer
> 0 votes
Another potential reason why this error might occur is that your script *file name* and script *class name* are different. **For example:**

**`Incorrect Setup`**

**`Correct Setup`**

---
Tags: unity
---


title: Screen space reflections bug

text:
# Question
Title: Screen space reflections bug
I try to implement screen space reflections in my graphics engine using ray marching algorithm. After a lot of trying I got this result:

https://youtu.be/yzkgpcliBVQ

As you can see, the reflections are cut off if you get closer and stretched if you move further away. All vectors seem to be in view space, the transformation function between spaces is correct.

```
void main()
{
    vec4 texelNormalWS = getNormal(TexCoords);

    vec4 texelNormalVS = inverse(transpose(view)) * texelNormalWS;
    vec4 texelPositionWS = getPosition(TexCoords);

    vec3 viewDirVS = (view * texelPositionWS).xyz;
    vec3 reflectDirVS = normalize(reflect(normalize(viewDirVS.xyz),normalize(texelNormalVS.xyz)));

    ...

    color = vec4(ssrVS(viewDirVS, reflectDirVS),1.0f);
}

vec2 viewSpaceToSS(vec3 position)
{
     vec4 pVP = proj * vec4(position,1.0f);
     pVP.xy /=pVP.w;
     pVP.xy = pVP.xy * 0.5f + 0.5f;
     return pVP.xy;
}

vec2 BinarySearchVS(vec3 ray, vec3 dir)
{
    vec2 projectedCoords;
    float depth;

    for(int i = 0; i < 5; i++)
    {
        projectedCoords = viewSpaceToSS(ray);
        depth = getPosition(projectedCoords).z;

        float dDepth = ray.z - depth;

        dir *= 0.5f;
        if(dDepth > 0.0f)
            ray += dir;
        else
            ray -= dir;
    }

    ray.z-=depth;
    return viewSpaceToSS(ray);
}

vec3 ssrVS(vec3 ray, vec3 dir)
{
    float stepSize = 0.2f;
    const int maxSteps = 100;
    vec2 projectedCoords;

    dir*=stepSize;

    for(int i = 0; i < maxSteps; i++)
    {
        ray+=dir;

        projectedCoords = viewSpaceToSS(ray);
        float depth = getPosition(projectedCoords).z;

        if (depth > 100.0f)
            continue;

        float dDepth = ray.z - depth;
        if(dDepth <= 0 && dir.z - dDepth < 1.2)
            projectedCoords = BinarySearchVS(ray,dir);
    }

    return getColor(projectedCoords).xyz;
}

```

Any idea how to fix this distortion?

**UPD:**

I figured out that

```
if(dDepth <= 0 && dir.z - dDepth < 1.2)

```

doesn't hit most of the time.

I added after hit checking branch:

```
return vec3(1.0f,0.0f,0.0f);

```

got this:

# Answer
If your are still interested by an answer, after working around myself with ssr, I came back to your code and ported for DX. I made some changes and below is the result. I use the ZMin/ZMax test inspired from the McGuire method instead of your dDepth test. At the end this modified code is the faster I have for now. Regarding the offset mirroring at horizon in the picture can it be a problem of normal used for ray direction not in the \[-1,1\] range? I saw problems like this when normal are saved in texture in the \[0,1\] range and not converted back to \[-1,1\] range.

I introduces a test on world position to skip self reflection on ground.

I hope this will have some insterest for you.

```
float2 BinarySearchVS(float3 ray, float3 dir)
{
    float4 PCoords;
    int3 TexCoords;
    float SX = (ScreenX-1)*0.5f;
    float SY = (ScreenY-1)*0.5f;
    float ZMax = ray.z;
    float ZMin = ray.z;
    float ZCur = ray.z;
    for(int i = 0; i < 5; i++)
    {
        PCoords = mul(float4(ray, 1), Proj);//retrieve coords in [-1,1] range
        PCoords.xy /=PCoords.w;
        if (( PCoords.x<-1 ) || ( PCoords.x >1 ) || ( PCoords.y<-1) || ( PCoords.y>1)) break;// exit if out of screen
        TexCoords = int3(int(SX+PCoords.x*SX), int(SY-PCoords.y*SY), 0);//get coords in screen size for DX Tex.Load method
        ZCur = txDepth1.Load(TexCoords).r;//get Depth from regular ZBuffer
        if ( ZCur == 0 ) break;
        ZCur = 1/(InvProj.z*ZCur+1);//retrieve Pos.z only in view space
        dir *= 0.5f;
        ZMin = ray.z; //set ZMin as old ray.z
        if (ZCur>ZMax) ray+=dir; else ray-=dir;//testing for dir sign
        if ((ZCur<ZMax)&&(ZCur>ZMin)) break;//If current depth=Pos.z in the range min/max stop
        ZMax = ray.z; //set ZMax as new ray.z
    }
     PCoords = mul(float4(ray, 1), Proj);
    return PCoords.xy /=PCoords.w;//retrieve coords in [-1,1] range
}
//some defined values
#define stepSize 4
#define maxSteps 35
#define thickness 1
#define UseBinary 1

float4 ssrVS(float3 ray, float3 dir)
{
    dir*=stepSize;
    float4 PosV;
    float4 PosW;
    float4 PCoords;
    int3 TexCoords;
    float SX = (ScreenX-1)*0.5f;
    float SY = (ScreenY-1)*0.5f;
    float ZMax = ray.z;
    float ZMin = ray.z;
    float ZCur = ray.z;
    for(int i = 0; i < maxSteps; i++)
    {
        ZMin = ray.z;
        ray+=dir;
        ZMax = ray.z;
        PCoords = mul(float4(ray, 1), Proj);
        PCoords.xy /=PCoords.w;
        if (( PCoords.x<-1 ) || ( PCoords.x >1 ) || ( PCoords.y<-1) || ( PCoords.y>1)) break;
        TexCoords = int3(int(SX+PCoords.x*SX), int(SY-PCoords.y*SY), 0);
        ZCur = txDepth1.Load(TexCoords).r;
        if ( ZCur == 0 ) break;
        if ( ZCur < 1 )
        {
            PosV = float4(PCoords.xy, ZCur, 1);//here we need full PosV to get PosW
            PosV.xyz = float3(InvProj.x*PosV.x,InvProj.y*PosV.y, 1)/(InvProj.z*PosV.z+1);
            PosW=mul(PosV,InvView);
            if ( PosW.y>0) //don’t self-reflect the ground who’s pos.y = 0
            {
                    ZCur = PosV.z;
                    if ((ZCur<ZMax+thickness)&&(ZCur>ZMin))
                    {
                                if ( UseBinary > 0 )
                                {
                                            PCoords.xy = BinarySearchVS(ray,dir);
                                            return float4(txDiffuse1.Load(int3(int(SX+PCoords.x*SX), int(SY-PCoords.y*SY), 0)).rgb,float(maxSteps-i)/maxSteps);//fading depending on the number of iterations
                                }
                                else return  float4(txDiffuse1.Load(int3(int(SX+PCoords.x*SX), int(SY-PCoords.y*SY), 0)).rgb,float(maxSteps-i)/maxSteps);
                    }
            }//( PosW.y>0)
        }//( ZCur < 1 )
    }//end loop
    return float4(0,0,0,0);
}

```
> 0 votes

---
Tags: opengl, 3d, shaders, graphics, glsl
---


title: Error when creating random buttons

text:
# Question
Title: Error when creating random buttons
```
 Traceback (most recent call last):
  File "C:\Users\User\Desktop\game 1.9.1.py", line 76, in <module>
    but_1 = Button(text='1', width=3, height=1, bg='blue', font='Hack 30', command=click_button, true = 1)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2679, in __init__
    Widget.__init__(self, master, 'button', cnf, kw)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2601, in __init__
    self.tk.call(
_tkinter.TclError: unknown option "-true"

```

I planned to make 1 correct button, and that it would change. When you click on the correct button, the score is added to 1, and if it is incorrect, the score is reset The game code itself:

```
from tkinter import *
import random as rn
import time

rn.seed()
timer = TIME = 5

root = Tk()
root.title('game')
root.geometry('720x1280')

true = 0

clicks = 0

def click_button():
    global clicks, timer, true
    clicks += 1
    timer = TIME
    labelClick['text'] = str(clicks)
    labelClick.pack() #Variable clicks

    count = rn.randrange(1,10,1)
    print(count)
    count = str(count) #randomizer of the correct button

    if count == '1':
        bgcolor='blue'
    if count == '2':
        bgcolor='green'
    if count == '3':
        bgcolor='red'
    if count == '4':
        bgcolor='yellow'
    if count == '5':
        bgcolor='orange'
    if count == '6':
        bgcolor='brown'
    if count == '7':
        bgcolor='violet'
    if count == '8':
        bgcolor='grey'
    if count == '9':
        bgcolor='pink'
    #bgcolor='blue' #random numbers and colors

    but_0 = Button(text=count, width=3, height=1, bg= bgcolor, font='Hack 30', command=click_button)
    print(bgcolor)
    but_0.place(x=310, y=140)
    but_0['state'] = 'disabled'

counter = 1000
def countdown():
    global timer, counter
    global clicks
    print(timer)
    timer -= 1
    counter -= 5
    if timer <= 0:
        clicks -= clicks
        timer = 5
    root.after(counter, countdown)

    but_10 = Button(text=timer, width=3, height=1, font='Hack 30', command=click_button)
    print(timer)
    but_10.place(x=310, y=40)
    but_10['state'] = 'disabled' #A button with the right button

labelClick = Label(root, text=clicks)
labelClick.pack()

but_1 = Button(text='1', width=3, height=1, bg='blue', font='Hack 30', command=click_button, true = 1)

but_2 = Button(text='2', width=3, height=1, bg='green', font='Hack 30', command=click_button, true = 2)

but_3 = Button(text='3', width=3, height=1, bg='red', font='Hack 30', command=click_button, true = 3)

but_4 = Button(text='4', width=3, height=1, bg='yellow', font='Hack 30', command=click_button, true = 4)

but_5 = Button(text='5', width=3, height=1, bg='orange', font='Hack 30', command=click_button, true = 5)

but_6 = Button(text='6', width=3, height=1, bg='brown', font='Hack 30', command=click_button, true = 6)

but_7 = Button(text='7', width=3, height=1, bg='violet', font='Hack 30', command=click_button, true = 7)

but_8 = Button(text='8', width=3, height=1, bg='grey', font='Hack 30', command=click_button, true = 8)

but_9 = Button(text='9', width=3, height=1, bg='pink', font='Hack 30', command=click_button, true = 9) #Buttons

if true == count:
    clicks += 1
else:
    clicks = 0

but_1.place(x=210, y=240)
but_2.place(x=310, y=240)
but_3.place(x=410, y=240)
but_4.place(x=210, y=340)
but_5.place(x=310, y=340)
but_6.place(x=410, y=340)
but_7.place(x=210, y=440)
but_8.place(x=310, y=440)
but_9.place(x=410, y=440) #button layout

root.after(1, countdown)
root.mainloop()

```

# Answer
Your question is a *little* unclear, and there seems to be some checks which are missing, so this answer won't give you a finished product. Also, you seem to be referencing saving the record (high score?) possibly to a file. File access is easy, well-documented, and I'm sure has been answered in a hundred different posts, so I won't add it here.

I suppose I'm just answering the timer question. I've also provided this answer in the style of the code you've already written.

For the timer you can initialize a global timer variable called `timer` using the line

```
timer = TIME = 5   #timer is the timer, TIME is the reset value

```

You should seed your randomizer, so I added that in there too. Inside your `click_button()` function you would include a global reference to `timer`

```
global clicks, timer

```

and you would reset it whenever there was a good click

```
timer = TIME

```

You would have another function which takes care of counting down the timer:

```
def countdown():
    global timer    #global reference to timer
    print(timer)    #print out current value
    timer -= 1      #decrement the timer by one
    if timer < 0:   #did it timeout?
        root.quit() #yes it did, so quit
    root.after(1000, countdown)    #waits 1000ms then runs countdown again

```

And at the bottom of your code, you would run mainloop like this:

```
run.after(1, countdown)    #starts the countdown timer
run.mainloop()             #enters the mainloop

```

You can also reduce the wait time between counter decrements by 1/20th of a second each time it's guessed correctly to provide some added challenge.

The modified code, with the added speed challenge, looks like this:

```
from tkinter import *
import random as rn
import time

random.seed()
timer = TIME = 5

root = Tk()
root.title('game')
root.geometry('720x1280')

clicks = 0
def click_button():
    global clicks, timer
    clicks += 1
    timer = TIME
    labelClick['text'] = str(clicks)
    labelClick.pack() #Variable clicks

    count = rn.randrange(1,10,1)
    print(count)
    count = str(count) #randomizer of the correct button

    if count == '1':
        bgcolor='blue'
    if count == '2':
        bgcolor='green'
    if count == '3':
        bgcolor='red'
    if count == '4':
        bgcolor='yellow'
    if count == '5':
        bgcolor='orange'
    if count == '6':
        bgcolor='brown'
    if count == '7':
        bgcolor='violet'
    if count == '8':
        bgcolor='grey'
    if count == '9':
        bgcolor='pink'
    #bgcolor='blue' #random numbers and colors

    but_0 = Button(text=count, width=3, height=1, bg= bgcolor, font='Hack 30', command=click_button)
    print(bgcolor)
    but_0.place(x=310, y=140)
    but_0['state'] = 'disabled' #A button with the right button

counter = 1000
def countdown():
    global timer, counter
    print(timer)
    timer -= 1
    counter -= 5
    if timer < 0:
        root.quit()
    root.after(counter, countdown)

labelClick = Label(root, text=clicks)
labelClick.pack()

but_1 = Button(text='1', width=3, height=1, bg='blue', font='Hack 30', command=click_button)
but_2 = Button(text='2', width=3, height=1, bg='green', font='Hack 30', command=click_button)
but_3 = Button(text='3', width=3, height=1, bg='red', font='Hack 30', command=click_button)
but_4 = Button(text='4', width=3, height=1, bg='yellow', font='Hack 30', command=click_button)
but_5 = Button(text='5', width=3, height=1, bg='orange', font='Hack 30', command=click_button)
but_6 = Button(text='6', width=3, height=1, bg='brown', font='Hack 30', command=click_button)
but_7 = Button(text='7', width=3, height=1, bg='violet', font='Hack 30', command=click_button)
but_8 = Button(text='8', width=3, height=1, bg='grey', font='Hack 30', command=click_button)
but_9 = Button(text='9', width=3, height=1, bg='pink', font='Hack 30', command=click_button) #Buttons

but_1.place(x=210, y=240)
but_2.place(x=310, y=240)
but_3.place(x=410, y=240)
but_4.place(x=210, y=340)
but_5.place(x=310, y=340)
but_6.place(x=410, y=340)
but_7.place(x=210, y=440)
but_8.place(x=310, y=440)
but_9.place(x=410, y=440) #button layout

root.after(1, countdown)
root.mainloop()

```
> 1 votes

# Answer
This question seems to have changed since the last time I answered it.

I don't remember there being a `true=` option for `Button()`, so I looked it up and no, there is no `true=` option. So take all those out.

Python allows you to add attributes to an object, so you could do something like this:

```
but_1 = Button(text='1', width=3, height=1, bg='blue', font='Hack 30', command=click_button)
but_1.true=1

```

And take this out:

```
 if true == count:
     clicks += 1
 else:
     clicks = 0

```
> 1 votes

---
Tags: android, python, pygame
---


# Question
Title: I have a "Floating Capsule Collider" setup, but if Collider stands on the edge of a platform, the player Mesh ends up looking 'stuck'
I have a "Floating Capsule Collider" setup, but it has an issue when the Collider stands on the very edge of a platform-- the player Mesh ends up looking 'stuck' inside of the platform. How might this be solved?

I tried this approach: Detect if Mesh is 'floating' longer than x seconds; if it is, then add downward force. However, this effect feels unnatural when playing; I was curious if anyone had different suggestions.

(Left) is an image of the issue I'm referencing:

If useful, here's the current controller code. It uses a SpringJoint to keep the Capsule floating above ground. But I think this problem would exist with any floating Collider approach.

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

public class Valet1 : MonoBehaviour
{
    Rigidbody r;
    public CapsuleCollider capsule;
    public Animator animator;
    public GameObject maleModel;
    [SerializeField] float stepsSinceLastGrounded = 0;

    public float maleModelCapsuleOffset;
    public float maleModelRigidbodyOffset;
    public float sphereCheckNumber;

    public float raycastDistance;
    public bool _rayDidHit;

    public Vector3 DownDir;
    public float RideSpringDamper;
    public float RideSpringStrength;
    public float RideHeight;
    RaycastHit _rayHit;

    //standard
    //Base Movement
    public float horizontalInput;
    public float verticalInput;
    public Vector3 moveDirection;
    public Vector3 moveDirectionRaw;
    public int rotDegPerSecond = 720;
    public float speed;
    public Transform cameraTransform;

    //GroundChecking
    public bool isGroundedCloser;
    public Transform groundCheckTransform;
    public float groundCheckRadius = 0.25f;
    public LayerMask groundLayerMask;
    public float distanceToGround;

    //FloatChecking
    public bool isFloating;
    public float stepsDistanceToGroundGreater = 0.0f;
    public float stepsSinceLastJump = 0.0f;

    //jump
    public bool jump;
    public ultimate_timer jumpTimer;
    [SerializeField] float jumpForce = 500f;
    [SerializeField] float snapAfterJumpLimit = 1.6f;

    // Start is called before the first frame update
    void Awake()
    {
        r = GetComponent<Rigidbody>();
        capsule = GetComponent<CapsuleCollider>();
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
        if (Physics.SphereCast(transform.position, sphereCheckNumber, -transform.up, out _rayHit, raycastDistance))
        {
            _rayDidHit = true;
        }
        else
        {
            _rayDidHit = false;
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            stepsSinceLastJump = 0;
            jump = true;
        }
    }

    private void FixedUpdate()
    {
        GroundCheck();
        FloatCheck();

        Ray();

        moveDirection = new Vector3(horizontalInput, 0.0f, verticalInput).normalized;
        moveDirection = (Quaternion.AngleAxis(cameraTransform.rotation.eulerAngles.y, Vector3.up) * moveDirection).normalized;
        moveDirectionRaw = new Vector3(Input.GetAxisRaw("Horizontal"), 0.0f, Input.GetAxisRaw("Vertical")).normalized;
        moveDirectionRaw = (Quaternion.AngleAxis(cameraTransform.rotation.eulerAngles.y, Vector3.up) * moveDirectionRaw).normalized;

        if (jump == true)
        {
            raycastDistance = 0f;
            r.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            jump = false;
        }

        if (distanceToGround <= snapAfterJumpLimit)
        {
            raycastDistance = 82.5f;
        }

        if (moveDirectionRaw != Vector3.zero && moveDirection != Vector3.zero)
        {
            animator.SetBool("isMoving", true);
            Quaternion targetRotation = Quaternion.LookRotation(moveDirection); //or moveDirectionRaw
            targetRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotDegPerSecond * Time.deltaTime);
            r.MoveRotation(targetRotation);
        }
        else
        {
            animator.SetBool("isMoving", false);
        }

        Vector3 force = moveDirection * speed;
        r.AddForce(force, ForceMode.VelocityChange);

        GroundStopSlide();
        UpdateState();
    }

    void UpdateState()
    {
        stepsSinceLastJump += 1;

        stepsSinceLastGrounded += 1;

        if (distanceToGround > 1.9)
        {
            stepsDistanceToGroundGreater += 1;
        }
        else
        {
            stepsDistanceToGroundGreater = 0;
        }
    }

    void GroundStopSlide()
    {
        if (moveDirectionRaw == Vector3.zero)
        {
            Vector3 zeroMe = new Vector3(0, r.velocity.y, 0);
            r.velocity = zeroMe;
        }
    }

    void Ray()
    {
        if (_rayDidHit)
        {
            Vector3 vel = r.velocity;
            Vector3 rayDir = transform.TransformDirection(DownDir);

            Vector3 otherVel = Vector3.zero;
            Rigidbody hitBody = _rayHit.rigidbody;

            if (hitBody != null)
            {
                otherVel = hitBody.velocity;
            }

            float rayDirVel = Vector3.Dot(rayDir, vel);
            float otherDirVel = Vector3.Dot(rayDir, otherVel);

            float relVel = rayDirVel - otherDirVel;

            float x = _rayHit.distance - RideHeight;

            float springForce = (x * RideSpringStrength) - (relVel * RideSpringDamper);

            Debug.DrawLine(transform.position, transform.position + (rayDir * springForce), Color.yellow);

            r.AddForce(rayDir * springForce);

            if (hitBody != null)
            {
                hitBody.AddForceAtPosition(rayDir * -springForce, _rayHit.point);
            }
        }

    }
    public void GroundCheck()
    {
        isGroundedCloser = Physics.CheckSphere(groundCheckTransform.position, groundCheckRadius, groundLayerMask);

        RaycastHit groundHit = new RaycastHit();
        if (Physics.Raycast(transform.position, -Vector3.up, out groundHit))
        {
            distanceToGround = groundHit.distance;
        }

        maleModel.transform.position = new Vector3(capsule.transform.position.x, Mathf.Max(capsule.transform.position.y, 1.69346f), capsule.transform.position.z)
            + new Vector3(0, maleModelRigidbodyOffset, 0);

        if (isGroundedCloser)
        {
            stepsSinceLastGrounded = 0;
        }
    }

    public void FloatCheck()
    {

        if (stepsSinceLastJump > 60 && stepsDistanceToGroundGreater > 10)
        {
            r.AddForce(Vector3.down * 100f, ForceMode.Force);
            isFloating = true;
            print("Floating for too long- Adding force");
        }
    }

}

```

# Answer
Thanks for addressing this problem. I'm also working on my custom floating capsule controller and mine has the same problem.

Adding more downward force would be very costly as it affects the play experience. A more effective way to solve this is to add a sphere collider at the bottom of the capsule collider and create a frictionless physics material for the platforms. Now, the bottom is more round due to the smaller radius of the sphere collider, making it easier for the character to slide past the edge.
> 1 votes

---
Tags: unity, physics, collider
---


# Question
Title: Unity hierarchical state machines and SOLID principles questions
i was wondering if you could help me out with some confusion i have over state machines and SOLID principles! sorry if the post gets too long, i'll try to keep things simple! So i have a huge player controller with dependencies of like 120 references and values (movement, crouch , mouse, jump , gravity etc etc) and i want to make it into a state machine. my confusion is in the whole state thing. i started out by trying to follow the Single responsibility principle so i broke down all functions to their own classes. so now i got movement.cs , jump.cs etc so all dependencies now are in their respective classes. But! my confusion again is, that if i were to make things into a state machine wouldn't the base class need to have those references? wouldnt that also make it become huge again? i.e. this is the new player controller

```
public class PlayerControllerManager : PortalTraveller, IDamageable
{
    protected PlayerBaseState currentState;
    protected PlayerStateFactory _statesFactory;
    public PlayerBaseState CurrentState { get { return currentState; } set { currentState = value; } }
    PlayerMovement playerMovement; // the first class i made from the previous player controller //
    public Transform GetTransform()
    {
        return transform;
    }
    private void Awake()
    {
        playerMovement = GetComponent<PlayerMovement>();
    }
}

```

The player movement class only holds values like speed, vectors and things like this. is this how its supposed to be? since the actual functions will go into their own state classes? am i overthinking it? am i doing stupid things??

ie this is the movement state class

```
public class PlayerMoveState : PlayerBaseState
{
    public PlayerMoveState(PlayerControllerManager currentContext, PlayerStateFactory playerStateFactory) : base(currentContext, playerStateFactory) { }
    public override void CheckSwitchStates() { }
    public override void EnterState() { }
    public override void ExitState() { }
    public override void IntializeSubState() { }
    public override void OnCollisionEnter() { }
    public override void UpdateState() { }
}

```

can i store dependencies in here? is it good/bad practice? is there a better or well proper way to handle both a state machine and keep the SOLID principles? i did try something out by getting a public variable like this in my Playercontroller class

```
    public Vector3 Move
    {
        get
        {
            return playerMovement.move;
        }
        set
        {
            Move = value;
        }
    }

```

and then did this in my moveState class

```
    public override void UpdateState()
    {
        Vector2 movement = InputManager.GetPlayerMovement();
        _baseContext.Move = new Vector3(movement.x, 0f, movement.y);
    }

```

Does that mean that i need to declare all my variables again from the movement class to the context class so i can access them? or should i do it like this

```
    public PlayerMovement playerMovement { get; set; }

```

and then just call

```
 _baseContext.playerMovement.move = new Vector3(movement.x, 0f, movement.y);

```

Thank you for your time!

# Answer
> 1 votes
One pattern I find very elegant in Unity is to represent each state of a state machine with an own game object. A game object with a state machine gets one child game object per state, which are all inactive by default. When the state machine enters a state, it does so by using `SetActive(bool)` to deactivate the gameObject representing the current state and activate the gameObject representing the next state.

Those child gameObjects then contain everything that's relevant about their state.

The advantages of this pattern are:

* The states can not just contain one script but any number of scripts. The state machine does not need to know anything about them.
* The scripts on the states can use standard Unity event methods, so you don't need to implement an own architecture for managing state transitions beyond deactivating the old and activating the new state gameObject:
    + `OnEnable()` for the logic which is to be executed when entering this state
    + `OnUpdate()` / `OnFixedUpdate()` / `OnCollision...` etc. for logic to be executed while in this state
    + `OnDisable()` for the logic which is to be executed when leaving this state
* These scripts do not need to extend a more specific base class than `MonoBehaviour`, implement a specific interface or even be aware that they are states within a state machine. As long as a script can deal with being enabled and disabled, it will work as a component of a state gameObject. So you get much better code re-usability and modularity.
* The states can also contain *non-script* components. Like for example particle effects which are only supposed to be visible in certain states. They can even contain more child gameObjects. Like a canvas hierarchy with the UI which is only supposed to show up while in a certain state.
* When states have dependencies (on components of the base object or on something outside of the base object), then you can set up those dependencies in the inspector.
* When you are testing your game, you can look at the scene hierarchy to see which state is currently active.

The disadvantage is that you have a lot more gameObjects in your hierarchy, and all the enabling and disabling when switching between states can be a tad more expensive than in other implementation patterns. But when you don't have too many objects governed by state machines like that, and state changes do not happen a hundred times per frame, then that should not be an issue.

This architecture applies all 5 solid principles:

* **Single-Responsibility Principle**: Each functionality can be put into a separate script which you then put onto one or more states. No other script needs to be changed to make that work. The state machine isn't aware of what scripts are on each state game-object, so it does not need to change either when you add functionality to states.
* **Open-Closed Principle**: States are open to extension by adding additional components to them.
* **Liskov Substitution Principle**: You can use components on states which were never intended to be used as such. In most cases, it will just work.
* **Interface Segregation Principle**: The state objects only implement the interface all MonoBehaviours implement - the standard Unity event methods. Which are all optional. The state machine does not depend on any of them. It just activates and deactivates gameObjects.
* **Dependency Inversion Principle**: The high-level state machine only sees GameObjects, and has no dependency to any of the scripts on those game objects which implement the low-level logic of that state.

---
Tags: unity, statemachine
---


# Question
Title: Synvar not syncing when Instantiating gameObject
I am instantiating a gameObject server-side using the code below. The problem I am facing is that the SyncVar "PlayerUnit" is null on the client, even though I referenced a networked gameObject. Anyone knows what the problem is and how to solve it? Thanks for any help!

```
[SyncVar]
public GameObject PlayerUnit;

public GameObject PlayerUnitPrefab;

void SpawnUnit()
        {
            print("Spawning Player Unit");
            GameObject newPlayerUnit = Instantiate(PlayerUnitPrefab);
            NetworkServer.Spawn(newPlayerUnit);
            PlayerUnit = newPlayerUnit;
        }

```

# Answer
I found a workaround using netIds. I think the problem was that when I tried to sync the gameobject, it wasn't spawned yet on the client, so it was null.

```
[SyncVar]
uint PlayerUnitNetworkID;
GameObject playerUnit;
public GameObject PlayerUnit
{
    get
    {
        if (playerUnit == null)
        {
            if (PlayerUnitNetworkID == 0)
            {
                return null;
            }
            playerUnit = NetworkIdentity.spawned[PlayerUnitNetworkID].gameObject;
        }
        return playerUnit;
    }
}

void SpawnUnit()
{
    print("Spawning Player Unit");
    GameObject newPlayerUnit = Instantiate(PlayerUnitPrefab);
    NetworkServer.Spawn(newPlayerUnit);
    playerUnit = newPlayerUnit;
    PlayerUnitNetworkID = newPlayerUnit.GetComponent<NetworkIdentity>().netId;
}

```
> 2 votes

---
Tags: unity, multiplayer, unity-networking, mirror-networking
---


# Question
Title: Maintaining unit formation while following path
I'm currently working on a 2D Age of Empires style RTS game.

Here's my problem:

I'm currently using the A\* algorithm (via Path finding package) to move my units.

When you select a "group" of units and set a destination, all units inside of the battalion will follow an A\* path and go to the destination. Here's a video of what it looks like.

I want that the group of units stays solid; I want that the whole group stays united and follows the path without the individual units separating.

# Answer
> 14 votes
My approach would be:

1. Designate one soldier of the formation "the leader". (this does not necessarily need to be the *actual* commanding officer of the formation. You can pick any soldier. You will probably get the best results when you pick the soldier closest to the center of the formation, but that might be worth experimenting with)
2. When the formation moves, calculate a path only for "the leader"
3. While "the leader" moves along the calculated path, have all other soldiers in the formation maintain their relative position to "the leader". This should not require additional route finding, only blindly moving into the relative direction.
4. Should that be impossible, for example because an obstacle in the way requires to break formation, then the individual soldier should calculate an individual path to its designated position within the formation. In order to regain unit cohesion before arriving at the destination, those separated soldiers should move faster than usual. Or alternatively the leader should notice when they lose a soldier and then slow down until the lost soldier has caught up.

When your game features combat with individual soldiers being able to die at any time, then you also need to handle the case that "the leader" dies, potentially even while the formation is on the move. In that case you would have to select a new solder as the new leader and reevaluate the relative positions in the formation of all remaining soldiers.

# Answer
> 2 votes
Maybe similar to Philipp's point but you could also make a separate object (maybe call it like navigator) and apply your pathfinding algorithm to that. Then you would make it so whenever your navigator moves, your soldiers each move by that same amount. Just instead of having to do a leader etc.

# Answer
> 0 votes
In the situation with no obstacles you could make the entire formation a thing you move, so a 3x4 formation can all move up, down, left, or right if the entire 3x4 formation is able to get to the new destination, and then use A\* on the graph modified to adjust what is legal for the formation.

If you adopted this approach you would need to decide upon your business rules for how to handle the situation where the group can't get through something in formation. The other issue you would have to decide is if you allow the formation to break while going through something what is the expected behavior after they squeeze through whatever - do you expect them to form up again, meaning some of the units sit there and do nothing until the trailing members get through?

---
Tags: algorithm, path-finding, rts, pyglet
---


# Question
Title: contentexporter FBX->SDKMESH warning and bad output
I am using the directxtk contentexporter to convert a a fbx file with animation to sdkmesh. The fbx file is exported from blender, it includes an animation using model bones. After exporting to fbx, I can load the fbx file using autodesk fbx review and the animation displays correctly. When using contentexporter to convert the fbx to sdkmesh I get the following warning "No model binding for mesh "..." so creating a default subset". When trying to load the sdkmesh in the directxtk model viewer I get an error "Error loading model ...sdkmesh".

# Answer
> 1 votes
The DirectX Tool Kit ContentExporter tool does not support skinned FBX models, in other words models containing skeletal animation.

You will need the FBX SDK or Assimp in your workflow pipeline to support skinned FBX animation in a DirectX app.

After a month or more of trial and error I was able to support FBX animation in a DirectX 12 game project, using just Blender and the FBX SDK.

For all static models, however, I'm also using ContentExporter to convert unskinned FBX models to SDKMESH format.

Textures are loaded separately in DirectX 12 and are bound to shaders via shader resource view (SRV) descriptor heaps.

---
Tags: animation, directx, fbx
---


# Question
Title: How to get UV coordinates for sphere (Cylindrical Projection)
I have created one sphere and I want to map onto it a texture map. But I want first to project my map texture to **cylinder** and **then** to **sphere**.

So I want to create a function which takes as parameter a 3D point from sphere and calculate a uv coordinate of this point using cylindrical coordinates. My guess is that I have to transform the spherical coordinates to cylindrical but I am not sure.

Is this possible and how can I implement it ?

# Answer
> 14 votes
Assuming atan2 returns an angle in radian between -pi and pi (π) you do something like:

```
n = Normalize(sphere_surface_point - sphere_center);
u = atan2(n.x, n.z) / (2*pi) + 0.5;
v = n.y * 0.5 + 0.5;

```

Where `sphere_surface_point` is the point on the sphere surface.

`/ (2*pi)` is there to convert the returned angle to a value between -0.5 and 0.5

Add 0.5 to shift it to the range 0..1 for texture mapping that gives you the `u` texture coordinate.

`n.y` is already your `v` texture coordinate.

---

It's more of a computer graphics (https://computergraphics.stackexchange.com/) question even though texture projections comes up a lot in the context of game dev.

# Answer
> 0 votes
Leaving this here for myself:

```
static const float PI = 3.14159265f;

// assumes p is a point on unit sphere

// https://en.wikipedia.org/wiki/File:Equirectangular_projection_SW.jpg
float2 sphere2mapUV_Equirectangular(float3 p)
{
    return float2(
        atan2(p.x, -p.z) / (2 * PI) + .5,
        p.y * .5 + .5
    );
}

// https://en.wikipedia.org/wiki/File:Lambert_cylindrical_equal-area_projection_SW.jpg
float2 sphere2mapUV_EqualArea(float3 p)
{
    return float2(
        (atan2(p.x, -p.z) / PI + 1) / 2,
        asin(p.y) / PI + .5
    );
}

```

I added links to example images in case you need a visual reference for checking which projection your map is made with.

Usage:

```
float2 uv = sphere2map(normalize(position));

```

That assumes position is in model space.

In case you're using this in vertex shader the `position` might already be normalized, so normalization could be skipped.

Your sphere model will usually have center at `float3(0,0,0)`, but if that's not the case you'll have to subtract the `sphere_center_position` from `position`.

---
Tags: projection, uv-mapping
---


# Question
Title: How to get player coordinates in Minecraft Forge?
I'm currently working on a Minecraft mod (Minecraft 1.12.2) using Minecraft Forge where the player can use a hotkey to send out a "SOS" message in a discord-server using a discord-bot. This SOS-message could contain things like the current coordinates of the player, the time of day, etc.

Now, I'm a total newbie on this topic and when trying to implement this mod I'm struggling to get certain information about the player (in this case the current coordinates). I assume this can be accessed through a certain class (not sure whether this is true or not), but when searching the web most search-results tell you how to see your current coordinates in game (which is not what I want: I want to be able to take these coordinates and send them to a discord-bot for example).

Anyone who has experience on this topic and could help me?

Just for information: tha name of the mod is "KDPVP" and my current program is written in the "KdPvp.java" file inside the package "com.cy4.kdpvp" inside the src/main/java folder of my project.

The current code in "KdPvp.java":

```
package com.cy4.kdpvp;

import net.minecraftforge.fml.common.Mod;

@Mod(modid = KdPvp.MODID, name = KdPvp.NAME, version = KdPvp.VERSION)
public class KdPvp
{
    public static final String MODID = "kdpvp";
    public static final String NAME = "KDPVP";
    public static final String VERSION = "1.0";

    public void sendSos()
    {
        // TODO take the current coordinates and send them to the discord bot
    }
}

```

# Answer
> 1 votes
Found this from - Here

```
int playerCord = entityPlayer.getPlayerCoordinates()

```

---
Tags: java, minecraft-modding
---


# Question
Title: HDRP indoor scene has no diffuse indirect light
The lights in my indoor scene correctly produce direct illumination, but no indirect diffuse illumination. So the areas that aren't directly lit are completely black before exposure/post-processing. The one exception is geometry in the zone of reflection probes, which is lit somewhat. By my calculation the lights should be producing about 750 lux, which is quite bright.

I've read every part of the Unity and HDRP manuals that I can find about lighting, and a bunch of other lighting guides, but I can't seem to figure it out. I've also messed around with the lighting section of the Rendering Debugger, but I don't know how to use the information. I gather that the lightmaps aren't getting the indirect lighting baked in.

Here's an example with automatic exposure (limit min 5) and no tone-mapping. Everything visible here is static geometry. All the light sources are wide-angle spotlights. The white boxes on the ceiling also have an emissive material.

Notice that there's extra light around the reflection probes. (The color is coming from nearby materials.)

And for reference, here's part of that image with default fixed exposure settings:

I'm working with Unity free 2022.1.3f1 and the High-Definition Render Pipeline 13.1.8. This happens regardless of forward rendering or deferred rendering.

I've been trying to figure this out for days, so I'd greatly appreciate help.

# Answer
> 0 votes
The problem was that the mesh did not have any normals or UV maps.

---
Tags: unity, lighting, hdrp
---


# Question
Title: How to extract the largest mipmap of a DXT5-compressed VTF file?
I'm trying to programmatically convert the largest mipmap of a 32x32 DXT5-compressed VTF file to a PNG. Here is what the image should look like after conversion:

And here is what mine looks like:

Obviously, something is wrong. Here is my code:

```
import texture2ddecoder, numpy
from PIL import Image

# 16x16 because VTF is 32x32
# and since we divide by 2 to get mipmap sizes
# largest mipmap would be 32/2 by 32/2 or 16 by 16
img_width =  16
img_height = 16

# ring_dot.vtf contains just the last 256 bytes of the original VTF
# My logic behind keeping just the last 256 bytes:
    # Mipmap height = 16 px
    # Mipmap width = 16 px
    # Mipmap area (px) = 16*16 = 256 px
    # 1 px = 8 bits (this is because of how DXT5 compression works)
    # Mipmap area (bits) = 256 * 8 = 2048 bits
    # 8 bits = 1 byte
    # Mipmap area (bytes) = 2048 / 8 = 256 bytes
    # 1 row (in hex editor) = 16 bytes
    # Mipmap area (rows) = 256 / 16 = 16 rows
encoded_binary = open('ring_dot.vtf','rb').read()

#decompressing dxt5 to get actual pixel colors, returns BGRA bytes
decoded_binary = texture2ddecoder.decode_bc3(encoded_binary, img_width, img_height)

#creating RGBA PNG, converting from BGRA
dec_img = Image.frombytes("RGBA", (img_width, img_height), decoded_binary, 'raw', ("BGRA"))

dec_img.show()
dec_img.save('ringDot.png')

```

I tried changing `img_width` and `img_height` to higher values like 32x32, 48x48, and 64x64 but to no avail. I suspect I'm determining the size of the largest mipmap (and therefore which bytes represent it in the binary) incorrectly, but the calculations make sense to me and if the largest mipmap really does come last, I don't see why it wouldn't be the last 256 bytes in this case. What am I doing wrong here?

# Answer
> 0 votes
Mipmaps cannot be greater than the original texture/image size, but they can be less than or equal to it. So, for a 32x32 VTF, the largest mipmap would actually be 32x32, not 16x16. This means that (1)`img_width` and `img_height` should both be 32 instead of 16 and (2)I would actually need to decompress the last 1024 bytes, not the last 256 bytes. Below is the working code, with some (I think) better comments and variable names:

import texture2ddecoder
from PIL import Image

# 32x32 because VTF is 32x32
# and since mipmaps can be <= original size
# largest mipmap would be 32x32
img_width =  32
img_height = 32

# ring_dot.vtf contains just the last 1024 bytes of the original VTF (will deal with parsing them out of the complete file later)
# My logic behind keeping just the last 1024 bytes:
    # Mipmap height = 32 px
    # Mipmap width = 32 px
    # Mipmap area (px) = 32*32= 1024 px
    # 1 px = 1 byte (this is because of how DXT5 compression works)
    # 1024 px = 1024 bytes
compressed_binary = open('ring_dot.vtf','rb').read()

#decompressing dxt5 to get actual pixel colors, returns BGRA bytes
decompressed_binary = texture2ddecoder.decode_bc3(compressed_binary, img_width, img_height)

#creating RGBA PNG, converting from BGRA
decompressed_img = Image.frombytes("RGBA", (img_width, img_height), decompressed_binary, 'raw', ("BGRA"))

decompressed_img.show()
decompressed_img.save('ringDot.png')
```

---
Tags: textures, python, mipmaps
---